ci: shared runtime images, single-repo lanes and release reconciliation #21

Merged
cflmy merged 1 commits from ci/images-reconcile into main 2026-11-27 14:36:35 +08:00
22 changed files with 709 additions and 12 deletions
Showing only changes of commit 4cde0e256a - Show all commits

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
# Release discovery, asset verification and tracking-Issue reconciliation.
#
# Runs only from the protected default branch, on a manual trigger or the
# `release-reconcile` cron. The fast path (component release workflows) only
# asks this same workflow to run; correctness comes from this reconcile.
when:
event: [manual, cron]
branch: [main]
steps:
reconcile:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment:
MARQDO_GIT_TOKEN:
from_secret: gitea_token
commands:
- python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json
- cat reconcile-report.json
+12
View File
@@ -0,0 +1,12 @@
# Shared Rust-component CI image: shell base + one pinned Rust toolchain
# (rustfmt/clippy included) and a warm cargo cache. Published by immutable tag;
# repositories only run their own scripts/ci.sh.
FROM marqdo-ci-shell:3.0.0-rc.5
COPY rust-toolchain /opt/rust
COPY cargo-home /opt/cargo-home
ENV PATH=/opt/rust/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
CARGO_HOME=/opt/cargo-home \
RUSTUP_HOME=/opt/rustup-unused
RUN cargo --version && rustc --version && cargo fmt --version && cargo clippy --version
+24
View File
@@ -0,0 +1,24 @@
# Shared shell/source-component CI image. Published to the Gitea container
# registry and consumed by component repos by immutable version tag.
#
# It contains the published CLI/Bundle (one pinned release), common test tools
# and the supported glibc baseline (Ubuntu 24.04, glibc 2.39). Repositories do
# not need apt installs, Rust toolchains or archive downloads in their lanes.
FROM ubuntu:24.04
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates curl git python3 python3-venv build-essential ripgrep \
xz-utils unzip \
&& rm -rf /var/lib/apt/lists/*
COPY marqdo.tar.gz /tmp/marqdo.tar.gz
RUN mkdir -p /opt/marqdo \
&& tar -xzf /tmp/marqdo.tar.gz -C /opt/marqdo \
&& rm /tmp/marqdo.tar.gz
ENV MARQDO_BIN=/opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo \
MARQDO_STDLIB_DIR=/opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/stdlib \
MARQDO_CLI_VERSION=3.0.0-rc.5
RUN test -x "$MARQDO_BIN" && "$MARQDO_BIN" --version
+24
View File
@@ -0,0 +1,24 @@
# Shared Web-domain CI image: Playwright base (Node 20/Chromium, glibc 2.39),
# the published CLI/Bundle and the packaged preview web Tool. The domain runs
# its real browser acceptance without installing a Rust toolchain.
FROM mcr.microsoft.com/playwright:v1.49.0-noble
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl git python3 \
&& rm -rf /var/lib/apt/lists/*
COPY marqdo.tar.gz /tmp/marqdo.tar.gz
COPY marqdo-web-preview.tgz /tmp/marqdo-web-preview.tgz
RUN mkdir -p /opt/marqdo /opt/web-tool \
&& tar -xzf /tmp/marqdo.tar.gz -C /opt/marqdo \
&& tar -xzf /tmp/marqdo-web-preview.tgz -C /opt/web-tool --strip-components=1 \
&& rm /tmp/marqdo.tar.gz /tmp/marqdo-web-preview.tgz
ENV MARQDO_BIN=/opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo \
MARQDO_STDLIB_DIR=/opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/stdlib \
MARQDO_WEB_TOOL_JSON=/opt/web-tool/tool.json \
PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
MARQDO_CLI_VERSION=3.0.0-rc.5
RUN test -x "$MARQDO_BIN" && "$MARQDO_BIN" --version && test -f "$MARQDO_WEB_TOOL_JSON"
+1
View File
@@ -0,0 +1 @@
Shared Marqdo CI images are project infrastructure, not product releases.
+24
View File
@@ -0,0 +1,24 @@
# Shared Marqdo CI images
The ecosystem publishes exactly these reusable runtime images to the Gitea
container registry, per released CLI version:
| Image | Contents | Consumers |
| --- | --- | --- |
| `git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5` | Ubuntu 24.04 (glibc 2.39), git/curl/python3/build tools, released CLI + Bundle (`MARQDO_BIN`/`MARQDO_STDLIB_DIR` preset) | standard library, extension, conformance and reconcile lanes |
| `git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5` | shell image + pinned Rust 1.100 toolchain (rustfmt/clippy) + warm cargo cache | Design/Preview and Rust tool lanes |
| `git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5` (planned) | Playwright Chromium/Node + released CLI/Bundle + packaged preview web Tool | Web domain browser acceptance |
Rules:
- Tags are immutable and tied to one released CLI version; do not move a tag.
A new CLI release publishes new tags; consumers update in reviewed PRs.
- Images are public for anonymous pull; CI never needs registry push credentials.
- Component lanes contain only their own `scripts/*` entry command. No per-repo
image variance, apt installs, Rust toolchain downloads or CLI rebuilds.
- Core CLI keeps its specialized Rust/Windows-cross gates; the root ecosystem
candidate keeps its Playwright/rustup image because it must build consumers and
run Docker archive checks. These two exceptions are documented in the
repository conventions, not copied per component.
- The images are CI infrastructure, not product releases; their provenance is
recorded here and in `docs/evidence/`.
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Build and optionally publish the shared Marqdo CI images.
#
# Usage:
# MARQDO_GIT_TOKEN=... ci/images/build.sh [--push]
#
# The images are immutable per released CLI version. They are the only shared
# CI runtime images: shell/source components use `marqdo-ci-shell`, Rust
# components use `marqdo-ci-rust`, the Web domain uses `marqdo-ci-web`.
# Core CLI/root keep their own specialized gates and images.
set -euo pipefail
if ! command -v cargo >/dev/null 2>&1; then
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
fi
root="$(cd "$(dirname "$0")/../.." && pwd)"
toolchain="${MARQDO_CI_RUST_TOOLCHAIN:-$(rustc --print sysroot)}"
cargo_cache="${MARQDO_CI_CARGO_CACHE:-${CARGO_HOME:-$HOME/.cargo}}"
preview_checkout="${MARQDO_CI_PREVIEW_CHECKOUT:-$root/extensions/web/preview}"
version="${MARQDO_CLI_VERSION:-3.0.0-rc.5}"
registry="${MARQDO_CI_REGISTRY:-git.cflmy.cn/cflmy}"
commit="${MARQDO_CI_IMAGE_COMMIT:-$(git -C "$root" rev-parse --short HEAD)}"
context="$root/.build/ci-images/$commit-$version"
push=0
[[ "${1:-}" == "--push" ]] && push=1
archive_url="https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v${version}/marqdo-${version}-x86_64-unknown-linux-gnu.tar.gz"
archive_sha="fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b"
rm -rf "$context"; mkdir -p "$context"
echo "==> download published CLI/Bundle"
curl -fsSL --retry 3 -o "$context/marqdo.tar.gz" "$archive_url"
echo "$archive_sha $context/marqdo.tar.gz" | sha256sum -c -
echo "==> package the preview web Tool from the pinned preview checkout"
(
cd "$preview_checkout"
scripts/package.sh >/dev/null
)
tar -czf "$context/marqdo-web-preview.tgz" -C "$preview_checkout/dist" marqdo-web-preview
echo "==> stage the pinned Rust toolchain and cargo cache"
cp -a "$toolchain" "$context/rust-toolchain"
cp -a "$cargo_cache" "$context/cargo-home"
cp "$root/ci/images/LICENSE" "$context/marqdo-ci-shell-license" 2>/dev/null || echo "internal CI image" > "$context/marqdo-ci-shell-license"
cp "$root/ci/images/Dockerfile.shell" "$root/ci/images/Dockerfile.rust" "$root/ci/images/Dockerfile.web" "$context/"
build() {
local tag="$1" file="$2"
echo "==> docker build $tag"
DOCKER_CONFIG="${DOCKER_CONFIG:-$root/.build/docker-config}" \
docker build -f "$context/$file" -t "$registry/$tag" "$context"
}
build "marqdo-ci-shell:$version" Dockerfile.shell
docker tag "$registry/marqdo-ci-shell:$version" "marqdo-ci-shell:$version"
build "marqdo-ci-rust:$version" Dockerfile.rust
build "marqdo-ci-web:$version" Dockerfile.web
if [[ "$push" == 1 ]]; then
: "${MARQDO_GIT_TOKEN:?set MARQDO_GIT_TOKEN to publish images}"
export DOCKER_CONFIG="${DOCKER_CONFIG:-$root/.build/docker-config}"
echo "$MARQDO_GIT_TOKEN" | docker login "${registry%%/*}" -u "${MARQDO_GIT_USERNAME:-cflmy}" --password-stdin
docker push "$registry/marqdo-ci-shell:$version"
docker push "$registry/marqdo-ci-rust:$version"
docker push "$registry/marqdo-ci-web:$version"
echo "published immutable CI images for $version"
fi
@@ -0,0 +1,46 @@
# 共享 CI 镜像、单仓 CI 与发布对账(2026-11-27)
来源:[marqdo#10](https://git.cflmy.cn/cflmy/marqdo/issues/10)。本文件记录本轮 CI/CD 基础设施实现与可验证结果。
## 共享运行时镜像(Gitea Container Registry)
组件不再各自安装工具链或重复下载/编译 CLI。根 `ci/images/` 定义并发布不可变镜像:
| 镜像 | digest | 内容 | 消费方 |
| --- | --- | --- | --- |
| `git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5` | `sha256:8184439a201d...` | Ubuntu 24.04/glibc 2.39、git/curl/python3/build 工具、已发布 CLI+Bundle(`MARQDO_BIN`/`MARQDO_STDLIB_DIR` 预置) | stdlib、extension、conformance、reconcile |
| `git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5` | `sha256:73481a353391...` | shell 镜像 + Rust 1.100(rustfmt/clippy)+ 预热 cargo cache | Design/Preview 与 Rust Tool |
| `git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5` | 未发布(Playwright 基础镜像拉取超时) | 计划:Playwright/Node + CLI/Bundle + 打包 preview web Tool | Web 领域浏览器验收 |
- 镜像通过 `ci/images/build.sh [--push]` 从**已发布 rc.5 CLI 归档**(sha256 固定)与固定预览包构建;标签不可变,按 CLI 版本发布;公开匿名拉取,CI 不需要 registry push 凭据。
- 单仓工作流因此只剩本仓入口命令;例如 stdlib/extension/conformance 为:
```yaml
steps:
test:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
commands: [sh scripts/test.sh]
```
Rust 组件为 `marqdo-ci-rust` + `scripts/ci.sh`。CLI/根仍保留各自专用镜像与门禁(CLI Windows 交叉、根 Playwright/Docker 冷安装),属有限例外。
## Woodpecker 接入
- 19 个仓库已在 Woodpecker 激活(std ×6、ext ×3、conformance、Design/Preview、tool ×4、ext-web domain、根、CLI)。
- 已写入并合并单仓 `.woodpecker/ci.yml`;std/conformance/ext 的 push/pull_request 镜像 lane 已实际 **success**(例如 conformance 使用 shell 镜像通过)。
- `.woodpecker/reconcile.yml`:仅保护默认分支、manual/cron;`release-reconcile` cron `@every 30m` 已创建;根 repo secret `gitea_token` 已设置(不记录值)。
- 快速通知路径:组件发布成功后由 release 工作流请求根 reconcile;丢失通知由 cron 补偿。两者共用 `scripts/reconcile-releases.py`,不新增接收服务或第二套协议。
## 发布对账
`scripts/reconcile-releases.py`:
- 从既有 catalog/gitmodules 派生受管仓库,扫描 Gitea release(含 prerelease,排除 draft),验证 tag/资产名、大小与下载字节 SHA-256;
- 在根仓库创建带 `release-tracking` 标签与稳定 marker 的追踪 Issue(幂等;历史 release 可用 `--published-after` 基线过滤);
- 只创建/更新追踪 Issue,不改 gitlink、不发布、不执行 release body/URL;失败资产验证会报告并返回非零;
- 6 个单元测试覆盖 dry-run、资产验证、幂等、draft 过滤、时间过滤、坏资产/路径。
## 未完成 / 限制
- `marqdo-ci-web` 未发布:本地拉取 Playwright 基础镜像超时;Web 领域 CI lane 与浏览器验收仍待该镜像或等价的 runner 缓存方案。当前 Web 组件已有 Design/Preview 的 Rust image lane,domain 只有入口脚本。
- Tool(view/knowledge/lint/prove)仍保留既有工作流/镜像,尚未全部迁到共享镜像;需在验证后统一。
- 组件 release 发布工作流(source archive/tool bundle 上传 + 快速通知)尚未全部落地;当前 CLI rc.5 已发布,reconcile 可追踪新发布。
- registry 镜像 digest/扫描策略、runner 拉取缓存与多架构未验证;CI 账号最小权限仍沿用现有项目 token(M0 记录限制)。
+1 -1
View File
@@ -32,7 +32,7 @@ ROOT = Path(__file__).resolve().parents[1]
NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"}
ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
ROOT_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts"}
ROOT_DIRS = {".gitea", ".woodpecker", "ci", "docs", "examples", "scripts"}
CATEGORY_READMES = {"stdlib/README.md", "extensions/README.md"}
RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"}
DOMAIN_RELEASE = {"none", "base"}
+350
View File
@@ -0,0 +1,350 @@
#!/usr/bin/env python3
"""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
import argparse
import hashlib
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"
MAX_ASSET_BYTES = 256 * 1024 * 1024
MAX_ASSETS = 128
class ReconcileError(Exception):
pass
class Gitea:
def __init__(self, token: str, base: str = API_BASE):
self.token = token
self.base = base.rstrip("/")
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):
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 managed_repositories(root: Path) -> dict[str, str]:
"""catalog id/path -> owner/name for direct components and domain children."""
catalog = tomllib.loads((root / "components.toml").read_text())
remotes = submodule_repositories(root)
managed: dict[str, str] = {}
for component in catalog.get("component", []):
path = component.get("path", "")
if path in remotes:
managed[f"{component.get('id')}@{path}"] = remotes[path]
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', '')}"
if child_path in domain_remotes:
managed[f"{child.get('id')}@{child_path}"] = domain_remotes[child_path]
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})
return verified
def release_marker(repository: str, tag: str) -> str:
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
def existing_issues(client: Gitea, label: str = LABEL) -> list[dict]:
issues = client.get(
f"/repos/{ROOT_REPOSITORY}/issues?state=all&limit=100&type=issues&labels={label}"
)
return issues if isinstance(issues, list) else []
def ensure_label(client: Gitea) -> int:
labels = client.get(f"/repos/{ROOT_REPOSITORY}/labels?limit=100")
for item in labels or []:
if item.get("name") == LABEL:
return int(item["id"])
created = client.post(
f"/repos/{ROOT_REPOSITORY}/labels",
{"name": LABEL, "color": "#bfd4f2", "description": "Release tracking created by reconcile"},
)
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 reconcile(
client: Gitea,
root: Path = PROJECT_ROOT,
apply: bool = False,
report_out: Path | None = None,
cutoff: str | None = None,
) -> 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) 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"})
continue
if not apply:
verified = []
status = "pending"
else:
try:
verified = verify_assets(client, {"assets": entry["assets"]})
except ReconcileError as 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 = {
"schema": "marqdo.release-reconcile.v1",
"schema_version": 1,
"generated_at": __import__("datetime").datetime.now(
__import__("datetime").timezone.utc
).isoformat(),
"apply": apply,
"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:
report_out.parent.mkdir(parents=True, exist_ok=True)
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
return report
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.add_argument("--apply", action="store_true", help="create tracking Issues")
parser.add_argument("--report-out", default=None)
parser.add_argument("--root", default=str(PROJECT_ROOT))
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,
)
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"))
for item in report["results"]
)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,132 @@
"""Release reconcile discovery/idempotency tests (issue #10 §6/§7)."""
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location(
"reconcile_releases", ROOT / "scripts" / "reconcile-releases.py"
)
reconcile = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(reconcile)
class FakeGitea:
def __init__(self, releases=None, assets=None, issues=None):
self.releases = releases or {}
self.asset_bytes = assets or {}
self.issues = list(issues or [])
self.posts = []
self.label_created = False
def get(self, path):
if path.startswith("/repos/") and path.endswith("/labels?limit=100"):
return [{"id": 5, "name": reconcile.LABEL}] if self.label_created else []
if "/issues?" in path:
return self.issues
for repository, releases in self.releases.items():
if path == f"/repos/{repository}/releases?limit=50":
return releases
return []
def post(self, path, data):
self.posts.append((path, data))
if path.endswith("/labels"):
self.label_created = True
return {"id": 5, "name": data["name"]}
if path.endswith("/issues"):
issue = {"number": 100 + len(self.issues), "body": data["body"], "title": data["title"]}
self.issues.append(issue)
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):
def test_dry_run_discovers_releases_without_writing(self):
client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
report = reconcile.reconcile(client, ROOT, apply=False)
self.assertFalse(client.posts)
self.assertGreaterEqual(report["releases"], 1)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertEqual(entry["status"], "pending")
self.assertEqual(entry["tag"], "v0.0.1")
def test_apply_verifies_assets_and_creates_marked_issue(self):
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")
def test_second_scan_is_idempotent(self):
client = FakeGitea(
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abc"},
)
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")
def test_published_after_filter_skips_historical_releases(self):
client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
skipped = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-28T00:00:00Z")
self.assertFalse([item for item in skipped["results"] if item["repository"] == "cflmy/marqdo-cli"])
kept = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-26T00:00:00Z")
self.assertTrue([item for item in kept["results"] if item["repository"] == "cflmy/marqdo-cli"])
def test_draft_releases_are_ignored(self):
client = FakeGitea(releases={"cflmy/marqdo-cli": [release(draft=True)]})
report = reconcile.reconcile(client, ROOT, apply=False)
self.assertFalse([item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"])
def test_asset_size_mismatch_and_unsafe_name_are_rejected(self):
bad_size = FakeGitea(
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abcdef"},
)
report = reconcile.reconcile(bad_size, ROOT, apply=True)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
self.assertFalse([path for path, _ in bad_size.posts if path.endswith("/issues")])
unsafe = release()
unsafe["assets"][0]["name"] = "../escape.tar.gz"
client = FakeGitea(releases={"cflmy/marqdo-cli": [unsafe]}, assets={"https://example.invalid/a.tar.gz": b"abc"})
report = reconcile.reconcile(client, ROOT, apply=True)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
if __name__ == "__main__":
unittest.main()