9 Commits
Author SHA1 Message Date
cflmy 3cc477de60 test: verify the source of upstream issue inputs
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/manual/upstream Pipeline failed
2026-11-27 22:07:41 +08:00
cflmy 8c8360c942 ci: read verified Knowledge upstream tasks by their issue number 2026-11-27 22:05:58 +08:00
cflmy 351f13e04a ci: verify selected upstream CLI releases with the Knowledge core gate
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
2026-11-27 21:47:11 +08:00
cflmy ecf23d0507 ci: leave tag protection review with the maintainer
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/push/ci Pipeline is pending
2026-11-27 21:26:13 +08:00
cflmy c03a8d9d98 ci: publish Knowledge through a verified immutable draft
ci/woodpecker/pr/ci Pipeline is pending
2026-11-27 21:19:22 +08:00
marqdo-ci a1a223f53f ci: notify the root reconcile on a completed release
ci/woodpecker/pr/ci Pipeline is pending
ci/woodpecker/pr/main Pipeline is pending
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/ci Pipeline was successful
Release event fast path: validate the secret is present, then ask the root
manual `reconcile` workflow to check the authoritative Gitea release. The call
is only a hint; correctness and lost-notification recovery stay in the root
reconcile cron/script.
2026-11-27 14:18:04 +08:00
marqdo-ci 917c12e760 ci: consume the shared Rust CI image
ci/woodpecker/push/ci Pipeline is pending
ci/woodpecker/push/main Pipeline is pending
ci/woodpecker/pr/ci Pipeline is pending
ci/woodpecker/pr/main Pipeline is pending
Replaces per-run rustup/apt/CLI setup with the published marqdo-ci-rust image
(pinned toolchain, rustfmt/clippy, warm cargo cache and released CLI/Bundle).
2026-11-27 14:15:02 +08:00
marqdo-norms 6e88100089 docs: adopt the ecosystem repository development conventions
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
Add the repository AGENTS.md boundary and anti-bloat rules required by
marqdo docs/REPOSITORY-CONVENTIONS.md, with the marker and canonical link so
scripts/check-repo-conventions.py can enforce it.
2026-11-27 11:36:14 +08:00
marqdo-knowledge d8fa201b28 docs(release): record 0.1.0-beta.3 publication evidence
ci/woodpecker/push/main Pipeline was successful
CI / fmt + clippy + workspace tests (push) Canceled after 0s
CI / MSRV check (1.89) (push) Canceled after 0s
CI / real Analysis integration (pinned core CLI) (push) Canceled after 0s
CI / beta release archive (push) Canceled after 0s
- add docs/evidence/2026-11-26-beta.3-release.md: tag/source commit, Gitea
  release URL and assets, published archive SHA-256, CI tag pipeline #11
  success and its archive SHA, local 139-test gate results, withdrawn beta.2
  tag, and the explicit secret-injection limitation with the reviewed local
  publish path
- link the release/evidence from docs/STATUS.md, the beta.3 release notes and
  docs/ci.md; keep the NOT RUN inventory unchanged
