Compare commits

..
Author SHA1 Message Date
cflmy 4584c8d65b docs: link to the root CI trigger policy
ci/woodpecker/pr/eco Pipeline was successful
2026-11-27 21:10:25 +08:00
cflmy 69212ae01f ci: avoid redundant ecosystem runs for topic pushes and prose
ci/woodpecker/pr/eco Pipeline was canceled
2026-11-27 21:06:12 +08:00
8 changed files with 475 additions and 662 deletions

No files matched your search

+18 -4
View File
@@ -1,13 +1,26 @@
when: when:
event: [push, pull_request, manual] - event: [pull_request, manual]
- event: push
branch: main
steps: steps:
layout: layout:
image: rust:1.100-bookworm image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1
commands: commands:
- apt-get update && apt-get install -y --no-install-recommends ca-certificates git python3
- python3 scripts/check-layout.py - python3 scripts/check-layout.py
- python3 -m unittest discover -s tests/integration - python3 -m unittest discover -s tests/integration
checkouts:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1
depends_on: [layout]
when: &needs_candidate
- event: manual
- event: [push, pull_request]
path:
# Governance, executable Markdown, packaging and unknown paths stay in scope.
exclude: [README.md, 'docs/evidence/*.md']
on_empty: true
commands:
- git submodule update --init - git submodule update --init
- | - |
set -eu set -eu
@@ -21,7 +34,8 @@ steps:
candidate: candidate:
# Match the Linux/glibc environment already used by View for the RC.4 artifact. # Match the Linux/glibc environment already used by View for the RC.4 artifact.
image: mcr.microsoft.com/playwright:v1.49.0-noble image: mcr.microsoft.com/playwright:v1.49.0-noble
depends_on: [layout] depends_on: [checkouts]
when: *needs_candidate
commands: commands:
- | - |
set -eu set -eu
+3 -6
View File
@@ -7,15 +7,12 @@ when:
event: [manual, cron] event: [manual, cron]
branch: [main] branch: [main]
concurrency: 1
steps: steps:
reconcile: reconcile:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1 image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment: environment:
MARQDO_GIT_TOKEN: MARQDO_GIT_TOKEN:
from_secret: gitea_reconcile_token from_secret: gitea_token
commands: commands:
- python3 scripts/check-layout.py
- git submodule update --init
- python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json - python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json
- cat reconcile-report.json
+2
View File
@@ -131,3 +131,5 @@ python3 -m unittest discover -s tests/integration
[各仓库任务](docs/REPOSITORY-TASKS.md) · [组件目录](components.toml) · [架构边界](docs/ARCHITECTURE.md) · [开发流程](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [架构决策记录](docs/adr/README.md) · [AGENTS](AGENTS.md) [各仓库任务](docs/REPOSITORY-TASKS.md) · [组件目录](components.toml) · [架构边界](docs/ARCHITECTURE.md) · [开发流程](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [架构决策记录](docs/adr/README.md) · [AGENTS](AGENTS.md)
旧版实现与文档可在历史标签查阅。 [v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1) 旧版实现与文档可在历史标签查阅。 [v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1)
根仓 CI 的触发条件见 [开发流程](docs/DEVELOPMENT.md#递归校验与组合检查)。
+1 -3
View File
@@ -35,7 +35,7 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
- 校验器读取 Git tree 中固定提交的 catalog,不以工作区改动替代候选;`--checkouts` 需要子模块已初始化,缺失、错误 HEAD、脏工作区、错误入口都明确 FAIL/UNVERIFIED,不静默跳过。CI 先验证并检出直属子模块,再用 `--domain-paths` 校验领域的子模块远端,最后逐个领域检出直属子库。 - 校验器读取 Git tree 中固定提交的 catalog,不以工作区改动替代候选;`--checkouts` 需要子模块已初始化,缺失、错误 HEAD、脏工作区、错误入口都明确 FAIL/UNVERIFIED,不静默跳过。CI 先验证并检出直属子模块,再用 `--domain-paths` 校验领域的子模块远端,最后逐个领域检出直属子库。
- 没有 active 领域时,新校验规则同样接受合法的直属功能组件,这不是历史协议兼容。 - 没有 active 领域时,新校验规则同样接受合法的直属功能组件,这不是历史协议兼容。
- 未知的 active 入口、未声明的 gitlink、目录与 catalog 不一致都必须让候选失败。`planned` 不进入验收计数。 - 未知的 active 入口、未声明的 gitlink、目录与 catalog 不一致都必须让候选失败。`planned` 不进入验收计数。
- 当前 CI 为 `layout` 与 `candidate` 两段;统一 CLI 制品准备、声明驱动调度与递归影响分析仍在推进(见 `.woodpecker/eco.yml` 与主仓库工单),不得以本文件描述当作已实现。 - 根 `eco` 在 PR、`main` 推送和显式手动运行时执行。PR 始终保留 `layout` 状态。仅改动根 `README.md` 或 `docs/evidence/` 下的 Markdown 记录时,自动运行只执行轻量结构校验和脚本测试。混合改动、其他路径、缺失变更列表和手动运行都执行递归检出及完整生态验收。
## 三层验收 ## 三层验收
@@ -80,8 +80,6 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
经过授权的 webhook 入口由根 `scripts/webhook-adapter.py` 实现:先以仓库 webhook secret 校验 `X-Gitea-Signature`(HMAC-SHA256)原始 body,再只接受 `push`(非删除)与 `pull_request`(opened/synchronized/reopened)事件;仓库必须来自 accepted 根图的远端允许列表,base 使用 accepted 图当前固定 SHA(payload base 只作 hint),CI 聚合要求至少一个状态且全部 success、URL 为允许 CI 主机上的 https。校验通过后交给同一 `candidate-notify.py` 做可达性/去重/重放/基线重验与影响分析,输出计划(不合并、不推送、不建 PR)。通知丢失的恢复由同一脚本 `--reconcile` 承担:扫描允许列表仓库的开放 PR 与 head statuses,对未入账的成功候选执行同一验证(幂等状态文件,重复运行只报 duplicate);API transient 错误有限退避重试,401/403 立即失败,不把触发成功当作下游已处理。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。 经过授权的 webhook 入口由根 `scripts/webhook-adapter.py` 实现:先以仓库 webhook secret 校验 `X-Gitea-Signature`(HMAC-SHA256)原始 body,再只接受 `push`(非删除)与 `pull_request`(opened/synchronized/reopened)事件;仓库必须来自 accepted 根图的远端允许列表,base 使用 accepted 图当前固定 SHA(payload base 只作 hint),CI 聚合要求至少一个状态且全部 success、URL 为允许 CI 主机上的 https。校验通过后交给同一 `candidate-notify.py` 做可达性/去重/重放/基线重验与影响分析,输出计划(不合并、不推送、不建 PR)。通知丢失的恢复由同一脚本 `--reconcile` 承担:扫描允许列表仓库的开放 PR 与 head statuses,对未入账的成功候选执行同一验证(幂等状态文件,重复运行只报 duplicate);API transient 错误有限退避重试,401/403 立即失败,不把触发成功当作下游已处理。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after <ISO-8601 时间>`。从固定根及领域 tree 解析受管仓库,核对 Gitea tag、`release-evidence.json`、同 SHA Woodpecker 组件 CI 和资产字节摘要。根 `reconcile` 工作流从当前受保护的 `main` 串行运行,使用 `gitea_reconcile_token` 以专用非管理员账号写追踪工单。`historical-baseline` 表示已登记历史输入,`blocked` 表示发布验证未通过,`tracked` 表示已记录经验证的发布。消费者验收和父级接受均需各自的 CI 与 PR 证据。
## 发行与回滚 ## 发行与回滚
- 组件可独立 SemVer 发布;领域可发布经过验证的组合制品;根生态 release 固定整个 gitlink 树。独立版本不代表维护多套现行协议。 - 组件可独立 SemVer 发布;领域可发布经过验证的组合制品;根生态 release 固定整个 gitlink 树。独立版本不代表维护多套现行协议。
+74 -37
View File
@@ -11,8 +11,8 @@ The affected set is computed in the order the development contract requires:
1. changed or removed leaves; 1. changed or removed leaves;
2. reverse transitive closure over `requires` edges from the union of both 2. reverse transitive closure over `requires` edges from the union of both
graphs (removed edges cannot hide a consumer); graphs (removed edges cannot hide a consumer);
3. `checks_with` and reverse dependency fixed point; 3. parent domains of affected components;
4. parent domains of affected components in both graphs. 4. `checks_with` fixed point (co-validation is not a build prerequisite).
When a domain cannot be expanded (missing object/checkout) the result is marked When a domain cannot be expanded (missing object/checkout) the result is marked
UNVERIFIED and the whole domain is treated as affected rather than silently UNVERIFIED and the whole domain is treated as affected rather than silently
@@ -217,42 +217,37 @@ def changed_components(
def affected_set( def affected_set(
accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict] accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict]
) -> tuple[list[str], list[str], list[str]]: ) -> tuple[list[str], list[str], list[str]]:
dependents: dict[str, set[str]] = {} graph = {**accepted, **candidate}
partners: dict[str, set[str]] = {} dependents: dict[str, set[str]] = {component_id: set() for component_id in graph}
parents: dict[str, set[str]] = {} for component in graph.values():
for graph in (accepted, candidate):
for component_id, component in graph.items():
for dependency in component.get("requires", []): for dependency in component.get("requires", []):
dependents.setdefault(dependency, set()).add(component_id) dependents.setdefault(dependency, set()).add(component["id"])
for partner in component.get("checks_with", []):
partners.setdefault(component_id, set()).add(partner)
partners.setdefault(partner, set()).add(component_id)
if component.get("parent"):
parents.setdefault(component_id, set()).add(component["parent"])
affected = {item["id"] for item in changed} affected = {item["id"] for item in changed}
queue = list(affected) queue = list(affected)
while queue: while queue:
for consumer in dependents.get(queue.pop(), set()) - affected: current = queue.pop()
for consumer in dependents.get(current, set()):
if consumer not in affected:
affected.add(consumer) affected.add(consumer)
queue.append(consumer) queue.append(consumer)
build_affected = affected.copy()
queue = list(affected)
while queue:
current = queue.pop()
additions = (partners.get(current, set()) | dependents.get(current, set())) - affected
affected.update(additions)
queue.extend(additions)
co_validation = {partner for current in affected for partner in partners.get(current, set())}
co_validation -= build_affected
domains = set() domains = set()
queue = list(affected) for component_id in list(affected):
while queue: parent = graph[component_id].get("parent")
for parent in parents.get(queue.pop(), set()) - affected - domains: while parent:
if parent not in affected:
domains.add(parent) domains.add(parent)
queue.append(parent) parent = graph[parent].get("parent") if parent in graph else None
co_validation: set[str] = set()
while True:
additions = set()
for component_id in affected:
for partner in graph[component_id].get("checks_with", []):
if partner not in affected:
additions.add(partner)
if not additions:
break
affected |= additions
co_validation |= additions
return sorted(affected), sorted(domains), sorted(co_validation) return sorted(affected), sorted(domains), sorted(co_validation)
@@ -266,14 +261,56 @@ def consumers_of(component_id: str, revision: str) -> dict:
revision_sha = resolve(ROOT, revision) revision_sha = resolve(ROOT, revision)
graph, unverified = load_graph(ROOT, revision_sha, "root") graph, unverified = load_graph(ROOT, revision_sha, "root")
if component_id not in graph: if component_id not in graph:
unverified.append( graph, unverified = load_graph(ROOT, revision_sha, "root")
f"unknown component {component_id!r} at {revision_sha}; scope widened" return {
) "schema": SCHEMA,
fallback = "full" if unverified else None "schema_version": SCHEMA_VERSION,
"accepted": {"ref": revision, "revision": revision_sha},
"component": component_id,
"affected": sorted(graph),
"checks_with": [],
"domain_ancestors": [],
"fallback": "full",
"unverified": unverified
+ [f"unknown component {component_id!r} at {revision_sha}; scope widened"],
}
dependents: dict[str, set[str]] = {key: set() for key in graph}
for component in graph.values():
for dependency in component.get("requires", []):
dependents.setdefault(dependency, set()).add(component["id"])
affected = {component_id}
queue = [component_id]
while queue:
current = queue.pop()
for consumer in dependents.get(current, set()):
if consumer not in affected:
affected.add(consumer)
queue.append(consumer)
domains = set()
for item in list(affected):
parent = graph[item].get("parent")
while parent:
if parent not in affected:
domains.add(parent)
parent = graph[parent].get("parent") if parent in graph else None
co_validation: set[str] = set()
while True:
additions = {
partner
for item in affected
for partner in graph[item].get("checks_with", [])
if partner not in affected
}
if not additions:
break
affected |= additions
co_validation |= additions
fallback = None
if unverified: if unverified:
affected, domains, co_validation = sorted(graph), [], [] affected = set(graph)
else: domains = set()
affected, domains, co_validation = affected_set(graph, graph, [{"id": component_id}]) co_validation = set()
fallback = "full"
return { return {
"schema": SCHEMA, "schema": SCHEMA,
"schema_version": SCHEMA_VERSION, "schema_version": SCHEMA_VERSION,
+272 -389
View File
@@ -1,433 +1,275 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Verify published releases and reconcile their tracking Issues (marqdo#10).""" """Release discovery and idempotent tracking for the Marqdo ecosystem.
Reads the authoritative catalog/gitlinks to derive managed repositories, scans
Gitea releases (including prereleases), verifies tag/source identity and asset
size/SHA-256, and creates one tracking Issue per release in the root repository.
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. A concurrent run can create a duplicate only if both
scan before either issue is visible; the workflow serializes runs.
"""
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import datetime
import hashlib import hashlib
import http.client
import json import json
import os import os
import re import re
import sys import sys
import tomllib
import urllib.error import urllib.error
import urllib.parse
import urllib.request import urllib.request
from pathlib import Path from pathlib import Path
import impact
PROJECT_ROOT = Path(__file__).resolve().parents[1] PROJECT_ROOT = Path(__file__).resolve().parents[1]
FORGE = "https://git.cflmy.cn" API_BASE = os.environ.get("MARQDO_GITEA_API", "https://git.cflmy.cn/api/v1")
CI = "https://ci.cflmy.cn" ROOT_REPOSITORY = os.environ.get("MARQDO_ROOT_REPOSITORY", "cflmy/marqdo")
ROOT_REPOSITORY = "cflmy/marqdo"
LABEL = "release-tracking" LABEL = "release-tracking"
RECONCILE_ACCOUNT = "marqdo-reconcile"
INDEX = "release-evidence.json"
PAGE_SIZE = 50
MAX_PAGES = 100
MAX_INDEX_BYTES = 1024 * 1024
MAX_ASSET_BYTES = 256 * 1024 * 1024 MAX_ASSET_BYTES = 256 * 1024 * 1024
MAX_ASSETS = 128 MAX_ASSETS = 128
MAX_DEPENDENCIES = 256
SHA = re.compile(r"[0-9a-f]{40}")
DIGEST = re.compile(r"[0-9a-f]{64}")
BASENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,254}")
TAG = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,127}")
REPOSITORY = re.compile(r"https://git\.cflmy\.cn/(cflmy/[A-Za-z0-9-]+)\.git")
HISTORICAL_CLI = ("cflmy/marqdo-cli", "v3.0.0-rc.5",
"c44b0f943875d563bb7c170f8ccd3fd56a82360f")
class ReconcileError(Exception): class ReconcileError(Exception):
pass pass
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, fp, code, message, headers, newurl):
return None
class Gitea: class Gitea:
def __init__(self, token: str): def __init__(self, token: str, base: str = API_BASE):
self.token = token self.token = token
self.opener = urllib.request.build_opener(NoRedirect()) self.base = base.rstrip("/")
def open(self, method, url, data=None, authenticated=False): def request(self, method: str, path: str, data=None, raw=False):
headers = {} body = json.dumps(data).encode() if data is not None else None
if authenticated and self.token: request = urllib.request.Request(
headers["Authorization"] = f"token {self.token}" self.base + path,
if data is not None: method=method,
headers["Content-Type"] = "application/json" data=body,
request = urllib.request.Request(url, data=data, headers=headers, method=method) headers={
return self.opener.open(request, timeout=30) "Authorization": f"token {self.token}",
"Content-Type": "application/json",
def request(self, method, base, path, data=None, authenticated=False): },
)
try: try:
with self.open(method, base + path, data, authenticated) as response: with urllib.request.urlopen(request, timeout=90) as response:
payload = response.read(8 * MAX_INDEX_BYTES + 1) content = response.read()
require(len(payload) <= 8 * MAX_INDEX_BYTES, "API response exceeds size limit") if raw:
return json.loads(payload) return content
return json.loads(content) if content else None
except urllib.error.HTTPError as error: except urllib.error.HTTPError as error:
raise ReconcileError(f"{method} {path}: HTTP {error.code}") from error raise ReconcileError(f"{method} {path}: HTTP {error.code}") from error
except (OSError, ValueError, http.client.HTTPException) as error: except urllib.error.URLError as error:
raise ReconcileError(f"{method} {path}: {error}") from error raise ReconcileError(f"{method} {path}: {error}") from error
def get(self, path): def get(self, path: str):
return self.request("GET", FORGE + "/api/v1", path, authenticated=True) return self.request("GET", path)
def post(self, path, data): def post(self, path: str, data):
return self.request("POST", FORGE + "/api/v1", path, return self.request("POST", path, data)
json.dumps(data).encode(), authenticated=True)
def ci(self, path): def download(self, url: str) -> bytes:
return self.request("GET", CI + "/api", path) request = urllib.request.Request(url, headers={"Authorization": f"token {self.token}"})
with urllib.request.urlopen(request, timeout=120) as response:
def asset(self, path, size, *, index=False): size = int(response.headers.get("Content-Length", "0"))
limit = MAX_INDEX_BYTES if index else MAX_ASSET_BYTES if size > MAX_ASSET_BYTES:
require(type(size) is int and 0 < size <= limit, "invalid asset size") raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
digest = hashlib.sha256() data = response.read(MAX_ASSET_BYTES + 1)
payload = bytearray() if len(data) > MAX_ASSET_BYTES:
received = 0 raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
try: return data
with self.open("GET", FORGE + path) as response:
while chunk := response.read(min(1024 * 1024, size - received + 1)):
received += len(chunk)
require(received <= size, f"asset {path} size mismatch")
digest.update(chunk)
if index:
payload.extend(chunk)
except urllib.error.HTTPError as error:
raise ReconcileError(f"GET {path}: HTTP {error.code}") from error
except (OSError, http.client.HTTPException) as error:
raise ReconcileError(f"GET {path}: {error}") from error
require(received == size, f"asset {path} size mismatch")
return digest.hexdigest(), bytes(payload)
def require(condition, message): def repository_from_url(url: str) -> str:
if not condition: match = re.match(r"https://git\.cflmy\.cn/([^/]+/[^/]+?)(?:\.git)?$", url)
raise ReconcileError(message) if not match:
raise ReconcileError(f"non-canonical repository URL: {url}")
return match.group(1)
def match(pattern, value): def submodule_repositories(repo_root: Path) -> dict[str, str]:
return isinstance(value, str) and pattern.fullmatch(value) is not None path = repo_root / ".gitmodules"
result: dict[str, str] = {}
if not path.is_file():
def exact_fields(value, fields, optional=()): return result
return (isinstance(value, dict) and set(fields) <= value.keys() current = None
and value.keys() <= set(fields) | set(optional)) for line in path.read_text().splitlines():
line = line.strip()
if line.startswith("[submodule "):
def unique_object(pairs): current = None
result = dict(pairs) elif line.startswith("path =") and current is None:
require(len(result) == len(pairs), "release evidence contains duplicate JSON fields") 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 return result
def pages(client, path, **params): def managed_repositories(root: Path) -> dict[str, str]:
for page in range(1, MAX_PAGES + 1): """catalog id/path -> owner/name for direct components and domain children."""
query = urllib.parse.urlencode(dict(params, limit=PAGE_SIZE, page=page)) catalog = tomllib.loads((root / "components.toml").read_text())
batch = client.get(f"{path}?{query}") remotes = submodule_repositories(root)
require(isinstance(batch, list) and all(isinstance(item, dict) for item in batch), managed: dict[str, str] = {}
f"{path}: invalid page {page}") for component in catalog.get("component", []):
require(len(batch) <= PAGE_SIZE, f"{path}: invalid page size") path = component.get("path", "")
yield from batch if path in remotes:
if len(batch) < PAGE_SIZE: managed[f"{component.get('id')}@{path}"] = remotes[path]
return if component.get("kind") == "domain":
raise ReconcileError(f"{path}: pagination limit reached") domain = root / path
domain_remotes = submodule_repositories(domain)
domain_catalog = domain / "components.toml"
def timestamp(value): if not domain_catalog.is_file():
try:
result = datetime.datetime.fromisoformat(value)
except (TypeError, ValueError) as error:
raise ReconcileError("invalid release timestamp") from error
require(result.tzinfo is not None, "release timestamp requires a time zone")
return result.astimezone(datetime.timezone.utc)
def managed_repositories(root):
try:
revision = impact.resolve(root, "HEAD")
graph, unverified = impact.load_graph(root, revision, "root")
except impact.ImpactError as error:
raise ReconcileError(str(error)) from error
require(not unverified, "; ".join(unverified))
managed = {}
for cid, item in sorted(graph.items()):
if not item["sha"]:
continue continue
remote = item["remote"] or "" for child in tomllib.loads(domain_catalog.read_text()).get("component", []):
canonical = REPOSITORY.fullmatch(remote) child_path = f"{path}/{child.get('path', '')}"
require(canonical is not None, f"{cid}: non-canonical repository") if child_path in domain_remotes:
repository = canonical[1] managed[f"{child.get('id')}@{child_path}"] = domain_remotes[child_path]
require(repository not in managed, f"duplicate repository {repository}") return managed
path = item["path"]
if item["parent"]:
path = f"{graph[item['parent']]['path']}/{path}"
managed[repository] = {**item, "path": path, "repository": repository}
return revision, graph, managed
def verify_pipeline(client, repository, source_sha, evidence): def verify_assets(client: Gitea, release: dict) -> list[dict]:
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}), assets = release.get("assets") or []
"invalid component CI evidence") if len(assets) > MAX_ASSETS:
number = evidence["pipeline_number"] raise ReconcileError(f"release has more than {MAX_ASSETS} assets")
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha, verified = []
"release has no component CI evidence for its exact SHA") for asset in assets:
repo = client.ci(f"/repos/lookup/{repository}") name = asset.get("name", "")
forge_repo = client.get(f"/repos/{repository}") if not name or "/" in name or name in (".", ".."):
require(isinstance(repo, dict) and repo.get("full_name") == repository raise ReconcileError(f"unsafe asset name: {name!r}")
and type(repo.get("id")) is int and repo["id"] > 0 url = asset.get("browser_download_url")
and isinstance(forge_repo, dict) and type(forge_repo.get("id")) is int if not url:
and repo.get("forge_remote_id") == str(forge_repo["id"]), raise ReconcileError(f"asset {name} has no download URL")
"CI repository identity mismatch") data = client.download(url)
expected_url = f"{CI}/repos/{repo['id']}/pipeline/{number}" if asset.get("size") is not None and int(asset["size"]) != len(data):
require(evidence["url"] == expected_url, "component CI URL mismatch") raise ReconcileError(f"asset {name} size mismatch")
pipeline = client.ci(f"/repos/{repo['id']}/pipelines/{number}") digest = hashlib.sha256(data).hexdigest()
workflow = "main" if repository == "cflmy/marqdo-cli" else "ci" verified.append({"name": name, "size": len(data), "sha256": digest})
require(isinstance(pipeline, dict) and pipeline.get("number") == number return verified
and pipeline.get("commit") == source_sha and pipeline.get("status") == "success"
and pipeline.get("event") in {"push", "pull_request", "manual"}
and any(w.get("name") == workflow and w.get("state") == "success"
and any(step.get("type") == "commands" and step.get("state") == "success"
for step in w.get("children", []))
for w in pipeline.get("workflows", [])), "component CI did not verify the exact SHA")
def asset_path(repository, tag, asset): def release_marker(repository: str, tag: str) -> str:
name = asset.get("name")
require(match(BASENAME, name), "unsafe release asset name")
escaped = urllib.parse.quote(name, safe="")
path = f"/{repository}/releases/download/{urllib.parse.quote(tag, safe='')}/{escaped}"
require(asset.get("browser_download_url") == FORGE + path,
f"asset {name} has a non-canonical URL")
return path
def verify_release(client, repository, component, tag, release, graph):
identity = client.get(f"/repos/{repository}/tags/{urllib.parse.quote(tag, safe='')}")
require(isinstance(identity, dict) and identity.get("name") == tag
and isinstance(identity.get("commit"), dict)
and match(SHA, identity["commit"].get("sha")), "invalid release tag identity")
source_sha = identity["commit"]["sha"]
attachments = release.get("assets")
require(isinstance(attachments, list) and 0 < len(attachments) <= MAX_ASSETS + 1,
"missing or excessive release assets")
assets = {}
for asset in attachments:
require(isinstance(asset, dict), "invalid release asset")
path = asset_path(repository, tag, asset)
name = asset["name"]
require(name not in assets, "duplicate release asset")
assets[name] = (path, asset.get("size"))
if INDEX not in assets and (repository, tag, source_sha) == HISTORICAL_CLI:
return {"source_sha": source_sha, "historical": True}
require(INDEX in assets, "release evidence index missing")
index_digest, payload = client.asset(*assets.pop(INDEX), index=True)
try:
evidence = json.loads(payload, object_pairs_hook=unique_object)
except (UnicodeDecodeError, ValueError, RecursionError) as error:
raise ReconcileError("invalid release evidence JSON") from error
require(exact_fields(evidence, {"repository", "component_id", "tag", "source_sha",
"ci", "assets", "dependencies"}), "invalid release evidence fields")
require((evidence["repository"], evidence["component_id"], evidence["tag"], evidence["source_sha"])
== (repository, component["id"], tag, source_sha), "release evidence identity mismatch")
verify_pipeline(client, repository, source_sha, evidence["ci"])
dependencies = evidence["dependencies"]
require(isinstance(dependencies, list) and len(dependencies) <= MAX_DEPENDENCIES,
"invalid release dependency list")
seen = set()
for dependency in dependencies:
require(exact_fields(dependency, {"id", "source_sha"}, {"asset_sha256"})
and isinstance(dependency["id"], str) and dependency["id"] in graph
and dependency["id"] not in seen and dependency["id"] != component["id"]
and match(SHA, dependency["source_sha"])
and ("asset_sha256" not in dependency or match(DIGEST, dependency["asset_sha256"])),
"invalid release dependency identity")
seen.add(dependency["id"])
require(set(component["requires"]) <= seen, "release evidence is missing a declared dependency")
records = evidence["assets"]
require(isinstance(records, list) and 0 < len(records) == len(assets),
"release evidence does not cover the published assets")
for item in records:
require(exact_fields(item, {"name", "size", "target", "sha256"})
and match(BASENAME, item["name"]) and item["name"] in assets
and match(BASENAME, item["target"]) and match(DIGEST, item["sha256"])
and type(item["size"]) is int, "invalid release asset evidence")
path, size = assets.pop(item["name"])
require(size == item["size"], f"asset {item['name']} size mismatch")
digest, _ = client.asset(path, size)
require(digest == item["sha256"], f"asset {item['name']} digest mismatch")
return {"source_sha": source_sha, "index_sha256": index_digest,
"ci": evidence["ci"], "assets": records, "dependencies": dependencies}
def release_marker(repository, tag):
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->" return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
def identity_marker(entry): def existing_issues(client: Gitea, label: str = LABEL) -> list[dict]:
return f"<!-- marqdo:verified-release {entry['source_sha']} {entry['index_sha256']} -->" issues = client.get(
f"/repos/{ROOT_REPOSITORY}/issues?state=all&limit=100&type=issues&labels={label}"
)
return issues if isinstance(issues, list) else []
def tracking_body(entry): def ensure_label(client: Gitea) -> int:
lines = [entry["marker"], f"## {entry['repository']} {entry['tag']}", labels = client.get(f"/repos/{ROOT_REPOSITORY}/labels?limit=100")
"", f"- Component: {entry['component']} ({entry['path']})", for item in labels or []:
f"- Published: {entry['published_at']}", f"- Accepted gitlink: {entry['accepted_sha']}", if item.get("name") == LABEL:
f"- Release: {FORGE}/{entry['repository']}/releases/tag/{entry['tag']}"] return int(item["id"])
if "error" in entry: created = client.post(
return "\n".join(lines + ["", "## Blocked", "", f"- {entry['error']}"]) f"/repos/{ROOT_REPOSITORY}/labels",
return "\n".join(lines + ["", identity_marker(entry), {"name": LABEL, "color": "#bfd4f2", "description": "Release tracking created by reconcile"},
f"- Source SHA: {entry['source_sha']}", f"- Index SHA-256: {entry['index_sha256']}", )
f"- Component CI: {entry['ci']['url']}", return int(created["id"])
"", "## Verified assets", "",
*(f"- {a['name']} ({a['target']}, {a['size']} bytes): {a['sha256']}" for a in entry["assets"]),
"", "## Pending consumer validation", "",
f"- Direct consumers: {', '.join(entry['direct_consumers']) or 'none'}",
f"- Affected: {', '.join(entry['affected']) or 'none'}",
f"- Governance owner: {entry['governance_owner']}"])
def is_writer(record): def discover(client: Gitea, root: Path) -> list[dict]:
return (record.get("user") or {}).get("login") == RECONCILE_ACCOUNT entries = []
for key, repository in sorted(managed_repositories(root).items()):
releases = client.get(f"/repos/{repository}/releases?limit=50")
def tracking_comments(client, issues_url, tracker): for release in releases or []:
if not is_writer(tracker):
return []
comments_url = f"{issues_url}/{tracker['number']}/comments"
return [comment.get("body") or "" for comment in pages(client, comments_url)
if is_writer(comment)]
def ensure_tracking_note(client, issues_url, tracker, entry, comments):
if not is_writer(tracker):
entry["tracking_update"] = "tracker author differs from configured account"
return
note = tracking_body(entry)
if note not in comments and note != tracker.get("body"):
client.post(f"{issues_url}/{tracker['number']}/comments", {"body": note})
def verify_apply_context(client, root_sha):
writer = client.get("/user")
require(isinstance(writer, dict) and writer.get("login") == RECONCILE_ACCOUNT
and writer.get("is_admin") is False, "apply requires the non-admin reconcile account")
root = client.get(f"/repos/{ROOT_REPOSITORY}")
require(isinstance(root, dict) and root.get("default_branch") == "main",
"apply requires the root default branch")
branch = client.get(f"/repos/{ROOT_REPOSITORY}/branches/main")
require(isinstance(branch, dict) and branch.get("protected") is True
and (branch.get("commit") or {}).get("id") == root_sha,
"apply requires the current protected root commit")
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None):
root_sha, graph, managed = managed_repositories(root)
cutoff_time = timestamp(cutoff) if cutoff else None
issues_url = f"/repos/{ROOT_REPOSITORY}/issues"
issues = list(pages(client, issues_url, state="all", type="issues", labels=LABEL))
if apply:
verify_apply_context(client, root_sha)
labels = f"/repos/{ROOT_REPOSITORY}/labels"
label_id = next((x["id"] for x in pages(client, labels) if x.get("name") == LABEL), None) if apply else None
results, errors = [], {}
for repository, component in managed.items():
known_tags = set()
try:
releases = list(pages(client, f"/repos/{repository}/releases"))
for release in releases:
if release.get("draft"): if release.get("draft"):
continue continue
tag = release.get("tag_name") tag = release.get("tag_name")
require(match(TAG, tag), "invalid release tag in listing") if not tag:
require(tag not in known_tags, f"duplicate release in paginated listing: {tag}")
known_tags.add(tag)
published = timestamp(release.get("published_at") or release.get("created_at"))
marker = release_marker(repository, tag)
trackers = [issue for issue in issues
if (issue.get("body") or "").splitlines()[:1] == [marker]]
if cutoff_time and published < cutoff_time and not trackers:
continue continue
entry = { marker = release_marker(repository, tag)
"component": component["id"], "path": component["path"], "repository": repository, entries.append(
"tag": tag, "marker": marker, "published_at": published.isoformat(), {
"accepted_sha": component["sha"], "component": key.split("@", 1)[0],
"component_state": component["state"], "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 [],
} }
comments = tracking_comments(client, issues_url, trackers[0]) if len(trackers) == 1 else [] )
recorded = comments + ([trackers[0].get("body") or ""] if trackers and return entries
is_writer(trackers[0]) else [])
try:
require(len(trackers) <= 1, "multiple release tracking Issues")
entry.update(verify_release(client, repository, component, tag, release, graph))
if entry.get("historical"):
entry["status"] = "historical-baseline"
else:
affected, domains, co_validation = impact.affected_set(
graph, graph, [{"id": component["id"]}])
direct = [cid for cid, item in graph.items()
if component["id"] in item["requires"]]
entry.update(status="pending", affected=affected, domains=domains,
checks_with=co_validation,
direct_consumers=sorted(cid for cid in direct if graph[cid]["state"] == "active"),
planned_consumers=sorted(cid for cid in direct if graph[cid]["state"] == "planned"),
governance_owner=component["parent"] or ROOT_REPOSITORY)
old = {line for body in recorded for line in body.splitlines()
if line.startswith("<!-- marqdo:verified-release ")}
require(not old or old == {identity_marker(entry)},
"published release identity or index digest changed")
except ReconcileError as error:
entry.update(status="blocked", error=str(error))
if trackers:
entry["issue"] = trackers[0]["number"] def published_after(entry: dict, cutoff: str | None) -> bool:
if entry["status"] == "pending" and any( if not cutoff:
identity_marker(entry) in body.splitlines() for body in recorded): return True
entry["status"] = "tracked" published = entry.get("published_at")
elif apply and len(trackers) == 1 and entry["status"] in {"pending", "blocked"}: if not published:
ensure_tracking_note(client, issues_url, trackers[0], entry, comments) return False
elif apply and entry["status"] in {"pending", "blocked"}: return published >= cutoff
require(label_id is not None, f"tracking label {LABEL!r} is missing")
created = client.post(issues_url, {
"title": f"[release] {repository} {tag}", "labels": [label_id], def reconcile(
"body": tracking_body(entry), client: Gitea,
}) root: Path = PROJECT_ROOT,
entry["issue"] = created["number"] apply: bool = False,
if entry["status"] == "pending": report_out: Path | None = None,
entry["status"] = "created" cutoff: str | None = None,
results.append(entry) ) -> dict:
prefix = f"<!-- marqdo:release-reconcile repository={repository} tag=" entries = [entry for entry in discover(client, root) if published_after(entry, cutoff)]
for issue in issues: known = {issue.get("body") or "" for issue in existing_issues(client)}
marker = (issue.get("body") or "").partition("\n")[0] results = []
if marker.startswith(prefix) and marker.endswith(" -->"): label_id = ensure_label(client) if apply else None
tag = marker[len(prefix):-4] for entry in entries:
if match(TAG, tag) and tag not in known_tags: marker = entry["marker"]
error = "previously tracked release is absent from the public list" if any(marker in body for body in known):
entry = {"repository": repository, "component": component["id"], results.append({**entry, "status": "tracked"})
"tag": tag, "issue": issue["number"], "status": "blocked", continue
"error": error} if not apply:
if apply and is_writer(issue): verified = []
note = f"{marker}\n\n## Blocked\n\n- {error}" status = "pending"
if note not in tracking_comments(client, issues_url, issue): else:
client.post(f"{issues_url}/{issue['number']}/comments", {"body": note}) try:
results.append(entry) verified = verify_assets(client, {"assets": entry["assets"]})
except ReconcileError as error: except ReconcileError as error:
errors[repository] = str(error) results.append(
{**entry, "assets": [], "status": f"asset-verify-failed: {error}"}
)
continue
status = "created"
body = render_issue(entry, verified)
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}"
results.append({**entry, "assets": verified, "status": status})
report = { report = {
"schema": "marqdo.release-reconcile.v1", "schema_version": 1, "schema": "marqdo.release-reconcile.v1",
"root_repository": ROOT_REPOSITORY, "root_sha": root_sha, "schema_version": 1,
"apply": apply, "repositories": len(managed), "releases": len(results), "generated_at": __import__("datetime").datetime.now(
"scan_complete": not errors, "scan_errors": errors, "results": results, __import__("datetime").timezone.utc
"counts": {status: sum(item["status"] == status for item in results) ).isoformat(),
for status in sorted({item["status"] for item in results})}, "apply": apply,
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "root_repository": ROOT_REPOSITORY,
"repositories": len({entry["repository"] for entry in entries}),
"releases": len(entries),
"results": results,
"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: if report_out:
report_out.parent.mkdir(parents=True, exist_ok=True) report_out.parent.mkdir(parents=True, exist_ok=True)
@@ -435,32 +277,73 @@ def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=No
return report return report
def main(argv): def render_issue(entry: dict, assets: list[dict]) -> str:
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']}",
"",
"## Assets (download-verified)",
"",
"| name | size | sha256 |",
"| --- | --- | --- |",
]
for asset in assets:
lines.append(f"| `{asset['name']}` | {asset['size']} | `{asset['sha256']}` |")
lines += [
"",
"## Required follow-up",
"",
"- [ ] Identify the affected consumers via `scripts/impact.py` and the accepted root graph.",
"- [ ] 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 main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group() parser.add_argument("--apply", action="store_true", help="create tracking Issues")
mode.add_argument("--plan", action="store_true", help="verify without writing to Gitea (default)") parser.add_argument("--report-out", default=None)
mode.add_argument("--apply", action="store_true", help="reconcile release tracking Issues") parser.add_argument("--root", default=str(PROJECT_ROOT))
parser.add_argument("--report-out", type=Path) parser.add_argument(
parser.add_argument("--root", type=Path, default=PROJECT_ROOT) "--published-after",
parser.add_argument("--published-after", default=os.environ.get("MARQDO_RECONCILE_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) args = parser.parse_args(argv)
token = os.environ.get("MARQDO_GIT_TOKEN", "") token = os.environ.get("MARQDO_GIT_TOKEN", "")
if args.apply and not token: if not token:
parser.error("--apply requires MARQDO_GIT_TOKEN") print("reconcile: error: MARQDO_GIT_TOKEN is required", file=sys.stderr)
return 2
try: try:
if args.published_after: report = reconcile(
timestamp(args.published_after) 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,
)
except ReconcileError as error: except ReconcileError as error:
parser.error(str(error)) print(f"reconcile: error: {error}", file=sys.stderr)
try: return 2
report = reconcile(Gitea(token), args.root.resolve(), args.apply,
args.report_out, args.published_after)
except (OSError, ReconcileError) as error:
print(f"reconcile: {error}", file=sys.stderr)
return 1
print(json.dumps(report, ensure_ascii=False, indent=2)) print(json.dumps(report, ensure_ascii=False, indent=2))
return int(not report["scan_complete"] or any( failed = any(
item["status"] == "blocked" or "tracking_update" in item for item in report["results"])) item["status"].startswith(("asset-verify-failed", "issue-create-failed"))
for item in report["results"]
)
return 1 if failed else 0
if __name__ == "__main__": if __name__ == "__main__":
+3 -15
View File
@@ -2,8 +2,9 @@
Builds real temporary Git repositories for two root candidates and asserts the Builds real temporary Git repositories for two root candidates and asserts the
ordering required by the development contract: changed leaves, reverse ordering required by the development contract: changed leaves, reverse
`requires` closure over the union graph, `checks_with` fixed point, then `requires` closure over the union graph, parent domains, then `checks_with`
parent domains. Undetermined scope widens to the full candidate. fixed point; undetermined scope widens to the full candidate instead of being
skipped.
""" """
import importlib.util import importlib.util
@@ -206,19 +207,6 @@ class ImpactTest(unittest.TestCase):
) )
self.assertIn("std-text", report["affected"]) self.assertIn("std-text", report["affected"])
def test_removed_requires_edge_remains_in_the_impact_scope(self):
leaves = self.leaf_shas()
first = self.make_tree(COMPONENTS_V1, leaves)
without_dependency = COMPONENTS_V1.replace(
'requires = ["cli", "std-core"]', 'requires = ["cli"]'
)
second = self.make_tree(without_dependency, leaves)
before, _ = impact.load_graph(self.root, first, "before")
after, _ = impact.load_graph(self.root, second, "after")
affected, _, partners = impact.affected_set(before, after, [{"id": "std-core"}])
self.assertIn("std-text", affected)
self.assertIn("probe", partners)
def test_domain_gitlink_change_expands_to_child_identity(self): def test_domain_gitlink_change_expands_to_child_identity(self):
child = init(self.root / "extensions/web") child = init(self.root / "extensions/web")
write(child / "components.toml", catalog( write(child / "components.toml", catalog(
+102 -208
View File
@@ -1,237 +1,131 @@
"""Release reconciliation tests for marqdo#10.""" """Release reconcile discovery/idempotency tests (issue #10 §6/§7)."""
import hashlib
import importlib.util import importlib.util
import json import json
import sys import tempfile
import unittest import unittest
from pathlib import Path from pathlib import Path
from unittest.mock import patch
from urllib.parse import parse_qs, urlsplit
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location( SPEC = importlib.util.spec_from_file_location(
"reconcile_releases", ROOT / "scripts" / "reconcile-releases.py" "reconcile_releases", ROOT / "scripts" / "reconcile-releases.py"
) )
reconcile = importlib.util.module_from_spec(SPEC) reconcile = importlib.util.module_from_spec(SPEC)
with patch.object(sys, "path", [str(ROOT / "scripts"), *sys.path]): SPEC.loader.exec_module(reconcile)
SPEC.loader.exec_module(reconcile)
REPO = "cflmy/marqdo-std-text"
SOURCE = "a" * 40
BASE = "b" * 40
TAG = "v0.1.0-rc.1"
PUBLISHED = "2026-11-27T08:00:00+08:00"
ASSET = "text-source.tar.gz"
ISSUES = "/repos/cflmy/marqdo/issues"
FORGE = reconcile.FORGE
ACTOR = {"login": reconcile.RECONCILE_ACCOUNT}
COMPONENT = {"id": "std-text", "sha": BASE, "path": "stdlib/text",
"parent": None, "requires": [], "checks_with": [], "state": "active"}
class FakeForge: class FakeGitea:
def __init__(self): def __init__(self, releases=None, assets=None, issues=None):
self.writes = [] self.releases = releases or {}
self.issues = [] self.asset_bytes = assets or {}
self.comments = {} self.issues = list(issues or [])
self.pages = [] self.posts = []
self.pipeline_reads = [] self.label_created = False
self.downloads = []
self.blobs = {ASSET: b"abc"}
self.evidence = {
"repository": REPO, "component_id": COMPONENT["id"], "tag": TAG, "source_sha": SOURCE,
"ci": {"pipeline_number": 12, "source_sha": SOURCE,
"url": f"{reconcile.CI}/repos/8/pipeline/12"},
"assets": [{"name": ASSET, "size": 3, "target": "source",
"sha256": hashlib.sha256(self.blobs[ASSET]).hexdigest()}],
"dependencies": [],
}
self.release = {"tag_name": TAG, "draft": False, "prerelease": True,
"published_at": PUBLISHED}
self.releases = [self.release]
self.protected = True
self.tag_sha = SOURCE
self.pipeline_sha = SOURCE
self.wrong_account = False
self.fail_page = None
self.refresh_assets()
def refresh_assets(self): def get(self, path):
self.blobs[reconcile.INDEX] = json.dumps(self.evidence).encode() if path.startswith("/repos/") and path.endswith("/labels?limit=100"):
self.release["assets"] = [ return [{"id": 5, "name": reconcile.LABEL}] if self.label_created else []
{"name": name, "size": len(blob), if "/issues?" in path:
"browser_download_url": f"{FORGE}/{REPO}/releases/download/{TAG}/{name}"} return self.issues
for name, blob in self.blobs.items() for repository, releases in self.releases.items():
] if path == f"/repos/{repository}/releases?limit=50":
return releases
def get(self, url): return []
parsed = urlsplit(url)
path = parsed.path
query = parse_qs(parsed.query)
if query:
page = int(query["page"][0])
self.pages.append((path, page))
if path.endswith("/releases") and page == self.fail_page:
raise reconcile.ReconcileError("API HTTP 503")
records = {
f"/repos/{REPO}/releases": self.releases,
ISSUES: self.issues,
"/repos/cflmy/marqdo/labels": [{"id": 5, "name": reconcile.LABEL}],
**self.comments,
}.get(path, [])
return records[(page - 1) * reconcile.PAGE_SIZE: page * reconcile.PAGE_SIZE]
return {
f"/repos/{REPO}": {"id": 10},
f"/repos/{REPO}/tags/{TAG}": {"name": TAG, "commit": {"sha": self.tag_sha}},
"/repos/cflmy/marqdo": {"default_branch": "main"},
"/repos/cflmy/marqdo/branches/main": {"protected": self.protected,
"commit": {"id": BASE}},
"/user": ({"login": "admin", "is_admin": True} if self.wrong_account
else {**ACTOR, "is_admin": False}),
}[path]
def ci(self, path):
self.pipeline_reads.append(path)
if path == f"/repos/lookup/{REPO}":
return {"id": 8, "full_name": REPO, "forge_remote_id": "10"}
if path == "/repos/8/pipelines/12":
return {"number": 12, "commit": self.pipeline_sha, "status": "success", "event": "push",
"workflows": [{"name": "ci", "state": "success",
"children": [{"type": "commands", "state": "success"}]}]}
raise AssertionError(path)
def asset(self, path, size, *, index=False):
self.downloads.append(path)
data = self.blobs[path.rsplit("/", 1)[1]]
if len(data) != size:
raise reconcile.ReconcileError("asset size mismatch")
return hashlib.sha256(data).hexdigest(), data if index else b""
def post(self, path, data): def post(self, path, data):
self.writes.append((path, data)) self.posts.append((path, data))
item = {"body": data["body"], "user": ACTOR} if path.endswith("/labels"):
if path == ISSUES: self.label_created = True
item["number"] = 100 + len(self.issues) return {"id": 5, "name": data["name"]}
self.issues.append(item) if path.endswith("/issues"):
else: issue = {"number": 100 + len(self.issues), "body": data["body"], "title": data["title"]}
self.comments.setdefault(path, []).append(item) self.issues.append(issue)
return item return issue
return {}
def download(self, url):
data = self.asset_bytes.get(url)
if data is None:
raise AssertionError(f"unexpected asset download {url}")
return data
def release(repository="cflmy/marqdo-cli", tag="v0.0.1", asset_url="https://example.invalid/a.tar.gz", draft=False):
return {
"tag_name": tag,
"name": tag,
"draft": draft,
"prerelease": True,
"html_url": f"https://git.cflmy.cn/{repository}/releases/tag/{tag}",
"published_at": "2026-11-27T00:00:00Z",
"assets": [{"name": "a.tar.gz", "size": 3, "browser_download_url": asset_url}],
}
class ReconcileTest(unittest.TestCase): class ReconcileTest(unittest.TestCase):
def setUp(self): def test_dry_run_discovers_releases_without_writing(self):
graph = {COMPONENT["id"]: COMPONENT} client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
catalog = (BASE, graph, {REPO: COMPONENT}) report = reconcile.reconcile(client, ROOT, apply=False)
mocked = patch.object(reconcile, "managed_repositories", return_value=catalog) self.assertFalse(client.posts)
mocked.start() self.assertGreaterEqual(report["releases"], 1)
self.addCleanup(mocked.stop) entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.forge = FakeForge()
def run_scan(self, **kwargs):
return reconcile.reconcile(self.forge, **kwargs)
def test_dry_run_fully_verifies_without_writing(self):
report = self.run_scan()
self.assertEqual(self.forge.writes, [])
entry, = report["results"]
self.assertEqual(entry["status"], "pending") self.assertEqual(entry["status"], "pending")
self.assertEqual(entry["source_sha"], SOURCE) self.assertEqual(entry["tag"], "v0.0.1")
self.assertEqual(entry["governance_owner"], "cflmy/marqdo")
self.assertEqual(len(self.forge.downloads), 2)
self.assertEqual(len(self.forge.pipeline_reads), 2)
def test_apply_creates_one_verified_tracker_then_rechecks_it(self): def test_apply_verifies_assets_and_creates_marked_issue(self):
entry, = self.run_scan(apply=True)["results"] client = FakeGitea(
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abc"},
)
report = reconcile.reconcile(client, ROOT, apply=True)
created = [data for path, data in client.posts if path.endswith("/issues")]
self.assertEqual(len(created), 1)
body = created[0]["body"]
self.assertIn(reconcile.release_marker("cflmy/marqdo-cli", "v0.0.1"), body)
self.assertIn("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", body)
self.assertEqual(created[0]["labels"], [5])
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertEqual(entry["status"], "created") self.assertEqual(entry["status"], "created")
self.assertEqual(entry["issue"], 100)
self.assertEqual(self.forge.writes[0][1]["labels"], [5]) def test_second_scan_is_idempotent(self):
body = self.forge.issues[0]["body"] client = FakeGitea(
self.assertIn(reconcile.release_marker(REPO, TAG), body) releases={"cflmy/marqdo-cli": [release()]},
self.assertIn(reconcile.identity_marker(entry), body) assets={"https://example.invalid/a.tar.gz": b"abc"},
entry, = self.run_scan(apply=True)["results"] )
reconcile.reconcile(client, ROOT, apply=True)
posts_after_first = len(client.posts)
report = reconcile.reconcile(client, ROOT, apply=True)
self.assertEqual(len(client.posts), posts_after_first)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertEqual(entry["status"], "tracked") self.assertEqual(entry["status"], "tracked")
self.assertEqual(len(self.forge.writes), 1)
self.assertEqual(len(self.forge.downloads), 4)
def test_partial_upload_and_wrong_ci_sha_block_once(self): def test_published_after_filter_skips_historical_releases(self):
self.forge.pipeline_sha = BASE client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
for _ in range(2): skipped = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-28T00:00:00Z")
entry, = self.run_scan(apply=True)["results"] self.assertFalse([item for item in skipped["results"] if item["repository"] == "cflmy/marqdo-cli"])
self.assertEqual(entry["status"], "blocked") kept = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-26T00:00:00Z")
self.assertIn("exact SHA", entry["error"]) self.assertTrue([item for item in kept["results"] if item["repository"] == "cflmy/marqdo-cli"])
self.assertEqual(len(self.forge.writes), 1)
self.forge.pipeline_sha = SOURCE
self.forge.release["assets"].pop(0)
entry, = self.run_scan()["results"]
self.assertEqual(entry["status"], "blocked")
self.assertIn("cover the published assets", entry["error"])
def test_validated_tracker_detects_an_updated_index_and_disappearing_release(self): def test_draft_releases_are_ignored(self):
self.run_scan(apply=True) client = FakeGitea(releases={"cflmy/marqdo-cli": [release(draft=True)]})
self.forge.evidence["assets"][0]["target"] = "x86_64-unknown-linux-gnu" report = reconcile.reconcile(client, ROOT, apply=False)
self.forge.refresh_assets() self.assertFalse([item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"])
entry, = self.run_scan(apply=True)["results"]
self.assertEqual(entry["status"], "blocked")
self.assertIn("index digest changed", entry["error"])
self.assertEqual(len(self.forge.issues), 1)
self.forge.releases = []
entry, = self.run_scan()["results"]
self.assertIn("absent", entry["error"])
def test_previously_blocked_tracker_records_verified_identity_in_bot_comment(self): def test_asset_size_mismatch_and_unsafe_name_are_rejected(self):
self.forge.pipeline_sha = BASE bad_size = FakeGitea(
self.run_scan(apply=True) releases={"cflmy/marqdo-cli": [release()]},
self.forge.pipeline_sha = SOURCE assets={"https://example.invalid/a.tar.gz": b"abcdef"},
entry, = self.run_scan(apply=True)["results"] )
self.assertEqual(entry["status"], "pending") report = reconcile.reconcile(bad_size, ROOT, apply=True)
self.assertIn(reconcile.identity_marker(entry), self.forge.writes[-1][1]["body"]) entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
entry, = self.run_scan(apply=True)["results"] self.assertTrue(entry["status"].startswith("asset-verify-failed"))
self.assertEqual(entry["status"], "tracked") self.assertFalse([path for path, _ in bad_size.posts if path.endswith("/issues")])
self.assertEqual(len(self.forge.writes), 2) unsafe = release()
unsafe["assets"][0]["name"] = "../escape.tar.gz"
def test_uses_normalized_publish_timestamp_and_skips_draft(self): client = FakeGitea(releases={"cflmy/marqdo-cli": [unsafe]}, assets={"https://example.invalid/a.tar.gz": b"abc"})
self.assertEqual(self.run_scan(cutoff="2026-11-27T00:00:01Z")["results"], []) report = reconcile.reconcile(client, ROOT, apply=True)
self.assertTrue(self.run_scan(cutoff="2026-11-27T00:00:00Z")["results"]) entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.forge.release["draft"] = True self.assertTrue(entry["status"].startswith("asset-verify-failed"))
self.assertEqual(self.run_scan()["results"], [])
def test_multiple_pages_and_partial_list_error(self):
self.forge.releases = [{"draft": True}] * reconcile.PAGE_SIZE + [self.forge.release]
report = self.run_scan()
self.assertTrue(report["scan_complete"])
self.assertEqual(len(report["results"]), 1)
self.assertIn((f"/repos/{REPO}/releases", 2), self.forge.pages)
self.forge.fail_page = 2
report = self.run_scan(apply=True)
self.assertFalse(report["scan_complete"])
self.assertEqual(report["scan_errors"][REPO], "API HTTP 503")
self.assertEqual(self.forge.writes, [])
def test_asset_location_name_and_digest_are_checked(self):
asset = self.forge.release["assets"][0]
asset["browser_download_url"] = "https://invalid.example/capture"
entry, = self.run_scan()["results"]
self.assertIn("non-canonical URL", entry["error"])
self.assertEqual(self.forge.downloads, [])
self.forge.refresh_assets()
self.forge.release["assets"][0]["name"] = "../escape.tar.gz"
entry, = self.run_scan()["results"]
self.assertIn("unsafe release asset name", entry["error"])
self.forge.refresh_assets()
self.forge.blobs[ASSET] = b"xxx"
entry, = self.run_scan()["results"]
self.assertIn("digest mismatch", entry["error"])
def test_apply_requires_current_protected_branch_and_non_admin_identity(self):
self.forge.protected = False
with self.assertRaisesRegex(reconcile.ReconcileError, "protected root"):
self.run_scan(apply=True)
self.forge.wrong_account = True
with self.assertRaisesRegex(reconcile.ReconcileError, "non-admin"):
self.run_scan(apply=True)
self.assertEqual(self.forge.writes, [])
if __name__ == "__main__": if __name__ == "__main__":