diff --git a/.github/workflows/ci-freshness.yml b/.github/workflows/ci-freshness.yml index 2030e2f2..63c7accd 100644 --- a/.github/workflows/ci-freshness.yml +++ b/.github/workflows/ci-freshness.yml @@ -1,16 +1,17 @@ name: Artifact freshness -# Nightly check that each committed native artifact's provenance still -# describes the tree. Each lane's sidecar records sourceRevision and -# recipeRevision, each computed by the producer as `git log -1 --format=%H` -# over a path set that excludes the artifact output directories — so a -# refresh writeback can never report itself stale. This job recomputes both -# at HEAD over the same sets and compares by equality: -# missing / "unknown" field → ::warning::, the lane is unverified, run green -# unequal → ::error:: + summary, the run fails -# headSha / appliedAtHead / producerCheckout are run identity and are never -# compared. No issue is opened: contents: read is the whole permission set, -# so the red run and the step summary are the only alert channel. +# Nightly check that each committed native artifact's recorded build inputs +# still describe the tree. Each lane compares the revisions recorded in its +# committed provenance sidecar — sourceRevision and recipeRevision per +# carrier — to HEAD over that carrier's compiled-source and recipe path sets. +# An unrelated commit, a test-only change or another platform's refresh never +# reports the lane stale; a real build-input change after a recorded revision +# does. +# recorded revision stale → ::error:: + summary, red +# missing/malformed/unresolvable record → ::error:: + summary, red +# check could not run (checker exit 2) → ::error::, red +# No issue is opened: contents: read is the whole permission set, so the red +# run and the step summary are the only alert channel. on: schedule: - cron: '17 3 * * *' @@ -31,133 +32,53 @@ jobs: # Full history: the recorded revisions must resolve in this clone. fetch-depth: 0 + - name: Setup Node.js + # actions/setup-node@v4.4.0 — Node 24 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: 24 + - name: Compare provenance baselines run: | - set -u - stale=0 - - # git pathspec exclusions for the artifact writeback directories and - # every provenance sidecar: a refresh commit moves neither baseline. - EXCLUDES=( - ':(exclude)crates/spoke-connect/bindings/swift/xcframework/**' - ':(exclude)crates/spoke-connect/bindings/swift/generated/**' - ':(exclude)crates/spoke-connect/bindings/cpp/native/**' - ':(exclude)**/provenance.json' - ) + set -uo pipefail - last_revision() { - git log -1 --format=%H -- "$@" "${EXCLUDES[@]}" - } + echo "## Artifact freshness" >> "$GITHUB_STEP_SUMMARY" - # compare - compare() { - local lane="$1" field="$2" recorded="$3" current="$4" - shift 4 - if [ -z "$recorded" ] || [ "$recorded" = "null" ] || [ "$recorded" = "unknown" ]; then - echo "::warning::${lane}: ${field} not recorded in committed provenance; freshness unverified" - echo "- :warning: **${lane}** \`${field}\` is not recorded; the lane's freshness is unverified until the next refresh writes it." >> "$GITHUB_STEP_SUMMARY" - return 0 - fi - if [ -z "$current" ]; then - echo "::warning::${lane}: no HEAD history resolves ${field}; baseline cannot be recomputed" - echo "- :warning: **${lane}** \`${field}\` has no history at HEAD; the baseline cannot be recomputed." >> "$GITHUB_STEP_SUMMARY" - return 0 - fi - if [ "$recorded" != "$current" ]; then - local first - first=$(git rev-list --reverse "${recorded}..HEAD" -- "$@" "${EXCLUDES[@]}" 2>/dev/null | head -1 || true) - echo "::error::${lane}: ${field} stale: recorded ${recorded}, HEAD ${current}" - { - echo "- :x: **${lane}** \`${field}\` stale" - echo " - recorded: \`${recorded}\`" - echo " - HEAD: \`${current}\`" - [ -n "$first" ] && echo " - first offending commit: \`${first}\`" - } >> "$GITHUB_STEP_SUMMARY" - return 1 - fi - echo "- :white_check_mark: **${lane}** \`${field}\` fresh at \`${current}\`" >> "$GITHUB_STEP_SUMMARY" - return 0 - } + report="$(mktemp)" + status=0 + node tooling/release/check-artifact-freshness.mjs --repo . > "$report" || status=$? - echo "## Artifact freshness" >> "$GITHUB_STEP_SUMMARY" + failed=0 + if [ "$status" -ne 0 ] && [ "$status" -ne 1 ]; then failed=1; fi + if ! jq -e '.lanes' "$report" > /dev/null 2>&1; then failed=1; fi - # --- C++ carrier (crates/spoke-connect/bindings/cpp/native) --- - # Path sets mirror cpp-build.mjs: BUILD_SOURCE_PATHS and - # BUILD_RECIPE_PATHS. - CPP_SOURCE=( - Cargo.toml Cargo.lock - crates/spoke-connect-capi crates/spoke-connect/src crates/spoke-connect/Cargo.toml - crates/spoke-operations crates/spoke-schemas - ) - CPP_RECIPE=( - tooling/connect/cpp-build.mjs - .github/workflows/cpp-connect.yml - ) - CPP_PROVENANCE=crates/spoke-connect/bindings/cpp/native/provenance.json - cpp_src_rev=$(last_revision "${CPP_SOURCE[@]}") - cpp_rec_rev=$(last_revision "${CPP_RECIPE[@]}") - # Missing, malformed, empty or non-object sidecar is a broken - # record, not an unknown baseline: fail the lane rather than - # warning green. `jq -e` also catches the zero-byte file that a - # bare parse accepts. - if [ ! -f "$CPP_PROVENANCE" ]; then - echo "::error::cpp-carrier: $CPP_PROVENANCE is missing" - echo "- :x: **cpp-carrier** committed provenance is missing." >> "$GITHUB_STEP_SUMMARY" - stale=1 - elif ! jq -e 'type == "object"' "$CPP_PROVENANCE" > /dev/null; then - echo "::error::cpp-carrier: $CPP_PROVENANCE is not a JSON object" - echo "- :x: **cpp-carrier** committed provenance is not a JSON object." >> "$GITHUB_STEP_SUMMARY" - stale=1 - elif [ "$(jq -r '.nativeArtifacts | type' "$CPP_PROVENANCE")" != "object" ]; then - echo "::error::cpp-carrier: $CPP_PROVENANCE has no nativeArtifacts object" - echo "- :x: **cpp-carrier** committed provenance has no \`nativeArtifacts\` object." >> "$GITHUB_STEP_SUMMARY" - stale=1 - elif cpp_rows=$(jq -r '.nativeArtifacts | keys[]' "$CPP_PROVENANCE"); [ -z "$cpp_rows" ]; then - echo "::warning::cpp-carrier: committed provenance has no nativeArtifacts entries" - echo "- :warning: **cpp-carrier** committed provenance records no carriers." >> "$GITHUB_STEP_SUMMARY" - else - while IFS= read -r rid; do - [ -z "$rid" ] && continue - rec_src=$(jq -r --arg rid "$rid" '.nativeArtifacts[$rid].sourceRevision // empty' "$CPP_PROVENANCE") - rec_rec=$(jq -r --arg rid "$rid" '.nativeArtifacts[$rid].recipeRevision // empty' "$CPP_PROVENANCE") - compare "cpp-carrier/${rid}" sourceRevision "$rec_src" "$cpp_src_rev" "${CPP_SOURCE[@]}" || stale=1 - compare "cpp-carrier/${rid}" recipeRevision "$rec_rec" "$cpp_rec_rev" "${CPP_RECIPE[@]}" || stale=1 - done <<< "$cpp_rows" + if [ "$failed" -eq 1 ]; then + # The checker prints its own error JSON; a crash may leave raw text. + detail="$(jq -r '.error // empty' "$report" 2>/dev/null || true)" + if [ -z "$detail" ]; then + detail="$(head -c 500 "$report" 2>/dev/null | tr '\n' ' ' || true)" + fi + echo "::error::artifact freshness check failed to run: ${detail}" + echo "- :x: **artifact freshness** check failed to run: ${detail}" >> "$GITHUB_STEP_SUMMARY" + exit 1 fi - # --- Swift xcframework (crates/spoke-connect/bindings/swift/xcframework) --- - # Source set = the xcframework rebuild pattern minus the four recipe - # files; recipe set = the files that define how the bundle is built. - XC_PROVENANCE=crates/spoke-connect/bindings/swift/xcframework/provenance.json - XC_SOURCE=( - Cargo.toml Cargo.lock .cargo rust-toolchain rust-toolchain.toml - crates/spoke-connect crates/spoke-schemas crates/spoke-operations - ) - XC_RECIPE=( - tooling/connect/build-swift-xcframework.sh - tooling/connect/xcframework-manifest.sh - tooling/connect/normalize-cargo-version.mjs - tooling/release/lockstep-surfaces.mjs - .github/workflows/xcframework.yml - ) - xc_src_rev=$(last_revision "${XC_SOURCE[@]}") - xc_rec_rev=$(last_revision "${XC_RECIPE[@]}") - if [ ! -f "$XC_PROVENANCE" ]; then - echo "::error::swift-xcframework: $XC_PROVENANCE is missing" - echo "- :x: **swift-xcframework** committed provenance is missing." >> "$GITHUB_STEP_SUMMARY" - stale=1 - elif ! jq -e 'type == "object"' "$XC_PROVENANCE" > /dev/null; then - echo "::error::swift-xcframework: $XC_PROVENANCE is not a JSON object" - echo "- :x: **swift-xcframework** committed provenance is not a JSON object." >> "$GITHUB_STEP_SUMMARY" - stale=1 - else - xc_rec_src=$(jq -r '.xcframework.sourceRevision // empty' "$XC_PROVENANCE") - xc_rec_rec=$(jq -r '.xcframework.recipeRevision // empty' "$XC_PROVENANCE") - compare "swift-xcframework" sourceRevision "$xc_rec_src" "$xc_src_rev" "${XC_SOURCE[@]}" || stale=1 - compare "swift-xcframework" recipeRevision "$xc_rec_rec" "$xc_rec_rev" "${XC_RECIPE[@]}" || stale=1 - fi + jq -r '.lanes[] as $lane + | if $lane.status == "fresh" then + "- :white_check_mark: **\($lane.lane)** fresh" + elif $lane.status == "stale" then + "- :x: **\($lane.lane)** stale\n" + + ($lane.stale | map(" - base `\(.base)` (`\(.label)`) changed by `\(.commit)`") | join("\n")) + else + "- :x: **\($lane.lane)** invalid provenance\n" + + ($lane.errors | map(" - \(.)") | join("\n")) + end' "$report" >> "$GITHUB_STEP_SUMMARY" + + jq -r '.lanes[] as $lane + | ($lane.errors[] | "::error::\($lane.lane): invalid provenance: \(.)"), + ($lane.stale[] | "::error::\($lane.lane): build inputs changed since \(.base) (\(.label)) (commit \(.commit))")' "$report" - if [ "$stale" -ne 0 ]; then - echo "::error::stale committed artifact baselines; refresh via the lane's apply tooling" + if [ "$status" -eq 1 ]; then + echo "::error::artifact freshness check reported stale or invalid provenance" exit 1 fi diff --git a/package.json b/package.json index 11ec4c8c..a6cd843d 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "test:operations": "pnpm -F @42ch/spoke-operations test", "test:connect-ts": "pnpm -F @42ch/spoke-connect test", "test:demo": "pnpm -F @42ch/spoke-demo-server test && pnpm -F @42ch/spoke-demo-client test", - "test:release": "node --test tooling/release/assert-lockstep-version.test.mjs tooling/release/assert-breaking-section.test.mjs tooling/release/bump-version.test.mjs tooling/release/check-pypi-published.test.mjs tooling/release/check-maven-published.test.mjs tooling/connect/cpp-build.test.mjs tooling/connect/apply-xcframework-artifact.test.mjs tooling/connect/cpp-symbol-check.test.mjs", + "test:release": "node --test tooling/release/assert-lockstep-version.test.mjs tooling/release/assert-breaking-section.test.mjs tooling/release/bump-version.test.mjs tooling/release/check-pypi-published.test.mjs tooling/release/check-maven-published.test.mjs tooling/release/check-artifact-freshness.test.mjs tooling/connect/cpp-build.test.mjs tooling/connect/apply-xcframework-artifact.test.mjs tooling/connect/cpp-symbol-check.test.mjs", "ci:typescript": "pnpm -F @42ch/spoke-schemas typecheck && pnpm run build:schema && pnpm -F @42ch/spoke-operations typecheck && pnpm run test && pnpm run build:operations && pnpm run test:release && pnpm run test:fixtures && pnpm -F @42ch/spoke-connect typecheck && pnpm run test:connect-ts && pnpm -F @42ch/spoke-connect build && pnpm -F @42ch/spoke-connect test:dist && pnpm -F @42ch/spoke-demo-server typecheck && pnpm -F @42ch/spoke-demo-client typecheck && pnpm run test:demo", "docs:dev": "pnpm run docs:diagrams && pnpm run docs:llms && vitepress dev docs", "docs:build": "pnpm run docs:diagrams && pnpm run docs:llms && vitepress build docs", diff --git a/tooling/release/check-artifact-freshness.mjs b/tooling/release/check-artifact-freshness.mjs new file mode 100755 index 00000000..1ddf4a14 --- /dev/null +++ b/tooling/release/check-artifact-freshness.mjs @@ -0,0 +1,385 @@ +#!/usr/bin/env node +/** + * Recorded-provenance artifact freshness check. + * + * Each lane compares the build-input revisions recorded in its committed + * provenance sidecar to HEAD over the lane's compiled-source and recipe path + * sets. A lane is stale only when a recorded revision's range `base..HEAD` + * touched one of those inputs, so a commit that does not change the build + * inputs never reports the lane stale. A refresh that rewrites one platform's + * entry clears only that entry's staleness. + * + * swift → `.xcframework.sourceRevision` / `.xcframework.recipeRevision` + * cpp → each `nativeArtifacts[rid].sourceRevision` / `.recipeRevision` + * + * Every recorded revision must be a full 40/64-hex commit that resolves in + * this checkout and is an ancestor of HEAD. A missing sidecar, a malformed + * sidecar, or a missing, malformed, unresolvable or non-ancestor revision is + * an invalid record — the lane reports `invalid`, never `fresh`. + * + * Usage: + * node tooling/release/check-artifact-freshness.mjs [--repo ] + * + * Prints a deterministic `{ "lanes": [ ... ] }` JSON report. + * Exit 0 when every lane is fresh, 1 when a lane is stale or invalid, + * 2 when the check itself could not run. + */ + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +const CONNECT_SOURCE = [ + "crates/spoke-connect/src", + "crates/spoke-connect/Cargo.toml", + "crates/spoke-connect/build.rs", +]; + +const SCHEMAS_SOURCE = [ + "crates/spoke-schemas/src", + "crates/spoke-schemas/Cargo.toml", +]; + +const OPERATIONS_SOURCE = [ + "crates/spoke-operations/src", + "crates/spoke-operations/Cargo.toml", +]; + +/** Shared inputs of both native builds: manifest, lockfile, toolchain, Rust sources. */ +const COMMON_SOURCE = [ + "Cargo.toml", + "Cargo.lock", + ".cargo", + "rust-toolchain", + "rust-toolchain.toml", + ...CONNECT_SOURCE, + ...SCHEMAS_SOURCE, + ...OPERATIONS_SOURCE, +]; + +/** The C++ carrier additionally compiles the capi crate. */ +const CPP_SOURCE = [ + "Cargo.toml", + "Cargo.lock", + ".cargo", + "rust-toolchain", + "rust-toolchain.toml", + "crates/spoke-connect-capi/src", + "crates/spoke-connect-capi/Cargo.toml", + ...CONNECT_SOURCE, + ...SCHEMAS_SOURCE, + ...OPERATIONS_SOURCE, +]; + +/** The Swift bundle selects `spoke-connect` only, never the capi crate. */ +const SWIFT_SOURCE = COMMON_SOURCE; + +/** Recipe files that define how the C++ carriers are built. */ +const CPP_RECIPE = [ + "tooling/connect/cpp-build.mjs", + ".github/workflows/cpp-connect.yml", +]; + +/** Recipe files that define how the Swift bundle is built. */ +const SWIFT_RECIPE = [ + "tooling/connect/build-swift-xcframework.sh", + "tooling/connect/xcframework-manifest.sh", + "tooling/connect/normalize-cargo-version.mjs", + "tooling/release/lockstep-surfaces.mjs", + ".github/workflows/xcframework.yml", +]; + +/** Full git object names recorded in provenance: SHA-1 or SHA-256. */ +const COMMIT_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i; + +const LANES = [ + { + lane: "swift", + provenance: + "crates/spoke-connect/bindings/swift/xcframework/provenance.json", + source: SWIFT_SOURCE, + recipe: SWIFT_RECIPE, + /** + * @param {Record} data + * @param {string[]} errors + */ + entries(data, errors) { + if (!isRecord(data.xcframework)) { + errors.push("xcframework is missing or not an object"); + return []; + } + return [{ label: "xcframework", record: data.xcframework }]; + }, + }, + { + lane: "cpp", + provenance: "crates/spoke-connect/bindings/cpp/native/provenance.json", + source: CPP_SOURCE, + recipe: CPP_RECIPE, + /** + * @param {Record} data + * @param {string[]} errors + */ + entries(data, errors) { + if (!isRecord(data.nativeArtifacts)) { + errors.push("nativeArtifacts is missing or not an object"); + return []; + } + const rids = Object.keys(data.nativeArtifacts).sort(); + if (rids.length === 0) { + errors.push("nativeArtifacts records no entries"); + return []; + } + const entries = []; + for (const rid of rids) { + const entry = data.nativeArtifacts[rid]; + if (!isRecord(entry)) { + errors.push(`nativeArtifacts.${rid} is not an object`); + continue; + } + entries.push({ label: `nativeArtifacts.${rid}`, record: entry }); + } + return entries; + }, + }, +]; + +/** + * @param {string} repoRoot + * @param {string[]} args + */ +function git(repoRoot, args) { + const result = spawnSync("git", args, { + cwd: repoRoot, + encoding: "utf8", + }); + if (result.error) { + throw new Error( + `git ${args.join(" ")} could not run: ${result.error.message}`, + ); + } + return { + ok: result.status === 0, + stdout: (result.stdout ?? "").trim(), + stderr: (result.stderr ?? "").trim(), + }; +} + +/** + * Git call the check cannot proceed without. + * @param {string} repoRoot + * @param {string[]} args + */ +function expectGit(repoRoot, args) { + const result = git(repoRoot, args); + if (!result.ok) { + throw new Error( + `git ${args.join(" ")} failed: ${result.stderr || "unknown error"}`, + ); + } + return result.stdout; +} + +/** + * @param {string} repoRoot + * @param {string} relPath + */ +function readJson(repoRoot, relPath) { + try { + return { + data: JSON.parse(readFileSync(join(repoRoot, relPath), "utf8")), + }; + } catch (error) { + if (error.code === "ENOENT") return { error: "is missing" }; + return { error: `is not valid JSON (${error.message})` }; + } +} + +/** + * @param {unknown} value + * @returns {value is Record} + */ +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * A recorded revision is usable only as a full object name that resolves to a + * commit in this checkout. + * @param {string} repoRoot + * @param {unknown} value + * @returns {string | null} + */ +function resolveCommit(repoRoot, value) { + if (typeof value !== "string") return null; + const candidate = value.trim(); + if (!COMMIT_PATTERN.test(candidate)) return null; + return git(repoRoot, ["cat-file", "-e", `${candidate}^{commit}`]).ok + ? candidate + : null; +} + +/** + * @param {string} repoRoot + * @param {(typeof LANES)[number]} spec + */ +function checkLane(repoRoot, spec) { + /** @type {string[]} */ + const errors = []; + const sidecar = readJson(repoRoot, spec.provenance); + + /** @type {{label: string, revision: string, inputs: string[]}[]} */ + const bases = []; + if (sidecar.error) { + errors.push(`${spec.provenance} ${sidecar.error}`); + } else if (!isRecord(sidecar.data)) { + errors.push(`${spec.provenance} is not a JSON object`); + } else { + for (const { label, record } of spec.entries(sidecar.data, errors)) { + for (const [field, inputs] of [ + ["sourceRevision", spec.source], + ["recipeRevision", spec.recipe], + ]) { + if (!Object.hasOwn(record, field)) { + errors.push(`${spec.provenance} ${label} is missing ${field}`); + continue; + } + const value = record[field]; + if ( + typeof value !== "string" || + !COMMIT_PATTERN.test(value.trim()) + ) { + errors.push( + `${spec.provenance} ${label} ${field} ${JSON.stringify(value)} is not a commit hash`, + ); + continue; + } + bases.push({ + label: `${label} ${field}`, + revision: value.trim(), + inputs, + }); + } + } + } + + /** @type {{label: string, revision: string, inputs: string[]}[]} */ + const resolved = []; + for (const base of bases) { + const commit = resolveCommit(repoRoot, base.revision); + if (!commit) { + errors.push( + `${spec.provenance} ${base.label} ${base.revision} does not resolve in this checkout`, + ); + continue; + } + if (!git(repoRoot, ["merge-base", "--is-ancestor", commit, "HEAD"]).ok) { + errors.push( + `${spec.provenance} ${base.label} ${commit} is not an ancestor of HEAD`, + ); + continue; + } + resolved.push({ ...base, revision: commit }); + } + + if (errors.length > 0) { + return { lane: spec.lane, status: "invalid", stale: [], errors }; + } + + /** @type {{base: string, label: string, commit: string}[]} */ + const stale = []; + for (const base of resolved) { + const commit = expectGit(repoRoot, [ + "log", + "-1", + "--format=%H", + `${base.revision}..HEAD`, + "--", + ...base.inputs, + ]); + if (commit) stale.push({ base: base.revision, label: base.label, commit }); + } + + return { + lane: spec.lane, + status: stale.length > 0 ? "stale" : "fresh", + stale, + errors: [], + }; +} + +/** + * @param {{repoRoot: string}} options + * @returns {{lanes: {lane: string, status: "fresh" | "stale" | "invalid", stale: {base: string, label: string, commit: string}[], errors: string[]}[]}} + */ +export function checkFreshness({ repoRoot }) { + expectGit(repoRoot, ["rev-parse", "--is-inside-work-tree"]); + return { lanes: LANES.map((spec) => checkLane(repoRoot, spec)) }; +} + +const USAGE = + "usage: node tooling/release/check-artifact-freshness.mjs [--repo ]"; + +/** + * @param {string[]} argv + */ +function parseArgs(argv) { + /** @type {{repoRoot: string} | null} */ + const options = { repoRoot: process.cwd() }; + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === "--help" || arg === "-h") return null; + if (arg !== "--repo") { + throw new Error(`unknown argument: ${arg}`); + } + const value = argv[index + 1]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`missing value for ${arg}`); + } + index += 1; + options.repoRoot = value; + } + return options; +} + +/** + * @param {string[]} argv + */ +function main(argv) { + let options; + try { + options = parseArgs(argv); + } catch (error) { + console.error(`${error.message}\n${USAGE}`); + process.exitCode = 2; + return; + } + if (!options) { + console.log(USAGE); + return; + } + + let report; + try { + report = checkFreshness({ repoRoot: options.repoRoot }); + } catch (error) { + process.stdout.write( + `${JSON.stringify({ error: error.message }, null, 2)}\n`, + ); + process.exitCode = 2; + return; + } + + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); + process.exitCode = report.lanes.every((lane) => lane.status === "fresh") + ? 0 + : 1; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + main(process.argv.slice(2)); +} diff --git a/tooling/release/check-artifact-freshness.test.mjs b/tooling/release/check-artifact-freshness.test.mjs new file mode 100644 index 00000000..89b381a9 --- /dev/null +++ b/tooling/release/check-artifact-freshness.test.mjs @@ -0,0 +1,394 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { checkFreshness } from "./check-artifact-freshness.mjs"; + +const SCRIPT_PATH = fileURLToPath( + new URL("./check-artifact-freshness.mjs", import.meta.url), +); + +const SWIFT_PROVENANCE = + "crates/spoke-connect/bindings/swift/xcframework/provenance.json"; +const CPP_PROVENANCE = + "crates/spoke-connect/bindings/cpp/native/provenance.json"; + +const IDENTITY = { + GIT_AUTHOR_NAME: "Freshness Test", + GIT_AUTHOR_EMAIL: "freshness-test@example.com", + GIT_COMMITTER_NAME: "Freshness Test", + GIT_COMMITTER_EMAIL: "freshness-test@example.com", + GIT_AUTHOR_DATE: "2026-01-01T00:00:00Z", + GIT_COMMITTER_DATE: "2026-01-01T00:00:00Z", +}; + +function git(repoRoot, args) { + const result = spawnSync("git", args, { + cwd: repoRoot, + encoding: "utf8", + env: { ...process.env, ...IDENTITY }, + }); + assert.equal( + result.status, + 0, + `git ${args.join(" ")} failed: ${result.stderr}`, + ); + return result.stdout.trim(); +} + +function write(repoRoot, relPath, content) { + const target = join(repoRoot, relPath); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, content); +} + +function createRepo(t) { + const repoRoot = mkdtempSync(join(tmpdir(), "spoke-freshness-")); + t.after(() => rmSync(repoRoot, { recursive: true, force: true })); + git(repoRoot, ["init", "--quiet"]); + return repoRoot; +} + +function commit(repoRoot, message) { + git(repoRoot, ["add", "-A"]); + git(repoRoot, ["-c", "commit.gpgsign=false", "commit", "--quiet", "-m", message]); + return git(repoRoot, ["rev-parse", "HEAD"]); +} + +function runCli(repoRoot) { + return spawnSync(process.execPath, [SCRIPT_PATH, "--repo", repoRoot], { + encoding: "utf8", + env: { ...process.env, ...IDENTITY }, + }); +} + +function lane(report, name) { + return report.lanes.find((entry) => entry.lane === name); +} + +function writeSwiftProvenance(repoRoot, { sourceRevision, recipeRevision }) { + write( + repoRoot, + SWIFT_PROVENANCE, + `${JSON.stringify( + { + schemaVersion: 1, + xcframework: { sourceRevision, recipeRevision }, + }, + null, + 2, + )}\n`, + ); +} + +function writeCppProvenance(repoRoot, nativeArtifacts) { + write( + repoRoot, + CPP_PROVENANCE, + `${JSON.stringify({ schemaVersion: 1, nativeArtifacts }, null, 2)}\n`, + ); +} + +/** Writes the compiled sources and both artifacts, then both sidecars. */ +function seedRepo(t) { + const repoRoot = createRepo(t); + write(repoRoot, "Cargo.toml", "[workspace]\n"); + write(repoRoot, "Cargo.lock", "# lockfile\n"); + write( + repoRoot, + "crates/spoke-connect/Cargo.toml", + '[package]\nname = "spoke-connect"\n', + ); + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v1\n"); + write( + repoRoot, + "crates/spoke-connect-capi/Cargo.toml", + '[package]\nname = "spoke-connect-capi"\n', + ); + write(repoRoot, "crates/spoke-connect-capi/src/lib.rs", "// capi v1\n"); + write( + repoRoot, + "crates/spoke-connect/bindings/cpp/native/osx-arm64/libspoke_connect_capi.dylib", + "binary\n", + ); + write( + repoRoot, + "crates/spoke-connect/bindings/swift/xcframework/spoke_connectFFI.xcframework/Info.plist", + "plist\n", + ); + const baseline = commit(repoRoot, "build(connect): initial sources"); + + writeSwiftProvenance(repoRoot, { + sourceRevision: baseline, + recipeRevision: baseline, + }); + writeCppProvenance(repoRoot, { + "osx-arm64": { sourceRevision: baseline, recipeRevision: baseline }, + }); + commit(repoRoot, "build(connect): record provenance"); + + return { repoRoot, baseline }; +} + +test("unrelated docs commit after the writeback is fresh", (t) => { + const { repoRoot } = seedRepo(t); + + write(repoRoot, "docs/notes.md", "# notes\n"); + commit(repoRoot, "docs: unrelated note"); + + const report = checkFreshness({ repoRoot }); + for (const name of ["swift", "cpp"]) { + assert.equal(lane(report, name).status, "fresh", name); + } + assert.equal(runCli(repoRoot).status, 0); +}); + +test("test-only change after the writeback is fresh", (t) => { + const { repoRoot } = seedRepo(t); + + write(repoRoot, "crates/spoke-connect/tests/freshness.rs", "// test\n"); + commit(repoRoot, "test(connect): cover freshness"); + + const report = checkFreshness({ repoRoot }); + for (const name of ["swift", "cpp"]) { + assert.equal(lane(report, name).status, "fresh", name); + } +}); + +test("compiled source commit after the writeback is stale", (t) => { + const { repoRoot, baseline } = seedRepo(t); + + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v2\n"); + const offending = commit(repoRoot, "feat(connect): change source"); + + const report = checkFreshness({ repoRoot }); + for (const name of ["swift", "cpp"]) { + const entry = lane(report, name); + const label = + name === "swift" + ? "xcframework sourceRevision" + : "nativeArtifacts.osx-arm64 sourceRevision"; + assert.equal(entry.status, "stale", name); + assert.deepEqual( + entry.stale, + [{ base: baseline, label, commit: offending }], + name, + ); + assert.deepEqual(entry.errors, []); + } + assert.equal(runCli(repoRoot).status, 1); +}); + +test("a refreshed C++ rid does not clear another rid's staleness", (t) => { + const repoRoot = createRepo(t); + write(repoRoot, "Cargo.toml", "[workspace]\n"); + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v1\n"); + write( + repoRoot, + "crates/spoke-connect/bindings/swift/xcframework/spoke_connectFFI.xcframework/Info.plist", + "plist\n", + ); + write( + repoRoot, + "crates/spoke-connect/bindings/cpp/native/osx-arm64/libspoke_connect_capi.dylib", + "binary\n", + ); + write( + repoRoot, + "crates/spoke-connect/bindings/cpp/native/win-x64/spoke_connect_capi.dll", + "binary\n", + ); + const oldBaseline = commit(repoRoot, "build(connect): initial sources"); + + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v2\n"); + const sourceChange = commit(repoRoot, "feat(connect): change source"); + + writeSwiftProvenance(repoRoot, { + sourceRevision: sourceChange, + recipeRevision: oldBaseline, + }); + writeCppProvenance(repoRoot, { + "osx-arm64": { + sourceRevision: oldBaseline, + recipeRevision: oldBaseline, + }, + "win-x64": { + sourceRevision: sourceChange, + recipeRevision: oldBaseline, + }, + }); + commit(repoRoot, "build(connect): refresh win-x64"); + + const report = checkFreshness({ repoRoot }); + assert.equal(lane(report, "swift").status, "fresh"); + const cpp = lane(report, "cpp"); + assert.equal(cpp.status, "stale"); + assert.deepEqual(cpp.stale, [ + { + base: oldBaseline, + label: "nativeArtifacts.osx-arm64 sourceRevision", + commit: sourceChange, + }, + ]); +}); + +test("two stale C++ rids keep distinct attribution", (t) => { + const repoRoot = createRepo(t); + write(repoRoot, "Cargo.toml", "[workspace]\n"); + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v1\n"); + write( + repoRoot, + "crates/spoke-connect/bindings/cpp/native/osx-arm64/libspoke_connect_capi.dylib", + "binary\n", + ); + write( + repoRoot, + "crates/spoke-connect/bindings/cpp/native/win-x64/spoke_connect_capi.dll", + "binary\n", + ); + const baseline = commit(repoRoot, "build(connect): initial sources"); + + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v2\n"); + const sourceChange = commit(repoRoot, "feat(connect): change source"); + + writeSwiftProvenance(repoRoot, { + sourceRevision: sourceChange, + recipeRevision: baseline, + }); + writeCppProvenance(repoRoot, { + "osx-arm64": { sourceRevision: baseline, recipeRevision: baseline }, + "win-x64": { sourceRevision: baseline, recipeRevision: baseline }, + }); + commit(repoRoot, "build(connect): record provenance"); + + const cpp = lane(checkFreshness({ repoRoot }), "cpp"); + assert.equal(cpp.status, "stale"); + assert.deepEqual( + cpp.stale.map((entry) => entry.label), + [ + "nativeArtifacts.osx-arm64 sourceRevision", + "nativeArtifacts.win-x64 sourceRevision", + ], + ); + assert.deepEqual( + cpp.stale.map((entry) => entry.base), + [baseline, baseline], + ); +}); + +test("a capi-only change is stale for C++ and fresh for Swift", (t) => { + const { repoRoot } = seedRepo(t); + + write(repoRoot, "crates/spoke-connect-capi/src/lib.rs", "// capi v2\n"); + commit(repoRoot, "feat(capi): change carrier source"); + + const report = checkFreshness({ repoRoot }); + assert.equal(lane(report, "swift").status, "fresh"); + assert.equal(lane(report, "cpp").status, "stale"); +}); + +test("missing sidecar is invalid, not fresh", (t) => { + const repoRoot = createRepo(t); + write(repoRoot, "Cargo.toml", "[workspace]\n"); + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source\n"); + commit(repoRoot, "build(connect): sources without provenance"); + + const report = checkFreshness({ repoRoot }); + for (const name of ["swift", "cpp"]) { + const entry = lane(report, name); + assert.equal(entry.status, "invalid", name); + assert.deepEqual(entry.stale, [], name); + assert.ok(entry.errors.length > 0, name); + } + assert.equal(runCli(repoRoot).status, 1); +}); + +test("malformed sidecar is invalid, not fresh", (t) => { + const { repoRoot } = seedRepo(t); + + write(repoRoot, SWIFT_PROVENANCE, "[]\n"); + write(repoRoot, CPP_PROVENANCE, "{}\n"); + commit(repoRoot, "build(connect): record unusable provenance"); + + const report = checkFreshness({ repoRoot }); + for (const name of ["swift", "cpp"]) { + const entry = lane(report, name); + assert.equal(entry.status, "invalid", name); + assert.deepEqual(entry.stale, [], name); + assert.ok(entry.errors.length > 0, name); + } + assert.equal(runCli(repoRoot).status, 1); +}); + +test("sourceRevision HEAD is invalid, not fresh", (t) => { + const { repoRoot, baseline } = seedRepo(t); + + writeSwiftProvenance(repoRoot, { + sourceRevision: "HEAD", + recipeRevision: baseline, + }); + commit(repoRoot, "build(connect): record malformed revision"); + + const report = checkFreshness({ repoRoot }); + const swift = lane(report, "swift"); + assert.equal(swift.status, "invalid"); + assert.deepEqual(swift.stale, []); + assert.ok(swift.errors.length > 0); + assert.equal(runCli(repoRoot).status, 1); +}); + +test("unresolvable recorded revision is invalid", (t) => { + const { repoRoot, baseline } = seedRepo(t); + + writeCppProvenance(repoRoot, { + "osx-arm64": { sourceRevision: "f".repeat(40), recipeRevision: baseline }, + }); + commit(repoRoot, "build(connect): record unresolvable revision"); + + const report = checkFreshness({ repoRoot }); + const cpp = lane(report, "cpp"); + assert.equal(cpp.status, "invalid"); + assert.deepEqual(cpp.stale, []); + assert.ok(cpp.errors.length > 0); +}); + +test("a revision outside HEAD history is invalid", (t) => { + const repoRoot = createRepo(t); + write(repoRoot, "Cargo.toml", "[workspace]\n"); + write(repoRoot, "crates/spoke-connect/src/lib.rs", "// source v1\n"); + const baseline = commit(repoRoot, "build(connect): initial sources"); + + const defaultBranch = git(repoRoot, ["branch", "--show-current"]); + git(repoRoot, ["checkout", "--quiet", "-b", "side"]); + write(repoRoot, "docs/side.md", "# side\n"); + const sideRevision = commit(repoRoot, "docs: side branch commit"); + git(repoRoot, ["checkout", "--quiet", defaultBranch]); + + writeSwiftProvenance(repoRoot, { + sourceRevision: sideRevision, + recipeRevision: baseline, + }); + writeCppProvenance(repoRoot, { + "osx-arm64": { sourceRevision: baseline, recipeRevision: baseline }, + }); + commit(repoRoot, "build(connect): record foreign revision"); + + const report = checkFreshness({ repoRoot }); + const swift = lane(report, "swift"); + assert.equal(swift.status, "invalid"); + assert.deepEqual(swift.stale, []); + assert.match(swift.errors.join("\n"), /not an ancestor of HEAD/); + assert.equal(runCli(repoRoot).status, 1); +}); + +test("CLI exits 2 when the check cannot run", (t) => { + const notARepo = mkdtempSync(join(tmpdir(), "spoke-freshness-norepo-")); + t.after(() => rmSync(notARepo, { recursive: true, force: true })); + + const result = runCli(notARepo); + assert.equal(result.status, 2, result.stderr); + assert.ok(JSON.parse(result.stdout).error); +});