- record the local release/CI bookkeeping in the git-ignored .secrets notes
2026-11-26 09:59:32 +08:00
14 changed files with 900 additions and 236 deletions

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# Unified Woodpecker CI for a Rust Marqdo Tool.
#
# One published `marqdo-ci-rust` image contains the pinned toolchain and the
# released CLI/Bundle (`MARQDO_BIN`, `MARQDO_STDLIB_DIR` preset); the lane only
# runs this repository's own checks. No per-run rustup/apt/CLI download.
when:
- event: [pull_request, manual]
- event: push
branch: master
steps:
test:
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
environment:
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_TEST_BIN: /opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo
MARQDO_TOOL_HOME: /tmp/marqdo-tool-home
commands:
- python3 tools/ci/test_release_metadata.py
- python3 tools/ci/test_publish_gitea.py
- python3 tools/ci/test_verify_upstream.py
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets --locked -- -D warnings
- cargo test --workspace --locked
- cargo build --release --locked
- target/release/marqdo-knowledge --help
minimum-rust:
image: rust:1.89-bookworm
when:
- event: manual
- event: [push, pull_request]
path:
include: ['**/*.rs', '**/Cargo.toml', Cargo.lock, '.cargo/**', '.woodpecker/**']
on_empty: true
commands:
- cargo check --locked --workspace --all-targets
+4 -33
View File
@@ -1,10 +1,10 @@
# Woodpecker CI pipeline for marqdo-knowledge.
# Tag-only compatibility and release artifact validation for marqdo-knowledge.
#
# Mirrors the local lanes in scripts/ci.sh and the GitHub workflow. The core CLI
# is built from the pinned marqdo-cli commit because the Analysis contract is an
# external boundary; integration tests always run against that real binary.
when:
event: [push, pull_request, tag]
event: [tag]
steps:
test:
@@ -44,43 +44,14 @@ steps:
release:
depends_on: [test, minimum-rust, core-analysis]
when:
event: [tag]
image: rust:1.100-bookworm
environment:
GITEA_TOKEN:
from_secret: GITEA_TOKEN
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git build-essential python3
- |
set -eu
core_sha=4bbefc92449ee480c8a2c89b0308feb4cda8d0e7
work=$(mktemp -d)
git clone --quiet https://git.cflmy.cn/cflmy/marqdo-cli.git "$work/core"
( cd "$work/core" && git checkout --quiet "$core_sha" \
&& cargo build --release --locked -p marqdo-cli )
export MARQDO_BIN="$work/core/target/release/marqdo"
cargo build --release --locked
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-knowledge"))')"
version="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/smoke.py --archive "dist/marqdo-knowledge-$version-x86_64-unknown-linux-gnu.tar.gz" --evidence-out dist/smoke-evidence.json
if [ -z "${GITEA_TOKEN:-}" ]; then
echo "publish: skipped (this Woodpecker instance did not inject the GITEA_TOKEN secret); the deterministic archive and smoke evidence above are the CI evidence. Publish the prerelease locally from the same tagged SHA with tools/release/publish-gitea.py."
else
python3 tools/release/publish-gitea.py \
--tag "$CI_COMMIT_TAG" \
--archive "dist/marqdo-knowledge-$version-x86_64-unknown-linux-gnu.tar.gz" \
--files dist/RELEASE_INFO.json dist/FILES.sha256 dist/smoke-evidence.json \
--body-file "docs/releases/$version.md"
fi
- cat dist/RELEASE_INFO.json
- cat dist/*.tar.gz.sha256
- cat dist/smoke-evidence.json
- |
if [ -f dist/gitea-release-evidence.json ]; then
cat dist/gitea-release-evidence.json
else
echo "publish: skipped (no GITEA_TOKEN secret injection on this instance)"
fi
+18
View File
@@ -0,0 +1,18 @@
# Fast-path notification: a completed Gitea release asks the root reconcile
# workflow to check it. The payload is only a hint; the root reconcile verifies
# the release/assets from the authoritative Gitea API. A lost call is 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_TOKEN:
from_secret: woodpecker_token
commands:
- |
set -eu
test -n "${WOODPECKER_TOKEN:?woodpecker_token secret missing}"
curl -fsS -X POST -H "Authorization: Bearer $WOODPECKER_TOKEN" -H "Content-Type: application/json" -d '{"branch":"main","workflow":"reconcile"}' https://ci.cflmy.cn/api/repos/6/pipelines
+10
View File
@@ -0,0 +1,10 @@
when:
- event: manual
branch: master
evaluate: 'MARQDO_UPSTREAM_ISSUE != nil && MARQDO_UPSTREAM_ISSUE != ""'
steps:
verify:
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5@sha256:73481a35339157b1a3f3b23076517e96e302fbb5158e6ffcb1582acf22c6af94
commands:
- python3 tools/ci/verify-upstream.py --issue "$MARQDO_UPSTREAM_ISSUE"
+37
View File
@@ -0,0 +1,37 @@
<!-- marqdo:repo-conventions v1 -->
# AGENTS.md — knowledge
全局规范唯一来源:[marqdo 仓库开发规范](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/REPOSITORY-CONVENTIONS.md)。本文件只写本仓边界,不复制全局规范或合同正文。
## 1. 本仓定位与唯一权威
- catalog ID:`knowledge`;父级:根;角色:tool;状态:active。
- 职责/本仓拥有:确定性离线知识编译/检索与文档投影
- 本仓不拥有:Markdown/语言 parser、CLI 核心、其它业务实现
- 权威输入/合同:CLI 公开 Analysis 3;`MARQDO_BIN` 与项目输入
## 2. 必做 / 禁止
| 必做 | 禁止 |
| --- | --- |
| 只在本仓职责内修改,先开本仓工单 | 实现其它仓库功能,复制 parser/实现/合同 |
| 用真实 CLI/制品与独立期望测试 | mock、字符串检查或原型冒充真实验收/PASS |
| 依赖使用固定 SHA/摘要与显式输入 | 依赖父仓 checkout、兄弟仓相对路径、浮动分支 |
| 未运行写 `UNVERIFIED` | 伪造 entry/版本/CI 徽章/gitlink/发布资产 |
| 记录 SHA、制品摘要、平台、命令、退出码 | 提交密钥、凭证、构建产物或本地绝对路径 |
| 跨仓变更走 C2 → B2 → A2 晋升 | 自动 tag/release/合并,或直接改父仓/兄弟仓 |
- 不新增第二 catalog/manifest/lock/版本表/发布流程;不为单功能拆仓或建空壳仓。
- 不在本仓登记其它仓库后代路径;治理树最多两级 gitlink。
## 3. 构建、测试与证据
- CI/验收入口:`scripts/ci.sh`(非交互、失败非零、不打印秘密、只写声明输出;构建与发布权限分离)。
- 输入与依赖:CLI 公开 Analysis 3;`MARQDO_BIN` 与项目输入
- 交付:Tool bundle + `tool.json` 与知识投影验收证据
- 证据:候选 SHA、依赖/制品 SHA-256、平台/工具链、命令与退出码、日志位置、测试范围;FAIL/UNVERIFIED 不得写成 PASS。
## 4. 工单路由
- 公共协议/字段缺失 → `marqdo-cli`;检索/投影语义 → 本仓。
- 不把知识检索做成第二套文档 parser。
+10 -2
View File
@@ -7,7 +7,14 @@ must not be claimed as passing.
## Release state
- Channel: **beta** (`0.1.0-beta.3`), Linux x86_64. Not a stable claim.
- Release notes: [`releases/0.1.0-beta.3.md`](releases/0.1.0-beta.3.md).
- Release: <https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
(prerelease; tag commit `3edad237cfa92fc59822cfa13dd5480c3fac6532`; published
archive SHA-256
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`).
- Release notes: [`releases/0.1.0-beta.3.md`](releases/0.1.0-beta.3.md);
release evidence: [`evidence/2026-11-26-beta.3-release.md`](evidence/2026-11-26-beta.3-release.md).
- `v0.1.0-beta.2` was withdrawn (release lane failed before packaging); its tag
was deleted.
- CI/CD: [`.woodpecker/main.yml`](../.woodpecker/main.yml),
[`.github/workflows/ci.yml`](../.github/workflows/ci.yml) and
[`scripts/ci.sh`](../scripts/ci.sh); procedure in [`ci.md`](ci.md) and
@@ -58,7 +65,8 @@ must not be claimed as passing.
| Windows/macOS native testing | Release candidate platform is Linux x86_64 only. |
| Upstream batch `--documents` Analysis interface (U01) | Current upstream exposes per-entry `check --emit`; this tool invokes it per `.mq.md` entry and merges contexts, as the specification permits for the development stage. |
| Release archive native install on other platforms | Archive was built and cold-installed on Linux x86_64 only. |
| CI provider run URL for this beta | The pipeline configuration is committed; no external Woodpecker/GitHub run URL is recorded in this workspace. Local lanes were executed on the release SHA. |
| Automatic CI publication of the Gitea release | The Woodpecker instance did not inject the repository token into tag pipelines; the tag lane records build/smoke evidence and a publish-skipped notice, and the prerelease was published from the same tagged SHA by a reviewed local invocation. |
| GitHub Actions run for this beta | The GitHub workflow is committed but this workspace has no GitHub remote/run; the Woodpecker lane is the executed CI evidence. |
| Version-freeze reproducibility of `RELEASE_INFO.json` | It contains build metadata (`built_at_utc`, rustc/cargo versions); the archive SHA is recorded by the pipeline, not reproducible byte-for-byte from the same commit. |
| Incremental write-granularity benchmark | Incremental compiles reuse facts (no re-analysis for plain-only edits) but rewrite the projection inside one transaction; the specification's write-count benchmark has not been run. |
+49 -12
View File
@@ -1,14 +1,14 @@
# CI/CD for marqdo-knowledge
The pipeline mirrors the upstream `marqdo-cli` approach: one fast Rust contract
lane, one minimum-Rust lane, one lane that builds the pinned core CLI and runs
the real-Analysis integration tests, and a tag-only release lane that builds a
deterministic archive, cold-installs it through a real `marqdo` binary and
publishes the checksum.
Ordinary Woodpecker checks use the existing shared image and its released CLI.
Pull requests, default-branch pushes and manual runs share one workflow. Rust
source, manifest and CI changes also check the minimum supported Rust. Release
tags check the pinned historical core and produce the package evidence.
Configurations:
- `.woodpecker/main.yml` — self-hosted Woodpecker (push, pull_request, tag).
- `.woodpecker/ci.yml` runs ordinary component checks. `.woodpecker/main.yml`
runs release-tag compatibility checks, packaging and cold installation.
- `.github/workflows/ci.yml` — GitHub Actions mirror (push, pull_request, tag).
- `scripts/ci.sh` — the same lanes locally (`test`, `minimum`, `core`,
`release`, `all`).
@@ -23,12 +23,28 @@ Configurations:
## Pinned core boundary
The core CLI is an external contract. CI does not use an already-installed
`marqdo`: it builds `cflmy/marqdo-cli` at
`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` (`3.0.0-rc.4`, Analysis revision 3)
and exports `MARQDO_TEST_BIN` for `tests/core_cli.rs` and
`tests/compile.rs`. Changing the pin requires re-running the tamper fixtures and
recording a new Analysis fixture artifact.
Ordinary CI uses the official `3.0.0-rc.5` CLI from the shared image. The tag
compatibility step also builds the existing `3.0.0-rc.4` core pin
`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` and runs the real-Analysis tests.
Changing the historical pin requires rerunning the tamper fixtures and
recording the new Analysis fixture evidence.
For a verified upstream task, run the consumer gate from the clean Knowledge
candidate using the tag, source SHA and Linux archive digest from the task.
```sh
python3 tools/ci/verify-upstream.py --tag "$cli_tag" \
--source-sha "$cli_source_sha" --archive-sha256 "$cli_archive_sha256"
```
Pass `--archive` to reuse locally staged bytes. The gate checks the Gitea tag,
artifact digest and installed Bundle before running the existing `core` lane.
Its output records the actual consumer commit and CLI identities for review.
The `upstream` Woodpecker workflow accepts `MARQDO_UPSTREAM_ISSUE` as the
Knowledge issue number and uses the protected root baseline, recorded input
digests and authorized forge account to resolve the candidate. This workflow
needs read access to public issues and release assets.
## Gates executed by CI
@@ -43,6 +59,27 @@ recording a new Analysis fixture artifact.
| release build | `cargo build --release --locked` |
| deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` |
## Reviewed forge publication
The tag lane prepares assets without credentials. From the clean reviewed tag,
select the successful default-branch `ci` pipeline for that exact commit. Keep
the archive, its checksum, `RELEASE_INFO.json`, `FILES.sha256`, and
`smoke-evidence.json` together. The smoke test verifies and records the released
CLI identity used for the cold installation.
```sh
python3 tools/release/publish-gitea.py --prepare \
--tag "$release_tag" --pipeline "$component_pipeline" --archive "$archive"
```
The maintainer verifies Gitea tag protection as part of release approval. The
approved publisher runs the same command with `--body-file` in place of
`--prepare` and a `GITEA_TOKEN` from the dedicated publisher account. The tool
checks the protected default branch and exact tag, resumes matching drafts,
verifies the bytes on the forge and publishes only a complete inventory. A
matching public release is idempotent. A changed asset blocks the operation and
needs a new release decision.
## Not gated by CI (explicit non-claims)
- Real-model semantic quality benchmark (§8.3/§16) — needs a pinned model and
+107
View File
@@ -0,0 +1,107 @@
# Evidence: 0.1.0-beta.3 beta release
Date: 2026-11-26 (Asia/Shanghai)
Release channel: **beta** (not a stable-version claim)
Platform: Linux x86_64
Tool version: `0.1.0-beta.3`
Source/tag commit: `3edad237cfa92fc59822cfa13dd5480c3fac6532`
Tag: `v0.1.0-beta.3` (annotated)
Core CLI baseline: `cflmy/marqdo-cli` `3.0.0-rc.4`
(`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`), Analysis revision 3.
Contracts: `marqdo.cli-tool` revision 1, tool API revision 1, consumed Analysis
revision 3, SQLite schema revision 1, result/error envelope schema_version 1,
OKF 0.3.
## Published release
- Release URL:
<https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
- Gitea release id: 76, `prerelease: true`, `draft: false`
- Assets uploaded and verified through the Gitea API:
- `marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz` (3,838,786 bytes)
- `marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz.sha256`
- `RELEASE_INFO.json`
- `FILES.sha256`
- `smoke-evidence.json`
- Published archive SHA-256:
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`
- Published archive `source_sha`: `3edad237cfa92fc59822cfa13dd5480c3fac6532`
## CI/CD evidence
Tag-only Woodpecker pipeline **#11**: **success** on commit `3edad237`.
- Pipeline: <https://ci.cflmy.cn/repos/4/pipeline/11>
- Lanes: `test` (metadata consistency, fmt, clippy `-D warnings`, locked
workspace tests), `minimum-rust` (1.89 check), `core-analysis` (builds the
pinned core CLI and runs the real Analysis integration tests), `release`
(locked release build, deterministic package, cold-install smoke).
- CI-produced archive SHA-256 (same source commit, CI build environment):
`358acbb2279740b35dd800764ac649b7a122e4940c7209ad99c306c12e55642c`
- CI smoke result: `smoke: OK`; packaged example compile 5 documents, query
4 hits, check database current with 0 errors.
Local gates on the same source commit:
- `python3 tools/ci/test_release_metadata.py`: PASS.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --workspace --all-targets --locked -- -D warnings`: clean.
- `cargo test --workspace --locked` with the real rc.4 core binary:
139 passed / 0 failed.
- `cargo build --release --locked`: clean.
- Local deterministic package and `tools/release/smoke.py` against the real
core CLI: `smoke: OK` (checksum/manifest/version, install, help, compile,
query, check, remove).
The CI archive and the published local archive are different byte streams
because they were built in different build environments, but both record the
same `SOURCE_SHA` and the same tool/contract versions. The published asset and
its checksum are the authoritative artifact for this release; the CI archive SHA
is recorded for traceability only.
## Publication path and known infrastructure limitation
This Woodpecker instance (3.20.1) did not inject the repository `GITEA_TOKEN`
secret into tag pipelines, neither as an implicit repo secret nor through an
explicit `environment.from_secret` mapping. The tag lane therefore keeps the
deterministic package and cold-install smoke as its CI evidence and records a
`publish: skipped` notice instead of failing. The Gitea prerelease was published
from the same tagged source commit by a reviewed local invocation of
`tools/release/publish-gitea.py`; the token was read from the local-only
`.secrets/release.env` (git-ignored) and never printed or committed.
The pipeline is configured to publish automatically when the secret injection
becomes available; no source or release change is required for that.
## Withdrawn tag
`v0.1.0-beta.2` was withdrawn and its remote tag deleted. Its tag-only release
lane failed before packaging because the lane did not build the tool release
binary; no archive or Gitea release was produced for it. Do not use that tag.
## Reproduction
```sh
# From the tagged commit, with a compatible core CLI:
python3 tools/ci/test_release_metadata.py
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --locked -- -D warnings
MARQDO_TEST_BIN=/path/to/marqdo cargo test --workspace --locked
cargo build --release --locked
python3 tools/release/package.py \
--source-sha "$(git rev-parse HEAD)" \
--version "$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)"
MARQDO_BIN=/path/to/marqdo python3 tools/release/smoke.py \
--archive "dist/marqdo-knowledge-0.1.0-beta.3-x86_64-unknown-linux-gnu.tar.gz"
```
## Not evidence for
- Real-model semantic retrieval quality (protocol mock only).
- Specification §16 retrieval/performance gates, latency/RSS/build-time or
incremental write-volume benchmarks.
- Windows/macOS platform support.
- Upstream batch Analysis interface (per-entry `check --emit` is used).
- Byte-identical archive reproducibility across different build environments.
+19 -6
View File
@@ -30,7 +30,7 @@ Contract versions (unchanged from beta.1):
traceback when the release binary is absent.
- No tool behaviour, CLI surface, contract or schema change.
Release evidence produced by the pipeline on this SHA:
Release evidence produced for this SHA:
- metadata consistency gate PASS;
- fmt/clippy/tests (including the real rc.4 Analysis integration) PASS;
@@ -39,8 +39,8 @@ Release evidence produced by the pipeline on this SHA:
- cold-install smoke through the real core CLI: archive checksum/manifest/
version verified, install -> help -> compile packaged example -> query ->
check (current, 0 errors) -> remove;
- Gitea prerelease for the tag with the archive and evidence assets attached
(recorded in `dist/gitea-release-evidence.json` by the release lane).
- Gitea prerelease for the tag with the archive and evidence assets attached;
see the Evidence section below for URLs and checksums.
## What is complete in this beta
@@ -129,6 +129,19 @@ Diagnostics never include source text, credentials or absolute paths.
integration and local cold install.
- `docs/STATUS.md` — implemented/tested vs NOT RUN matrix.
- `docs/ci.md`, `docs/releasing.md` — gates, non-gates and frozen-SHA procedure.
- Pipeline run, archive checksum, `FILES.sha256`, `RELEASE_INFO.json`,
`dist/smoke-evidence.json` and the Gitea prerelease record the same release
SHA.
- Gitea prerelease:
<https://git.cflmy.cn/cflmy/marqdo-knowledge/releases/tag/v0.1.0-beta.3>
(release id 76, `prerelease: true`) with the archive, sidecar checksum,
`RELEASE_INFO.json`, `FILES.sha256` and `smoke-evidence.json` attached.
- Source/tag commit `3edad237cfa92fc59822cfa13dd5480c3fac6532`; published
archive SHA-256
`feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55`.
- CI tag pipeline #11 success:
<https://ci.cflmy.cn/repos/4/pipeline/11>; CI archive SHA-256
`358acbb2279740b35dd800764ac649b7a122e4940c7209ad99c306c12e55642c`
(different build environment, same `SOURCE_SHA`).
- Full record: [`docs/evidence/2026-11-26-beta.3-release.md`](../evidence/2026-11-26-beta.3-release.md).
- Note: this Woodpecker instance does not inject repository secrets into tag
pipelines, so the tag lane records build/smoke evidence and a
`publish: skipped` notice; the prerelease was published from the same tagged
SHA by a reviewed local invocation of `tools/release/publish-gitea.py`.
+103
View File
@@ -0,0 +1,103 @@
"""Publication transaction regressions, without a forge write."""
import hashlib
import importlib.util
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
SCRIPT = Path(__file__).resolve().parents[1] / "release/publish-gitea.py"
SPEC = importlib.util.spec_from_file_location("publish_gitea", SCRIPT)
publish = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(publish)
TAG = "v0.1.0-beta.4"
SOURCE = "a" * 40
INDEX = "release-evidence.json"
class Forge:
def __init__(self):
self.release = None
self.assets = {}
self.changes = []
self.tag_sha = SOURCE
def json(self, path, method="GET", payload=None, **kwargs):
if method == "POST":
self.changes.append("create")
assert payload["draft"] is True
self.release = {"id": 12, **payload}
return self.release
if method == "PATCH":
self.changes.append("publish")
self.release.update(payload)
return self.release
if path.endswith("/assets"):
return [{"name": name, "size": len(content)} for name, content in self.assets.items()]
if path.endswith(f"/releases/tags/{TAG}"):
return self.release
if path.endswith(f"/tags/{TAG}"):
return {"commit": {"sha": self.tag_sha}}
raise AssertionError(path)
def digest_attachment(self, asset, size):
return hashlib.sha256(self.assets[asset["name"]]).hexdigest()
def upload(self, service, release_path, path, record):
assert self.release["draft"]
self.changes.append(path.name)
self.assets[path.name] = path.read_bytes()
class PublishTest(unittest.TestCase):
def setUp(self):
folder = Path(self.enterContext(tempfile.TemporaryDirectory()))
self.assets = {}
for name, data in {"tool.tar.gz": b"tool", INDEX: b"evidence"}.items():
path = folder / name
path.write_bytes(data)
self.assets[name] = path, publish.asset_record(path, "x86_64-unknown-linux-gnu")
self.forge = Forge()
def run_publish(self):
return publish.publish_release(self.forge, TAG, SOURCE, self.assets, "notes")
def test_publish_verifies_draft_and_is_idempotent(self):
with patch.object(publish, "upload", self.forge.upload):
self.assertFalse(self.run_publish()["draft"])
self.run_publish()
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
def test_interruption_leaves_a_draft_and_resumes_only_missing_assets(self):
def fail_index(service, path, asset, record):
if asset.name == INDEX:
raise ConnectionError("interrupted")
self.forge.upload(service, path, asset, record)
with patch.object(publish, "upload", fail_index):
with self.assertRaises(ConnectionError):
self.run_publish()
self.assertTrue(self.forge.release["draft"])
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz"])
with patch.object(publish, "upload", self.forge.upload):
self.assertFalse(self.run_publish()["draft"])
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
def test_rejects_changed_public_bytes_and_a_moved_tag(self):
with patch.object(publish, "upload", self.forge.upload):
self.forge.tag_sha = "b" * 40
with self.assertRaisesRegex(publish.PublicationError, "tag moved"):
self.run_publish()
self.assertTrue(self.forge.release["draft"])
self.forge.tag_sha = SOURCE
self.run_publish()
self.forge.assets["tool.tar.gz"] = b"oops"
with self.assertRaisesRegex(publish.PublicationError, "published bytes differ"):
self.run_publish()
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
if __name__ == "__main__":
unittest.main()
+69
View File
@@ -0,0 +1,69 @@
"""Regression tests for the root task and Knowledge verification boundary."""
import hashlib
import importlib.util
import json
import unittest
from pathlib import Path
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("upstream", Path(__file__).with_name("verify-upstream.py"))
upstream = importlib.util.module_from_spec(spec)
spec.loader.exec_module(upstream)
def digest(value):
return hashlib.sha256(value.encode()).hexdigest()
class UpstreamTaskTest(unittest.TestCase):
def setUp(self):
self.source, self.consumer, self.root, self.index, self.asset = (c * n for c, n in
(("a", 40), ("b", 40), ("c", 40), ("d", 64), ("e", 64)))
self.tag = "v3.0.0-rc.6"
key = digest(f"{upstream.REPO}\n{self.tag}\n{self.source}")
inputs = {"consumer": {"id": "knowledge", "source_sha": self.consumer},
"accepted_dependencies": [],
"release": {"repository": upstream.REPO, "tag": self.tag, "source_sha": self.source,
"index_sha256": self.index, "dependencies": [],
"assets": [{"name": f"marqdo-{self.tag[1:]}-{upstream.TARGET}.tar.gz",
"sha256": self.asset, "target": upstream.TARGET, "size": 9}]}}
value = digest(json.dumps(inputs, sort_keys=True, separators=(",", ":")))
task = digest(f"{key}\nknowledge\n{value}")
user = {"login": upstream.COORDINATOR}
fence = chr(96) * 3
self.issue = {"state": "open", "user": user, "body":
f"<!-- marqdo:upstream release={key} consumer=knowledge -->\n"
f"<!-- marqdo:candidate-inputs {task} -->\n"
f"- Root tracking issue: {upstream.FORGE}/{upstream.ROOT_REPO}/issues/11\n"
f"- Root candidate: {self.root}\n- Input digest: {value}\n- State: pending\n"
f"\n{fence}json\n{json.dumps(inputs)}\n{fence}"}
self.tracker = {"state": "open", "user": user, "body":
f"<!-- marqdo:release-reconcile repository={upstream.REPO} tag={self.tag} -->\n"
f"<!-- marqdo:verified-release {self.source} {self.index} -->"}
self.branch = {"protected": True, "commit": {"id": self.root}}
def forge(self, opener, path):
if "comments?" in path:
return []
return {f"/repos/{upstream.CONSUMER}/issues/12": self.issue,
f"/repos/{upstream.ROOT_REPO}/branches/main": self.branch,
f"/repos/{upstream.ROOT_REPO}/issues/11": self.tracker}[path]
def run_verify(self):
with patch.object(upstream, "forge_json", self.forge):
return upstream.issue_input(None, 12, self.consumer)
def test_current_authorized_task_resolves_to_exact_cli(self):
self.assertEqual(self.run_verify(), (self.tag, self.source, self.asset))
def test_stale_root_and_wrong_task_author_are_rejected(self):
self.branch["commit"]["id"] = "f" * 40
with self.assertRaisesRegex(upstream.VerificationError, "stale"):
self.run_verify()
self.issue["user"] = {"login": "untrusted"}
with self.assertRaisesRegex(upstream.VerificationError, "reconcile account"):
self.run_verify()
if __name__ == "__main__":
unittest.main()
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Run Knowledge's real Analysis checks against an exact published CLI."""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
from pathlib import Path, PurePosixPath
ROOT = Path(__file__).resolve().parents[2]
FORGE = "https://git.cflmy.cn"
REPO = "cflmy/marqdo-cli"
CONSUMER = "cflmy/marqdo-knowledge"
COORDINATOR = "marqdo-reconcile"
ROOT_REPO = "cflmy/marqdo"
TARGET = "x86_64-unknown-linux-gnu"
MAX_ARCHIVE = 64 * 1024 * 1024
MAX_EXPANDED = 256 * 1024 * 1024
class VerificationError(Exception):
pass
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, fp, code, message, headers, newurl):
return None
def require(condition, message):
if not condition:
raise VerificationError(message)
def forge_json(opener, path):
with opener.open(FORGE + "/api/v1" + path, timeout=30) as response:
body = response.read(2 * 1024 * 1024 + 1)
require(len(body) <= 2 * 1024 * 1024, "forge response exceeds the size limit")
return json.loads(body)
def coordinator_notes(opener, path):
issue = forge_json(opener, path)
require(issue["state"] == "open" and issue["user"]["login"] == COORDINATOR,
"expected an open task from the reconcile account")
notes = [issue["body"]]
for page in range(1, 11):
batch = forge_json(opener, f"{path}/comments?limit=50&page={page}")
notes.extend(item["body"] for item in batch if item["user"]["login"] == COORDINATOR)
if len(batch) < 50:
return notes
raise VerificationError("too many task comments to verify safely")
def issue_input(opener, number, consumer_sha):
notes = coordinator_notes(opener, f"/repos/{CONSUMER}/issues/{number}")
marker = notes[0].splitlines()[0]
require(re.fullmatch(r"<!-- marqdo:upstream release=[0-9a-f]{64} consumer=knowledge -->", marker),
"task does not have a verified release marker")
body = next(note for note in reversed(notes) if note.splitlines()[:1] == [marker])
start = "\n```json\n"
require(body.count(start) == 1 and body.endswith("\n```"), "task has no candidate input data")
header, _, encoded = body.partition(start)
inputs = json.loads(encoded.removesuffix("\n```"))
digest = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
require(f"- Input digest: {digest}" in header.splitlines()
and "- State: pending" in header.splitlines(), "task input digest or state differs")
require(inputs["consumer"] == {"id": "knowledge", "source_sha": consumer_sha},
"task targets a different consumer commit")
release = inputs["release"]
tag, sha = release["tag"], release["source_sha"]
require(release["repository"] == REPO and release["index_sha256"], "task does not name a CLI release")
key = hashlib.sha256(f"{REPO}\n{tag}\n{sha}".encode()).hexdigest()
task_key = hashlib.sha256(f"{key}\nknowledge\n{digest}".encode()).hexdigest()
require(marker == f"<!-- marqdo:upstream release={key} consumer=knowledge -->"
and f"<!-- marqdo:candidate-inputs {task_key} -->" in header.splitlines(),
"task identity differs from the candidate input")
root_id = re.search(rf"(?m)^- Root tracking issue: {re.escape(FORGE)}/{ROOT_REPO}/issues/([1-9][0-9]*)$", header)
base = re.search(r"(?m)^- Root candidate: ([0-9a-f]{40})$", header)
require(root_id and base, "task lacks its root tracker or accepted baseline")
branch = forge_json(opener, f"/repos/{ROOT_REPO}/branches/main")
require(branch["protected"] and branch["commit"]["id"] == base[1], "task root baseline is stale")
tracker = coordinator_notes(opener, f"/repos/{ROOT_REPO}/issues/{root_id[1]}")
require(tracker[0].splitlines()[:1] == [f"<!-- marqdo:release-reconcile repository={REPO} tag={tag} -->"]
and any(f"<!-- marqdo:verified-release {sha} {release['index_sha256']} -->" in note.splitlines()
for note in tracker), "root tracker does not verify this producer release")
name = f"marqdo-{tag[1:]}-{TARGET}.tar.gz"
assets = [asset for asset in release["assets"] if asset["name"] == name and asset["target"] == TARGET]
require(len(assets) == 1, "task does not specify one Linux CLI archive")
return tag, sha, assets[0]["sha256"]
def copy_verified(stream, output, digest):
actual = hashlib.sha256()
size = 0
with output.open("wb") as destination:
while chunk := stream.read(1024 * 1024):
size += len(chunk)
require(size <= MAX_ARCHIVE, "CLI archive exceeds the size limit")
actual.update(chunk)
destination.write(chunk)
require(actual.hexdigest() == digest, "CLI archive SHA-256 does not match the candidate")
def unpack(archive, output, top):
seen = set()
total = 0
with tarfile.open(archive, "r:gz") as tar:
for member in tar:
path = PurePosixPath(member.name)
require(path.parts and path.parts[0] == top and ".." not in path.parts
and "\\" not in member.name and path not in seen
and (member.isfile() or member.isdir()), "unexpected CLI archive entry")
seen.add(path)
total += member.size
require(len(seen) <= 2048 and total <= MAX_EXPANDED, "CLI archive expansion exceeds limits")
tar.extractall(output, filter="data")
return output / top
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--issue", type=int, help="read an authoritative Knowledge propagation task")
parser.add_argument("--tag")
parser.add_argument("--source-sha")
parser.add_argument("--archive-sha256")
parser.add_argument("--archive", type=Path, help="use already downloaded bytes")
args = parser.parse_args()
if args.issue is not None and (args.issue < 1 or args.tag or args.source_sha or args.archive_sha256):
parser.error("--issue requires a positive number and supplies all candidate identities")
opener = urllib.request.build_opener(NoRedirect())
try:
consumer = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip()
require(not subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True),
"consumer checkout has uncommitted changes")
if args.issue is not None:
args.tag, args.source_sha, args.archive_sha256 = issue_input(opener, args.issue, consumer)
require(re.fullmatch(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?", args.tag or "")
and re.fullmatch(r"[0-9a-f]{40}", args.source_sha or "")
and re.fullmatch(r"[0-9a-f]{64}", args.archive_sha256 or ""),
"expected an exact tag, source SHA and Linux archive SHA-256")
top = f"marqdo-{args.tag[1:]}-{TARGET}"
tag = forge_json(opener, f"/repos/{REPO}/tags/{args.tag}")
require(tag["name"] == args.tag and tag["commit"]["sha"] == args.source_sha,
"authoritative CLI tag does not match the candidate")
with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-upstream-") as temporary:
work = Path(temporary)
archive = work / (top + ".tar.gz")
source = (args.archive.open("rb") if args.archive else opener.open(
f"{FORGE}/{REPO}/releases/download/{args.tag}/{archive.name}", timeout=45))
with source:
copy_verified(source, archive, args.archive_sha256)
release = unpack(archive, work, top)
metadata = json.loads((release / "RELEASE_INFO.json").read_text(encoding="utf-8"))
sha = (release / "SOURCE_SHA").read_text(encoding="utf-8").strip()
require(sha == args.source_sha == metadata["source_sha"]
and metadata["target_triple"] == TARGET, "CLI release identity or target does not match")
binary = release / "marqdo"
bundle = release / "stdlib"
require(binary.is_file() and os.access(binary, os.X_OK) and (bundle / "stdlib.json").is_file(),
"CLI archive lacks its executable or installed Bundle")
env = dict(os.environ, MARQDO_BIN=str(binary), MARQDO_STDLIB_DIR=str(bundle))
subprocess.run([ROOT / "scripts/ci.sh", "core"], cwd=ROOT, env=env, check=True)
require(subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip() == consumer,
"consumer identity changed during validation")
print(json.dumps({"consumer_sha": consumer, "task_issue": args.issue,
"cli_tag": args.tag, "cli_source_sha": sha, "archive_sha256": args.archive_sha256,
"target": TARGET, "status": "passed"}, sort_keys=True))
except (VerificationError, OSError, ValueError, KeyError, IndexError, TypeError,
tarfile.TarError, subprocess.CalledProcessError) as error:
print(f"upstream verification: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+236 -176
View File
@@ -1,26 +1,14 @@
#!/usr/bin/env python3
"""Create/update the prerelease on the project's Gitea forge and attach assets.
Reads the token from the environment (`GITEA_TOKEN` or `gitea_token`), never
prints or stores it. Idempotent: an existing release for the tag is updated and
existing assets are replaced so a re-run of the tag pipeline produces the same
release instead of failing.
Usage:
GITEA_TOKEN=... python3 tools/release/publish-gitea.py \
--tag v0.1.0-beta.2 \
--archive dist/marqdo-knowledge-...tar.gz \
--files dist/marqdo-knowledge-....sha256 dist/RELEASE_INFO.json \
dist/FILES.sha256 dist/smoke-evidence.json \
--body-file docs/releases/0.1.0-beta.2.md
"""
"""Publish the reviewed Knowledge artifact to a protected Gitea tag."""
from __future__ import annotations
import argparse
import hashlib
import json
import mimetypes
import os
import re
import subprocess
import sys
import urllib.error
import urllib.parse
@@ -28,182 +16,254 @@ import urllib.request
import uuid
from pathlib import Path
DEFAULT_API = "https://git.cflmy.cn/api/v1"
DEFAULT_REPO = "cflmy/marqdo-knowledge"
FORGE = "https://git.cflmy.cn"
CI = "https://ci.cflmy.cn"
REPO = "cflmy/marqdo-knowledge"
ROOT = Path(__file__).resolve().parents[2]
TAG = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?")
SHA = re.compile(r"[a-f0-9]{40}")
DIGEST = re.compile(r"[a-f0-9]{64}")
BASENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,180}")
MAX_ASSET = 256 * 1024 * 1024
def fail(message: str) -> "NoReturn":
print(f"publish-gitea: FAIL: {message}", file=sys.stderr)
raise SystemExit(1)
class PublicationError(Exception):
pass
def token() -> str:
value = os.environ.get("GITEA_TOKEN") or os.environ.get("gitea_token")
if not value:
fail("GITEA_TOKEN (or gitea_token) is not set")
return value
def require(condition, reason):
if not condition:
raise PublicationError(reason)
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=60) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def decode(body: bytes) -> object:
try:
return json.loads(body)
except Exception:
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def create_or_update_release(
api: str, repo: str, tag: str, body: str, token_value: str
) -> dict:
path = f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}"
status, response = request(api, "GET", path, token_value)
payload = {
"tag_name": tag,
"name": f"marqdo-knowledge {tag.removeprefix('v')}",
"prerelease": True,
"draft": False,
"body": body,
}
if status == 200:
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
fail("existing release response is malformed")
status, response = request(
api, "PATCH", f"/repos/{repo}/releases/{release['id']}", token_value, payload
)
if status != 200:
fail(f"updating the existing release failed with HTTP {status}")
release = decode(response)
print(f"updated release id={release.get('id')} tag={tag}")
return release
if status != 404:
fail(f"looking up the release failed with HTTP {status}")
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
if status not in (201, 200):
fail(f"creating the release failed with HTTP {status}")
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
fail("release create response is malformed")
print(f"created release id={release.get('id')} tag={tag}")
return release
class Service:
def __init__(self, token):
self.token = token
self.opener = urllib.request.build_opener(NoRedirect())
def open(self, url, method="GET", data=None, content_type=None, authenticate=False):
headers = {"Accept": "application/json"}
if authenticate and self.token:
headers["Authorization"] = f"token {self.token}"
if content_type:
headers["Content-Type"] = content_type
request = urllib.request.Request(url, headers=headers, data=data, method=method)
return self.opener.open(request, timeout=45)
def json(self, path, method="GET", payload=None, *, missing_ok=False, ci=False, upload=None):
if upload is not None:
data, content_type = upload
elif payload is not None:
data, content_type = json.dumps(payload).encode(), "application/json"
else:
data, content_type = None, None
url = (CI + "/api" if ci else FORGE + "/api/v1") + path
try:
with self.open(url, method, data, content_type, authenticate=not ci) as response:
raw = response.read(2 * 1024 * 1024 + 1)
require(len(raw) <= 2 * 1024 * 1024, f"{method} {path}: response too large")
return json.loads(raw)
except urllib.error.HTTPError as error:
if missing_ok and error.code == 404:
return None
raise PublicationError(f"{method} {path}: HTTP {error.code}") from error
def digest_attachment(self, attachment, size):
identity = uuid.UUID(attachment["uuid"])
with self.open(f"{FORGE}/attachments/{identity}", authenticate=True) as response:
return consume(response, size)
def upload_asset(
api: str, repo: str, release_id: int, path: Path, token_value: str
) -> dict:
name = path.name
status, response = request(
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
)
if status == 200:
existing = decode(response)
if isinstance(existing, list):
for asset in existing:
if asset.get("name") == name:
request(
api,
"DELETE",
f"/repos/{repo}/releases/{release_id}/assets/{asset['id']}",
token_value,
)
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 (201, 200):
fail(f"uploading asset {name} failed with HTTP {status}")
result = decode(response)
print(f"uploaded asset {name} ({path.stat().st_size} bytes)")
return result if isinstance(result, dict) else {}
def consume(stream, limit):
digest = hashlib.sha256()
size = 0
while block := stream.read(min(1024 * 1024, limit - size + 1)):
size += len(block)
require(size <= limit, "asset exceeds its recorded size")
digest.update(block)
require(size == limit, "asset size differs from its record")
return digest.hexdigest()
def main() -> int:
def asset_record(path, target):
require(path.is_file() and BASENAME.fullmatch(path.name), f"invalid asset {path}")
size = path.stat().st_size
require(0 < size <= MAX_ASSET, f"invalid size for {path.name}")
with path.open("rb") as stream:
return {"name": path.name, "target": target, "size": size,
"sha256": consume(stream, size)}
def ready_ci(service, head, number, repo):
repository = service.json(f"/repos/lookup/{REPO}", ci=True)
require(repository["full_name"] == REPO and repository["forge_remote_id"] == str(repo["id"]),
"Woodpecker repository identity differs from the forge")
ci_id = repository["id"]
run = service.json(f"/repos/{ci_id}/pipelines/{number}", ci=True)
require(run["number"] == number and run["commit"] == head and run["status"] == "success"
and run["ref"] == f"refs/heads/{repo['default_branch']}"
and run["event"] in {"push", "manual"} and not run.get("from_fork")
and any(w["name"] == "ci" and w["state"] == "success"
and any(s["name"] == "test" and s["state"] == "success" for s in w["children"])
for w in run["workflows"]),
"release requires successful default-branch component CI for this exact SHA")
return {"pipeline_number": number, "source_sha": head,
"url": f"{CI}/repos/{ci_id}/pipeline/{number}"}
def candidate(service, tag, pipeline, paths, *, publish):
repository = service.json(f"/repos/{REPO}")
branch = repository["default_branch"]
branch_info = service.json(f"/repos/{REPO}/branches/{urllib.parse.quote(branch, safe='')}")
head = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip()
status = subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True)
require(not status and SHA.fullmatch(head), "release requires a clean checkout")
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
branch_sha = branch_info["commit"]["id"]
require(tag_info["name"] == tag and tag_info["commit"]["sha"] == head
and SHA.fullmatch(branch_sha), "tag and checkout do not match")
ancestry = subprocess.run(["git", "-C", ROOT, "merge-base", "--is-ancestor", head, branch_sha],
capture_output=True, check=False)
require(ancestry.returncode == 0, "tag is outside the verified default-branch history; fetch first")
if publish:
actor = service.json("/user")
require(actor["login"] == "marqdo-publisher" and actor.get("is_admin") is False,
"publication requires the non-admin publisher account")
require(branch_info["protected"] is True, "default branch must be protected")
ci = ready_ci(service, head, pipeline, repository)
archive = paths[0]
info = json.loads((archive.parent / "RELEASE_INFO.json").read_text())
smoke = json.loads((archive.parent / "smoke-evidence.json").read_text())
records = [asset_record(path, info["target"]) for path in paths]
core_sha = smoke.get("core_source_sha", "")
core_digest = smoke.get("core_binary_sha256", "")
require(info["product"] == "marqdo-knowledge" and info["source_sha"] == head
and f"v{info['product_version']}" == tag
and smoke["source_sha"] == head and smoke["version"] == info["product_version"]
and smoke["archive"] == archive.name and smoke["archive_sha256"] == records[0]["sha256"]
and SHA.fullmatch(core_sha) and DIGEST.fullmatch(core_digest),
"package or cold-install evidence does not match the candidate")
checksum = (archive.parent / f"{archive.name}.sha256").read_text().split()
require(checksum == [records[0]["sha256"], archive.name], "archive checksum sidecar mismatch")
return {"component_id": "knowledge", "repository": REPO, "tag": tag, "source_sha": head,
"ci": ci, "assets": records,
"dependencies": [{"id": "cli", "source_sha": core_sha, "asset_sha256": core_digest}]}
def inventory(service, release_path):
attachments = service.json(release_path + "/assets")
require(isinstance(attachments, list), "invalid attachment inventory")
by_name = {item["name"]: item for item in attachments}
require(len(by_name) == len(attachments), "duplicate names in the release")
return by_name
def check_assets(service, attachments, expected, complete):
require(attachments.keys() <= expected.keys(), "unexpected attachment in release")
require(not complete or attachments.keys() == expected.keys(), "incomplete release assets")
for name, remote in attachments.items():
_, record = expected[name]
require(remote["size"] == record["size"]
and service.digest_attachment(remote, record["size"]) == record["sha256"],
f"published bytes differ for {name}")
def upload(service, release_path, path, record):
with path.open("rb") as stream:
data = stream.read(record["size"] + 1)
require(len(data) == record["size"] and hashlib.sha256(data).hexdigest() == record["sha256"],
f"local asset changed: {path.name}")
boundary = uuid.uuid4().hex
header = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="attachment"; filename="{path.name}"\r\n'
"Content-Type: application/octet-stream\r\n\r\n"
).encode()
body = header + data + f"\r\n--{boundary}--\r\n".encode()
service.json(release_path + "/assets?" + urllib.parse.urlencode({"name": path.name}),
"POST", upload=(body, f"multipart/form-data; boundary={boundary}"))
def publish_release(service, tag, source, expected, notes):
releases = f"/repos/{REPO}/releases"
by_tag = releases + "/tags/" + urllib.parse.quote(tag, safe="")
release = service.json(by_tag, missing_ok=True)
if release is None:
release = service.json(releases, "POST", {
"tag_name": tag, "target_commitish": source, "name": f"marqdo-knowledge {tag[1:]}",
"body": notes, "prerelease": True, "draft": True,
})
require(release["draft"], "forge did not create a draft release")
require(release["tag_name"] == tag and release["prerelease"], "existing release identity differs")
release_path = f"{releases}/{release['id']}"
attachments = inventory(service, release_path)
check_assets(service, attachments, expected, complete=not release["draft"])
if release["draft"]:
for name, (path, record) in expected.items():
if name not in attachments:
upload(service, release_path, path, record)
check_assets(service, inventory(service, release_path), expected, complete=True)
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
require(tag_info["commit"]["sha"] == source, "tag moved during draft publication")
service.json(release_path, "PATCH", {"draft": False})
confirmed = service.json(by_tag)
require(confirmed["id"] == release["id"] and not confirmed["draft"] and confirmed["prerelease"],
"public release identity changed")
check_assets(service, inventory(service, release_path), expected, complete=True)
return confirmed
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
parser.add_argument("--repo", default=DEFAULT_REPO)
parser.add_argument("--tag", required=True)
parser.add_argument("--archive", required=True)
parser.add_argument("--files", nargs="*", default=[])
parser.add_argument("--body-file", required=True)
parser.add_argument("--evidence-out", default="dist/gitea-release-evidence.json")
parser.add_argument("--pipeline", type=int, required=True)
parser.add_argument("--archive", type=Path, required=True)
parser.add_argument("--files", nargs="*", type=Path, default=[])
parser.add_argument("--body-file", type=Path)
parser.add_argument("--prepare", action="store_true", help="write the evidence index without using a token")
parser.add_argument("--evidence-out", type=Path, default=Path("dist/gitea-release-evidence.json"))
args = parser.parse_args()
token_value = token()
archive = Path(args.archive)
if not archive.is_file():
fail(f"archive {archive} does not exist")
body = Path(args.body_file).read_text(encoding="utf-8")
release = create_or_update_release(args.api_url, args.repo, args.tag, body, token_value)
release_id = release["id"]
assets = [archive]
assets.extend(Path(item) for item in args.files if Path(item).is_file())
uploaded = []
for path in assets:
result = upload_asset(args.api_url, args.repo, release_id, path, token_value)
uploaded.append(
{
"name": path.name,
"size": path.stat().st_size,
"sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest(),
"browser_url": result.get("browser_download_url"),
}
)
evidence = {
"schema": "marqdo.knowledge.gitea-release",
"schema_version": 1,
"tag": args.tag,
"release_id": release_id,
"html_url": release.get("html_url"),
"prerelease": True,
"assets": uploaded,
}
evidence_path = Path(args.evidence_out)
evidence_path.parent.mkdir(parents=True, exist_ok=True)
evidence_path.write_text(
json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
encoding="utf-8",
)
print(f"release_url: {release.get('html_url')}")
print(f"evidence: {evidence_path}")
if not TAG.fullmatch(args.tag) or args.pipeline < 1:
parser.error("expected a release tag and a positive component CI pipeline number")
value = "" if args.prepare else os.environ.get("GITEA_TOKEN", "")
if not args.prepare and (not value or args.body_file is None):
parser.error("publication requires GITEA_TOKEN and --body-file")
try:
archive = args.archive.resolve()
folder = archive.parent
defaults = [folder / name for name in
(archive.name + ".sha256", "RELEASE_INFO.json", "FILES.sha256", "smoke-evidence.json")]
paths = list(dict.fromkeys([archive, *defaults, *(path.resolve() for path in args.files)]))
require(len(paths) <= 20, "too many release assets")
index = folder / "release-evidence.json"
require(index.name not in {path.name for path in paths}
and len({path.name for path in paths}) == len(paths), "duplicate release asset names")
service = Service(value)
proof = candidate(service, args.tag, args.pipeline, paths, publish=not args.prepare)
index.write_text(json.dumps(proof, sort_keys=True, indent=2) + "\n", encoding="utf-8")
if args.prepare:
print(index)
return 0
expected = {record["name"]: (path, record) for path, record in
zip(paths, proof["assets"], strict=True)}
expected[index.name] = (index, asset_record(index, proof["assets"][0]["target"]))
release = publish_release(service, args.tag, proof["source_sha"], expected,
args.body_file.read_text(encoding="utf-8"))
evidence = {"schema": "marqdo.knowledge.gitea-release", "schema_version": 1,
"tag": args.tag, "release_id": release["id"], "html_url": release["html_url"],
"prerelease": True, "assets": [record for _, record in expected.values()]}
args.evidence_out.parent.mkdir(parents=True, exist_ok=True)
args.evidence_out.write_text(json.dumps(evidence, sort_keys=True, indent=2) + "\n", encoding="utf-8")
print(f"release_url: {release['html_url']}")
except (OSError, ValueError, KeyError, TypeError, PublicationError, subprocess.CalledProcessError) as error:
print(f"publish-gitea: FAIL: {error}", file=sys.stderr)
return 1
return 0
+15 -7
View File
@@ -58,7 +58,7 @@ def main() -> int:
parser.add_argument("--evidence-out", default="")
args = parser.parse_args()
marqdo = Path(args.marqdo_bin)
marqdo = Path(args.marqdo_bin).resolve()
if not marqdo.is_file():
fail("set --marqdo-bin or MARQDO_BIN to a real core CLI binary")
archive = Path(args.archive).resolve()
@@ -190,17 +190,25 @@ def main() -> int:
"query_hits": len(query_report["hits"]),
"database": check_report["payload"]["database"],
}
print(json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False))
if args.evidence_out:
Path(args.evidence_out).write_text(
json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
encoding="utf-8",
)
finally:
run([str(marqdo), "tool", "remove", "knowledge"], env=env)
remaining = run([str(marqdo), "tool", "list"], env=env)
if "knowledge" in remaining:
fail("tool was not removed")
core_info_path = marqdo.with_name("RELEASE_INFO.json")
source_path = marqdo.with_name("SOURCE_SHA")
if core_info_path.is_file() and source_path.is_file():
core_info = json.loads(core_info_path.read_text(encoding="utf-8"))
core_source = source_path.read_text(encoding="utf-8").strip()
core_digest = sha256_file(marqdo)
if (core_info.get("source_sha") != core_source
or core_info.get("binaries", {}).get("marqdo", {}).get("sha256") != core_digest):
fail("core executable does not match its release metadata")
evidence.update(core_source_sha=core_source, core_binary_sha256=core_digest)
rendered = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False)
print(rendered)
if args.evidence_out:
Path(args.evidence_out).write_text(rendered + "\n", encoding="utf-8")
print("smoke: OK")
return 0