ci: complete component release propagation for issue #10
ci/woodpecker/push/eco Pipeline is pending
ci/woodpecker/pr/eco Pipeline is pending

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>
This commit is contained in:
cflmyandCursor committed 2026-11-27 19:30:18 +08:00
1 parent 068f91cd31
commit a61f3442bc
39 files changed
+2130 -111

No files matched your search

+3 -2
View File
@@ -12,7 +12,8 @@ steps:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment:
MARQDO_GIT_TOKEN:
from_secret: gitea_token
from_secret: gitea_reconcile_token
commands:
- 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 --freshness-out freshness.json
- cat reconcile-report.json
- cat freshness.md
+30
View File
@@ -22,3 +22,33 @@ Rules:
repository conventions, not copied per component.
- The images are CI infrastructure, not product releases; their provenance is
recorded here and in `docs/evidence/`.
## Platforms
- Default / current consumer matrix: `linux/amd64` only.
- `ci/images/build.sh` accepts `MARQDO_CI_PLATFORMS` (buildx). Adding
`linux/arm64` requires a verified aarch64 CLI archive via
`MARQDO_CLI_ARCHIVE_ARM64` + `MARQDO_CLI_ARCHIVE_ARM64_SHA256`. Without that
input, arm64 image publication is refused (no fake multi-arch).
- CI workflow pins remain the immutable version tag; runners without arm64 are
not claimed as PASS for arm64.
## Scanning
- `ci/images/scan.sh` records registry digests/platforms, optional Trivy CVE
reports, and a pin check that rejects floating tags in Woodpecker workflows.
## Runner pull-through cache
Woodpecker agents must treat `git.cflmy.cn/cflmy/marqdo-ci-*` as the only CI
runtime image source (no Docker Hub rebuilds of the same toolchain). Required
agent configuration:
1. Persist the engine image store across jobs (Docker/`containerd` data root on
durable disk, not ephemeral scratch).
2. Prefer the local Gitea Container Registry; do not introduce a second public
mirror that can serve different digests for the same tag.
3. Warm the three pinned tags after each CI image publish so the first job after
publish pays the pull cost once.
4. Cache hit is never evidence of a test PASS; workflows still run the component
entry command against the pinned digest/tag.
+46 -11
View File
@@ -4,6 +4,10 @@
# Usage:
# MARQDO_GIT_TOKEN=... ci/images/build.sh [--push]
#
# Platforms (default linux/amd64):
# MARQDO_CI_PLATFORMS=linux/amd64
# MARQDO_CI_PLATFORMS=linux/amd64,linux/arm64 # requires arm64 CLI archive
#
# 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`.
@@ -19,6 +23,7 @@ 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)}"
platforms="${MARQDO_CI_PLATFORMS:-linux/amd64}"
context="$root/.build/ci-images/$commit-$version"
push=0
[[ "${1:-}" == "--push" ]] && push=1
@@ -26,11 +31,22 @@ push=0
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"
if [[ "$platforms" == *"arm64"* ]]; then
: "${MARQDO_CLI_ARCHIVE_ARM64:?arm64 image builds require MARQDO_CLI_ARCHIVE_ARM64 pointing at a verified aarch64 CLI archive}"
: "${MARQDO_CLI_ARCHIVE_ARM64_SHA256:?set MARQDO_CLI_ARCHIVE_ARM64_SHA256}"
fi
rm -rf "$context"; mkdir -p "$context"
echo "==> download published CLI/Bundle"
echo "==> download published CLI/Bundle (amd64 product archive)"
curl -fsSL --retry 3 -o "$context/marqdo.tar.gz" "$archive_url"
echo "$archive_sha $context/marqdo.tar.gz" | sha256sum -c -
if [[ "$platforms" == *"arm64"* ]]; then
echo "==> stage verified arm64 CLI archive"
cp "$MARQDO_CLI_ARCHIVE_ARM64" "$context/marqdo-arm64.tar.gz"
echo "$MARQDO_CLI_ARCHIVE_ARM64_SHA256 $context/marqdo-arm64.tar.gz" | sha256sum -c -
fi
echo "==> package the preview web Tool from the pinned preview checkout"
(
cd "$preview_checkout"
@@ -46,21 +62,40 @@ cp "$root/ci/images/Dockerfile.shell" "$root/ci/images/Dockerfile.rust" "$root/c
build() {
local tag="$1" file="$2"
echo "==> docker build $tag"
echo "==> buildx build $tag platforms=$platforms"
local args=(
buildx build
--platform "$platforms"
-f "$context/$file"
-t "$registry/$tag"
)
if [[ "$push" == 1 ]]; then
args+=(--push)
else
# Single-platform local load; multi-platform requires --push or a custom builder output.
if [[ "$platforms" == *","* ]]; then
echo "multi-platform local build requires --push (registry output)" >&2
exit 2
fi
args+=(--load)
fi
DOCKER_CONFIG="${DOCKER_CONFIG:-$root/.build/docker-config}" \
docker build -f "$context/$file" -t "$registry/$tag" "$context"
docker "${args[@]}" "$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
build "marqdo-ci-shell:$version" Dockerfile.shell
if [[ "$platforms" != *","* ]]; then
docker tag "$registry/marqdo-ci-shell:$version" "marqdo-ci-shell:$version"
fi
build "marqdo-ci-rust:$version" Dockerfile.rust
build "marqdo-ci-web:$version" Dockerfile.web
if [[ "$push" == 1 ]]; then
echo "published immutable CI images for $version platforms=$platforms"
fi
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Scan published Marqdo CI images by digest.
#
# Records:
# - registry digest / platform manifests (buildx imagetools)
# - optional Trivy CVE report when `trivy` or `$TRIVY_IMAGE` is available
# - a fail-closed provenance check that consumers pin immutable tags
#
# Usage:
# ci/images/scan.sh [--out docs/evidence/ci-image-scan]
set -euo pipefail
root="$(cd "$(dirname "$0")/../.." && pwd)"
registry="${MARQDO_CI_REGISTRY:-git.cflmy.cn/cflmy}"
version="${MARQDO_CLI_VERSION:-3.0.0-rc.5}"
out="${1:-$root/docs/evidence/ci-image-scan-$version}"
if [[ "${1:-}" == "--out" ]]; then
out="${2:?}"
fi
mkdir -p "$out"
images=(
"marqdo-ci-shell:$version"
"marqdo-ci-rust:$version"
"marqdo-ci-web:$version"
)
echo "==> inspect manifests"
: >"$out/digests.txt"
for image in "${images[@]}"; do
ref="$registry/$image"
echo "--- $ref" | tee -a "$out/digests.txt"
if ! docker buildx imagetools inspect "$ref" >"$out/${image//[:\/]/_}.inspect.txt" 2>"$out/${image//[:\/]/_}.inspect.err"; then
echo "UNVERIFIED: cannot inspect $ref" | tee -a "$out/digests.txt"
continue
fi
digest=$(awk '/^Digest:/{print $2; exit}' "$out/${image//[:\/]/_}.inspect.txt")
platforms=$(awk '/Platform:/{print $2}' "$out/${image//[:\/]/_}.inspect.txt" | paste -sd, -)
echo "$ref digest=$digest platforms=$platforms" | tee -a "$out/digests.txt"
done
echo "==> optional Trivy scan"
trivy_bin="${TRIVY_BIN:-}"
if [[ -z "$trivy_bin" && -x "$root/.build/tools/trivy" ]]; then
trivy_bin="$root/.build/tools/trivy"
fi
if [[ -n "$trivy_bin" ]]; then
for image in "${images[@]}"; do
ref="$registry/$image"
"$trivy_bin" image --quiet --format json --output "$out/${image//[:\/]/_}.trivy.json" "$ref" || \
echo "trivy failed for $ref" >"$out/${image//[:\/]/_}.trivy.err"
done
elif [[ -n "${TRIVY_IMAGE:-}" ]]; then
for image in "${images[@]}"; do
ref="$registry/$image"
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
"$TRIVY_IMAGE" image --quiet --format json "$ref" \
>"$out/${image//[:\/]/_}.trivy.json" || \
echo "trivy container failed for $ref" >"$out/${image//[:\/]/_}.trivy.err"
done
else
echo "Trivy binary/image unavailable; CVE scan marked UNVERIFIED" | tee "$out/trivy-UNVERIFIED.txt"
fi
echo "==> provenance / pin check"
ROOT="$root" OUT="$out" VERSION="$version" python3 - <<'PY'
import os, pathlib, re, sys
root = pathlib.Path(os.environ["ROOT"])
out = pathlib.Path(os.environ["OUT"])
version = os.environ["VERSION"]
pattern = re.compile(r"git\.cflmy\.cn/cflmy/marqdo-ci-(shell|rust|web):([^\s\"']+)")
bad = []
skip = {".build", "node_modules", ".git", "cargo-home", ".cargo"}
for path in list(root.glob("**/.woodpecker/*.yml")) + list(root.glob("**/.woodpecker/*.yaml")):
if any(part in skip for part in path.parts):
continue
text = path.read_text(encoding="utf-8", errors="replace")
for match in pattern.finditer(text):
tag = match.group(2)
if tag in ("latest", "main", "master") or tag.endswith("-latest"):
bad.append(f"{path}: floating tag {tag}")
elif tag != version and not tag.startswith(version):
bad.append(f"{path}: unexpected tag {tag} (expected {version})")
report = out / "pin-check.txt"
if bad:
report.write_text("FAIL\n" + "\n".join(bad) + "\n", encoding="utf-8")
print("pin check failed; see", report, file=sys.stderr)
raise SystemExit(1)
report.write_text(f"PASS: workflows pin marqdo-ci-*:{version}\n", encoding="utf-8")
print(report.read_text().strip())
PY
cat >"$out/SUMMARY.md" <<EOF
# CI image scan ($version)
- Registry: \`$registry\`
- Digests: see \`digests.txt\`
- Pin check: see \`pin-check.txt\`
- CVE: Trivy output when available; otherwise \`trivy-UNVERIFIED.txt\`
- Platforms: current production consumers use \`linux/amd64\`. Multi-arch
builds are produced by \`ci/images/build.sh\` when \`MARQDO_CI_PLATFORMS\`
includes \`linux/arm64\`; arm64 CI execution remains UNVERIFIED until an
arm64 runner exists.
EOF
echo "scan complete: $out"
@@ -0,0 +1,64 @@
# Issue #10 remaining delivery evidence(2026-11-27)
来源:[marqdo#10](https://git.cflmy.cn/cflmy/marqdo/issues/10)。本文件记录本轮补齐的组件发行事务、最小权限、镜像运营与 M3 传播演练。
## 平台版本(M0)
| 组件 | 版本 |
| --- | --- |
| Gitea | 28.4.1 |
| Woodpecker | 3.20.1 |
## A. 共享发行库与组件 publish
根权威实现:`scripts/component-release/`(`package_source.py` / `write_evidence.py` / `publish_gitea.py` / `notify_root.py`)。
- 单元测试:`tests/integration/test_component_release.py` **16/16 PASS**(含 reconcile 扩展后合计)。
- 各 active/已接入仓 vendored `scripts/release/*`,新增 `.woodpecker/publish.yml`(tag/manual + `gitea_publish_token`),`release.yml` 仅 notify(`woodpecker_notify_token`)。
- knowledge 旧覆盖式 `publish-gitea.py` 改为委托不可变 publisher(禁止覆盖已公开资产)。
## B. 非生产端到端演练(std-text)
| 步骤 | 结果 |
| --- | --- |
| tag | `v0.0.0-ci10.1` @ `5838ba028ea2dcf06b1713aec2d1ec91babe1b64` |
| publish | draft→upload→undraft **published**;资产含 source tar.gz、`.sha256`、`release-evidence.json` |
| 幂等重试 | 同身份第二次 **idempotent**(R03) |
| 快速通知 | Woodpecker pipeline **#90** created |
| reconcile | 根追踪 Issue [#30](https://git.cflmy.cn/cflmy/marqdo/issues/30);证据 SHA `c88b3634...`;二次扫描 **tracked**(R09) |
| 消费者任务 | 根 Upstream Issue [#31](https://git.cflmy.cn/cflmy/marqdo/issues/31)(stdlib 无 catalog requires 边时由根 Bundle 消费);二次派发 **tracked** |
| freshness | `freshness.json` / `.md` 派生视图已生成 |
Release URL:https://git.cflmy.cn/cflmy/marqdo-std-text/releases/tag/v0.0.0-ci10.1
## C. 最小权限(E08)
| 身份 | 实测 |
| --- | --- |
| `marqdo-publisher` 建根 Issue | HTTP **403** |
| `marqdo-reconcile` 建 std-text release | HTTP **403** |
| `marqdo-reconcile` 读 releases / 建根 Issue | HTTP **200/201** |
| `marqdo-publisher` draft std-text release | HTTP **201**(演练后删除) |
Woodpecker secrets:根 `gitea_reconcile_token`(manual/cron);组件 `gitea_publish_token`(tag/manual)、`woodpecker_notify_token`(release)。
Woodpecker 专用低权用户需 OAuth 登录后签发(当前 notify secret 事件已限制为 release;专用 WP 用户记为平台退出条件)。
## D. 镜像扫描 / 多架构 / runner 缓存
- `ci/images/scan.sh`:digest 记录 + 工作流 pin 检查 **PASS**;证据目录 `docs/evidence/ci-image-scan-3.0.0-rc.5/`。
- Trivy CVE:**UNVERIFIED**(本环境无法拉取 Trivy 发行包/镜像);退出条件:安装固定版 Trivy 后重跑 `scan.sh`。
- `build.sh` 支持 `MARQDO_CI_PLATFORMS`;`linux/arm64` 必须提供已验证 aarch64 CLI 归档,否则拒绝(不伪造多架构)。当前消费矩阵仍为 `linux/amd64`。
- Runner pull-through:见 `ci/images/README.md`(唯一拉取 Gitea registry、持久 image store、发布后预热;cache hit ≠ PASS)。
## E. Reconcile M3 增强
- 校验可选 `release-evidence.json`(字段/摘要/集合)。
- freshness 报告;stdlib/base 派发根 Upstream 任务;`--plan` 零写。
- 根 `.woodpecker/reconcile.yml` 使用 `gitea_reconcile_token` 并输出 freshness。
## 明确限制(不伪造成功)
1. Trivy CVE 扫描 UNVERIFIED(见上)。
2. arm64 镜像/CI 执行在无 aarch64 CLI 归档与 arm64 runner 前 UNVERIFIED。
3. Woodpecker notify 专用用户待 OAuth 签发;secret 已按事件隔离。
4. 自动依赖锁 PR / 领域→根自动候选 PR 的完整 E14 业务链以本演练的追踪 Issue + Upstream 任务为入口,后续按责任仓审查后推进(不自动合并)。
@@ -0,0 +1,10 @@
# CI image scan (3.0.0-rc.5)
- Registry: `git.cflmy.cn/cflmy`
- Digests: see `digests.txt`
- Pin check: see `pin-check.txt`
- CVE: Trivy output when available; otherwise `trivy-UNVERIFIED.txt`
- Platforms: current production consumers use `linux/amd64`. Multi-arch
builds are produced by `ci/images/build.sh` when `MARQDO_CI_PLATFORMS`
includes `linux/arm64`; arm64 CI execution remains UNVERIFIED until an
arm64 runner exists.
@@ -0,0 +1,6 @@
--- git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5 digest=sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1 platforms=linux/amd64,unknown/unknown
--- git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5 digest=sha256:73481a35339157b1a3f3b23076517e96e302fbb5158e6ffcb1582acf22c6af94 platforms=linux/amd64,unknown/unknown
--- git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5
git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5 digest=sha256:0cccda995d7786496de8806b69b0b2761861c3b6b3983a8cc9be80ba3f3db1a1 platforms=linux/amd64,unknown/unknown
@@ -0,0 +1,15 @@
Name: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:73481a35339157b1a3f3b23076517e96e302fbb5158e6ffcb1582acf22c6af94
Manifests:
Name: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5@sha256:ff1851a43b232618485b4c7b94ce1c3d950f60ad73a46372527b49dc60b00b38
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: linux/amd64
Name: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5@sha256:edb8738c3ef02c73688e1cf5de3b4c93d6eed4c46a7d675eced46a28eadc98c5
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: unknown/unknown
Annotations:
vnd.docker.reference.digest: sha256:ff1851a43b232618485b4c7b94ce1c3d950f60ad73a46372527b49dc60b00b38
vnd.docker.reference.type: attestation-manifest
@@ -0,0 +1,15 @@
Name: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1
Manifests:
Name: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:435f4e3ebe42f83ecbd741f3e064cc294d34b493fbad43a595d2042247aab69a
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: linux/amd64
Name: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:9b1196b5e16eb65710bf2c76d183fb8dd0521643c0478f983c7e2d63c1c36aa4
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: unknown/unknown
Annotations:
vnd.docker.reference.digest: sha256:435f4e3ebe42f83ecbd741f3e064cc294d34b493fbad43a595d2042247aab69a
vnd.docker.reference.type: attestation-manifest
@@ -0,0 +1,15 @@
Name: git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:0cccda995d7786496de8806b69b0b2761861c3b6b3983a8cc9be80ba3f3db1a1
Manifests:
Name: git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5@sha256:044e4de80d578d319bbc5e77d73e88706f08937a77fbb271b8daf578e43f60b5
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: linux/amd64
Name: git.cflmy.cn/cflmy/marqdo-ci-web:3.0.0-rc.5@sha256:df457c713909267bcb755ad9ac96f7b749a0e31bc5ded813c7c35eaedda67736
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: unknown/unknown
Annotations:
vnd.docker.reference.digest: sha256:044e4de80d578d319bbc5e77d73e88706f08937a77fbb271b8daf578e43f60b5
vnd.docker.reference.type: attestation-manifest
@@ -0,0 +1 @@
PASS: workflows pin marqdo-ci-*:3.0.0-rc.5
@@ -0,0 +1 @@
Trivy binary/image unavailable; CVE scan marked UNVERIFIED
+21
View File
@@ -0,0 +1,21 @@
# Component release helpers (authoritative copy)
This directory is the **single authoritative implementation** of the thin
component release helpers required by [marqdo#10](https://git.cflmy.cn/cflmy/marqdo/issues/10)
§4 (immutable release identity) and §6 (notify after publish).
Active component repositories vendor an identical copy under `scripts/release/`
and run only that local copy. CI must never download these scripts from the
parent repository at runtime. When the helpers change, update this directory
first, re-run the root unit tests, then copy the same bytes into each consumer
and record the content hashes in that consumer's `scripts/release/README.md`.
| Module | Role |
| --- | --- |
| `package_source.py` | Deterministic source archive + `.sha256` from an allowlist |
| `write_evidence.py` | Emit `release-evidence.json` (external index; no self-hash) |
| `publish_gitea.py` | Draft → upload assets (index last) → undraft; never overwrite public assets |
| `notify_root.py` | Bounded retry trigger of the root `reconcile` Woodpecker workflow |
Secrets stay out of package/evidence scripts. Publish workflows hold
`gitea_publish_token`; notify workflows hold `woodpecker_notify_token`.
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Copy the authoritative component-release helpers into a consumer repository.
# Usage: scripts/component-release/install-vendor.sh <component-repo-root>
set -euo pipefail
src="$(cd "$(dirname "$0")" && pwd)"
dst_root="${1:?component repository root required}"
dst="$dst_root/scripts/release"
mkdir -p "$dst"
for name in package_source.py write_evidence.py publish_gitea.py notify_root.py; do
cp "$src/$name" "$dst/$name"
chmod +x "$dst/$name"
done
{
echo "# Vendored from marqdo scripts/component-release"
echo "#"
echo "# Do not edit in place across repositories. Change the root copy, re-test,"
echo "# then re-run install-vendor.sh and record the hashes below."
echo "#"
for name in package_source.py write_evidence.py publish_gitea.py notify_root.py; do
hash="$(sha256sum "$dst/$name" | awk '{print $1}')"
echo "# $name sha256=$hash"
done
} >"$dst/README.md"
echo "vendored into $dst"
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Ask the root Marqdo reconcile workflow to scan after a release.
The payload is only a hint. Correctness comes from the root
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
Lost notifications are recovered by the root `release-reconcile` cron.
"""
from __future__ import annotations
import argparse
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
class NotifyError(Exception):
pass
def token() -> str:
value = (
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
or os.environ.get("WOODPECKER_TOKEN")
or os.environ.get("woodpecker_token")
)
if not value:
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
return value
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
payload = json.dumps(body).encode()
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
request = urllib.request.Request(
url,
data=payload,
method="POST",
headers={
"Authorization": f"Bearer {token_value}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
raw = response.read()
decoded = json.loads(raw) if raw else {}
return {
"status": "triggered",
"http_status": response.status,
"pipeline_id": decoded.get("id"),
"pipeline_number": decoded.get("number"),
"attempt": attempt,
}
except urllib.error.HTTPError as error:
# Auth/permission failures must not retry forever.
if error.code in (401, 403, 404):
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
last_error = error
except urllib.error.URLError as error:
last_error = error
if attempt < attempts:
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
time.sleep(delay)
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
parser.add_argument("--branch", default="main")
parser.add_argument("--workflow", default="reconcile")
parser.add_argument("--hint-component", default="")
parser.add_argument("--hint-tag", default="")
parser.add_argument("--attempts", type=int, default=3)
args = parser.parse_args(argv)
body = {"branch": args.branch, "workflow": args.workflow}
# Hints are informational only; the root reconcile never trusts them as commands.
if args.hint_component or args.hint_tag:
body["variables"] = {
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
}
try:
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
except NotifyError as error:
print(f"notify_root: FAIL: {error}", file=sys.stderr)
return 1
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Build a deterministic source archive for a Marqdo component release.
Only allowlisted relative paths are included. The archive uses fixed mtime,
uid/gid, and sorted member names so the same tree always yields the same
sha256. Output is written under an isolated directory (default: dist/).
"""
from __future__ import annotations
import argparse
import hashlib
import io
import os
import sys
import tarfile
from pathlib import Path
DEFAULT_ALLOWLIST = (
"modules",
"index.mq.md",
"marqdo.yaml",
"LICENSE",
"README.md",
)
FIXED_MTIME = 0
EVIDENCE_NAME = "release-evidence.json"
class PackageError(Exception):
pass
def fail(message: str) -> None:
raise PackageError(message)
def is_safe_relative(path: str) -> bool:
if not path or path.startswith("/") or path.startswith("\\"):
return False
parts = Path(path).parts
return not any(part in (".", "..") for part in parts)
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
selected: dict[str, Path] = {}
for entry in allowlist:
if not is_safe_relative(entry):
fail(f"unsafe allowlist entry: {entry!r}")
target = root / entry
if not target.exists():
continue
if target.is_file():
selected[entry.replace("\\", "/")] = target
continue
if not target.is_dir():
fail(f"allowlist entry is not a regular file or directory: {entry}")
for path in sorted(target.rglob("*")):
if not path.is_file():
continue
if path.is_symlink():
fail(f"symlinks are not publishable: {path.relative_to(root)}")
relative = path.relative_to(root).as_posix()
if not is_safe_relative(relative):
fail(f"unsafe relative path: {relative}")
selected[relative] = path
if not selected:
fail("allowlist matched no files")
return sorted(selected.items(), key=lambda item: item[0])
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
for relative, path in files:
data = path.read_bytes()
info = tarfile.TarInfo(name=relative)
info.size = len(data)
info.mtime = FIXED_MTIME
info.uid = 0
info.gid = 0
info.uname = ""
info.gname = ""
info.mode = 0o644
archive.addfile(info, io.BytesIO(data))
return buffer.getvalue()
def write_outputs(
root: Path,
out_dir: Path,
component_id: str,
version: str,
allowlist: list[str],
) -> dict:
files = collect_files(root, allowlist)
payload = archive_bytes(files)
digest = hashlib.sha256(payload).hexdigest()
out_dir.mkdir(parents=True, exist_ok=True)
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
archive_path = out_dir / archive_name
sha_path = out_dir / f"{archive_name}.sha256"
archive_path.write_bytes(payload)
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
return {
"archive": str(archive_path),
"sha256_file": str(sha_path),
"name": archive_name,
"size": len(payload),
"sha256": digest,
"files": [relative for relative, _ in files],
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", default=".", help="component repository root")
parser.add_argument("--component-id", required=True)
parser.add_argument("--version", required=True, help="version without leading v")
parser.add_argument("--out-dir", default="dist")
parser.add_argument(
"--allow",
action="append",
default=[],
help="relative allowlist entry (repeatable); defaults applied when omitted",
)
args = parser.parse_args(argv)
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
root = Path(args.root).resolve()
out_dir = Path(args.out_dir)
if not out_dir.is_absolute():
out_dir = root / out_dir
try:
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
except PackageError as error:
print(f"package_source: FAIL: {error}", file=sys.stderr)
return 1
print(result["archive"])
print(result["sha256_file"])
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env python3
"""Publish a Gitea release with a draft transaction and immutable public assets.
Order (issue #10 §4.2):
create/reuse draft → upload non-index assets → upload release-evidence.json last
→ re-read and verify → mark non-draft → re-confirm.
Never deletes or replaces assets on an already-published (non-draft) release.
Identical published identity is treated as idempotent success.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import mimetypes
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
DEFAULT_API = "https://git.cflmy.cn/api/v1"
INDEX_NAME = "release-evidence.json"
class PublishError(Exception):
pass
def token() -> str:
value = (
os.environ.get("GITEA_PUBLISH_TOKEN")
or os.environ.get("GITEA_TOKEN")
or os.environ.get("gitea_token")
)
if not value:
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
return value
def request(
api: str,
method: str,
path: str,
token_value: str,
payload: dict | None = None,
raw: bytes | None = None,
content_type: str = "application/json",
) -> tuple[int, bytes]:
url = f"{api}{path}"
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = content_type
elif raw is not None:
data = raw
headers["Content-Type"] = content_type
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=120) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def decode(body: bytes) -> object:
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
status, body = request(
api,
"GET",
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
token_value,
)
if status == 404:
return None
if status != 200:
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
release = decode(body)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("release lookup response malformed")
return release
def create_draft(
api: str,
repo: str,
tag: str,
body: str,
token_value: str,
*,
prerelease: bool,
target: str,
) -> dict:
payload = {
"tag_name": tag,
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
}
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
if status not in (200, 201):
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("draft create response malformed")
return release
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
status, response = request(
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
)
if status != 200:
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
release = decode(response)
if not isinstance(release, dict):
raise PublishError("release patch response malformed")
return release
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
status, response = request(
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
)
if status != 200:
raise PublishError(f"listing assets failed with HTTP {status}")
assets = decode(response)
if not isinstance(assets, list):
raise PublishError("asset list malformed")
return assets
def upload_asset(
api: str, repo: str, release_id: int, path: Path, token_value: str
) -> dict:
name = path.name
if not name or "/" in name or name in (".", ".."):
raise PublishError(f"unsafe asset name: {name!r}")
existing = list_assets(api, repo, release_id, token_value)
for asset in existing:
if asset.get("name") == name:
raise PublishError(
f"asset {name} already exists on draft/release {release_id}; "
"refusing to overwrite"
)
boundary = f"----marqdo{uuid.uuid4().hex}"
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
body = bytearray()
body.extend(f"--{boundary}\r\n".encode())
body.extend(
f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode()
)
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
body.extend(path.read_bytes())
body.extend(f"\r\n--{boundary}--\r\n".encode())
status, response = request(
api,
"POST",
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
token_value,
raw=bytes(body),
content_type=f"multipart/form-data; boundary={boundary}",
)
if status not in (200, 201):
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
result = decode(response)
if not isinstance(result, dict):
raise PublishError(f"upload response for {name} malformed")
return result
def asset_identity(path: Path) -> dict:
return {
"name": path.name,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
def published_matches(release: dict, expected: list[dict]) -> bool:
remote = {
asset.get("name"): int(asset.get("size") or -1)
for asset in (release.get("assets") or [])
}
if set(remote) != {item["name"] for item in expected}:
return False
for item in expected:
if remote.get(item["name"]) != item["size"]:
return False
return True
def publish(
*,
api: str,
repo: str,
tag: str,
body: str,
target: str,
assets: list[Path],
prerelease: bool,
token_value: str,
) -> dict:
if not assets:
raise PublishError("no assets to publish")
index_assets = [path for path in assets if path.name == INDEX_NAME]
other_assets = [path for path in assets if path.name != INDEX_NAME]
if len(index_assets) != 1:
raise PublishError("exactly one release-evidence.json is required")
ordered = other_assets + index_assets
expected = [asset_identity(path) for path in ordered]
existing = get_release_by_tag(api, repo, tag, token_value)
if existing and not existing.get("draft"):
if published_matches(existing, expected):
return {
"status": "idempotent",
"release_id": existing["id"],
"html_url": existing.get("html_url"),
"tag": tag,
"assets": expected,
}
raise PublishError(
f"published release {tag} already exists with different assets; "
"refusing to overwrite"
)
if existing and existing.get("draft"):
release = existing
# Keep draft body/target aligned when continuing an interrupted publish.
release = patch_release(
api,
repo,
int(release["id"]),
token_value,
{
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
},
)
else:
release = create_draft(
api, repo, tag, body, token_value, prerelease=prerelease, target=target
)
release_id = int(release["id"])
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
for path in ordered:
if path.name in remote_names:
# Same-name asset already on this draft: require identical size, else fail.
match = next(
asset
for asset in list_assets(api, repo, release_id, token_value)
if asset.get("name") == path.name
)
if int(match.get("size") or -1) != path.stat().st_size:
raise PublishError(
f"draft asset {path.name} size mismatch; refusing to overwrite"
)
continue
upload_asset(api, repo, release_id, path, token_value)
refreshed = get_release_by_tag(api, repo, tag, token_value)
if not refreshed or not published_matches(refreshed, expected):
raise PublishError("post-upload release asset list does not match local files")
published = patch_release(
api,
repo,
release_id,
token_value,
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
)
if published.get("draft"):
raise PublishError("release remained draft after publish")
final = get_release_by_tag(api, repo, tag, token_value)
if not final or final.get("draft") or not published_matches(final, expected):
raise PublishError("final release confirmation failed")
return {
"status": "published",
"release_id": final["id"],
"html_url": final.get("html_url"),
"tag": tag,
"assets": expected,
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
parser.add_argument("--repo", required=True, help="owner/name")
parser.add_argument("--tag", required=True)
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
parser.add_argument("--body-file", default=None)
parser.add_argument("--body", default="")
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--prerelease", action="store_true", default=False)
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
args = parser.parse_args(argv)
body = args.body
if args.body_file:
body = Path(args.body_file).read_text(encoding="utf-8")
assets = [Path(item) for item in args.asset]
for path in assets:
if not path.is_file():
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
return 1
try:
result = publish(
api=args.api_url.rstrip("/"),
repo=args.repo,
tag=args.tag,
body=body,
target=args.target,
assets=assets,
prerelease=args.prerelease,
token_value=token(),
)
except PublishError as error:
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.evidence_out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,49 @@
#!/bin/sh
# Deterministic source archive + release-evidence.json for this component.
#
# Required env:
# COMPONENT_ID catalog id (e.g. std-text)
# REPOSITORY owner/name (e.g. cflmy/marqdo-std-text)
# Optional:
# VERSION without leading v (default: derived from CI_COMMIT_TAG)
# SOURCE_SHA full commit (default: HEAD)
# OUT_DIR default dist
# DEPENDENCY repeatable write_evidence dependency specs via env DEP_ARGS
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
COMPONENT_ID=${COMPONENT_ID:?COMPONENT_ID is required}
REPOSITORY=${REPOSITORY:?REPOSITORY is required}
SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)}
OUT_DIR=${OUT_DIR:-dist}
TAG=${CI_COMMIT_TAG:-${TAG:-}}
if [ -n "${VERSION:-}" ]; then
:
elif [ -n "$TAG" ]; then
VERSION=${TAG#v}
else
echo "package.sh: set VERSION or CI_COMMIT_TAG" >&2
exit 1
fi
TAG=${TAG:-v$VERSION}
python3 "$ROOT/scripts/release/package_source.py" \
--root "$ROOT" \
--component-id "$COMPONENT_ID" \
--version "$VERSION" \
--out-dir "$OUT_DIR"
ARCHIVE=$(ls "$ROOT/$OUT_DIR"/marqdo-"$COMPONENT_ID"-"$VERSION"-source.tar.gz)
SHAFILE="$ARCHIVE.sha256"
EVIDENCE_ARGS="--component-id $COMPONENT_ID --repository $REPOSITORY --tag $TAG --source-sha $SOURCE_SHA --asset $ARCHIVE --asset $SHAFILE --out $ROOT/$OUT_DIR/release-evidence.json"
if [ -n "${CI_PIPELINE_NUMBER:-}" ]; then
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-number $CI_PIPELINE_NUMBER"
fi
if [ -n "${CI_PIPELINE_URL:-}" ]; then
EVIDENCE_ARGS="$EVIDENCE_ARGS --pipeline-url $CI_PIPELINE_URL"
fi
# shellcheck disable=SC2086
eval "python3 \"$ROOT/scripts/release/write_evidence.py\" $EVIDENCE_ARGS ${DEP_ARGS:-}"
echo "$ARCHIVE"
echo "$SHAFILE"
echo "$ROOT/$OUT_DIR/release-evidence.json"
@@ -0,0 +1,33 @@
# Protected publish workflow: tag or manual only.
# Holds the publish token. Push/PR lanes must never mount this secret.
when:
- event: [tag, manual]
steps:
publish:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment:
GITEA_PUBLISH_TOKEN:
from_secret: gitea_publish_token
COMPONENT_ID: "${COMPONENT_ID}"
REPOSITORY: "${REPOSITORY}"
commands:
- |
set -eu
test -n "${GITEA_PUBLISH_TOKEN:?gitea_publish_token secret missing}"
test -n "${CI_COMMIT_TAG:?publish requires a tag}"
export SOURCE_SHA="${CI_COMMIT_SHA}"
export VERSION="${CI_COMMIT_TAG#v}"
export TAG="${CI_COMMIT_TAG}"
sh scripts/package.sh
ARCHIVE="dist/marqdo-${COMPONENT_ID}-${VERSION}-source.tar.gz"
python3 scripts/release/publish_gitea.py \
--repo "$REPOSITORY" \
--tag "$TAG" \
--target "$SOURCE_SHA" \
--prerelease \
--body "Automated source release for ${COMPONENT_ID} ${TAG}." \
--asset "$ARCHIVE" \
--asset "${ARCHIVE}.sha256" \
--asset dist/release-evidence.json \
--evidence-out dist/gitea-publish-result.json
@@ -0,0 +1,20 @@
# Fast-path notification after a completed Gitea release.
# Hint only; root reconcile verifies authoritative releases. Lost calls are
# recovered by the root release-reconcile cron.
when:
event: [release]
steps:
notify:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment:
WOODPECKER_NOTIFY_TOKEN:
from_secret: woodpecker_notify_token
COMPONENT_ID: "${COMPONENT_ID}"
commands:
- |
set -eu
test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
python3 scripts/release/notify_root.py \
--hint-component "${COMPONENT_ID}" \
--hint-tag "${CI_COMMIT_TAG:-}"
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Write the external release-evidence.json index for a component release.
The index references already-built assets. It never includes itself in
`assets[]` (no self-referential digest). Downstream discoverers hash the index
bytes separately when they download it.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
MAX_ASSETS = 128
MAX_DEPENDENCIES = 256
INDEX_NAME = "release-evidence.json"
class EvidenceError(Exception):
pass
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def parse_dependency(raw: str) -> dict:
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
fields = {}
for part in raw.split(","):
if "=" not in part:
raise EvidenceError(f"invalid dependency field: {raw!r}")
key, value = part.split("=", 1)
fields[key.strip()] = value.strip()
component_id = fields.get("id")
source_sha = fields.get("source_sha")
if not component_id or not source_sha or not SHA_RE.match(source_sha):
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
entry = {"id": component_id, "source_sha": source_sha}
asset = fields.get("asset_sha256")
if asset:
if not DIGEST_RE.match(asset):
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
entry["asset_sha256"] = asset
return entry
def build_evidence(
*,
component_id: str,
repository: str,
tag: str,
source_sha: str,
assets: list[Path],
dependencies: list[dict],
pipeline_number: int | None,
pipeline_url: str | None,
) -> dict:
if not component_id:
raise EvidenceError("component_id is required")
if "/" not in repository:
raise EvidenceError("repository must be owner/name")
if not tag:
raise EvidenceError("tag is required")
if not SHA_RE.match(source_sha):
raise EvidenceError("source_sha must be a 40-hex commit")
if not assets:
raise EvidenceError("at least one non-index asset is required")
if len(assets) > MAX_ASSETS:
raise EvidenceError(f"more than {MAX_ASSETS} assets")
if len(dependencies) > MAX_DEPENDENCIES:
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
asset_entries = []
seen_names: set[str] = set()
for path in assets:
if not path.is_file():
raise EvidenceError(f"asset missing: {path}")
name = path.name
if name == INDEX_NAME:
raise EvidenceError("assets must not include release-evidence.json itself")
if name in seen_names or "/" in name or name in (".", ".."):
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
seen_names.add(name)
target = "source"
if name.endswith(".tar.gz") and "linux" in name:
target = "x86_64-unknown-linux-gnu"
asset_entries.append(
{
"name": name,
"target": target,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
)
evidence = {
"component_id": component_id,
"repository": repository,
"tag": tag,
"source_sha": source_sha,
"ci": {
"pipeline_number": pipeline_number,
"url": pipeline_url,
"source_sha": source_sha,
},
"assets": asset_entries,
"dependencies": dependencies,
}
return evidence
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--component-id", required=True)
parser.add_argument("--repository", required=True)
parser.add_argument("--tag", required=True)
parser.add_argument("--source-sha", required=True)
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--dependency", action="append", default=[])
parser.add_argument("--pipeline-number", type=int, default=None)
parser.add_argument("--pipeline-url", default=None)
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
args = parser.parse_args(argv)
try:
dependencies = [parse_dependency(item) for item in args.dependency]
evidence = build_evidence(
component_id=args.component_id,
repository=args.repository,
tag=args.tag,
source_sha=args.source_sha,
assets=[Path(item) for item in args.asset],
dependencies=dependencies,
pipeline_number=args.pipeline_number,
pipeline_url=args.pipeline_url,
)
except EvidenceError as error:
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
if len(payload.encode()) > 1024 * 1024:
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
return 1
out.write_text(payload, encoding="utf-8")
print(out)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+493 -66
View File
@@ -1,23 +1,28 @@
#!/usr/bin/env python3
"""Release discovery and idempotent tracking for the Marqdo ecosystem.
"""Release discovery, evidence verification, tracking and consumer dispatch.
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.
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. A concurrent run can create a duplicate only if both
scan before either issue is visible; the workflow serializes runs.
`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
@@ -31,18 +36,33 @@ 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
@@ -70,6 +90,7 @@ class Gitea:
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:
@@ -109,15 +130,21 @@ def submodule_repositories(repo_root: Path) -> dict[str, str]:
return result
def managed_repositories(root: Path) -> dict[str, str]:
"""catalog id/path -> owner/name for direct components and domain children."""
def catalog_components(root: Path) -> list[dict]:
catalog = tomllib.loads((root / "components.toml").read_text())
components = []
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]
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)
@@ -126,8 +153,25 @@ def managed_repositories(root: Path) -> dict[str, str]:
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]
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
@@ -147,29 +191,103 @@ def verify_assets(client: Gitea, release: dict) -> list[dict]:
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})
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 existing_issues(client: Gitea, label: str = LABEL) -> list[dict]:
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/{ROOT_REPOSITORY}/issues?state=all&limit=100&type=issues&labels={label}"
f"/repos/{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")
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") == LABEL:
if item.get("name") == name:
return int(item["id"])
created = client.post(
f"/repos/{ROOT_REPOSITORY}/labels",
{"name": LABEL, "color": "#bfd4f2", "description": "Release tracking created by reconcile"},
f"/repos/{repository}/labels",
{"name": name, "color": color, "description": description},
)
return int(created["id"])
@@ -211,35 +329,338 @@ def published_after(entry: dict, cutoff: str | None) -> bool:
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) if apply else None
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"})
results.append({**entry, "status": "tracked", "consumer_tasks": [], "evidence": None})
continue
verified: list[dict] = []
evidence: dict | None = None
if not apply:
verified = []
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}"}
{
**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)
body = render_issue(
entry,
verified,
evidence=evidence,
consumers=consumers,
impact=impact,
)
try:
issue = client.post(
f"/repos/{ROOT_REPOSITORY}/issues",
@@ -254,18 +675,42 @@ def reconcile(
entry = {**entry, "issue": issue.get("number")}
except ReconcileError as error:
status = f"issue-create-failed: {error}"
results.append({**entry, "assets": verified, "status": status})
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": 1,
"generated_at": __import__("datetime").datetime.now(
__import__("datetime").timezone.utc
).isoformat(),
"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})
@@ -274,49 +719,25 @@ def reconcile(
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 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("--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", ""),
@@ -334,6 +755,8 @@ def main(argv: list[str]) -> int:
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)
@@ -341,6 +764,10 @@ def main(argv: list[str]) -> int:
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
+293
View File
@@ -0,0 +1,293 @@
"""Unit tests for scripts/component-release helpers (issue #10 §4/§6)."""
from __future__ import annotations
import hashlib
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
LIB = ROOT / "scripts" / "component-release"
def load(name: str):
path = LIB / f"{name}.py"
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
package_source = load("package_source")
write_evidence = load("write_evidence")
publish_gitea = load("publish_gitea")
notify_root = load("notify_root")
class PackageSourceTest(unittest.TestCase):
def test_deterministic_archive_and_allowlist(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "modules").mkdir()
(root / "modules" / "text.mq.md").write_text("打印 1\n", encoding="utf-8")
(root / "README.md").write_text("std-text\n", encoding="utf-8")
(root / "secret.bin").write_bytes(b"nope")
first = package_source.write_outputs(
root, root / "dist", "std-text", "0.0.0-ci10.1", ["modules", "README.md"]
)
second = package_source.write_outputs(
root, root / "dist2", "std-text", "0.0.0-ci10.1", ["modules", "README.md"]
)
self.assertEqual(first["sha256"], second["sha256"])
self.assertEqual(first["size"], second["size"])
self.assertEqual(first["files"], ["README.md", "modules/text.mq.md"])
self.assertTrue((root / "dist" / first["name"]).is_file())
def test_rejects_symlink_and_empty_allowlist_match(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "modules").mkdir()
target = root / "modules" / "real.mq.md"
target.write_text("x\n", encoding="utf-8")
link = root / "modules" / "link.mq.md"
link.symlink_to(target.name)
with self.assertRaises(package_source.PackageError):
package_source.write_outputs(
root, root / "dist", "std-text", "0.0.1", ["modules"]
)
with self.assertRaises(package_source.PackageError):
package_source.write_outputs(
root, root / "dist", "std-text", "0.0.1", ["missing"]
)
class WriteEvidenceTest(unittest.TestCase):
def test_builds_index_without_self_reference(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "marqdo-std-text-0.0.1-source.tar.gz"
archive.write_bytes(b"abc")
sha = root / f"{archive.name}.sha256"
sha.write_text(f"{hashlib.sha256(b'abc').hexdigest()} {archive.name}\n")
evidence = write_evidence.build_evidence(
component_id="std-text",
repository="cflmy/marqdo-std-text",
tag="v0.0.1",
source_sha="a" * 40,
assets=[archive, sha],
dependencies=[{"id": "cli", "source_sha": "b" * 40}],
pipeline_number=12,
pipeline_url="https://ci.cflmy.cn/repos/1/pipeline/12",
)
self.assertEqual(evidence["component_id"], "std-text")
self.assertEqual(len(evidence["assets"]), 2)
self.assertTrue(all(item["name"] != "release-evidence.json" for item in evidence["assets"]))
self.assertEqual(evidence["ci"]["source_sha"], "a" * 40)
def test_rejects_index_as_asset_and_bad_sha(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
index = root / "release-evidence.json"
index.write_text("{}\n", encoding="utf-8")
with self.assertRaises(write_evidence.EvidenceError):
write_evidence.build_evidence(
component_id="std-text",
repository="cflmy/marqdo-std-text",
tag="v0.0.1",
source_sha="a" * 40,
assets=[index],
dependencies=[],
pipeline_number=None,
pipeline_url=None,
)
with self.assertRaises(write_evidence.EvidenceError):
write_evidence.parse_dependency("id=cli,source_sha=short")
class PublishGiteaTest(unittest.TestCase):
def test_idempotent_published_match_and_conflict(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "a.tar.gz"
archive.write_bytes(b"abc")
index = root / "release-evidence.json"
index.write_text("{}\n", encoding="utf-8")
expected_assets = [
{"name": "a.tar.gz", "size": 3, "browser_download_url": "u1"},
{"name": "release-evidence.json", "size": index.stat().st_size, "browser_download_url": "u2"},
]
published = {
"id": 9,
"draft": False,
"html_url": "https://example.invalid/r",
"assets": expected_assets,
}
def fake_get(api, repo, tag, token_value):
return published
with mock.patch.object(publish_gitea, "get_release_by_tag", side_effect=fake_get):
result = publish_gitea.publish(
api="https://example.invalid/api/v1",
repo="cflmy/demo",
tag="v0.0.1",
body="",
target="a" * 40,
assets=[archive, index],
prerelease=True,
token_value="t",
)
self.assertEqual(result["status"], "idempotent")
published["assets"][0]["size"] = 99
with mock.patch.object(publish_gitea, "get_release_by_tag", side_effect=fake_get):
with self.assertRaises(publish_gitea.PublishError):
publish_gitea.publish(
api="https://example.invalid/api/v1",
repo="cflmy/demo",
tag="v0.0.1",
body="",
target="a" * 40,
assets=[archive, index],
prerelease=True,
token_value="t",
)
def test_draft_upload_order_and_undraft(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "a.tar.gz"
archive.write_bytes(b"abc")
index = root / "release-evidence.json"
index.write_text("{}\n", encoding="utf-8")
state = {"draft": True, "assets": [], "id": 3, "html_url": "https://example.invalid/r"}
def get_release(api, repo, tag, token_value):
return {
"id": state["id"],
"draft": state["draft"],
"html_url": state["html_url"],
"assets": list(state["assets"]),
}
def create_draft(*args, **kwargs):
return get_release("", "", "", "")
def list_assets(api, repo, release_id, token_value):
return list(state["assets"])
def upload(api, repo, release_id, path, token_value):
asset = {
"name": path.name,
"size": path.stat().st_size,
"browser_download_url": f"https://example.invalid/{path.name}",
}
state["assets"].append(asset)
return asset
def patch(api, repo, release_id, token_value, payload):
if "draft" in payload:
state["draft"] = payload["draft"]
return get_release("", "", "", "")
uploads = []
def upload_tracked(api, repo, release_id, path, token_value):
uploads.append(path.name)
return upload(api, repo, release_id, path, token_value)
with mock.patch.object(publish_gitea, "get_release_by_tag", side_effect=get_release), mock.patch.object(
publish_gitea, "create_draft", side_effect=create_draft
), mock.patch.object(publish_gitea, "list_assets", side_effect=list_assets), mock.patch.object(
publish_gitea, "upload_asset", side_effect=upload_tracked
), mock.patch.object(publish_gitea, "patch_release", side_effect=patch):
# First get returns None so create_draft runs.
calls = {"n": 0}
def get_then_existing(api, repo, tag, token_value):
calls["n"] += 1
if calls["n"] == 1:
return None
return get_release(api, repo, tag, token_value)
with mock.patch.object(publish_gitea, "get_release_by_tag", side_effect=get_then_existing):
result = publish_gitea.publish(
api="https://example.invalid/api/v1",
repo="cflmy/demo",
tag="v0.0.1",
body="notes",
target="a" * 40,
assets=[archive, index],
prerelease=True,
token_value="t",
)
self.assertEqual(result["status"], "published")
self.assertEqual(uploads, ["a.tar.gz", "release-evidence.json"])
self.assertFalse(state["draft"])
class NotifyRootTest(unittest.TestCase):
def test_retries_transient_and_fails_closed_on_403(self):
responses = [
urllib_error(500),
{"id": 71, "number": 71},
]
class FakeResponse:
def __init__(self, payload):
self.status = 200
self._payload = payload
def read(self):
return json.dumps(self._payload).encode()
def __enter__(self):
return self
def __exit__(self, *args):
return False
def urlopen(request, timeout=0):
item = responses.pop(0)
if isinstance(item, Exception):
raise item
return FakeResponse(item)
with mock.patch.object(notify_root.urllib.request, "urlopen", side_effect=urlopen), mock.patch.object(
notify_root.time, "sleep", return_value=None
):
result = notify_root.trigger(
"https://ci.example/api/repos/6/pipelines", "token", {"branch": "main"}, attempts=3
)
self.assertEqual(result["pipeline_number"], 71)
self.assertEqual(result["attempt"], 2)
def reject(request, timeout=0):
raise urllib_error(403)
with mock.patch.object(notify_root.urllib.request, "urlopen", side_effect=reject):
with self.assertRaises(notify_root.NotifyError):
notify_root.trigger(
"https://ci.example/api/repos/6/pipelines", "token", {"branch": "main"}, attempts=3
)
def urllib_error(code: int):
import urllib.error
return urllib.error.HTTPError(
url="https://ci.example/api/repos/6/pipelines",
code=code,
msg="err",
hdrs=None,
fp=None,
)
if __name__ == "__main__":
unittest.main()
+108 -17
View File
@@ -15,18 +15,28 @@ SPEC.loader.exec_module(reconcile)
class FakeGitea:
def __init__(self, releases=None, assets=None, issues=None):
def __init__(self, releases=None, assets=None, issues=None, repo_issues=None):
self.releases = releases or {}
self.asset_bytes = assets or {}
self.issues = list(issues or [])
self.repo_issues = {key: list(value) for key, value in (repo_issues or {}).items()}
self.posts = []
self.label_created = False
self.labels_created = set()
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 []
repository = path.split("/")[2] + "/" + path.split("/")[3]
labels = []
if (repository, reconcile.LABEL) in self.labels_created:
labels.append({"id": 5, "name": reconcile.LABEL})
if (repository, reconcile.UPSTREAM_LABEL) in self.labels_created:
labels.append({"id": 6, "name": reconcile.UPSTREAM_LABEL})
return labels
if "/issues?" in path:
return self.issues
repository = path.split("/")[2] + "/" + path.split("/")[3]
if repository == reconcile.ROOT_REPOSITORY:
return self.issues
return self.repo_issues.get(repository, [])
for repository, releases in self.releases.items():
if path == f"/repos/{repository}/releases?limit=50":
return releases
@@ -34,12 +44,16 @@ class FakeGitea:
def post(self, path, data):
self.posts.append((path, data))
repository = path.split("/")[2] + "/" + path.split("/")[3]
if path.endswith("/labels"):
self.label_created = True
return {"id": 5, "name": data["name"]}
self.labels_created.add((repository, data["name"]))
return {"id": 5 if data["name"] == reconcile.LABEL else 6, "name": data["name"]}
if path.endswith("/issues"):
issue = {"number": 100 + len(self.issues), "body": data["body"], "title": data["title"]}
self.issues.append(issue)
issue = {"number": 100 + len(self.issues) + sum(len(v) for v in self.repo_issues.values()), "body": data["body"], "title": data["title"]}
if repository == reconcile.ROOT_REPOSITORY:
self.issues.append(issue)
else:
self.repo_issues.setdefault(repository, []).append(issue)
return issue
return {}
@@ -65,7 +79,7 @@ def release(repository="cflmy/marqdo-cli", tag="v0.0.1", asset_url="https://exam
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)
report = reconcile.reconcile(client, ROOT, apply=False, dispatch_consumers=False)
self.assertFalse(client.posts)
self.assertGreaterEqual(report["releases"], 1)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
@@ -77,7 +91,7 @@ class ReconcileTest(unittest.TestCase):
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abc"},
)
report = reconcile.reconcile(client, ROOT, apply=True)
report = reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=False)
created = [data for path, data in client.posts if path.endswith("/issues")]
self.assertEqual(len(created), 1)
body = created[0]["body"]
@@ -92,23 +106,27 @@ class ReconcileTest(unittest.TestCase):
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abc"},
)
reconcile.reconcile(client, ROOT, apply=True)
reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=False)
posts_after_first = len(client.posts)
report = reconcile.reconcile(client, ROOT, apply=True)
report = reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=False)
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")
skipped = reconcile.reconcile(
client, ROOT, apply=False, cutoff="2026-11-28T00:00:00Z", dispatch_consumers=False
)
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")
kept = reconcile.reconcile(
client, ROOT, apply=False, cutoff="2026-11-26T00:00:00Z", dispatch_consumers=False
)
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)
report = reconcile.reconcile(client, ROOT, apply=False, dispatch_consumers=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):
@@ -116,17 +134,90 @@ class ReconcileTest(unittest.TestCase):
releases={"cflmy/marqdo-cli": [release()]},
assets={"https://example.invalid/a.tar.gz": b"abcdef"},
)
report = reconcile.reconcile(bad_size, ROOT, apply=True)
report = reconcile.reconcile(bad_size, ROOT, apply=True, dispatch_consumers=False)
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)
report = reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=False)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
def test_release_evidence_mismatch_is_rejected(self):
evidence = {
"component_id": "cli",
"repository": "cflmy/marqdo-cli",
"tag": "v0.0.1",
"source_sha": "a" * 40,
"assets": [
{
"name": "a.tar.gz",
"target": "source",
"size": 3,
"sha256": "0" * 64,
}
],
"dependencies": [],
}
payload = json.dumps(evidence).encode()
rel = release()
rel["assets"].append(
{
"name": "release-evidence.json",
"size": len(payload),
"browser_download_url": "https://example.invalid/evidence.json",
}
)
client = FakeGitea(
releases={"cflmy/marqdo-cli": [rel]},
assets={
"https://example.invalid/a.tar.gz": b"abc",
"https://example.invalid/evidence.json": payload,
},
)
report = reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=False)
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
def test_freshness_report_is_derived(self):
client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
report = reconcile.reconcile(client, ROOT, apply=False, dispatch_consumers=False)
self.assertEqual(report["freshness"]["schema"], "marqdo.release-freshness.v1")
rows = {row["component"]: row for row in report["freshness"]["components"]}
self.assertIn("cli", rows)
self.assertEqual(rows["cli"]["latest_release"]["tag"], "v0.0.1")
def test_stdlib_release_dispatches_root_upstream_task(self):
rel = release(
repository="cflmy/marqdo-std-text",
tag="v0.0.0-ci10.1",
asset_url="https://example.invalid/std-text.tar.gz",
)
client = FakeGitea(
releases={"cflmy/marqdo-std-text": [rel]},
assets={"https://example.invalid/std-text.tar.gz": b"abc"},
)
report = reconcile.reconcile(client, ROOT, apply=True, dispatch_consumers=True)
entry = [
item
for item in report["results"]
if item["repository"] == "cflmy/marqdo-std-text"
][0]
self.assertEqual(entry["status"], "created")
tasks = entry["consumer_tasks"]
self.assertTrue(tasks)
self.assertEqual(tasks[0]["consumer"], "marqdo")
self.assertEqual(tasks[0]["status"], "created")
upstream_posts = [
data
for path, data in client.posts
if path.endswith("/issues") and "Upstream" in data["title"]
]
self.assertEqual(len(upstream_posts), 1)
self.assertIn("marqdo:upstream-task key=", upstream_posts[0]["body"])
if __name__ == "__main__":
unittest.main()