diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a0d6715..492af13 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: with: components: rustfmt, clippy - uses: Swatinem/rust-cache@v2 + - name: Release metadata consistency + run: python3 tools/ci/test_release_metadata.py - run: cargo fmt --all -- --check - run: cargo clippy --workspace --all-targets --locked -- -D warnings - run: cargo test --workspace --locked @@ -74,13 +76,14 @@ jobs: cd /tmp/marqdo-cli git checkout --quiet "$CORE_SHA" cargo build --release --locked -p marqdo-cli - - name: Package and cold-install smoke + - name: Deterministic package and cold-install smoke env: MARQDO_BIN: /tmp/marqdo-cli/target/release/marqdo - SOURCE_SHA: ${{ github.sha }} run: | - scripts/package-release.sh - scripts/verify-release.sh + version="$(python3 -c 'import re,pathlib;print(re.search(r"(?m)^version\s*=\s*\"([^\"]+)\"", pathlib.Path("Cargo.toml").read_text()).group(1))')" + python3 tools/release/package.py --source-sha "${{ github.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 + cat dist/RELEASE_INFO.json dist/*.tar.gz.sha256 dist/smoke-evidence.json - name: Upload release archive uses: actions/upload-artifact@v4 with: @@ -89,6 +92,8 @@ jobs: dist/*.tar.gz dist/*.sha256 dist/RELEASE_INFO.json + dist/FILES.sha256 + dist/smoke-evidence.json - name: Publish GitHub prerelease uses: softprops/action-gh-release@v2 with: @@ -97,4 +102,6 @@ jobs: dist/*.tar.gz dist/*.sha256 dist/RELEASE_INFO.json - body_path: docs/releases/0.1.0-beta.1.md + dist/FILES.sha256 + dist/smoke-evidence.json + body_path: docs/releases/0.1.0-beta.2.md diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 4f8e174..148baa8 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -11,8 +11,9 @@ steps: image: rust:1.100-bookworm commands: - apt-get update - - apt-get install -y --no-install-recommends ca-certificates + - apt-get install -y --no-install-recommends ca-certificates python3 - rustup component add clippy rustfmt + - python3 tools/ci/test_release_metadata.py - cargo fmt --all -- --check - cargo clippy --workspace --all-targets --locked -- -D warnings - cargo test --workspace --locked @@ -57,7 +58,9 @@ steps: ( cd "$work/core" && git checkout --quiet "$core_sha" \ && cargo build --release --locked -p marqdo-cli ) export MARQDO_BIN="$work/core/target/release/marqdo" - SOURCE_SHA="$CI_COMMIT_SHA" scripts/package-release.sh - scripts/verify-release.sh + version="$(python3 -c 'import re,pathlib;print(re.search(r"(?m)^version\s*=\s*\"([^\"]+)\"", pathlib.Path("Cargo.toml").read_text()).group(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 - cat dist/RELEASE_INFO.json - cat dist/*.tar.gz.sha256 + - cat dist/smoke-evidence.json diff --git a/docs/ci.md b/docs/ci.md index dd9b490..fb1e1f6 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -12,10 +12,14 @@ Configurations: - `.github/workflows/ci.yml` — GitHub Actions mirror (push, pull_request, tag). - `scripts/ci.sh` — the same lanes locally (`test`, `minimum`, `core`, `release`, `all`). -- `scripts/package-release.sh` — locked release build, archive, - `SOURCE_SHA`/`RELEASE_INFO.json`, SHA-256 checksum. -- `scripts/verify-release.sh` — cold install in an isolated - `MARQDO_TOOL_HOME`, dispatch, compile/query/check smoke, remove. +- `tools/release/package.py` — deterministic archive, `SOURCE_SHA`, + `FILES.sha256`, `RELEASE_INFO.json`, SHA-256 sidecar. +- `tools/release/smoke.py` — checksum/manifest/version verification and cold + install in an isolated `MARQDO_TOOL_HOME` (install, help, compile/query/check, + remove; writes `dist/smoke-evidence.json`). +- `tools/ci/test_release_metadata.py` — version/fact consistency gate. +- `scripts/package-release.sh` / `scripts/verify-release.sh` — thin wrappers for + the Python tooling. ## Pinned core boundary @@ -30,13 +34,14 @@ recording a new Analysis fixture artifact. | Gate | Command | |---|---| +| release metadata consistency | `python3 tools/ci/test_release_metadata.py` | | formatting | `cargo fmt --all -- --check` | | lints | `cargo clippy --workspace --all-targets --locked -- -D warnings` | | unit + integration tests | `cargo test --workspace --locked` | | real core CLI boundary | `MARQDO_TEST_BIN= cargo test --workspace --locked` | | minimum Rust | `cargo +1.89 check --locked --workspace --all-targets` | | release build | `cargo build --release --locked` | -| package + cold install | `scripts/package-release.sh && scripts/verify-release.sh` | +| deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` | ## Not gated by CI (explicit non-claims) diff --git a/docs/releasing.md b/docs/releasing.md index f9d780f..21f7e7e 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,6 @@ # Releasing marqdo-knowledge -This project is on the **beta** channel (`0.1.0-beta.N`). A beta release claims +This project is on the **beta** channel (`0.1.0-beta.N`); current version `0.1.0-beta.2`. A beta release claims only what the pipeline and recorded evidence establish. It does **not** claim stable quality gates, and the development specification's §16 retrieval and performance targets remain NOT RUN. @@ -40,11 +40,14 @@ substitute for the pipeline run recorded for the release commit, and vice versa. MARQDO_BIN=/path/to/marqdo scripts/ci.sh release ``` -This runs `scripts/package-release.sh` (refuses a dirty tree or mismatched -`SOURCE_SHA`, emits `dist/marqdo-knowledge--.tar.gz`, -`.sha256` and `RELEASE_INFO.json`) and `scripts/verify-release.sh` (extracts the -archive in a clean directory, installs it into an isolated `MARQDO_TOOL_HOME`, -runs `knowledge --help`, compile/query/check smoke, removes the tool). +This runs the deterministic packager (`tools/release/package.py`: refuses a +dirty tree or mismatched `SOURCE_SHA`, emits +`dist/marqdo-knowledge--.tar.gz`, `.sha256`, `FILES.sha256`, +`RELEASE_INFO.json`) and the smoke verifier (`tools/release/smoke.py`: checksum, +manifest, source SHA and version checks, then installs the archive into an +isolated `MARQDO_TOOL_HOME`, runs help/compile/query/check and removes the +tool). Two package runs from the same commit, binary and toolchain must produce +the same archive SHA-256. Record the archive name and SHA-256 in the tag annotation and release page. Do not commit build artifacts: `dist/` is ignored. @@ -52,7 +55,7 @@ not commit build artifacts: `dist/` is ignored. ## 4. Tag and publish (beta) ```sh -git tag -a v0.1.0-beta.1 -m "marqdo-knowledge 0.1.0-beta.1; archive sha256 " +git tag -a v0.1.0-beta.N -m "marqdo-knowledge 0.1.0-beta.N; archive sha256 " git push origin master --tags ``` diff --git a/scripts/ci.sh b/scripts/ci.sh index 081f966..23fc17c 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -23,6 +23,7 @@ cd "$ROOT" lane_test() { echo "== lane: test ==" + python3 tools/ci/test_release_metadata.py "$CARGO" fmt --all -- --check "$CARGO" clippy --all-targets --locked -- -D warnings "$CARGO" test --workspace --locked diff --git a/scripts/package-release.sh b/scripts/package-release.sh index 8046a96..c63b6e1 100755 --- a/scripts/package-release.sh +++ b/scripts/package-release.sh @@ -1,62 +1,16 @@ #!/bin/sh -# Build a reproducible release archive from the exact current commit. +# Thin wrapper around the deterministic Python packager. # -# Refuses a dirty tree (unless ALLOW_DIRTY=1), records SOURCE_SHA and -# RELEASE_INFO.json inside the bundle, and emits a sha256 checksum. CI sets -# SOURCE_SHA=CI_COMMIT_SHA; the value must match HEAD or packaging fails. +# SOURCE_SHA=<40-hex> scripts/package-release.sh [--out-dir dist] +# +# Requires a clean tree matching HEAD, a locked release build in +# target/release/marqdo-knowledge and the version declared in Cargo.toml. set -eu ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' "$ROOT/Cargo.toml" | head -1) -TARGET=${TARGET:-x86_64-unknown-linux-gnu} -SPEC_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)} -HEAD_SHA=$(git -C "$ROOT" rev-parse HEAD) -DIRTY=$(git -C "$ROOT" status --porcelain) - -if [ "${ALLOW_DIRTY:-0}" != "1" ] && [ -n "$DIRTY" ]; then - echo "package-release: working tree is dirty; commit or pass ALLOW_DIRTY=1" >&2 - exit 2 -fi -if [ "$SPEC_SHA" != "$HEAD_SHA" ]; then - echo "package-release: SOURCE_SHA $SPEC_SHA does not match HEAD $HEAD_SHA" >&2 - exit 2 -fi - -"$ROOT/scripts/cargo.sh" build --release --locked - -DIST="$ROOT/dist/marqdo-knowledge-$VERSION-$TARGET" -rm -rf "$DIST" -mkdir -p "$DIST/bin" "$DIST/docs" "$DIST/spec" "$DIST/docs/releases" -cp "$ROOT/target/release/marqdo-knowledge" "$DIST/bin/marqdo-knowledge" -chmod 755 "$DIST/bin/marqdo-knowledge" -cp "$ROOT/packaging/tool.json" "$DIST/tool.json" -cp "$ROOT/README.md" "$ROOT/CHANGELOG.md" "$ROOT/LICENSE-APACHE" "$DIST/" -cp "$ROOT/docs/STATUS.md" "$DIST/docs/" -cp -r "$ROOT/docs/architecture" "$DIST/docs/" -cp -r "$ROOT/docs/releases/." "$DIST/docs/releases/" -cp "$ROOT/spec/knowledge.md" "$DIST/spec/" -printf '%s\n' "$SPEC_SHA" > "$DIST/SOURCE_SHA" -cat > "$DIST/RELEASE_INFO.json" < "$(basename "$ARCHIVE").sha256" ) -printf 'archive: %s\n' "$ARCHIVE" -cat "$ARCHIVE.sha256" +SOURCE_SHA=${SOURCE_SHA:-$(git -C "$ROOT" rev-parse HEAD)} +OUT_DIR=${OUT_DIR:-dist} +python3 "$ROOT/tools/release/package.py" \ + --source-sha "$SOURCE_SHA" \ + --version "$VERSION" \ + --out-dir "$OUT_DIR" diff --git a/scripts/verify-release.sh b/scripts/verify-release.sh index 8e069da..e7ca349 100755 --- a/scripts/verify-release.sh +++ b/scripts/verify-release.sh @@ -1,51 +1,13 @@ #!/bin/sh -# Cold-install the packaged release archive through a real core CLI and run the -# documented smoke path: install -> help -> compile -> query -> check -> remove. +# Thin wrapper around the cold-install smoke test. +# +# MARQDO_BIN=/path/to/marqdo scripts/verify-release.sh [ARCHIVE] set -eu ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) MARQDO=${MARQDO_BIN:?set MARQDO_BIN to the core marqdo binary} VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' "$ROOT/Cargo.toml" | head -1) TARGET=${TARGET:-x86_64-unknown-linux-gnu} -ARCHIVE="$ROOT/dist/marqdo-knowledge-$VERSION-$TARGET.tar.gz" - -test -f "$ARCHIVE" -( cd "$ROOT/dist" && sha256sum -c "$(basename "$ARCHIVE").sha256" ) -WORK=$(mktemp -d) -TOOL_HOME=$(mktemp -d) -trap 'rm -rf "$WORK" "$TOOL_HOME"' EXIT -tar -xzf "$ARCHIVE" -C "$WORK" -PKG="$WORK/marqdo-knowledge-$VERSION-$TARGET" -export MARQDO_TOOL_HOME="$TOOL_HOME" - -"$MARQDO" tool install "$PKG" -"$MARQDO" tool list | grep -q knowledge -"$MARQDO" knowledge --help >/dev/null -"$MARQDO" knowledge compile "$ROOT/examples/mixed" --json > "$WORK/compile.json" -"$MARQDO" knowledge query '归一化' --root "$ROOT/examples/mixed" --format json > "$WORK/query.json" -"$MARQDO" knowledge check "$ROOT/examples/mixed" --json > "$WORK/check.json" -python3 - "$WORK" <<'PY' -import json, sys -work = sys.argv[1] -compile_report = json.load(open(f"{work}/compile.json")) -query_report = json.load(open(f"{work}/query.json")) -check_report = json.load(open(f"{work}/check.json")) -assert compile_report["success"] and compile_report["payload"]["documents"] > 0 -assert query_report["success"] and len(query_report["hits"]) > 0 -assert check_report["success"] and check_report["payload"]["errors"] == 0 -assert check_report["payload"]["database"] == "current" -print( - "smoke: compile documents=%s query_hits=%s database=%s" - % ( - compile_report["payload"]["documents"], - len(query_report["hits"]), - check_report["payload"]["database"], - ) -) -PY -"$MARQDO" tool remove knowledge -if "$MARQDO" tool list | grep -q knowledge; then - echo "verify-release: tool was not removed" >&2 - exit 1 -fi -printf 'verify-release: ok (v%s, core %s, sha %s)\n' \ - "$VERSION" "$("$MARQDO" --version)" "$(cat "$PKG/SOURCE_SHA")" +ARCHIVE=${1:-"$ROOT/dist/marqdo-knowledge-$VERSION-$TARGET.tar.gz"} +MARQDO_BIN="$MARQDO" python3 "$ROOT/tools/release/smoke.py" \ + --archive "$ARCHIVE" \ + --evidence-out "$ROOT/dist/smoke-evidence.json" diff --git a/tools/ci/__pycache__/test_release_metadata.cpython-314.pyc b/tools/ci/__pycache__/test_release_metadata.cpython-314.pyc new file mode 100644 index 0000000..a3589b9 Binary files /dev/null and b/tools/ci/__pycache__/test_release_metadata.cpython-314.pyc differ diff --git a/tools/ci/test_release_metadata.py b/tools/ci/test_release_metadata.py new file mode 100755 index 0000000..30acccc --- /dev/null +++ b/tools/ci/test_release_metadata.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Metadata consistency gate for the beta release. + +Checks that the tool version, Cargo files, tool manifest, public spec, changelog, +release notes and CI configuration describe the same facts. This is a +documentation/contract gate, not a functional test. +""" + +from __future__ import annotations + +import json +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def fail(message: str) -> "NoReturn": + print(f"release-metadata: FAIL: {message}", file=sys.stderr) + raise SystemExit(1) + + +def main() -> int: + cargo = (ROOT / "Cargo.toml").read_text(encoding="utf-8") + match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', cargo) + if not match: + fail("Cargo.toml has no version") + version = match.group(1) + if not re.fullmatch(r"\d+\.\d+\.\d+-beta\.\d+", version): + fail(f"version {version} is not a beta semver (expected x.y.z-beta.N)") + lock = (ROOT / "Cargo.lock").read_text(encoding="utf-8") + if not re.search( + r'\[\[package\]\]\nname = "marqdo-knowledge"\nversion = "' + re.escape(version) + r'"', + lock, + ): + fail("Cargo.lock version does not match Cargo.toml") + + tool = json.loads((ROOT / "packaging/tool.json").read_text(encoding="utf-8")) + expected = { + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "marqdo-knowledge", + "version": version, + "command": "knowledge", + "entrypoint": "bin/marqdo-knowledge", + "requires": {"api_revision": 1, "analysis": 3}, + } + if tool != expected: + fail(f"packaging/tool.json is not the current exact manifest: {tool}") + + spec = (ROOT / "spec/knowledge.md").read_text(encoding="utf-8") + if f'"version": "{version}"' not in spec: + fail("spec/knowledge.md tool identity version is stale") + if '"requires": {"api_revision": 1, "analysis": 3}' not in spec: + fail("spec/knowledge.md requirements are stale") + + changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + if f"## {version}" not in changelog: + fail("CHANGELOG.md has no section for this version") + notes = ROOT / "docs/releases" / f"{version}.md" + if not notes.is_file(): + fail(f"missing docs/releases/{version}.md") + body = notes.read_text(encoding="utf-8") + for heading in ("What is complete in this beta", "What is NOT complete in this beta", "Compatibility and upgrade notes"): + if heading not in body: + fail(f"release notes are missing section `{heading}`") + + readme = (ROOT / "README.md").read_text(encoding="utf-8") + if version not in readme: + fail("README.md does not mention the current version") + + for configuration in (".woodpecker/main.yml", ".github/workflows/ci.yml"): + text = (ROOT / configuration).read_text(encoding="utf-8") + if "tools/release/package.py" not in text: + fail(f"{configuration} does not use the deterministic packager") + if "tools/release/smoke.py" not in text: + fail(f"{configuration} does not run the archive smoke test") + + ci_docs = (ROOT / "docs/ci.md").read_text(encoding="utf-8") + if "NOT RUN" not in ci_docs: + fail("docs/ci.md must state the non-gated items") + print(f"release-metadata: OK (version {version})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/__pycache__/package.cpython-314.pyc b/tools/release/__pycache__/package.cpython-314.pyc new file mode 100644 index 0000000..7ce124c Binary files /dev/null and b/tools/release/__pycache__/package.cpython-314.pyc differ diff --git a/tools/release/__pycache__/smoke.cpython-314.pyc b/tools/release/__pycache__/smoke.cpython-314.pyc new file mode 100644 index 0000000..dcafa54 Binary files /dev/null and b/tools/release/__pycache__/smoke.cpython-314.pyc differ diff --git a/tools/release/package.py b/tools/release/package.py new file mode 100755 index 0000000..cac6b99 --- /dev/null +++ b/tools/release/package.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Build the deterministic marqdo-knowledge beta release archive. + +The archive is reproducible: sorted entries, commit timestamp for all mtimes, +uid/gid 0, normalised modes, gzip without a timestamp. It refuses a dirty tree, +a version that does not match `Cargo.toml`, or a HEAD that differs from +`--source-sha`. It never publishes anything; tagging is a separate reviewed +step. + +Usage (from the repository root, after `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)" +""" + +from __future__ import annotations + +import argparse +import datetime +import gzip +import hashlib +import json +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +TARGET = "x86_64-unknown-linux-gnu" +CORE_BASELINE = ( + "cflmy/marqdo-cli@4bbefc92449ee480c8a2c89b0308feb4cda8d0e7 (3.0.0-rc.4)" +) +COPY_FILES = ( + "tool.json", + "README.md", + "LICENSE-APACHE", + "CHANGELOG.md", + "docs/STATUS.md", + "docs/ci.md", + "docs/releasing.md", +) +COPY_TREES = ( + "docs/architecture", + "docs/releases", + "examples", + "spec", +) +SKIP_TREE_PARTS = {".git", ".marqdo", "target", "dist", ".cargo-home", ".scratch"} +SKIP_SUFFIXES = {".sqlite", ".sqlite-journal", ".sqlite-wal", ".sqlite-shm"} + + +def fail(message: str) -> "NoReturn": + print(f"package: error: {message}", file=sys.stderr) + raise SystemExit(1) + + +def run(command: list[str], *, cwd: Path = ROOT, capture: bool = False) -> str: + completed = subprocess.run( + command, + cwd=cwd, + check=True, + text=True, + capture_output=capture, + ) + return completed.stdout.strip() if capture else "" + + +def git(*args: str) -> str: + return run(["git", *args], capture=True) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def cargo_version() -> str: + text = (ROOT / "Cargo.toml").read_text(encoding="utf-8") + match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text) + if not match: + fail("Cargo.toml has no package version") + return match.group(1) + + +def check_version_consistency(version: str) -> None: + if cargo_version() != version: + fail(f"--version {version} does not match Cargo.toml {cargo_version()}") + lock = (ROOT / "Cargo.lock").read_text(encoding="utf-8") + match = re.search( + r'\[\[package\]\]\nname = "marqdo-knowledge"\nversion = "([^"]+)"', lock + ) + if not match or match.group(1) != version: + fail("Cargo.lock marqdo-knowledge version does not match Cargo.toml") + tool = json.loads((ROOT / "packaging/tool.json").read_text(encoding="utf-8")) + if tool.get("version") != version: + fail("packaging/tool.json version does not match Cargo.toml") + if tool.get("entrypoint") != "bin/marqdo-knowledge": + fail("packaging/tool.json entrypoint must be bin/marqdo-knowledge") + if tool.get("requires") != {"api_revision": 1, "analysis": 3}: + fail("packaging/tool.json requires must be exactly api_revision 1 / analysis 3") + spec = (ROOT / "spec/knowledge.md").read_text(encoding="utf-8") + if f'"version": "{version}"' not in spec: + fail("spec/knowledge.md tool identity version is stale") + notes = ROOT / "docs/releases" / f"{version}.md" + if not notes.is_file(): + fail(f"missing release notes {notes.relative_to(ROOT)}") + + +def clean_tree() -> None: + status = git("status", "--porcelain") + if status: + fail("working tree is dirty; commit before packaging") + head = git("rev-parse", "HEAD") + if not re.fullmatch(r"[a-f0-9]{40}", head): + fail("HEAD is not a full commit sha") + return head + + +def collect_examples(stage: Path, version: str) -> None: + examples = ROOT / "examples" + if not examples.is_dir(): + fail("examples directory is missing") + for path in sorted(examples.rglob("*")): + relative = path.relative_to(ROOT) + if any(part in SKIP_TREE_PARTS for part in relative.parts): + continue + if path.is_dir() or path.suffix in SKIP_SUFFIXES: + continue + destination = stage / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + # The compiled database is never shipped. + for stale in stage.rglob(".marqdo"): + if stale.is_dir(): + shutil.rmtree(stale) + if not (stage / "examples/mixed/notes.md").is_file(): + fail("examples/mixed is missing from the staged archive") + + +def build_stage(stage: Path, version: str, source_sha: str, commit_time: datetime.datetime) -> None: + binary = ROOT / "target/release/marqdo-knowledge" + if not binary.is_file(): + fail("target/release/marqdo-knowledge is missing; run cargo build --release --locked") + (stage / "bin").mkdir(parents=True) + shutil.copyfile(binary, stage / "bin/marqdo-knowledge") + (stage / "bin/marqdo-knowledge").chmod(0o755) + + for name in COPY_FILES: + source = ROOT / name + if not source.is_file(): + fail(f"missing required file {name}") + shutil.copyfile(source, stage / name) + shutil.copyfile(ROOT / "packaging/tool.json", stage / "tool.json") + + for tree in COPY_TREES: + source = ROOT / tree + if not source.is_dir(): + fail(f"missing required directory {tree}") + for path in sorted(source.rglob("*")): + if path.is_dir() or path.suffix in SKIP_SUFFIXES: + continue + if any(part in SKIP_TREE_PARTS for part in path.relative_to(ROOT).parts): + continue + destination = stage / path.relative_to(ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + collect_examples(stage, version) + + (stage / "SOURCE_SHA").write_text(source_sha + "\n", encoding="utf-8") + + # Per-file manifest. FILES.sha256 and RELEASE_INFO.json are themselves not + # listed, so the manifest stays independent of these metadata files. + files = [] + for path in sorted(stage.rglob("*")): + if not path.is_file(): + continue + relative = path.relative_to(stage).as_posix() + if relative in {"FILES.sha256", "RELEASE_INFO.json"}: + continue + files.append((relative, sha256_file(path), path.stat().st_size)) + manifest_lines = "".join( + f"{digest} {relative}\n" for relative, digest, _size in files + ) + (stage / "FILES.sha256").write_text(manifest_lines, encoding="utf-8") + manifest_digest = sha256_file(stage / "FILES.sha256") + + binary_info = { + "sha256": sha256_file(stage / "bin/marqdo-knowledge"), + "size": (stage / "bin/marqdo-knowledge").stat().st_size, + } + info = { + "schema": "marqdo.knowledge.release-info", + "schema_version": 1, + "product": "marqdo-knowledge", + "product_version": version, + "channel": "beta", + "target": TARGET, + "build_profile": "release", + "source_sha": source_sha, + "commit_time_utc": commit_time.strftime("%Y-%m-%dT%H:%M:%SZ"), + "protocols": { + "cli_tool": 1, + "tool_api_revision": 1, + "analysis": 3, + "sqlite_schema": 1, + "okf": "0.3", + }, + "binaries": {"marqdo-knowledge": binary_info}, + "core_baseline": CORE_BASELINE, + "files_manifest": "FILES.sha256", + "files_manifest_sha256": manifest_digest, + "file_count": len(files) + 2, + "known_limitations": "docs/STATUS.md", + "notes": [ + "Checksums prove content integrity only; they are not a publisher signature.", + "Install through `marqdo tool install `; direct execution requires a compatible core CLI.", + "Run `python3 tools/release/smoke.py --archive ` before publishing.", + ], + } + (stage / "RELEASE_INFO.json").write_text( + json.dumps(info, indent=2, sort_keys=True, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + + +def write_archive(stage: Path, commit_time: datetime.datetime, out_dir: Path, version: str) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + base = f"marqdo-knowledge-{version}-{TARGET}" + archive = out_dir / f"{base}.tar.gz" + if archive.exists(): + archive.unlink() + with tempfile.NamedTemporaryFile(dir=out_dir, delete=False) as raw: + raw_path = Path(raw.name) + try: + with raw_path.open("wb") as raw_file: + with gzip.GzipFile(filename="", mode="wb", fileobj=raw_file, mtime=0, compresslevel=9) as compressed: + with tarfile.open(fileobj=compressed, mode="w", format=tarfile.GNU_FORMAT) as tar: + for path in sorted(stage.rglob("*")): + relative = path.relative_to(stage).as_posix() + info = tarfile.TarInfo(name=f"{base}/{relative}") + info.uid = 0 + info.gid = 0 + info.uname = "" + info.gname = "" + info.mtime = int(commit_time.timestamp()) + if path.is_dir(): + info.type = tarfile.DIRTYPE + info.mode = 0o755 + tar.addfile(info) + else: + info.type = tarfile.REGTYPE + info.mode = 0o755 if relative.startswith("bin/") else 0o644 + info.size = path.stat().st_size + with path.open("rb") as handle: + tar.addfile(info, handle) + shutil.move(raw_path, archive) + finally: + if raw_path.exists(): + raw_path.unlink() + digest = sha256_file(archive) + checksum = out_dir / f"{archive.name}.sha256" + checksum.write_text(f"{digest} {archive.name}\n", encoding="utf-8") + print(f"archive: {archive}") + print(f"sha256: {digest}") + print(f"manifest: {out_dir / 'RELEASE_INFO.json'}") + return archive + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--out-dir", default="dist") + args = parser.parse_args() + + head = clean_tree() + if args.source_sha != head: + fail(f"--source-sha {args.source_sha} does not match HEAD {head}") + check_version_consistency(args.version) + + version_output = run( + [str(ROOT / "target/release/marqdo-knowledge"), "--version"], capture=True + ) + if version_output != f"marqdo-knowledge {args.version}": + fail(f"release binary reports `{version_output}`, expected version {args.version}") + + commit_epoch = int(git("show", "-s", "--format=%ct", head)) + commit_time = datetime.datetime.fromtimestamp(commit_epoch, datetime.timezone.utc) + out_dir = (ROOT / args.out_dir).resolve() if not Path(args.out_dir).is_absolute() else Path(args.out_dir) + with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-package-") as temporary: + stage = Path(temporary) + build_stage(stage, args.version, head, commit_time) + archive = write_archive(stage, commit_time, out_dir, args.version) + shutil.copyfile(stage / "RELEASE_INFO.json", out_dir / "RELEASE_INFO.json") + shutil.copyfile(stage / "FILES.sha256", out_dir / "FILES.sha256") + print(f"source_sha: {head}") + print(f"target: {TARGET}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/smoke.py b/tools/release/smoke.py new file mode 100755 index 0000000..6d18410 --- /dev/null +++ b/tools/release/smoke.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Cold-install smoke test for a built marqdo-knowledge release archive. + +Extracts the archive into a fresh directory, verifies its checksum, source SHA, +file manifest and version consistency, installs the bundle through the real +core CLI into an isolated MARQDO_TOOL_HOME, then exercises the shipped tool: +help, compile/query/check on the packaged examples, and removal. It never uses +the development source tree. + +Usage: + MARQDO_BIN=/path/to/marqdo python3 tools/release/smoke.py \ + --archive dist/marqdo-knowledge-0.1.0-beta.2-x86_64-unknown-linux-gnu.tar.gz +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +from pathlib import Path + + +def fail(message: str) -> "NoReturn": + print(f"smoke: FAIL: {message}", file=sys.stderr) + raise SystemExit(1) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def run(command: list[str], *, env: dict[str, str] | None = None) -> str: + completed = subprocess.run( + command, + check=True, + text=True, + capture_output=True, + env=env, + ) + return completed.stdout.strip() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", required=True) + parser.add_argument("--marqdo-bin", default=os.environ.get("MARQDO_BIN", "")) + parser.add_argument("--evidence-out", default="") + args = parser.parse_args() + + marqdo = Path(args.marqdo_bin) + if not marqdo.is_file(): + fail("set --marqdo-bin or MARQDO_BIN to a real core CLI binary") + archive = Path(args.archive).resolve() + if not archive.is_file(): + fail(f"archive {archive} does not exist") + checksum_path = archive.with_name(archive.name + ".sha256") + if not checksum_path.is_file(): + fail(f"missing checksum {checksum_path.name}") + expected = checksum_path.read_text(encoding="utf-8").split()[0] + actual = sha256_file(archive) + if expected != actual: + fail(f"archive SHA-256 {actual} does not match checksum {expected}") + + with tempfile.TemporaryDirectory(prefix="marqdo-knowledge-smoke-") as work: + work_path = Path(work) + with tarfile.open(archive, "r:gz") as tar: + members = tar.getnames() + if any(name.startswith("/") or ".." in Path(name).parts for name in members): + fail("archive contains an unsafe path") + tar.extractall(work_path) + roots = [path for path in work_path.iterdir() if path.is_dir()] + if len(roots) != 1: + fail("archive must contain exactly one top directory") + package = roots[0] + info = json.loads((package / "RELEASE_INFO.json").read_text(encoding="utf-8")) + tool = json.loads((package / "tool.json").read_text(encoding="utf-8")) + source_sha = (package / "SOURCE_SHA").read_text(encoding="utf-8").strip() + if not re.fullmatch(r"[a-f0-9]{40}", source_sha): + fail("SOURCE_SHA is not a full commit sha") + if info.get("source_sha") != source_sha: + fail("RELEASE_INFO source_sha does not match SOURCE_SHA") + if info.get("product_version") != tool.get("version"): + fail("RELEASE_INFO product_version does not match tool.json") + if tool.get("entrypoint") != "bin/marqdo-knowledge": + fail("tool.json entrypoint is not bin/marqdo-knowledge") + binary = package / "bin/marqdo-knowledge" + if not binary.is_file() or not os.access(binary, os.X_OK): + fail("packaged entrypoint is missing or not executable") + version_output = run([str(binary), "--version"]) + if version_output != f"marqdo-knowledge {tool.get('version')}": + fail(f"packaged binary reports `{version_output}`") + manifest = package / "FILES.sha256" + listed: dict[str, str] = {} + for line in manifest.read_text(encoding="utf-8").splitlines(): + parts = line.split(" ", 1) + if len(parts) != 2: + fail("FILES.sha256 has a malformed line") + digest, relative = parts + listed[relative] = digest + manifest_digest = sha256_file(manifest) + if info.get("files_manifest_sha256") != manifest_digest: + fail("RELEASE_INFO files_manifest_sha256 does not match FILES.sha256") + for relative, digest in listed.items(): + path = package / relative + if not path.is_file(): + fail(f"manifest lists missing file {relative}") + if sha256_file(path) != digest: + fail(f"file digest mismatch for {relative}") + + tool_home = work_path / "tool-home" + tool_home.mkdir() + env = os.environ.copy() + env["MARQDO_TOOL_HOME"] = str(tool_home) + env.pop("MARQDO_API_REVISION", None) + run([str(marqdo), "tool", "install", str(package)], env=env) + try: + listing = run([str(marqdo), "tool", "list"], env=env) + if "knowledge" not in listing: + fail("tool was not listed after install") + run([str(marqdo), "knowledge", "--help"], env=env) + compile_report = json.loads( + run( + [ + str(marqdo), + "knowledge", + "compile", + str(package / "examples/mixed"), + "--json", + ], + env=env, + ) + ) + if not compile_report.get("success"): + fail("compile did not succeed") + if compile_report["payload"]["documents"] <= 0: + fail("compile reported no documents") + query_report = json.loads( + run( + [ + str(marqdo), + "knowledge", + "query", + "归一化", + "--root", + str(package / "examples/mixed"), + "--format", + "json", + ], + env=env, + ) + ) + if not query_report.get("success") or not query_report.get("hits"): + fail("query returned no hits") + check_report = json.loads( + run( + [ + str(marqdo), + "knowledge", + "check", + str(package / "examples/mixed"), + "--json", + ], + env=env, + ) + ) + if not check_report.get("success") or check_report["payload"]["errors"] != 0: + fail("check failed") + if check_report["payload"]["database"] != "current": + fail("check did not report a current database") + evidence = { + "schema": "marqdo.knowledge.smoke", + "schema_version": 1, + "archive": archive.name, + "archive_sha256": actual, + "source_sha": source_sha, + "version": tool["version"], + "core": run([str(marqdo), "--version"]), + "documents": compile_report["payload"]["documents"], + "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") + print("smoke: OK") + return 0 + + +if __name__ == "__main__": + sys.exit(main())