diff --git a/.github/workflows/cut-release.yml b/.github/workflows/cut-release.yml new file mode 100644 index 000000000..a6487c226 --- /dev/null +++ b/.github/workflows/cut-release.yml @@ -0,0 +1,413 @@ +name: Cut Release + +# One-click release preparation (and optional automated publish) via workflow_dispatch. +# - Default (auto_publish: false): checks Milestone zero-open (in stable mode), bumps versions +# and lockfiles, updates README badges and CHANGELOG.md skeleton, rebuilds release-notes-generated.js +# and client.js, runs verification tests + leak scan, and opens the `release: vX.Y.Z` PR to main. +# - Optional (auto_publish: true): requires repository secret RELEASE_BOT_TOKEN so PRs and Releases +# actually trigger downstream workflows (fail-fast when missing), waits for required checks, +# merges the release PR to main, publishes the GitHub Release WITHOUT Latest (so release.yml +# attaches packages and marks Latest), and opens the `main -> dev` merge-back PR. + +on: + workflow_dispatch: + inputs: + version: + description: Target release version without leading v (e.g. 0.4.2) + required: true + type: string + mode: + description: Release mode (stable enforces Milestone 0 open items; hotfix uses fast-lane) + required: true + default: stable + type: choice + options: + - stable + - hotfix + auto_publish: + description: Auto-merge PR after checks pass, create Release (not Latest), and open main->dev PR + type: boolean + default: false + +permissions: + contents: write + pull-requests: write + issues: read + +concurrency: + group: cut-release + cancel-in-progress: false + +jobs: + cut-release: + name: Cut release v${{ inputs.version }} (${{ inputs.mode }}) + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + GH_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN || github.token }} + HAS_RELEASE_BOT_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN != '' }} + INPUT_VERSION: ${{ inputs.version }} + MODE: ${{ inputs.mode }} + AUTO_PUBLISH: ${{ inputs.auto_publish }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.RELEASE_BOT_TOKEN || github.token }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Validate inputs, token requirements, and release base branch + id: meta + run: | + set -euo pipefail + if [ "$AUTO_PUBLISH" = "true" ] && [ "$HAS_RELEASE_BOT_TOKEN" != "true" ]; then + echo "::error::auto_publish=true requires secrets.RELEASE_BOT_TOKEN; github.token cannot trigger downstream CI or release.yml on created PRs/Releases." + exit 1 + fi + + version="${INPUT_VERSION#v}" + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "::error::Invalid version '$INPUT_VERSION'; expected semver like 0.4.2 or 0.4.2-rc.1." + exit 1 + fi + tag="v$version" + + # Validate GITHUB_REF_NAME strictly before referencing it in git commands. + if ! [[ "$GITHUB_REF_NAME" =~ ^[A-Za-z0-9._/-]+$ ]] || [[ "$GITHUB_REF_NAME" == -* ]] || [[ "$GITHUB_REF_NAME" == *".."* ]]; then + echo "::error::Unsafe dispatch ref name: '$GITHUB_REF_NAME'." + exit 1 + fi + + git fetch origin main dev --tags --force + if git rev-parse --verify "refs/tags/$tag" >/dev/null 2>&1; then + echo "::error::Tag $tag already exists." + exit 1 + fi + + if [ "$MODE" = "hotfix" ]; then + if [[ "$GITHUB_REF_NAME" == hotfix/* || "$GITHUB_REF_NAME" == fix/hot-* ]]; then + git fetch origin "refs/heads/$GITHUB_REF_NAME:refs/remotes/origin/$GITHUB_REF_NAME" + base_ref="origin/$GITHUB_REF_NAME" + elif [ "$GITHUB_REF_NAME" = "main" ]; then + base_ref="origin/main" + else + echo "::error::Hotfix mode must be dispatched from a hotfix/*, fix/hot-*, or main branch (got '$GITHUB_REF_NAME')." + exit 1 + fi + branch="hotfix/release-$version" + else + base_ref="origin/dev" + branch="chore/release-$version" + fi + base_sha="$(git rev-parse "$base_ref")" + + prerelease=false + if [[ "$version" == *-* ]]; then prerelease=true; fi + + { + echo "version=$version" + echo "tag=$tag" + echo "base_ref=$base_ref" + echo "base_sha=$base_sha" + echo "branch=$branch" + echo "prerelease=$prerelease" + } | tee -a "$GITHUB_OUTPUT" + + - name: Check release Milestone gate + id: milestone + env: + TARGET_TAG: ${{ steps.meta.outputs.tag }} + TARGET_BRANCH: ${{ steps.meta.outputs.branch }} + BASE_REF: ${{ steps.meta.outputs.base_ref }} + run: | + set -euo pipefail + # Ignore an already-open release PR for this branch so re-running cut-release never deadlocks on itself. + existing_pr="$(gh pr list --base main --head "$TARGET_BRANCH" --state open --json number --jq '.[0].number // empty' || true)" + args=(--version "$TARGET_TAG" --repo "$GITHUB_REPOSITORY" --base-ref origin/main --head-ref "$BASE_REF" --json) + if [ -n "$existing_pr" ]; then + args+=(--ignore-pr "$existing_pr") + fi + if [ "$MODE" = "hotfix" ]; then + args+=(--hotfix) + fi + status=0 + node scripts/check-release-milestone.mjs "${args[@]}" > "$RUNNER_TEMP/milestone-check.json" || status=$? + node -e ' + const fs = require("node:fs"); + const out = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); + if (out.message) console.log(out.message); + const nums = (out.resolvedPendingMain || []).map(i => i.number).filter(n => Number.isSafeInteger(n) && n > 0); + fs.writeFileSync(process.argv[2], nums.join(" ")); + ' "$RUNNER_TEMP/milestone-check.json" "$RUNNER_TEMP/resolved-issues.txt" + resolved_issues="$(cat "$RUNNER_TEMP/resolved-issues.txt")" + echo "resolved_issues=$resolved_issues" >> "$GITHUB_OUTPUT" + exit "$status" + + - name: Create release branch and bump versions, README badges, and CHANGELOG + env: + TARGET_VERSION: ${{ steps.meta.outputs.version }} + TARGET_BRANCH: ${{ steps.meta.outputs.branch }} + BASE_REF: ${{ steps.meta.outputs.base_ref }} + BASE_SHA: ${{ steps.meta.outputs.base_sha }} + run: | + set -euo pipefail + git config user.name "${GITHUB_ACTOR}" + git config user.email "${GITHUB_ACTOR}@users.noreply.github.com" + if git ls-remote --exit-code --heads origin "$TARGET_BRANCH" >/dev/null 2>&1; then + git fetch origin "$TARGET_BRANCH" + if [ "$MODE" = "hotfix" ] && [ "$GITHUB_REF_NAME" != "$TARGET_BRANCH" ]; then + prev_source="$(git log --format=%B origin/main.."origin/$TARGET_BRANCH" | awk -F': ' '/^Hotfix-Source: / { print $2; exit }')" + prev_sha="$(git log --format=%B origin/main.."origin/$TARGET_BRANCH" | awk -F': ' '/^Hotfix-Source-Sha: / { print $2; exit }')" + if [ -z "$prev_source" ] || [ "$prev_source" != "$GITHUB_REF_NAME" ]; then + echo "::error::Remote branch '$TARGET_BRANCH' already exists (recorded Hotfix-Source: '${prev_source:-unknown}') and does not match dispatch branch '$GITHUB_REF_NAME'. Delete the obsolete branch and close its PR before cutting a replacement hotfix." + exit 1 + fi + if [ -z "$prev_sha" ] || ! git merge-base --is-ancestor "$prev_sha" "$BASE_REF" 2>/dev/null; then + echo "::error::Dispatch branch '$GITHUB_REF_NAME' ($BASE_SHA) does not descend from the source commit ($prev_sha) already merged into '$TARGET_BRANCH'. Delete the obsolete branch and close its PR before replacing it." + exit 1 + fi + fi + git checkout -B "$TARGET_BRANCH" "origin/$TARGET_BRANCH" + if ! git merge-base --is-ancestor "$BASE_REF" HEAD; then + if [ "$MODE" = "hotfix" ]; then + git merge --no-edit "$BASE_REF" -m "$(printf 'Merge %s into %s\n\nHotfix-Source: %s\nHotfix-Source-Sha: %s' "$BASE_REF" "$TARGET_BRANCH" "$GITHUB_REF_NAME" "$BASE_SHA")" + else + git merge --no-edit "$BASE_REF" + fi + fi + else + git checkout -B "$TARGET_BRANCH" "$BASE_REF" + fi + + VERSION="$TARGET_VERSION" node -e ' + const { execFileSync } = require("node:child_process"); + const fs = require("node:fs"); + const version = process.env.VERSION; + const today = new Date().toISOString().slice(0, 10); + + function updateJson(file, updater) { + const data = JSON.parse(fs.readFileSync(file, "utf8")); + updater(data); + fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`); + } + + updateJson("ds-bot/package.json", (pkg) => { pkg.version = version; }); + updateJson("ds-bot/package-lock.json", (lock) => { + lock.version = version; + if (lock.packages && lock.packages[""]) lock.packages[""].version = version; + }); + updateJson("app/package.json", (pkg) => { pkg.version = version; }); + updateJson("app/package-lock.json", (lock) => { + lock.version = version; + if (lock.packages && lock.packages[""]) lock.packages[""].version = version; + if (lock.packages && lock.packages["node_modules/ds-bot"]) lock.packages["node_modules/ds-bot"].version = version; + if (lock.packages && lock.packages["../ds-bot"]) lock.packages["../ds-bot"].version = version; + }); + + const readmeEn = fs.readFileSync("README.md", "utf8") + .replace(/badge\/version-v[0-9A-Za-z._-]+-blue/u, `badge/version-v${version.replace(/-/g, "--")}-blue`); + fs.writeFileSync("README.md", readmeEn); + + const readmeZh = fs.readFileSync("README.zh.md", "utf8") + .replace(/badge\/版本-v[0-9A-Za-z._-]+-blue/u, `badge/版本-v${version.replace(/-/g, "--")}-blue`); + fs.writeFileSync("README.zh.md", readmeZh); + + const changelog = fs.readFileSync("CHANGELOG.md", "utf8"); + const headingRe = new RegExp(`^## \\[${version.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\$&")}\\]`, "mu"); + if (!headingRe.test(changelog)) { + let commits = []; + try { + const raw = execFileSync("git", ["log", "--no-merges", "--max-count=40", "--pretty=format:- %s", "origin/main..HEAD"], { encoding: "utf8" }).trim(); + if (raw) commits = raw.split(/\r?\n/); + } catch {} + const bullets = commits.length > 0 ? commits.join("\n") : `- Release v${version}.`; + const section = `## [${version}] - ${today}\n\n### Changed\n\n${bullets}\n`; + const updated = changelog.replace( + /^(## \[Unreleased\]\s*\n)/mu, + `$1\n${section}\n`, + ); + fs.writeFileSync("CHANGELOG.md", updated); + } + ' + + - name: Rebuild bundles and release-notes-generated.js + working-directory: ds-bot + run: | + set -euo pipefail + npm ci --no-fund --no-audit + npm ci --no-fund --no-audit --prefix ../link + npm run harness + npm run build + node scripts/build-client.mjs --check + npm run lint + node --import ./test/harness-resolve.mjs --test \ + test/client-bundle.test.js \ + test/release-notes.test.js \ + test/ci-workflows.test.js \ + test/release-milestone.test.js + + - name: Verify app release-notes contract and leak scan + run: | + set -euo pipefail + (cd app && ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm ci --no-fund --no-audit && node --import ./test/reset-env.mjs --test test/release-notes.test.mjs) + git status --short + + - name: Commit, push, and open release PR to main + id: pr + env: + TARGET_TAG: ${{ steps.meta.outputs.tag }} + TARGET_BRANCH: ${{ steps.meta.outputs.branch }} + BASE_SHA: ${{ steps.meta.outputs.base_sha }} + RESOLVED_ISSUES: ${{ steps.milestone.outputs.resolved_issues }} + run: | + set -euo pipefail + git config user.name "${GITHUB_ACTOR}" + git config user.email "${GITHUB_ACTOR}@users.noreply.github.com" + + if ! git diff --quiet; then + git add ds-bot/package.json ds-bot/package-lock.json \ + app/package.json app/package-lock.json \ + README.md README.zh.md CHANGELOG.md \ + ds-bot/client.js ds-bot/src/shared/release-notes-generated.js + if [ "$MODE" = "hotfix" ]; then + git commit -m "release: $TARGET_TAG" -m "$(printf 'Hotfix-Release: true\nHotfix-Source: %s\nHotfix-Source-Sha: %s' "$GITHUB_REF_NAME" "$BASE_SHA")" + else + git commit -m "release: $TARGET_TAG" + fi + fi + + # Scan the tracked tree as it will be published. + mkdir -p "$RUNNER_TEMP/tree" + git archive HEAD | tar -x -C "$RUNNER_TEMP/tree" + node scripts/scan.mjs "$RUNNER_TEMP/tree" + + git push -u origin "$TARGET_BRANCH" + + existing="$(gh pr list --base main --head "$TARGET_BRANCH" --state open --json number --jq '.[0].number // empty')" + if [ -n "$existing" ]; then + pr_num="$existing" + echo "Reusing existing release PR #$pr_num" + # Idempotently refresh the block on existing stable release PRs + # without touching maintainer-authored text. + if [ "$MODE" = "stable" ] && [ -n "$RESOLVED_ISSUES" ]; then + gh pr view "$pr_num" --json body --jq .body > "$RUNNER_TEMP/existing-pr-body.md" + RESOLVED_ISSUES="$RESOLVED_ISSUES" node -e ' + const fs = require("node:fs"); + const nums = process.env.RESOLVED_ISSUES.trim().split(/\s+/).filter(Boolean); + const block = ["", ...nums.map(n => `Fixes #${n}`), ""].join("\n"); + const prev = fs.readFileSync(process.argv[1], "utf8"); + const re = /[\s\S]*?/u; + const next = re.test(prev) ? prev.replace(re, block) : `${prev.trimEnd()}\n\n${block}\n`; + fs.writeFileSync(process.argv[2], next); + ' "$RUNNER_TEMP/existing-pr-body.md" "$RUNNER_TEMP/updated-pr-body.md" + gh pr edit "$pr_num" --body-file "$RUNNER_TEMP/updated-pr-body.md" + fi + else + body_file="$RUNNER_TEMP/pr-body.md" + { + echo "## Release $TARGET_TAG ($MODE)" + echo "" + echo "- Version bumped in \`ds-bot/package.json\`, \`app/package.json\`, lockfiles, and README badges." + echo "- \`CHANGELOG.md\` and \`ds-bot/src/shared/release-notes-generated.js\` updated and verified." + if [ "$MODE" = "hotfix" ]; then + echo "- Mode: **hotfix** (fast-lane CI enabled via \`release/hotfix\` label; release commit carries \`Hotfix-Release: true\` so manual GitHub Releases also preserve hotfix exemption, or include \`\` in the Release notes)." + else + echo "- Mode: **stable** (Milestone \`$TARGET_TAG\` verified at 0 blocking open items)." + if [ -n "$RESOLVED_ISSUES" ]; then + echo "" + echo "" + for issue_num in $RESOLVED_ISSUES; do + echo "Fixes #$issue_num" + done + echo "" + fi + fi + } > "$body_file" + + create_args=(pr create --base main --head "$TARGET_BRANCH" --title "release: $TARGET_TAG" --body-file "$body_file") + if [ "$MODE" = "hotfix" ]; then + create_args+=(--label "release/hotfix") + fi + if gh api "repos/$GITHUB_REPOSITORY/milestones?state=all&per_page=100" --jq '.[].title' | grep -qx "$TARGET_TAG"; then + create_args+=(--milestone "$TARGET_TAG") + fi + pr_url="$(gh "${create_args[@]}")" + pr_num="$(gh pr view "$pr_url" --json number --jq .number)" + fi + + pr_url="$(gh pr view "$pr_num" --json url --jq .url)" + echo "number=$pr_num" >> "$GITHUB_OUTPUT" + echo "url=$pr_url" >> "$GITHUB_OUTPUT" + echo "Opened release PR #$pr_num: $pr_url" >> "$GITHUB_STEP_SUMMARY" + + - name: Auto-merge, publish GitHub Release (not Latest), and open main->dev merge-back PR + if: inputs.auto_publish + env: + TARGET_VERSION: ${{ steps.meta.outputs.version }} + TARGET_TAG: ${{ steps.meta.outputs.tag }} + PR_NUMBER: ${{ steps.pr.outputs.number }} + IS_PRERELEASE: ${{ steps.meta.outputs.prerelease }} + run: | + set -euo pipefail + # Wait briefly for GitHub Actions check runs to register on the newly created PR + # before invoking --watch, avoiding a race where 0 checks exits immediately. + checks_seen=false + for _ in $(seq 1 12); do + count="$(gh pr checks "$PR_NUMBER" --json name --jq 'length' 2>/dev/null || echo 0)" + if [ "${count:-0}" -gt 0 ]; then + checks_seen=true + break + fi + sleep 5 + done + if [ "$checks_seen" != "true" ]; then + echo "::error::No PR checks registered on PR #$PR_NUMBER within 60s; aborting auto-merge." + exit 1 + fi + + gh pr checks "$PR_NUMBER" --watch --interval 20 + gh pr merge "$PR_NUMBER" --merge + + # Extract this version's section from CHANGELOG.md (line-based to span blank lines cleanly). + VERSION="$TARGET_VERSION" MODE="$MODE" node -e ' + const fs = require("node:fs"); + const version = process.env.VERSION; + const lines = fs.readFileSync("CHANGELOG.md", "utf8").split(/\r?\n/u); + const startRe = new RegExp(`^## \\[${version.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\$&")}\\](?:\\s|$)`, "u"); + const startIdx = lines.findIndex((line) => startRe.test(line)); + let body = `Release v${version}`; + if (startIdx !== -1) { + const collected = []; + for (let i = startIdx + 1; i < lines.length; i += 1) { + if (/^## \[/.test(lines[i])) break; + collected.push(lines[i]); + } + const trimmed = collected.join("\n").trim(); + if (trimmed) body = trimmed; + } + if (process.env.MODE === "hotfix") { + body = `\n\n${body}`; + } + fs.writeFileSync(`${process.env.RUNNER_TEMP}/release-notes.md`, `${body}\n`); + ' + + release_args=(release create "$TARGET_TAG" --target main --latest=false --title "$TARGET_TAG" --notes-file "$RUNNER_TEMP/release-notes.md") + if [ "$IS_PRERELEASE" = "true" ]; then + release_args+=(--prerelease) + fi + gh "${release_args[@]}" + + # Open main -> dev merge-back PR. + git fetch origin main dev + merge_branch="chore/merge-main-$TARGET_VERSION" + git checkout -B "$merge_branch" origin/dev + if git merge --no-edit origin/main; then + git push -u origin "$merge_branch" + gh pr create --base dev --head "$merge_branch" \ + --title "chore: merge $TARGET_TAG from main into dev" \ + --body "Merge release \`$TARGET_TAG\` back from \`main\` into \`dev\`." + else + echo "::warning::Merging main into dev had conflicts; resolve manually and open the merge-back PR." + git merge --abort || true + fi diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml new file mode 100644 index 000000000..4345df2a1 --- /dev/null +++ b/.github/workflows/nightly-release.yml @@ -0,0 +1,609 @@ +name: Nightly Release + +# Daily rolling pre-release built from dev at 20:00 UTC (04:00 +08:00). +# Exits early with zero wasted runner minutes when dev has no new commits since the last +# nightly tag or latest release tag. Never marks Latest and never publishes to npm. + +on: + schedule: + - cron: '0 20 * * *' + workflow_dispatch: + inputs: + force: + description: Build nightly even when dev has no new commits + type: boolean + default: false + build_android: + description: Force building the Android APK even if mobile files did not change + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: nightly-release + cancel-in-progress: false + +jobs: + check: + name: Check dev changes & release readiness + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: read + pull-requests: read + outputs: + should_run: ${{ steps.plan.outputs.should_run }} + sha: ${{ steps.plan.outputs.sha }} + short_sha: ${{ steps.plan.outputs.short_sha }} + build_android: ${{ steps.plan.outputs.build_android }} + steps: + - uses: actions/checkout@v4 + with: + ref: dev + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Detect new dev commits and build Release Readiness report + id: plan + env: + GH_TOKEN: ${{ github.token }} + FORCE: ${{ inputs.force }} + FORCE_ANDROID: ${{ inputs.build_android }} + run: | + set -euo pipefail + head_sha="$(git rev-parse HEAD)" + short_sha="$(git rev-parse --short=8 HEAD)" + + base_ref="" + if git rev-parse --verify "refs/tags/nightly^{commit}" >/dev/null 2>&1; then + base_ref="nightly" + else + latest_tag="$(git describe --tags --abbrev=0 2>/dev/null || true)" + if [ -n "$latest_tag" ]; then + base_ref="$latest_tag" + fi + fi + + should_run=true + if [ "$FORCE" != "true" ] && [ -n "$base_ref" ]; then + base_sha="$(git rev-parse "${base_ref}^{commit}")" + if [ "$head_sha" = "$base_sha" ]; then + should_run=false + echo "dev ($short_sha) has no new commits since $base_ref; skipping nightly build." | tee -a "$GITHUB_STEP_SUMMARY" + fi + fi + + build_android=false + if [ "$should_run" = "true" ]; then + if [ "$FORCE_ANDROID" = "true" ]; then + build_android=true + elif [ -n "$base_ref" ]; then + changed="$(git -c core.quotepath=false diff --name-only "${base_ref}..HEAD" | grep -Ev '^ds-bot/src/shared/release-notes(-generated\.js|\.json)$' || true)" + if grep -qE '^(mobile/|link/|\.github/gradle/|ds-bot/src/shared/|ds-bot/src/client/(i18n|themes|sources|inks|characters|usage-data|lru|learning-card-model|mark-states|motion-rest|inbox-text|effects)\.js$|ds-bot/src/client/(avatar|locales)/)' <<< "$changed"; then + build_android=true + fi + fi + fi + + # Generate Release Readiness report (recent commits, active Milestone open items, needs-product-ok PRs). + mkdir -p "$RUNNER_TEMP/readiness" + HEAD_SHA="$head_sha" SHORT_SHA="$short_sha" BASE_REF="$base_ref" BUILD_ANDROID="$build_android" \ + node --input-type=module -e ' + import { execFileSync } from "node:child_process"; + import { readFileSync, writeFileSync } from "node:fs"; + import { resolveActiveDevMilestone } from "./scripts/check-release-milestone.mjs"; + + const repo = process.env.GITHUB_REPOSITORY || "Fei-Craft/DS-Bot"; + const token = process.env.GH_TOKEN || ""; + const headSha = process.env.HEAD_SHA; + const shortSha = process.env.SHORT_SHA; + const baseRef = process.env.BASE_REF || ""; + const buildAndroid = process.env.BUILD_ANDROID === "true"; + const currentVersion = JSON.parse(readFileSync("ds-bot/package.json", "utf8")).version; + + const logRange = baseRef ? `${baseRef}..HEAD` : "HEAD"; + let commits = []; + try { + const raw = execFileSync("git", ["log", "--no-merges", "--max-count=30", "--pretty=format:- `%h` %s", logRange], { encoding: "utf8" }).trim(); + if (raw) commits = raw.split(/\r?\n/); + } catch {} + + const headers = { + Accept: "application/vnd.github+json", + "User-Agent": "ds-bot-nightly-release", + "X-GitHub-Api-Version": "2022-11-28", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + async function api(path) { + const res = await fetch(`https://api.github.com${path}`, { headers }); + if (!res.ok) return null; + return res.json(); + } + + const milestones = (await api(`/repos/${repo}/milestones?state=open&per_page=100`)) || []; + const active = resolveActiveDevMilestone(currentVersion, milestones); + let milestoneOpenItems = []; + if (active && active.milestone.open_issues > 0) { + milestoneOpenItems = (await api(`/repos/${repo}/issues?milestone=${active.milestone.number}&state=open&per_page=50`)) || []; + } + const productOkIssues = (await api(`/repos/${repo}/issues?state=open&labels=needs-product-ok&per_page=50`)) || []; + const productOkPrs = productOkIssues.filter(item => Boolean(item?.pull_request)); + + const lines = [ + `## Nightly Build (\`dev\` @ \`${shortSha}\`)`, + "", + `- **Commit**: \`${headSha}\``, + `- **Base version**: \`v${currentVersion}\``, + `- **Android APK**: ${buildAndroid ? "rebuilt for this nightly" : "skipped (no mobile changes since last baseline)"}`, + "- **Channel**: rolling GitHub Pre-release (`nightly`); never marked Latest and never published to npm `latest`.", + "", + "## Release Readiness", + "", + ]; + + if (active) { + const openCount = Number(active.milestone.open_issues ?? 0); + const closedCount = Number(active.milestone.closed_issues ?? 0); + lines.push(`- **Active Milestone**: \`${active.parsed.tag}\` — **${openCount} open** / ${closedCount} closed`); + if (milestoneOpenItems.length > 0) { + for (const item of milestoneOpenItems.slice(0, 15)) { + const kind = item.pull_request ? "PR" : "Issue"; + lines.push(` - [${kind}] #${item.number} ${item.title}`); + } + } + } else { + lines.push(`- **Active Milestone**: none open above \`v${currentVersion}\``); + } + + lines.push(`- **Open PRs waiting on \`needs-product-ok\`**: ${productOkPrs.length}`); + for (const pr of productOkPrs.slice(0, 15)) { + lines.push(` - [PR] #${pr.number} ${pr.title}`); + } + + lines.push("", `## Commits since \`${baseRef || "initial"}\``, ""); + if (commits.length > 0) { + lines.push(...commits); + } else { + lines.push("- No new non-merge commits."); + } + lines.push(""); + + writeFileSync(`${process.env.RUNNER_TEMP}/readiness/report.md`, lines.join("\n")); + ' + + cat "$RUNNER_TEMP/readiness/report.md" >> "$GITHUB_STEP_SUMMARY" + + { + echo "should_run=$should_run" + echo "sha=$head_sha" + echo "short_sha=$short_sha" + echo "build_android=$build_android" + } | tee -a "$GITHUB_OUTPUT" + - name: Upload Release Readiness report + if: steps.plan.outputs.should_run == 'true' + uses: actions/upload-artifact@v4 + with: + name: nightly-readiness + path: ${{ runner.temp }}/readiness/report.md + retention-days: 3 + if-no-files-found: error + + verify: + name: Verify ds-bot (dev) + needs: check + if: needs.check.outputs.should_run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 25 + defaults: + run: + shell: bash + working-directory: ds-bot + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: | + ds-bot/package-lock.json + link/package-lock.json + - run: npm ci --no-fund --no-audit + - run: npm ci --no-fund --no-audit --prefix ../link + - name: Restore DSH test harness + id: harness-cache + uses: actions/cache/restore@v4 + with: + path: ds-bot/dev/harness/node_modules + key: dsh-harness-${{ runner.os }}-${{ runner.arch }}-node24-${{ hashFiles('ds-bot/dev/harness/package.json', 'ds-bot/dev/harness/package-lock.json') }} + - name: Install DSH test harness + if: steps.harness-cache.outputs.cache-hit != 'true' + run: npm run harness + - run: node scripts/build-client.mjs --check + - run: npm test + - run: npm run lint + - name: Pack plugin tarball (no npm publish) + run: npm pack + - name: Upload plugin tarball artifact + uses: actions/upload-artifact@v4 + with: + name: nightly-plugin + path: ds-bot/ds-bot-*.tgz + retention-days: 3 + if-no-files-found: error + compression-level: 0 + + package-windows: + name: Nightly package (Windows x64) + needs: [check, verify] + if: needs.check.outputs.should_run == 'true' + runs-on: windows-latest + timeout-minutes: 35 + defaults: + run: + shell: bash + working-directory: app + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: app/package-lock.json + - name: Name the download cache + id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} + run: | + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + echo "prefix=$prefix" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" + - name: Restore Electron and the build tools + uses: actions/cache/restore@v4 + with: + path: | + ~/AppData/Local/electron/Cache + ~/AppData/Local/electron-builder/Cache + key: ${{ steps.downloads-key.outputs.key }} + restore-keys: ${{ steps.downloads-key.outputs.prefix }} + - run: npm ci --no-fund --no-audit + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + - run: node scripts/seed-electron-checksums.mjs + - name: Restore the locked runtime archives + uses: actions/cache/restore@v4 + with: + path: app/build/runtime-cache + key: runtime-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('app/scripts/primary-runtime.lock.json') }} + - run: npm run dist + env: + ELECTRON_BUILDER_COMPRESSION_LEVEL: '1' + - run: node scripts/check-packed.mjs + - name: Upload Windows nightly artifact + uses: actions/upload-artifact@v4 + with: + name: nightly-win-x64 + path: app/dist-pack/DS-Bot-*-win-x64.exe + retention-days: 3 + if-no-files-found: error + compression-level: 0 + + package-macos-arm64: + name: Nightly package (macOS arm64) + needs: [check, verify] + if: needs.check.outputs.should_run == 'true' + runs-on: macos-latest + timeout-minutes: 40 + defaults: + run: + shell: bash + working-directory: app + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: app/package-lock.json + - name: Name the download cache + id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} + run: | + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + echo "prefix=$prefix" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" + - name: Restore Electron and the build tools + uses: actions/cache/restore@v4 + with: + path: | + ~/Library/Caches/electron + ~/Library/Caches/electron-builder + key: ${{ steps.downloads-key.outputs.key }} + restore-keys: ${{ steps.downloads-key.outputs.prefix }} + - run: npm ci --no-fund --no-audit + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + - run: node scripts/seed-electron-checksums.mjs + - name: Restore the locked runtime archives + uses: actions/cache/restore@v4 + with: + path: app/build/runtime-cache + key: runtime-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('app/scripts/primary-runtime.lock.json') }} + - run: npm run dist + env: + ELECTRON_BUILDER_COMPRESSION_LEVEL: '5' + - run: node scripts/check-packed.mjs + - name: Upload macOS arm64 nightly artifact + uses: actions/upload-artifact@v4 + with: + name: nightly-mac-arm64 + path: app/dist-pack/DS-Bot-*-mac-arm64.zip + retention-days: 3 + if-no-files-found: error + compression-level: 0 + + package-linux: + name: Nightly package (Linux x64) + needs: [check, verify] + if: needs.check.outputs.should_run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + defaults: + run: + shell: bash + working-directory: app + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: app/package-lock.json + - name: Name the download cache + id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} + run: | + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + echo "prefix=$prefix" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" + - name: Restore Electron and the build tools + uses: actions/cache/restore@v4 + with: + path: | + ~/.cache/electron + ~/.cache/electron-builder + key: ${{ steps.downloads-key.outputs.key }} + restore-keys: ${{ steps.downloads-key.outputs.prefix }} + - run: npm ci --no-fund --no-audit + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + - run: node scripts/seed-electron-checksums.mjs + - name: Restore the locked runtime archives + uses: actions/cache/restore@v4 + with: + path: app/build/runtime-cache + key: runtime-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('app/scripts/primary-runtime.lock.json') }} + - run: npm run dist + - name: Check packaged Linux app + run: | + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + xvfb-run -a node scripts/check-packed.mjs + - name: Upload Linux nightly artifact + uses: actions/upload-artifact@v4 + with: + name: nightly-linux-x64 + path: | + app/dist-pack/DS-Bot-*-linux-x86_64.AppImage + app/dist-pack/DS-Bot-*-linux-amd64.deb + retention-days: 3 + if-no-files-found: error + compression-level: 0 + + package-android: + name: Nightly package (Android APK) + needs: [check, verify] + if: needs.check.outputs.should_run == 'true' && needs.check.outputs.build_android == 'true' + runs-on: ubuntu-latest + timeout-minutes: 50 + defaults: + run: + shell: bash + working-directory: mobile + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: | + mobile/package-lock.json + link/package-lock.json + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - run: npm ci --no-fund --no-audit --prefix ../link + - run: npm ci --no-fund --no-audit + - run: npm run typecheck + - run: npm test + - run: npx expo prebuild --platform android --no-install + - name: Install ccache + run: | + if ! command -v ccache >/dev/null 2>&1; then + sudo apt-get update -qq && sudo apt-get install -y -qq ccache + fi + echo "CCACHE_BIN=$(command -v ccache)" >> "$GITHUB_ENV" + - name: Restore Android C++ ccache + uses: actions/cache/restore@v4 + with: + path: ~/.ccache + key: android-ccache-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('mobile/package-lock.json', 'mobile/app.json', 'mobile/plugins/**', '.github/gradle/ccache.init.gradle') }} + restore-keys: android-ccache-v2-${{ runner.os }}-${{ runner.arch }}- + - uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: false + - name: Build nightly APK + env: + KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + CCACHE_BASEDIR: ${{ github.workspace }} + CCACHE_NOHASHDIR: 'true' + CCACHE_COMPILERCHECK: content + CCACHE_SLOPPINESS: include_file_mtime,include_file_ctime,time_macros + CCACHE_MAXSIZE: 600M + run: | + export CCACHE_DIR="$HOME/.ccache" + mkdir -p "$CCACHE_DIR" + if [ -n "$KEYSTORE_BASE64" ]; then + printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/upload.jks" + export DSBOT_ANDROID_KEYSTORE="$RUNNER_TEMP/upload.jks" DSBOT_ANDROID_KEYSTORE_PASSWORD="$KEYSTORE_PASSWORD" DSBOT_ANDROID_KEY_ALIAS="$KEY_ALIAS" + fi + (cd android && ./gradlew assembleRelease --no-daemon --build-cache --console=plain -PreactNativeArchitectures=arm64-v8a,armeabi-v7a --init-script "$GITHUB_WORKSPACE/.github/gradle/ccache.init.gradle") + rm -f "$RUNNER_TEMP/upload.jks" + mkdir -p dist + cp android/app/build/outputs/apk/release/app-release.apk dist/DS-Bot-nightly-android.apk + - name: Upload Android nightly artifact + uses: actions/upload-artifact@v4 + with: + name: nightly-android + path: mobile/dist/DS-Bot-nightly-android.apk + retention-days: 3 + if-no-files-found: error + compression-level: 0 + + publish-nightly: + name: Publish rolling nightly pre-release + needs: [check, verify, package-windows, package-macos-arm64, package-linux, package-android] + if: >- + ${{ !cancelled() && + needs.check.outputs.should_run == 'true' && + needs.verify.result == 'success' && + needs.package-windows.result == 'success' && + needs.package-macos-arm64.result == 'success' && + needs.package-linux.result == 'success' && + (needs.package-android.result == 'success' || (needs.check.outputs.build_android == 'false' && needs.package-android.result == 'skipped')) && + (github.event_name == 'workflow_dispatch' || github.repository == 'Fei-Craft/DS-Bot') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + NIGHTLY_SHA: ${{ needs.check.outputs.sha }} + NIGHTLY_SHORT_SHA: ${{ needs.check.outputs.short_sha }} + BUILD_ANDROID: ${{ needs.check.outputs.build_android }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.check.outputs.sha }} + fetch-depth: 1 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Download readiness report and nightly artifacts + uses: actions/download-artifact@v4 + with: + pattern: nightly-* + path: ${{ runner.temp }}/nightly + merge-multiple: true + - name: Normalize nightly asset names and compute SHA256SUMS.txt + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/upload" + for f in "$RUNNER_TEMP"/nightly/*; do + base="$(basename "$f")" + case "$base" in + report.md) continue ;; + DS-Bot-*-win-x64.exe) cp "$f" "$RUNNER_TEMP/upload/DS-Bot-nightly-win-x64.exe" ;; + DS-Bot-*-mac-arm64.zip) cp "$f" "$RUNNER_TEMP/upload/DS-Bot-nightly-mac-arm64.zip" ;; + DS-Bot-*-linux-x86_64.AppImage) cp "$f" "$RUNNER_TEMP/upload/DS-Bot-nightly-linux-x86_64.AppImage" ;; + DS-Bot-*-linux-amd64.deb) cp "$f" "$RUNNER_TEMP/upload/DS-Bot-nightly-linux-amd64.deb" ;; + DS-Bot-nightly-android.apk) cp "$f" "$RUNNER_TEMP/upload/DS-Bot-nightly-android.apk" ;; + ds-bot-*.tgz) cp "$f" "$RUNNER_TEMP/upload/ds-bot-nightly.tgz" ;; + esac + done + (cd "$RUNNER_TEMP/upload" && sha256sum * > SHA256SUMS.txt) + + # When Android build was skipped, keep SHA256SUMS.txt consistent with any retained APK: + # preserve its verified digest line (and record its source in report.md), or delete the + # stale APK asset if no verified digest is available. + if [ "$BUILD_ANDROID" = "false" ] && gh release view nightly >/dev/null 2>&1; then + rel_json="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/nightly" 2>/dev/null || echo '{}')" + has_old_apk="$(node -e ' + const rel = JSON.parse(process.argv[1] || "{}"); + const apk = (rel.assets || []).find(a => a?.name === "DS-Bot-nightly-android.apk"); + if (!apk) process.exit(0); + const digest = typeof apk.digest === "string" && apk.digest.startsWith("sha256:") ? apk.digest.slice(7).toLowerCase() : ""; + const target = String(rel.target_commitish || "").slice(0, 8); + console.log(`${digest}\t${target}`); + ' "$rel_json" || true)" + + if [ -n "$has_old_apk" ]; then + IFS=$'\t' read -r api_digest prev_target <<< "$has_old_apk" + preserved_sha="" + if gh release download nightly -p SHA256SUMS.txt -D "$RUNNER_TEMP/prev" --clobber >/dev/null 2>&1; then + sums_sha="$(grep -E '^[0-9a-fA-F]{64}[[:space:]]+\*?DS-Bot-nightly-android\.apk$' "$RUNNER_TEMP/prev/SHA256SUMS.txt" | awk '{print tolower($1)}' | head -n1 || true)" + if [ -n "$sums_sha" ] && { [ -z "$api_digest" ] || [ "$sums_sha" = "$api_digest" ]; }; then + preserved_sha="$sums_sha" + fi + elif [ -n "$api_digest" ]; then + preserved_sha="$api_digest" + fi + + if [ -n "$preserved_sha" ]; then + echo "${preserved_sha} DS-Bot-nightly-android.apk" >> "$RUNNER_TEMP/upload/SHA256SUMS.txt" + echo "" >> "$RUNNER_TEMP/nightly/report.md" + echo "_Note: \`DS-Bot-nightly-android.apk\` was retained unchanged from previous nightly (\`${prev_target:-previous}\`) with its verified SHA-256 preserved in \`SHA256SUMS.txt\`._" >> "$RUNNER_TEMP/nightly/report.md" + else + echo "Deleting stale DS-Bot-nightly-android.apk because no verified SHA-256 checksum was found." + gh release delete-asset nightly DS-Bot-nightly-android.apk --yes || true + fi + fi + fi + ls -lh "$RUNNER_TEMP/upload" + - name: Update rolling nightly tag and GitHub pre-release + run: | + set -euo pipefail + git tag -f nightly "$NIGHTLY_SHA" + git push origin refs/tags/nightly --force + + title="Nightly (dev @ $NIGHTLY_SHORT_SHA)" + notes="$RUNNER_TEMP/nightly/report.md" + if gh release view nightly >/dev/null 2>&1; then + gh release edit nightly \ + --prerelease \ + --latest=false \ + --title "$title" \ + --notes-file "$notes" + else + gh release create nightly \ + --target "$NIGHTLY_SHA" \ + --prerelease \ + --latest=false \ + --title "$title" \ + --notes-file "$notes" + fi + node app/scripts/release-upload.mjs nightly "$RUNNER_TEMP"/upload/* + cat "$notes" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 34bbc82ed..24e6554ae 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -46,7 +46,9 @@ jobs: outputs: checkout_ref: ${{ steps.filter.outputs.checkout_ref }} full: ${{ steps.filter.outputs.full }} + hotfix: ${{ steps.filter.outputs.hotfix }} app_package_full: ${{ steps.filter.outputs.app_package_full }} + app_package_macos_x64: ${{ steps.filter.outputs.app_package_macos_x64 }} app_package_linux: ${{ steps.filter.outputs.app_package_linux }} app_update: ${{ steps.filter.outputs.app_update }} mobile_ios: ${{ steps.filter.outputs.mobile_ios }} @@ -62,22 +64,44 @@ jobs: EVENT: ${{ github.event_name }} REF: ${{ github.ref }} BASE_REF: ${{ github.base_ref }} + HEAD_REF: ${{ github.head_ref }} BEFORE: ${{ github.event.before }} SHA: ${{ github.sha }} PR_NUMBER: ${{ github.event.pull_request.number }} + IS_SAME_REPO: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }} PR_FULL_PACKAGE: ${{ inputs.force_full || (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci/full-package')) }} + PR_HOTFIX: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'release/hotfix') }} GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} run: | set -euo pipefail full=false + explicit_full=false + hotfix=false main_push=false - if [ "$EVENT" = "pull_request" ] && [ "$PR_FULL_PACKAGE" != "true" ] && [ -n "$PR_NUMBER" ] && [ -n "$GH_TOKEN" ]; then - if gh api "repos/$GH_REPO/issues/$PR_NUMBER/labels" --jq '.[].name' 2>/dev/null | grep -qx 'ci/full-package'; then + + if [ "$EVENT" = "pull_request" ] && [ -n "$PR_NUMBER" ] && [ -n "$GH_TOKEN" ]; then + live_labels="$(gh api "repos/$GH_REPO/issues/$PR_NUMBER/labels" --jq '.[].name' 2>/dev/null || true)" + if [ "$PR_FULL_PACKAGE" != "true" ] && grep -qx 'ci/full-package' <<< "$live_labels"; then PR_FULL_PACKAGE=true fi + if [ "$PR_HOTFIX" != "true" ] && grep -qx 'release/hotfix' <<< "$live_labels"; then + PR_HOTFIX=true + fi + fi + + if [ "$EVENT" = "pull_request" ] && [ "$BASE_REF" = "main" ]; then + if [ "$PR_HOTFIX" = "true" ]; then + hotfix=true + elif [ "$IS_SAME_REPO" = "true" ] && [[ "$HEAD_REF" == hotfix/* || "$HEAD_REF" == fix/hot-* ]]; then + hotfix=true + fi fi - if [ "$EVENT" = "schedule" ] || [ "$EVENT" = "workflow_dispatch" ] || [ "$BASE_REF" = "main" ] || [ "$PR_FULL_PACKAGE" = "true" ]; then + + if [ "$EVENT" = "schedule" ] || [ "$EVENT" = "workflow_dispatch" ] || [ "$PR_FULL_PACKAGE" = "true" ]; then + explicit_full=true + full=true + elif [ "$BASE_REF" = "main" ] && [ "$hotfix" = "false" ]; then full=true elif [ "$EVENT" = "push" ] && [ "$REF" = "refs/heads/main" ]; then # Release PRs already pass the full matrix on BASE_REF=main before merge, and daily @@ -103,8 +127,51 @@ jobs: fi fi + # In hotfix fast-lane mode on BASE_REF=main, a pure version bump inside package.json or + # package-lock.json must not force 24m iOS, 14m Android, or 4-OS Electron packaging. + effective_changed="$changed" + if [ "$hotfix" = "true" ] && [ "$full" = "false" ] && [ -n "$changed" ]; then + effective_changed="$(BASE_REF="$BASE_REF" CHANGED_FILES="$changed" node -e ' + const { execFileSync } = require("node:child_process"); + const fs = require("node:fs"); + const baseRef = process.env.BASE_REF; + const files = process.env.CHANGED_FILES.split(/\r?\n/).filter(Boolean); + const VERSION_BUMP_FILES = new Set([ + "ds-bot/package.json", + "ds-bot/package-lock.json", + "app/package.json", + "app/package-lock.json", + ]); + function stripVersion(file, obj) { + if (!obj || typeof obj !== "object") return obj; + const copy = JSON.parse(JSON.stringify(obj)); + delete copy.version; + if (file.endsWith("package-lock.json") && copy.packages && typeof copy.packages === "object") { + if (copy.packages[""]) delete copy.packages[""].version; + if (copy.packages["node_modules/ds-bot"]) delete copy.packages["node_modules/ds-bot"].version; + if (copy.packages["../ds-bot"]) delete copy.packages["../ds-bot"].version; + } + return copy; + } + function isVersionOnlyChange(file) { + try { + const baseRaw = execFileSync("git", ["show", `origin/${baseRef}:${file}`], { + encoding: "utf8", + maxBuffer: 16 * 1024 * 1024, + }); + const headRaw = fs.readFileSync(file, "utf8"); + return JSON.stringify(stripVersion(file, JSON.parse(baseRaw))) === JSON.stringify(stripVersion(file, JSON.parse(headRaw))); + } catch { + return false; + } + } + const kept = files.filter((file) => !(VERSION_BUMP_FILES.has(file) && isVersionOnlyChange(file))); + process.stdout.write(kept.join("\n")); + ' 2>/dev/null || printf '%s' "$changed")" + fi + has() { - grep -qE "$1" <<< "$changed" + grep -qE "$1" <<< "$effective_changed" } if [ "$full" = "false" ] && [ "$main_push" = "false" ] && has '^\.github/workflows/(package|full-package|release)\.yml$'; then @@ -123,6 +190,26 @@ jobs: app_update=false mobile_ios=false mobile_android=false + elif [ "$hotfix" = "true" ]; then + # Hotfix fast-lane on BASE_REF=main: run Linux packaged smoke by default and trigger + # native/4-OS packaging only for genuinely affected paths in origin/main...HEAD. + app_package_full=false + app_package_linux=true + app_update=false + mobile_ios=false + mobile_android=false + if has '^(app/(package\.json|package-lock\.json|electron-builder\.yml|\.npmrc|build/|engine/|assets/|scripts/((before-pack|check-lifecycle|check-packed|check-update|dist|prepare-runtime|seed-electron-checksums)\.|primary-runtime\.lock\.json$)|src/(update|mac-updater\.mjs))|ds-bot/(package\.json|package-lock\.json|cordis\.patch\.yml|office\.js|src/office/|src/host/computer/))'; then + app_package_full=true + fi + if has '^app/(package\.json|package-lock\.json|electron-builder\.yml|build/|scripts/(before-pack|check-update|dist)\.|src/(update|mac-updater\.mjs))'; then + app_update=true + fi + if has '^(mobile/(app\.json|app\.config\.js|package\.json|package-lock\.json|plugins/|ios/|assets/|eas\.json)|ds-bot/package\.json$)'; then + mobile_ios=true + fi + if has '^(mobile/(app\.json|app\.config\.js|package\.json|package-lock\.json|plugins/|android/|assets/|eas\.json)|ds-bot/package\.json$|\.github/gradle/)'; then + mobile_android=true + fi else # Everyday PRs to dev defer heavy installers and native mobile builds to the daily # dev Nightly, release/hotfix PRs to main, or an explicit `ci/full-package` label. @@ -133,6 +220,13 @@ jobs: mobile_android=false fi + # macos-26-intel routinely queues for an hour; skip it on pull_request events unless + # explicitly requested via ci/full-package, workflow_dispatch, or daily schedule. + app_package_macos_x64=false + if [ "$app_package_full" = "true" ] && [ "$explicit_full" = "true" ]; then + app_package_macos_x64=true + fi + checkout_ref="" if [ "$EVENT" = "schedule" ] || [ "$EVENT" = "workflow_dispatch" ]; then # Pin every downstream packaging job to one immutable SHA so macOS/Windows queues @@ -143,7 +237,9 @@ jobs: { echo "checkout_ref=$checkout_ref" echo "full=$full" + echo "hotfix=$hotfix" echo "app_package_full=$app_package_full" + echo "app_package_macos_x64=$app_package_macos_x64" echo "app_package_linux=$app_package_linux" echo "app_update=$app_update" echo "mobile_ios=$mobile_ios" @@ -468,9 +564,7 @@ jobs: strategy: fail-fast: false matrix: - include: - - { arch: arm64, runner: macos-latest } - - { arch: x64, runner: macos-26-intel } + include: ${{ fromJson(needs.changes.outputs.app_package_macos_x64 == 'true' && '[{"arch":"arm64","runner":"macos-latest"},{"arch":"x64","runner":"macos-26-intel"}]' || '[{"arch":"arm64","runner":"macos-latest"}]') }} defaults: run: shell: bash diff --git a/.github/workflows/pr-merge-guard.yml b/.github/workflows/pr-merge-guard.yml new file mode 100644 index 000000000..8c02888b0 --- /dev/null +++ b/.github/workflows/pr-merge-guard.yml @@ -0,0 +1,169 @@ +name: PR Merge Guard + +# Dedicated merge-guard workflow isolated from comment/review events so a skipped run on +# issue_comment or pull_request_review can never satisfy or shadow branch protection. +# Publishes commit status "PR merge guard" (distinct from job name "Evaluate merge guard") +# on each open PR head SHA, and refreshes open dev PRs whenever Milestones change. + +on: + pull_request_target: + types: [opened, reopened, synchronize, edited, labeled, unlabeled, milestoned, demilestoned] + milestone: + types: [created, closed, opened, edited, deleted] + +permissions: + contents: read + +concurrency: + group: >- + ${{ github.event_name == 'milestone' + && 'pr-merge-guard-milestone' + || format('pr-merge-guard-pr-{0}', github.event.pull_request.number) }} + cancel-in-progress: false + +jobs: + evaluate-merge-guard: + name: Evaluate merge guard + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: read + pull-requests: read + statuses: write + steps: + - name: Checkout trusted guard script and dev version + uses: actions/checkout@v4 + with: + ref: dev + fetch-depth: 1 + persist-credentials: false + sparse-checkout: | + ds-bot/package.json + scripts/check-release-milestone.mjs + sparse-checkout-cone-mode: false + - name: Evaluate needs-product-ok and future Milestone guards + uses: actions/github-script@v7 + with: + script: | + const fs = require('node:fs'); + const path = require('node:path'); + const { pathToFileURL } = require('node:url'); + + const { owner, repo } = context.repo; + const guardPath = path.resolve('scripts/check-release-milestone.mjs'); + const pkgPath = path.resolve('ds-bot/package.json'); + if (!fs.existsSync(guardPath) || !fs.existsSync(pkgPath)) { + core.warning('PR Merge Guard skipped: guard script or ds-bot/package.json not yet present on dev.'); + return; + } + + const currentVersion = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version; + const { evaluatePrMergeGuard } = await import(pathToFileURL(guardPath).href); + const openMilestones = await github.paginate(github.rest.issues.listMilestones, { + owner, + repo, + state: 'open', + per_page: 100, + }); + + async function publishStatus(prNumber, sha, verdict) { + if (!sha) return; + const description = verdict.ok + ? verdict.summary.slice(0, 140) + : `${verdict.reasons.map((r) => r.code).join(', ')}: ${verdict.summary}`.slice(0, 140); + try { + await github.rest.repos.createCommitStatus({ + owner, + repo, + sha, + state: verdict.ok ? 'success' : 'failure', + context: 'PR merge guard', + description, + target_url: `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`, + }); + } catch (err) { + core.warning(`PR #${prNumber}: could not publish commit status (${err?.message || err}).`); + } + } + + if (context.eventName === 'milestone') { + const openDevPrs = await github.paginate(github.rest.pulls.list, { + owner, + repo, + state: 'open', + base: 'dev', + per_page: 100, + }); + const summaryLines = [ + `### Milestone event (\`${context.payload.action}\`: \`${context.payload.milestone?.title || ''}\`) — refreshed ${openDevPrs.length} open \`dev\` PR(s)`, + `- **Current \`dev\` version**: \`v${currentVersion}\``, + ]; + for (const pr of openDevPrs) { + const verdict = evaluatePrMergeGuard({ + baseRef: String(pr.base?.ref || 'dev'), + labels: Array.isArray(pr.labels) ? pr.labels : [], + prMilestoneTitle: pr.milestone?.title ?? null, + currentVersion, + milestones: openMilestones, + }); + await publishStatus(pr.number, pr.head?.sha, verdict); + summaryLines.push( + `- PR #${pr.number} (\`${pr.milestone?.title || 'no milestone'}\`): ${verdict.ok ? 'PASS' : `BLOCKED (${verdict.reasons.map((r) => r.code).join(', ')})`}`, + ); + } + if (process.env.GITHUB_STEP_SUMMARY) { + fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${summaryLines.join('\n')}\n`); + } + core.info(`Refreshed PR merge guard status for ${openDevPrs.length} open dev PR(s).`); + return; + } + + const prNumber = context.payload.pull_request?.number; + if (!prNumber) return; + + const { data: livePr } = await github.rest.pulls.get({ + owner, + repo, + pull_number: prNumber, + }); + if (!livePr || livePr.state !== 'open') { + core.info(`PR #${prNumber} is no longer open; skipping merge guard.`); + return; + } + + const verdict = evaluatePrMergeGuard({ + baseRef: String(livePr.base?.ref || ''), + labels: Array.isArray(livePr.labels) ? livePr.labels : [], + prMilestoneTitle: livePr.milestone?.title ?? null, + currentVersion, + milestones: openMilestones, + }); + + await publishStatus(prNumber, livePr.head?.sha, verdict); + + const summaryLines = [ + `### PR #${prNumber} merge guard`, + `- **Base branch**: \`${livePr.base?.ref || ''}\``, + `- **Current \`dev\` version**: \`v${currentVersion}\``, + `- **Active \`dev\` Milestone**: ${verdict.activeMilestone ? `\`${verdict.activeMilestone}\`` : '_none_'}`, + `- **PR Milestone**: ${verdict.prMilestone ? `\`${verdict.prMilestone}\`` : '_none_'}`, + `- **Result**: ${verdict.ok ? 'PASS' : 'BLOCKED'}`, + ]; + if (!verdict.ok) { + for (const reason of verdict.reasons) { + summaryLines.push(`- **Blocked (${reason.code})**: ${reason.message}`); + } + } + if (process.env.GITHUB_STEP_SUMMARY) { + fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${summaryLines.join('\n')}\n`); + } + + if (!verdict.ok) { + for (const reason of verdict.reasons) { + core.error(reason.message); + } + core.setFailed(verdict.summary); + } else { + core.info(verdict.summary); + } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index acfbe8acb..e402d0cc8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,10 +1,11 @@ name: Release # Publishes ds-bot to npm when a GitHub release is published, then attaches the desktop app's -# Windows installer, macOS zips and Linux packages, and the phone app's Android APK, to the release. Windows and the Linux -# AppImage update from latest.yml / latest-linux.yml; macOS self-updates from its zip and SHA256SUMS.txt -# (falling back to the release page when read-only or translocated); the Linux deb opens the release -# page for a manual download. +# Windows installer, macOS zips and Linux packages, and (when mobile changed) the phone app's +# Android APK to the release. Windows and the Linux AppImage update from latest.yml / +# latest-linux.yml; macOS self-updates from its zip and SHA256SUMS.txt (falling back to the +# release page when read-only or translocated); the Linux deb opens the release page for a +# manual download. # # npm Trusted Publishing: npm trusts this workflow through GitHub's OIDC token, so the # repository keeps no npm token, and every version gets a provenance statement. It is set @@ -15,9 +16,10 @@ name: Release # main. A version with a pre-release part (0.2.0-rc.1) goes to the npm tag "next", so that # "latest" stays on the last stable version. # -# Publish the release with "Set as latest release" turned off: the last job marks it Latest -# once every package, the download table and SHA256SUMS.txt are on it, so a releases/latest -# link never finds a release whose installer is still being built. +# Publish the release with "Set as latest release" turned off: the downloads job marks it Latest +# once npm publish, Windows, macOS arm64, Linux, and (when needed) Android succeed (~8-10 min). +# The Intel macOS (x64) build runs in parallel without blocking Latest, then asynchronously +# attaches DS-Bot-*-mac-x64.zip and idempotently refreshes the download table and SHA256SUMS.txt. on: release: @@ -28,23 +30,33 @@ on: description: Run every check and pack the package, but do not publish type: boolean default: true + force_android: + description: Force rebuilding the Android APK even if mobile files did not change + type: boolean + default: false permissions: - # write: attach the package file to the release. - contents: write - id-token: write + contents: read concurrency: group: release cancel-in-progress: false jobs: - # Fast pre-flight gate (~5 s) so invalid tags or mismatched versions fail immediately - # without blocking the platform build jobs behind npm tests. + # Fast pre-flight gate (~5-10 s) so invalid tags, mismatched versions, or unfinished release + # Milestones fail immediately, and decides whether Android APK needs rebuilding. validate: name: Validate release metadata runs-on: ubuntu-latest timeout-minutes: 5 + permissions: + contents: read + issues: read + pull-requests: read + outputs: + build_android: ${{ steps.android-scope.outputs.build_android }} + android_fallback_version: ${{ steps.android-scope.outputs.android_fallback_version }} + android_fallback_size: ${{ steps.android-scope.outputs.android_fallback_size }} defaults: run: shell: bash @@ -78,12 +90,110 @@ jobs: echo "::error::app/package.json has version $app, but ds-bot/package.json has $version. Give both the same version." exit 1 fi + - name: Check release Milestone + env: + GH_TOKEN: ${{ github.token }} + EVENT: ${{ github.event_name }} + DRY_RUN: ${{ inputs.dry_run }} + RELEASE_BODY: ${{ github.event.release.body }} + run: | + set -euo pipefail + version="$(node -p "require('./package.json').version")" + prev_tag="$(git describe --tags --abbrev=0 --match 'v*' --exclude='*-*' HEAD^ 2>/dev/null || true)" + # Only inspect commits introduced by this release (HEAD itself, and for merge commits the + # second-parent range HEAD^1..HEAD), never older main history on HEAD^1 so a regular + # release after a hotfix cannot inherit the previous hotfix's trailer. + if git rev-parse --verify HEAD^2 >/dev/null 2>&1; then + release_commits_msg="$(git log --format=%B HEAD^1..HEAD 2>/dev/null || true)" + else + release_commits_msg="$(git log -1 --format=%B HEAD 2>/dev/null || true)" + fi + args=(--version "v$version" --repo "$GITHUB_REPOSITORY" --head-ref HEAD) + if [ -n "$prev_tag" ]; then + args+=(--base-ref "$prev_tag") + fi + if [ "$EVENT" = "workflow_dispatch" ] && [ "$DRY_RUN" = "true" ]; then + args+=(--allow-open) + elif grep -Fq '' <<< "$RELEASE_BODY" \ + || grep -qE '(^Hotfix-Release:\s*true$|Merge pull request #[0-9]+ from [^/]+/(hotfix/|fix/hot-))' <<< "$release_commits_msg"; then + args+=(--hotfix) + fi + node ../scripts/check-release-milestone.mjs "${args[@]}" + - name: Decide Android APK build scope + id: android-scope + env: + GH_TOKEN: ${{ github.token }} + FORCE_ANDROID: ${{ inputs.force_android }} + EVENT_TAG: ${{ github.event.release.tag_name }} + run: | + set -euo pipefail + build_android=true + fallback_version="" + fallback_size="" + + if [ "$FORCE_ANDROID" != "true" ]; then + current_ver="$(node -p "require('./package.json').version")" + current_tag="${EVENT_TAG:-v$current_ver}" + + # Filter release metadata via --jq and stream via stdin to node (never via argv, which + # overflows Linux MAX_ARG_STRLEN at 128 KiB on rich release notes). + if candidates="$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=20" \ + --jq '[.[] | {tag_name, draft, prerelease, assets: [.assets[]? | {name, size}]}]' \ + | CURRENT_TAG="$current_tag" node -e ' + const fs = require("node:fs"); + const releases = JSON.parse(fs.readFileSync(0, "utf8") || "[]"); + const currentTag = process.env.CURRENT_TAG || ""; + for (const rel of releases) { + if (!rel || rel.draft || rel.prerelease) continue; + const tag = String(rel.tag_name || ""); + if (!tag || tag === currentTag || !/^v\d+\.\d+\.\d+$/u.test(tag)) continue; + const ver = tag.slice(1); + const assets = Array.isArray(rel.assets) ? rel.assets : []; + const apk = assets.find(a => a?.name === `DS-Bot-${ver}-android.apk` && Number(a.size) > 0); + const sums = assets.find(a => a?.name === "SHA256SUMS.txt"); + if (apk && sums) { + console.log(`${tag}\t${ver}\t${apk.size}`); + } + } + ')"; then + while IFS=$'\t' read -r apk_tag apk_ver apk_size; do + [ -z "$apk_tag" ] && continue + if ! git rev-parse --verify "refs/tags/$apk_tag^{commit}" >/dev/null 2>&1; then + continue + fi + if ! git merge-base --is-ancestor "refs/tags/$apk_tag^{commit}" HEAD^ 2>/dev/null; then + continue + fi + # Exclude generated release-notes metadata that changes on every release bump so + # desktop-only releases can reuse the previous signed Android APK. + changed="$(git -c core.quotepath=false diff --name-only "$apk_tag..HEAD" | grep -Ev '^ds-bot/src/shared/release-notes(-generated\.js|\.json)$' || true)" + if ! grep -qE '^(mobile/|link/|\.github/gradle/|ds-bot/src/shared/|ds-bot/src/client/(i18n|themes|sources|inks|characters|usage-data|lru|learning-card-model|mark-states|motion-rest|inbox-text|effects)\.js$|ds-bot/src/client/(avatar|locales)/)' <<< "$changed"; then + build_android=false + fallback_version="$apk_ver" + fallback_size="$apk_size" + echo "No mobile changes since ancestor $apk_tag (signed APK present); skipping Android rebuild." + fi + break + done <<< "$candidates" + else + echo "::warning::Failed to inspect previous GitHub Releases for Android APK reuse; falling back to rebuilding Android APK." + fi + fi + + { + echo "build_android=$build_android" + echo "android_fallback_version=$fallback_version" + echo "android_fallback_size=$fallback_size" + } | tee -a "$GITHUB_OUTPUT" publish: name: Check and publish needs: validate runs-on: ubuntu-latest timeout-minutes: 20 + permissions: + contents: write + id-token: write defaults: run: shell: bash @@ -162,10 +272,14 @@ jobs: cache-dependency-path: app/package-lock.json - name: Name the download cache id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} run: | - prefix="electron-downloads-${{ runner.os }}-${{ runner.arch }}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" echo "prefix=$prefix" >> "$GITHUB_OUTPUT" - echo "key=${prefix}${{ hashFiles('app/electron-builder.yml') }}" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" - name: Restore Electron and the build tools id: downloads uses: actions/cache/restore@v4 @@ -177,8 +291,6 @@ jobs: restore-keys: ${{ steps.downloads-key.outputs.prefix }} - run: npm ci --no-fund --no-audit env: - # Packaging downloads/reuses Electron via @electron/get after seed-electron-checksums.mjs - # under dist.mjs retries, avoiding an unused binary download during npm ci. ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - run: node scripts/seed-electron-checksums.mjs - name: Restore the locked runtime archives @@ -205,7 +317,7 @@ jobs: - name: Check the packaged app run: node scripts/check-packed.mjs # Upload as a workflow artifact so nothing lands on the public GitHub Release until - # publish and every platform build have succeeded (downloads attaches everything at once). + # publish and every primary platform build have succeeded (downloads attaches them at once). - name: Upload installer artifact uses: actions/upload-artifact@v4 with: @@ -218,17 +330,11 @@ jobs: if-no-files-found: error compression-level: 0 - app-macos: - name: Desktop app zip (macOS ${{ matrix.arch }}) + app-macos-arm64: + name: Desktop app zip (macOS arm64) needs: validate - runs-on: ${{ matrix.runner }} + runs-on: macos-latest timeout-minutes: 45 - strategy: - fail-fast: false - matrix: - include: - - { arch: arm64, runner: macos-latest } - - { arch: x64, runner: macos-26-intel } defaults: run: shell: bash @@ -242,10 +348,14 @@ jobs: cache-dependency-path: app/package-lock.json - name: Name the download cache id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} run: | - prefix="electron-downloads-${{ runner.os }}-${{ runner.arch }}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" echo "prefix=$prefix" >> "$GITHUB_OUTPUT" - echo "key=${prefix}${{ hashFiles('app/electron-builder.yml') }}" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" - name: Restore Electron and the build tools id: downloads uses: actions/cache/restore@v4 @@ -257,8 +367,6 @@ jobs: restore-keys: ${{ steps.downloads-key.outputs.prefix }} - run: npm ci --no-fund --no-audit env: - # Packaging downloads/reuses Electron via @electron/get after seed-electron-checksums.mjs - # under dist.mjs retries, avoiding an unused binary download during npm ci. ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - run: node scripts/seed-electron-checksums.mjs - name: Restore the locked runtime archives @@ -287,21 +395,95 @@ jobs: key: ${{ steps.downloads.outputs.cache-primary-key }} - name: Check packaged binary architecture run: | - if [ "${{ matrix.arch }}" = x64 ]; then - exe="dist-pack/mac/DS Bot.app/Contents/MacOS/DS Bot" - expected=x86_64 - else - exe="dist-pack/mac-arm64/DS Bot.app/Contents/MacOS/DS Bot" - expected=arm64 - fi - file -b "$exe" | grep -F "$expected" + exe="dist-pack/mac-arm64/DS Bot.app/Contents/MacOS/DS Bot" + file -b "$exe" | grep -F "arm64" + - name: Check the packaged app + run: node scripts/check-packed.mjs + - name: Upload zip artifact + uses: actions/upload-artifact@v4 + with: + name: DS-Bot-mac-arm64 + path: app/dist-pack/DS-Bot-*-mac-arm64.zip + retention-days: 7 + if-no-files-found: error + compression-level: 0 + + # Decoupled from downloads so Intel runner queues never block marking the release Latest. + # Once both downloads and app-macos-x64 finish, downloads-macos-x64 attaches the zip and + # idempotently refreshes the download table and SHA256SUMS.txt. + app-macos-x64: + name: Desktop app zip (macOS x64) + needs: validate + runs-on: macos-26-intel + timeout-minutes: 45 + defaults: + run: + shell: bash + working-directory: app + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: app/package-lock.json + - name: Name the download cache + id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} + run: | + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + echo "prefix=$prefix" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" + - name: Restore Electron and the build tools + id: downloads + uses: actions/cache/restore@v4 + with: + path: | + ~/Library/Caches/electron + ~/Library/Caches/electron-builder + key: ${{ steps.downloads-key.outputs.key }} + restore-keys: ${{ steps.downloads-key.outputs.prefix }} + - run: npm ci --no-fund --no-audit + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + - run: node scripts/seed-electron-checksums.mjs + - name: Restore the locked runtime archives + id: runtime-cache + uses: actions/cache/restore@v4 + with: + path: app/build/runtime-cache + key: runtime-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('app/scripts/primary-runtime.lock.json') }} + - run: npm run dist + env: + ELECTRON_BUILDER_COMPRESSION_LEVEL: '5' + - name: Save the locked runtime archives + if: github.event_name != 'release' && steps.runtime-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: app/build/runtime-cache + key: ${{ steps.runtime-cache.outputs.cache-primary-key }} + - name: Save Electron and the build tools + if: github.event_name != 'release' && steps.downloads.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: | + ~/Library/Caches/electron + ~/Library/Caches/electron-builder + key: ${{ steps.downloads.outputs.cache-primary-key }} + - name: Check packaged binary architecture + run: | + exe="dist-pack/mac/DS Bot.app/Contents/MacOS/DS Bot" + file -b "$exe" | grep -F "x86_64" - name: Check the packaged app run: node scripts/check-packed.mjs - name: Upload zip artifact uses: actions/upload-artifact@v4 with: - name: DS-Bot-mac-${{ matrix.arch }} - path: app/dist-pack/DS-Bot-*-mac-${{ matrix.arch }}.zip + name: DS-Bot-mac-x64 + path: app/dist-pack/DS-Bot-*-mac-x64.zip retention-days: 7 if-no-files-found: error compression-level: 0 @@ -324,10 +506,14 @@ jobs: cache-dependency-path: app/package-lock.json - name: Name the download cache id: downloads-key + env: + RUNNER_OS: ${{ runner.os }} + RUNNER_ARCH: ${{ runner.arch }} + BUILDER_HASH: ${{ hashFiles('app/electron-builder.yml') }} run: | - prefix="electron-downloads-${{ runner.os }}-${{ runner.arch }}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" + prefix="electron-downloads-${RUNNER_OS}-${RUNNER_ARCH}-$(node -p "const d = require('./package.json').devDependencies; 'electron-' + d.electron + '-builder-' + d['electron-builder']")-" echo "prefix=$prefix" >> "$GITHUB_OUTPUT" - echo "key=${prefix}${{ hashFiles('app/electron-builder.yml') }}" >> "$GITHUB_OUTPUT" + echo "key=${prefix}${BUILDER_HASH}" >> "$GITHUB_OUTPUT" - name: Restore Electron and the build tools id: downloads uses: actions/cache/restore@v4 @@ -339,8 +525,6 @@ jobs: restore-keys: ${{ steps.downloads-key.outputs.prefix }} - run: npm ci --no-fund --no-audit env: - # Packaging downloads/reuses Electron via @electron/get after seed-electron-checksums.mjs - # under dist.mjs retries, avoiding an unused binary download during npm ci. ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - run: node scripts/seed-electron-checksums.mjs - name: Restore the locked runtime archives @@ -394,6 +578,7 @@ jobs: app-android: name: Phone app (Android) needs: validate + if: needs.validate.outputs.build_android == 'true' runs-on: ubuntu-latest timeout-minutes: 60 defaults: @@ -433,8 +618,6 @@ jobs: restore-keys: android-ccache-v2-${{ runner.os }}-${{ runner.arch }}- - uses: gradle/actions/setup-gradle@v4 with: - # Tag builds cannot share newly written caches with later tags; main's scheduled CI - # and branch workflow_dispatch runs keep Gradle and ccache warm. cache-read-only: ${{ github.event_name == 'release' }} - name: Build the APK env: @@ -443,7 +626,6 @@ jobs: KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} CCACHE_BASEDIR: ${{ github.workspace }} CCACHE_NOHASHDIR: 'true' - # Default mtime check misses whenever GitHub rotates runner image builds with identical NDK binaries. CCACHE_COMPILERCHECK: content CCACHE_SLOPPINESS: include_file_mtime,include_file_ctime,time_macros CCACHE_MAXSIZE: 600M @@ -477,8 +659,6 @@ jobs: echo "::error::Release APK contains x86 simulator binaries." exit 1 fi - # --min-sdk-version 21 makes apksigner verify the v1 JAR signature too, even though - # the app's minSdkVersion is 24 (where Android prefers v2/v3). apksigner="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)/apksigner" zipalign="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)/zipalign" aapt2="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)/aapt2" @@ -517,9 +697,19 @@ jobs: downloads: name: Download table, checksums and Latest - needs: [publish, app-windows, app-macos, app-linux, app-android] + needs: [validate, publish, app-windows, app-macos-arm64, app-linux, app-android] + if: >- + ${{ !cancelled() && + needs.validate.result == 'success' && + needs.publish.result == 'success' && + needs.app-windows.result == 'success' && + needs.app-macos-arm64.result == 'success' && + needs.app-linux.result == 'success' && + (needs.app-android.result == 'success' || (needs.validate.outputs.build_android == 'false' && needs.app-android.result == 'skipped')) }} runs-on: ubuntu-latest timeout-minutes: 20 + permissions: + contents: write defaults: run: shell: bash @@ -527,35 +717,66 @@ jobs: env: GH_TOKEN: ${{ github.token }} TAG: ${{ github.event.release.tag_name }} + BUILD_ANDROID: ${{ needs.validate.outputs.build_android }} + ANDROID_FALLBACK_VERSION: ${{ needs.validate.outputs.android_fallback_version }} + ANDROID_FALLBACK_SIZE: ${{ needs.validate.outputs.android_fallback_size }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - - name: Download built package artifacts + - name: Download Windows package artifact uses: actions/download-artifact@v4 with: - pattern: DS-Bot-* + name: DS-Bot-win-x64 + path: ${{ runner.temp }}/packages + - name: Download macOS arm64 package artifact + uses: actions/download-artifact@v4 + with: + name: DS-Bot-mac-arm64 + path: ${{ runner.temp }}/packages + - name: Download Linux package artifact + uses: actions/download-artifact@v4 + with: + name: DS-Bot-linux-x64 + path: ${{ runner.temp }}/packages + - name: Download Android package artifact + if: needs.validate.outputs.build_android == 'true' + uses: actions/download-artifact@v4 + with: + name: DS-Bot-android path: ${{ runner.temp }}/packages - merge-multiple: true - name: Read current release notes if: github.event_name == 'release' run: gh release view "$TAG" --json body --jq .body > "$RUNNER_TEMP/notes.md" - name: Write the download table and the checksums run: | + set -euo pipefail version="$(node -p "require('./package.json').version")" - notes=() - if [ -f "$RUNNER_TEMP/notes.md" ]; then notes=("$RUNNER_TEMP/notes.md"); fi - node scripts/release-notes.mjs "$version" "$RUNNER_TEMP/packages" "$RUNNER_TEMP/attach" "${notes[@]}" > "$RUNNER_TEMP/body.md" + args=("$version" "$RUNNER_TEMP/packages" "$RUNNER_TEMP/attach") + if [ -f "$RUNNER_TEMP/notes.md" ]; then args+=("$RUNNER_TEMP/notes.md"); fi + args+=(--pending mac-x64.zip --write-manifest "$RUNNER_TEMP/manifest/release-manifest.json") + if [ "$BUILD_ANDROID" = "false" ] && [ -n "$ANDROID_FALLBACK_VERSION" ]; then + ext="android.apk=$ANDROID_FALLBACK_VERSION" + if [ -n "$ANDROID_FALLBACK_SIZE" ]; then ext="${ext}:${ANDROID_FALLBACK_SIZE}"; fi + args+=(--external-package "$ext") + fi + node scripts/release-notes.mjs "${args[@]}" > "$RUNNER_TEMP/body.md" ls -l "$RUNNER_TEMP/packages" "$RUNNER_TEMP/attach" cat "$RUNNER_TEMP/body.md" >> "$GITHUB_STEP_SUMMARY" - - name: Attach all packages, checksums and copies to the release + - name: Upload release manifest for async macOS x64 attachment + uses: actions/upload-artifact@v4 + with: + name: release-manifest + path: ${{ runner.temp }}/manifest/release-manifest.json + retention-days: 7 + if-no-files-found: error + - name: Attach all primary packages, checksums and copies to the release if: github.event_name == 'release' run: | version="$(node -p "require('./package.json').version")" node scripts/legacy-release-assets.mjs \ "$RUNNER_TEMP/packages/DS-Bot-$version-mac-arm64.zip" \ - "$RUNNER_TEMP/packages/DS-Bot-$version-mac-x64.zip" \ "$RUNNER_TEMP/packages/DS-Bot-$version-linux-amd64.deb" node scripts/release-upload.mjs "$TAG" "$RUNNER_TEMP"/packages/* "$RUNNER_TEMP"/attach/* - name: Put the download table on top of the notes @@ -565,3 +786,60 @@ jobs: - name: Mark the release as Latest if: github.event_name == 'release' && !github.event.release.prerelease run: gh release edit "$TAG" --latest + + downloads-macos-x64: + name: Attach macOS x64 zip and refresh checksums + needs: [validate, downloads, app-macos-x64] + if: ${{ !cancelled() && needs.downloads.result == 'success' && needs.app-macos-x64.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + defaults: + run: + shell: bash + working-directory: app + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.release.tag_name }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Download release manifest + uses: actions/download-artifact@v4 + with: + name: release-manifest + path: ${{ runner.temp }}/manifest + - name: Download macOS x64 package artifact + uses: actions/download-artifact@v4 + with: + name: DS-Bot-mac-x64 + path: ${{ runner.temp }}/packages + - name: Read current release notes + if: github.event_name == 'release' + run: gh release view "$TAG" --json body --jq .body > "$RUNNER_TEMP/notes.md" + - name: Recompute download table and SHA256SUMS.txt idempotently + run: | + set -euo pipefail + version="$(node -p "require('./package.json').version")" + args=("$version" "$RUNNER_TEMP/packages" "$RUNNER_TEMP/attach") + if [ -f "$RUNNER_TEMP/notes.md" ]; then args+=("$RUNNER_TEMP/notes.md"); fi + args+=(--merge-manifest "$RUNNER_TEMP/manifest/release-manifest.json") + node scripts/release-notes.mjs "${args[@]}" > "$RUNNER_TEMP/body.md" + ls -l "$RUNNER_TEMP/packages" "$RUNNER_TEMP/attach" + cat "$RUNNER_TEMP/body.md" >> "$GITHUB_STEP_SUMMARY" + - name: Attach macOS x64 zip, legacy alias and updated SHA256SUMS.txt + if: github.event_name == 'release' + run: | + version="$(node -p "require('./package.json').version")" + node scripts/legacy-release-assets.mjs \ + "$RUNNER_TEMP/packages/DS-Bot-$version-mac-x64.zip" + # Upload updated SHA256SUMS.txt before publishing the macOS x64 archives so + # early downloaders never observe an archive missing from the checksum file. + node scripts/release-upload.mjs "$TAG" "$RUNNER_TEMP"/attach/* + node scripts/release-upload.mjs "$TAG" "$RUNNER_TEMP"/packages/* + - name: Refresh the download table on the release + if: github.event_name == 'release' + run: gh release edit "$TAG" --notes-file "$RUNNER_TEMP/body.md" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 160fb4dc9..1cbbbcc0d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -39,6 +39,8 @@ jobs: outputs: checkout_ref: ${{ steps.filter.outputs.checkout_ref }} full: ${{ steps.filter.outputs.full }} + hotfix: ${{ steps.filter.outputs.hotfix }} + release_pr: ${{ steps.filter.outputs.release_pr }} ds_bot: ${{ steps.filter.outputs.ds_bot }} ds_bot_browser: ${{ steps.filter.outputs.ds_bot_browser }} ds_bot_win: ${{ steps.filter.outputs.ds_bot_win }} @@ -59,13 +61,37 @@ jobs: EVENT: ${{ github.event_name }} REF: ${{ github.ref }} BASE_REF: ${{ github.base_ref }} + HEAD_REF: ${{ github.head_ref }} BEFORE: ${{ github.event.before }} SHA: ${{ github.sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + IS_SAME_REPO: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }} + PR_HOTFIX: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'release/hotfix') }} + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} run: | set -euo pipefail full=false main_push=false - if [ "$EVENT" = "schedule" ] || [ "$EVENT" = "workflow_dispatch" ] || [ "$BASE_REF" = "main" ]; then + hotfix=false + release_pr=false + + if [ "$EVENT" = "pull_request" ] && [ "$BASE_REF" = "main" ]; then + if [ "$PR_HOTFIX" = "true" ]; then + hotfix=true + elif [ "$IS_SAME_REPO" = "true" ] && [[ "$HEAD_REF" == hotfix/* || "$HEAD_REF" == fix/hot-* ]]; then + hotfix=true + elif [ -n "$PR_NUMBER" ] && [ -n "$GH_TOKEN" ]; then + if gh api "repos/$GH_REPO/issues/$PR_NUMBER/labels" --jq '.[].name' 2>/dev/null | grep -qx 'release/hotfix'; then + hotfix=true + fi + fi + if [ "$hotfix" = "false" ]; then + release_pr=true + fi + fi + + if [ "$EVENT" = "schedule" ] || [ "$EVENT" = "workflow_dispatch" ] || [ "$release_pr" = "true" ]; then full=true elif [ "$EVENT" = "push" ] && [ "$REF" = "refs/heads/main" ]; then # Release PRs already pass the full matrix on BASE_REF=main before merge, and daily @@ -129,12 +155,18 @@ jobs: mobile=false link=false docker=false - if has '^(ds-bot/|link/|start\.ps1$|CHANGELOG\.md$|scripts/check-pure-base-sync\.mjs$|\.github/workflows/(package|full-package|pr-triage-labels)\.yml$)'; then ds_bot=true; fi + if has '^(ds-bot/|link/|start\.ps1$|CHANGELOG\.md$|scripts/(check-pure-base-sync|check-release-milestone)\.mjs$|\.github/workflows/(package|full-package|pr-triage-labels|pr-merge-guard|release|nightly-release|cut-release)\.yml$)'; then ds_bot=true; fi if has '^(ds-bot/(src/client/|src/host/browser/|src/host/fonts\.js$|src/shared/|assets/|test/(browser/|harness-resolve\.mjs$)|scripts/|dev/harness/|package\.json$|package-lock\.json$)|app/ui/src/html-preview\.js$)'; then ds_bot_browser=true; fi - if has '^(app/|ds-bot/|link/|README\.md$|README\.zh\.md$)'; then app_unit=true; fi - if has '^(mobile/|link/|CHANGELOG\.md$|ds-bot/package\.json$|ds-bot/src/shared/|ds-bot/src/client/(i18n|themes|inks|characters|usage-data|lru|learning-card-model|mark-states|motion-rest)\.js$|ds-bot/src/client/avatar/)'; then mobile=true; fi + if has '^(app/|ds-bot/|link/|README\.md$|README\.zh\.md$|\.github/workflows/release\.yml$)'; then app_unit=true; fi + if has '^(mobile/|link/|CHANGELOG\.md$|ds-bot/(package\.json|link\.js)$|ds-bot/src/shared/|ds-bot/src/host/phone\.js$|ds-bot/src/client/(i18n|themes|sources|inks|characters|usage-data|lru|learning-card-model|mark-states|motion-rest|inbox-text|effects)\.js$|ds-bot/src/client/(avatar|locales)/)'; then mobile=true; fi if has '^link/'; then link=true; fi if has '^(docker/|docker-compose.*\.yml$|\.dockerignore$)'; then docker=true; fi + # Hotfix PRs targeting main still run the fast 4-shard Windows unit suites (~5m) + # whenever plugin or desktop code changes so main never loses Windows test coverage. + if [ "$hotfix" = "true" ]; then + if [ "$ds_bot" = "true" ]; then ds_bot_win=true; fi + if [ "$app_unit" = "true" ]; then app_unit_win=true; fi + fi # Push to dev stays fast and Linux-only so rapid merges warm Linux caches and catch # cross-PR regressions immediately without hogging Windows or Docker runners; Windows, # Node 22, and Docker :dev publishing run on the daily dev Nightly. @@ -155,6 +187,8 @@ jobs: { echo "checkout_ref=$checkout_ref" echo "full=$full" + echo "hotfix=$hotfix" + echo "release_pr=$release_pr" echo "ds_bot=$ds_bot" echo "ds_bot_browser=$ds_bot_browser" echo "ds_bot_win=$ds_bot_win" @@ -273,11 +307,15 @@ jobs: run: npm run test:browser test-windows: - name: windows-latest · Node 24 + name: windows-latest · Node 24 (shard ${{ matrix.shard }}/4) needs: changes if: needs.changes.outputs.ds_bot_win == 'true' runs-on: windows-latest - timeout-minutes: 30 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] defaults: run: shell: bash @@ -306,16 +344,18 @@ jobs: if: steps.harness-cache.outputs.cache-hit != 'true' run: npm run harness - name: Save DSH test harness - if: (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.ref == '')) && steps.harness-cache.outputs.cache-hit != 'true' + if: matrix.shard == 1 && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.ref == '')) && steps.harness-cache.outputs.cache-hit != 'true' uses: actions/cache/save@v4 with: path: ds-bot/dev/harness/node_modules key: ${{ steps.harness-cache.outputs.cache-primary-key }} - - name: Run unit tests (Windows) - # Windows file locking plus several concurrent test-file processes make the same - # local asynchronous chains take several times longer; two at a time removes the - # contention instead of hiding it behind longer assertions. - run: npm run test:windows + - name: Run unit tests (Windows shard ${{ matrix.shard }}/4) + env: + MATRIX_SHARD: ${{ matrix.shard }} + run: | + # Split Windows unit tests across 4 balanced parallel shards while keeping + # --test-concurrency=2 per shard to avoid Windows file-lock contention. + npm run test:windows:shard -- --shard "${MATRIX_SHARD}/4" test-node22: name: ubuntu-latest · Node 22 @@ -358,6 +398,42 @@ jobs: key: ${{ steps.harness-cache.outputs.cache-primary-key }} - run: npm test + release-milestone: + name: Release milestone gate + needs: changes + if: needs.changes.outputs.release_pr == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + issues: read + pull-requests: read + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.changes.outputs.checkout_ref }} + fetch-depth: 0 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Verify target release Milestone has zero blocking open items + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }} + run: | + set -euo pipefail + version="$(node -p "require('./ds-bot/package.json').version")" + args=(--version "v$version" --repo "$GITHUB_REPOSITORY" --base-ref origin/main --head-ref HEAD) + if [ -n "$PR_NUMBER" ]; then + args+=(--ignore-pr "$PR_NUMBER") + fi + # Fork PRs may receive a restricted token; gracefully skip only on 401/403. + if [ "$IS_FORK" = "true" ]; then + args+=(--allow-missing-token) + fi + node scripts/check-release-milestone.mjs "${args[@]}" + scan: name: Leak scan needs: changes @@ -552,9 +628,11 @@ jobs: # The one check that branch rules require. A job whose needs failed is skipped, # and GitHub counts a skipped required check as passed, so this job always runs # and fails unless every job required for the changed paths passed. + # Live label/milestone merge gating (needs-product-ok, future Milestone) runs in + # pr-merge-guard.yml via the independent "PR merge guard" commit status. result: name: Test result - needs: [changes, test, test-browser, test-windows, test-node22, scan, app, app-windows, mobile, link, docker] + needs: [changes, test, test-browser, test-windows, test-node22, release-milestone, scan, app, app-windows, mobile, link, docker] if: always() runs-on: ubuntu-latest steps: @@ -570,6 +648,8 @@ jobs: TEST_WIN_RESULT: ${{ needs.test-windows.result }} RUN_NODE22: ${{ needs.changes.outputs.node22 }} NODE22_RESULT: ${{ needs.test-node22.result }} + RUN_RELEASE_MILESTONE: ${{ needs.changes.outputs.release_pr }} + RELEASE_MILESTONE_RESULT: ${{ needs.release-milestone.result }} RUN_APP_UNIT: ${{ needs.changes.outputs.app_unit }} APP_RESULT: ${{ needs.app.result }} RUN_APP_UNIT_WIN: ${{ needs.changes.outputs.app_unit_win }} @@ -606,6 +686,7 @@ jobs: check "test-browser" "$RUN_DS_BOT_BROWSER" "$TEST_BROWSER_RESULT" check "test-windows" "$RUN_DS_BOT_WIN" "$TEST_WIN_RESULT" check "test-node22" "$RUN_NODE22" "$NODE22_RESULT" + check "release-milestone" "$RUN_RELEASE_MILESTONE" "$RELEASE_MILESTONE_RESULT" check "app" "$RUN_APP_UNIT" "$APP_RESULT" check "app-windows" "$RUN_APP_UNIT_WIN" "$APP_WIN_UNIT_RESULT" check "mobile" "$RUN_MOBILE" "$MOBILE_RESULT" diff --git a/app/scripts/release-notes.mjs b/app/scripts/release-notes.mjs index f01f37781..e244c7895 100644 --- a/app/scripts/release-notes.mjs +++ b/app/scripts/release-notes.mjs @@ -1,13 +1,20 @@ // Writes what a release offers for download: the "Download / 下载" table at the top of its notes, // SHA256SUMS.txt, and a copy of each package without the version in its name, which a fixed // releases/latest/download/ link can name. -// Usage: node scripts/release-notes.mjs [] +// +// Usage: +// node scripts/release-notes.mjs [] +// [--external-package =[:]] +// [--pending ] +// [--write-manifest ] +// [--merge-manifest ] +// // It prints the notes with the table on top. MIRROR_BASE, when set, is a URL that holds the // packages under the same names; GITHUB_REPOSITORY names the repository (default Fei-Craft/DS-Bot). import { createHash } from 'node:crypto' -import { createReadStream, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import { copyFile } from 'node:fs/promises' -import { join } from 'node:path' +import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' export const REPO = 'Fei-Craft/DS-Bot' @@ -28,10 +35,14 @@ const END = '' export const packageName = (version, entry) => `DS-Bot-${version}-${entry.file}` export const copyName = entry => `DS-Bot-${entry.file}` -/** @returns {string[]} the packages of `version` that are not among `names` */ -export function missingPackages(version, names) { +/** @returns {string[]} the required packages of `version` that are not among `names` */ +export function missingPackages(version, names, { optionalFiles = [] } = {}) { const have = new Set(names) - return PACKAGES.map(entry => packageName(version, entry)).filter(name => !have.has(name)) + const optional = new Set(optionalFiles) + return PACKAGES + .filter(entry => !optional.has(entry.file)) + .map(entry => packageName(version, entry)) + .filter(name => !have.has(name)) } export function formatSize(bytes) { @@ -46,16 +57,56 @@ function mirrorUrl(mirror, name) { return `${mirror.replace(/\/+$/u, '')}/${encodeURIComponent(name)}` } -/** `sizes`: bytes by package name. Without `mirror` each package has its GitHub link only. */ -export function downloadBlock({ version, sizes, repo = REPO, mirror }) { - const links = (name) => { - const github = releaseUrl({ repo, version, name }) - return mirror ? `${name}: [Mirror / 国内镜像](${mirrorUrl(mirror, name)}) · [GitHub](${github})` : `[${name}](${github})` +function mirrorBaseForVersion(mirror, currentVersion, targetVersion) { + if (!mirror || currentVersion === targetVersion) return mirror + const cleanCurrent = String(currentVersion).replace(/^v/u, '') + const cleanTarget = String(targetVersion).replace(/^v/u, '') + const escaped = cleanCurrent.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&') + // Rewrite versioned mirror path segment (e.g. .../v0.4.2 -> .../v0.4.0) so reused + // historical packages never 404 under the current release's mirror folder. + const versionSegment = new RegExp(`(/v?)${escaped}(?=/|$)`, 'u') + return versionSegment.test(mirror) ? mirror.replace(versionSegment, `$1${cleanTarget}`) : mirror +} + +/** + * Render the Markdown download table block. + * - `sizes`: bytes by package name for packages attached to `version`. + * - `externalPackages`: map of `entry.file` -> `{ version, size?, mirror? }` for packages reused unchanged from an earlier release (e.g. Android APK during desktop-only hotfixes). + * - `pendingPackages`: iterable of `entry.file` currently building asynchronously (e.g. `mac-x64.zip`). + */ +export function downloadBlock({ + version, + sizes = {}, + repo = REPO, + mirror, + externalPackages = {}, + pendingPackages = [], +}) { + const pendingSet = new Set(pendingPackages) + const links = (targetVersion, name, customMirror) => { + const github = releaseUrl({ repo, version: targetVersion, name }) + const effectiveMirror = customMirror ?? mirrorBaseForVersion(mirror, version, targetVersion) + return effectiveMirror + ? `${name}: [Mirror / 国内镜像](${mirrorUrl(effectiveMirror, name)}) · [GitHub](${github})` + : `[${name}](${github})` } const rows = PACKAGES.map((entry) => { - const name = packageName(version, entry) const system = entry.note === undefined ? entry.system : `${entry.system}
${entry.note}` - return `| ${system} | ${links(name)} | ${formatSize(sizes[name])} |` + const name = packageName(version, entry) + if (sizes[name] !== undefined) { + return `| ${system} | ${links(version, name)} | ${formatSize(sizes[name])} |` + } + const ext = externalPackages?.[entry.file] + if (ext && typeof ext.version === 'string' && ext.version.trim() !== '') { + const extVersion = ext.version.trim().replace(/^v/u, '') + const extName = packageName(extVersion, entry) + const sizeCell = Number.isFinite(ext.size) && ext.size > 0 ? formatSize(ext.size) : '—' + return `| ${system} | ${links(extVersion, extName, ext.mirror)} *(unchanged since v${extVersion} / 同 v${extVersion})* | ${sizeCell} |` + } + if (pendingSet.has(entry.file)) { + return `| ${system} | Building… / 构建中… | — |` + } + return `| ${system} | ${links(version, name)} | ${formatSize(sizes[name])} |` }) const sums = releaseUrl({ repo, version, name: SUMS }) return [ @@ -75,13 +126,15 @@ export function downloadBlock({ version, sizes, repo = REPO, mirror }) { ].join('\n') } -/** `hashes`: SHA-256 hex by package name. Each package is listed under both of its names. */ +/** `hashes`: SHA-256 hex by package name. Lists only packages actually present in `hashes`, never fabricating checksums for omitted/external/pending files. */ export function checksums(version, hashes) { const lines = PACKAGES.flatMap((entry) => { - const hash = hashes[packageName(version, entry)] - return [`${hash} ${packageName(version, entry)}`, `${hash} ${copyName(entry)}`] + const name = packageName(version, entry) + const hash = hashes[name] + if (typeof hash !== 'string' || hash === '') return [] + return [`${hash} ${name}`, `${hash} ${copyName(entry)}`] }) - return `${lines.join('\n')}\n` + return lines.length === 0 ? '' : `${lines.join('\n')}\n` } /** The release notes with `block` on top, in place of a table from an earlier run. */ @@ -93,27 +146,114 @@ export function withDownloads(notes, block) { return body === '' ? `${block}\n` : `${block}\n\n${body}\n` } +/** Parse `=[:]` CLI specs into `{ file, version, size }`. */ +export function parseExternalPackageSpec(raw) { + const match = /^([A-Za-z0-9._-]+)=v?([0-9A-Za-z._-]+)(?::(\d+))?$/u.exec(String(raw || '').trim()) + if (match === null) { + throw new Error(`Invalid --external-package value "${String(raw)}"; expected =[:]`) + } + const file = match[1] + if (!PACKAGES.some(entry => entry.file === file)) { + throw new Error(`Unknown package key "${file}" in --external-package`) + } + const version = match[2] + const size = match[3] !== undefined ? Number(match[3]) : undefined + return { file, version, ...(size !== undefined ? { size } : {}) } +} + +export function parseCliArgs(argv) { + const positional = [] + const externalPackages = {} + const pendingPackages = [] + let writeManifest = null + let mergeManifest = null + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--external-package') { + const spec = parseExternalPackageSpec(argv[++i]) + externalPackages[spec.file] = { version: spec.version, ...(spec.size !== undefined ? { size: spec.size } : {}) } + } else if (arg === '--pending') { + const file = String(argv[++i] || '').trim() + if (!PACKAGES.some(entry => entry.file === file)) { + throw new Error(`Unknown package key "${file}" in --pending`) + } + pendingPackages.push(file) + } else if (arg === '--write-manifest') { + writeManifest = argv[++i] ?? null + } else if (arg === '--merge-manifest') { + mergeManifest = argv[++i] ?? null + } else if (arg.startsWith('--')) { + throw new Error(`Unknown option: ${arg}`) + } else { + positional.push(arg) + } + } + + return { + version: positional[0], + from: positional[1], + to: positional[2], + notesFile: positional[3], + externalPackages, + pendingPackages, + writeManifest, + mergeManifest, + } +} + async function sha256(file) { const hash = createHash('sha256') for await (const chunk of createReadStream(file)) hash.update(chunk) return hash.digest('hex') } -async function main([version, from, to, notesFile]) { +async function main(argv) { + let opts + try { + opts = parseCliArgs(argv) + } catch (err) { + console.error(`release-notes: ${err instanceof Error ? err.message : String(err)}`) + process.exit(2) + } + + const { version, from, to, notesFile, writeManifest, mergeManifest } = opts if (!version || !from || !to) { console.error('release-notes: usage: node scripts/release-notes.mjs []') process.exit(2) } - const missing = missingPackages(version, readdirSync(from)) + + let baseSizes = {} + let baseHashes = {} + let baseExternal = {} + if (mergeManifest) { + const loaded = JSON.parse(readFileSync(mergeManifest, 'utf8')) + if (loaded.version && loaded.version !== version) { + console.error(`release-notes: manifest version ${loaded.version} does not match ${version}`) + process.exit(1) + } + baseSizes = { ...(loaded.sizes ?? {}) } + baseHashes = { ...(loaded.hashes ?? {}) } + baseExternal = { ...(loaded.externalPackages ?? {}) } + } + + const externalPackages = { ...baseExternal, ...opts.externalPackages } + const presentInFrom = new Set(readdirSync(from)) + const knownNames = new Set([...presentInFrom, ...Object.keys(baseSizes)]) + const optionalFiles = [...Object.keys(externalPackages), ...opts.pendingPackages] + const missing = missingPackages(version, [...knownNames], { optionalFiles }) if (missing.length > 0) { console.error(`release-notes: ${from} has no ${missing.join(', ')}`) process.exit(1) } + mkdirSync(to, { recursive: true }) - const sizes = {} - const hashes = {} + const sizes = { ...baseSizes } + const hashes = { ...baseHashes } + await Promise.all(PACKAGES.map(async (entry) => { const name = packageName(version, entry) + if (!presentInFrom.has(name)) return const source = join(from, name) sizes[name] = statSync(source).size const [hash] = await Promise.all([ @@ -121,10 +261,33 @@ async function main([version, from, to, notesFile]) { copyFile(source, join(to, copyName(entry))), ]) hashes[name] = hash + delete externalPackages[entry.file] })) + writeFileSync(join(to, SUMS), checksums(version, hashes)) - const block = downloadBlock({ version, sizes, repo: process.env.GITHUB_REPOSITORY || REPO, mirror: process.env.MIRROR_BASE || undefined }) + + if (writeManifest) { + const dir = dirname(resolve(writeManifest)) + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }) + writeFileSync(writeManifest, `${JSON.stringify({ version, sizes, hashes, externalPackages }, null, 2)}\n`) + } + + const effectivePending = opts.pendingPackages.filter((file) => { + const entry = PACKAGES.find(p => p.file === file) + return entry ? sizes[packageName(version, entry)] === undefined : false + }) + + const block = downloadBlock({ + version, + sizes, + repo: process.env.GITHUB_REPOSITORY || REPO, + mirror: process.env.MIRROR_BASE || undefined, + externalPackages, + pendingPackages: effectivePending, + }) process.stdout.write(withDownloads(notesFile === undefined ? '' : readFileSync(notesFile, 'utf8'), block)) } -if (process.argv[1] === fileURLToPath(import.meta.url)) await main(process.argv.slice(2)) +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + await main(process.argv.slice(2)) +} diff --git a/app/test/release-notes.test.mjs b/app/test/release-notes.test.mjs index 53669f1c5..6478f6a08 100644 --- a/app/test/release-notes.test.mjs +++ b/app/test/release-notes.test.mjs @@ -7,7 +7,7 @@ import { join } from 'node:path' import { test } from 'node:test' import { fileURLToPath } from 'node:url' import YAML from 'yaml' -import { checksums, copyName, downloadBlock, formatSize, missingPackages, PACKAGES, packageName, withDownloads } from '../scripts/release-notes.mjs' +import { checksums, copyName, downloadBlock, formatSize, missingPackages, PACKAGES, packageName, parseExternalPackageSpec, withDownloads } from '../scripts/release-notes.mjs' const script = fileURLToPath(new URL('../scripts/release-notes.mjs', import.meta.url)) const read = file => readFileSync(new URL(file, import.meta.url), 'utf8') @@ -63,7 +63,7 @@ test('a mirror comes before GitHub, and a fork links to its own releases', () => assert.doesNotMatch(block, /Fei-Craft/u) }) -test('SHA256SUMS.txt lists each package under both of its names, in the format sha256sum checks', () => { +test('SHA256SUMS.txt lists each present package under both of its names and omits absent packages without fabricating hashes', () => { const hashes = Object.fromEntries(names('0.2.3').map((name, index) => [name, String(index).repeat(64)])) const lines = checksums('0.2.3', hashes).split('\n') assert.equal(lines.pop(), '') @@ -72,15 +72,83 @@ test('SHA256SUMS.txt lists each package under both of its names, in the format s assert.equal(lines[1], `${'0'.repeat(64)} DS-Bot-win-x64.exe`) assert.equal(lines[9], `${'4'.repeat(64)} DS-Bot-linux-amd64.deb`) assert.equal(lines[11], `${'5'.repeat(64)} DS-Bot-android.apk`) + + const partialHashes = { ...hashes } + delete partialHashes['DS-Bot-0.2.3-android.apk'] + delete partialHashes['DS-Bot-0.2.3-mac-x64.zip'] + const partialSums = checksums('0.2.3', partialHashes) + assert.doesNotMatch(partialSums, /android\.apk|mac-x64\.zip|undefined/u) + assert.equal(partialSums.trim().split('\n').length, 8) }) -test('a missing package is named; other files in the folder do not count', () => { +test('a missing package is named; optionalFiles excludes intentionally skipped or pending packages', () => { const present = ['DS-Bot-0.2.3-win-x64.exe', 'DS-Bot-0.2.3-win-x64.exe.blockmap', 'DS-Bot-mac-arm64.zip', 'DS-Bot-0.2.2-mac-x64.zip', 'DS-Bot-0.2.3-linux-x86_64.AppImage', 'DS-Bot-0.2.3-linux-amd64.deb', 'latest.yml'] assert.deepEqual(missingPackages('0.2.3', present), ['DS-Bot-0.2.3-mac-arm64.zip', 'DS-Bot-0.2.3-mac-x64.zip', 'DS-Bot-0.2.3-android.apk']) + assert.deepEqual( + missingPackages('0.2.3', present, { optionalFiles: ['mac-x64.zip', 'android.apk'] }), + ['DS-Bot-0.2.3-mac-arm64.zip'], + ) assert.deepEqual(missingPackages('0.2.3', names('0.2.3')), []) }) +test('reused external Android APK points at its historical release and pending macOS x64 displays a building placeholder', () => { + assert.deepEqual(parseExternalPackageSpec('android.apk=0.4.0:64000000'), { + file: 'android.apk', + version: '0.4.0', + size: 64_000_000, + }) + assert.throws(() => parseExternalPackageSpec('unknown.bin=0.4.0'), /Unknown package key/u) + + const sizes = { + 'DS-Bot-0.4.2-win-x64.exe': 120 * MB, + 'DS-Bot-0.4.2-mac-arm64.zip': 150 * MB, + 'DS-Bot-0.4.2-linux-x86_64.AppImage': 140 * MB, + 'DS-Bot-0.4.2-linux-amd64.deb': 130 * MB, + } + const block = downloadBlock({ + version: '0.4.2', + sizes, + externalPackages: { 'android.apk': { version: '0.4.0', size: 62 * MB } }, + pendingPackages: ['mac-x64.zip'], + }) + assert.match( + block, + /\| macOS, Intel \| Building… \/ 构建中… \| — \|/u, + ) + assert.match( + block, + /\| Android \(phone app \/ 手机 App\) \| \[DS-Bot-0\.4\.0-android\.apk\]\(https:\/\/github\.com\/Fei-Craft\/DS-Bot\/releases\/download\/v0\.4\.0\/DS-Bot-0\.4\.0-android\.apk\) \*\(unchanged since v0\.4\.0 \/ 同 v0\.4\.0\)\* \| 62 MB \|/u, + ) + + // Versioned mirror URLs rewrite /v0.4.2 -> /v0.4.0 for reused packages so they never 404. + const withVersionedMirror = downloadBlock({ + version: '0.4.2', + sizes, + mirror: 'https://mirror.example/ds-bot/v0.4.2/', + externalPackages: { 'android.apk': { version: '0.4.0', size: 62 * MB } }, + pendingPackages: ['mac-x64.zip'], + }) + assert.match( + withVersionedMirror, + /DS-Bot-0\.4\.0-android\.apk: \[Mirror \/ 国内镜像\]\(https:\/\/mirror\.example\/ds-bot\/v0\.4\.0\/DS-Bot-0\.4\.0-android\.apk\) · \[GitHub\]\(https:\/\/github\.com\/Fei-Craft\/DS-Bot\/releases\/download\/v0\.4\.0\/DS-Bot-0\.4\.0-android\.apk\)/u, + ) + assert.doesNotMatch(withVersionedMirror, /v0\.4\.2\/DS-Bot-0\.4\.0-android\.apk/u) + + // Flat mirror URLs (without version segment) keep their base intact. + const withFlatMirror = downloadBlock({ + version: '0.4.2', + sizes, + mirror: 'https://dl.dsbot.app', + externalPackages: { 'android.apk': { version: '0.4.0', size: 62 * MB } }, + pendingPackages: ['mac-x64.zip'], + }) + assert.match( + withFlatMirror, + /DS-Bot-0\.4\.0-android\.apk: \[Mirror \/ 国内镜像\]\(https:\/\/dl\.dsbot\.app\/DS-Bot-0\.4\.0-android\.apk\)/u, + ) +}) + test('the table goes on top of the notes, and a second run replaces it', () => { const sizes = Object.fromEntries(names('0.2.3').map(name => [name, MB])) const block = downloadBlock({ version: '0.2.3', sizes }) @@ -119,6 +187,81 @@ test('the script hashes and copies the packages and prints the notes', (t) => { } }) +test('two-stage release manifest workflow: primary release skips Android + marks macOS x64 pending, then macOS x64 merges idempotently', (t) => { + const work = mkdtempSync(join(tmpdir(), 'ds-bot-release-merge-')) + t.after(() => { rmSync(work, { recursive: true, force: true }) }) + const primaryFrom = join(work, 'primary-packages') + const primaryTo = join(work, 'primary-attach') + const x64From = join(work, 'x64-packages') + const x64To = join(work, 'x64-attach') + const manifestPath = join(work, 'manifest', 'release-manifest.json') + mkdirSync(primaryFrom) + mkdirSync(x64From) + + for (const file of ['win-x64.exe', 'mac-arm64.zip', 'linux-x86_64.AppImage', 'linux-amd64.deb']) { + writeFileSync(join(primaryFrom, `DS-Bot-0.4.2-${file}`), `primary ${file}`) + } + writeFileSync(join(work, 'notes.md'), '### Fixed\n\n- Hotfix item\n') + const env = { ...process.env, GITHUB_REPOSITORY: '', MIRROR_BASE: '' } + + // Stage 1: primary downloads job with skipped Android APK (reused from 0.4.1) and pending mac-x64.zip. + const stage1 = spawnSync(process.execPath, [ + script, + '0.4.2', + primaryFrom, + primaryTo, + join(work, 'notes.md'), + '--pending', 'mac-x64.zip', + '--external-package', 'android.apk=0.4.1:65000000', + '--write-manifest', manifestPath, + ], { encoding: 'utf8', env }) + assert.equal(stage1.status, 0, stage1.stderr) + assert.match(stage1.stdout, /Building… \/ 构建中…/u) + assert.match(stage1.stdout, /releases\/download\/v0\.4\.1\/DS-Bot-0\.4\.1-android\.apk/u) + const stage1Sums = readFileSync(join(primaryTo, 'SHA256SUMS.txt'), 'utf8') + assert.doesNotMatch(stage1Sums, /mac-x64\.zip|android\.apk/u) + assert.match(stage1Sums, /DS-Bot-0\.4\.2-mac-arm64\.zip/u) + + // Stage 2: async macOS x64 finishes and merges into manifest + existing release body. + writeFileSync(join(work, 'notes-after-stage1.md'), stage1.stdout) + writeFileSync(join(x64From, 'DS-Bot-0.4.2-mac-x64.zip'), 'intel mac bundle') + const stage2 = spawnSync(process.execPath, [ + script, + '0.4.2', + x64From, + x64To, + join(work, 'notes-after-stage1.md'), + '--merge-manifest', manifestPath, + ], { encoding: 'utf8', env }) + assert.equal(stage2.status, 0, stage2.stderr) + assert.doesNotMatch(stage2.stdout, /Building…/u) + assert.match(stage2.stdout, /releases\/download\/v0\.4\.2\/DS-Bot-0\.4\.2-mac-x64\.zip/u) + assert.match(stage2.stdout, /releases\/download\/v0\.4\.1\/DS-Bot-0\.4\.1-android\.apk/u) + assert.equal(stage2.stdout.split('## Download / 下载').length, 2, 'download table must be replaced idempotently') + assert.ok(stage2.stdout.endsWith('### Fixed\n\n- Hotfix item\n')) + + // Re-running stage 2 produces byte-identical release notes. + writeFileSync(join(work, 'notes-after-stage2.md'), stage2.stdout) + const stage2Repeat = spawnSync(process.execPath, [ + script, + '0.4.2', + x64From, + join(work, 'x64-attach-2'), + join(work, 'notes-after-stage2.md'), + '--merge-manifest', manifestPath, + ], { encoding: 'utf8', env }) + assert.equal(stage2Repeat.status, 0, stage2Repeat.stderr) + assert.equal(stage2Repeat.stdout, stage2.stdout) + + // Stage 2 SHA256SUMS.txt contains all 5 built desktop packages (including mac-x64) and still omits reused Android. + const stage2Sums = readFileSync(join(x64To, 'SHA256SUMS.txt'), 'utf8') + const x64Hash = createHash('sha256').update('intel mac bundle').digest('hex') + assert.ok(stage2Sums.includes(`${x64Hash} DS-Bot-0.4.2-mac-x64.zip\n`)) + assert.ok(stage2Sums.includes(`${x64Hash} DS-Bot-mac-x64.zip\n`)) + assert.ok(stage2Sums.includes('DS-Bot-0.4.2-win-x64.exe\n')) + assert.doesNotMatch(stage2Sums, /android\.apk/u) +}) + test('the script stops when a package is missing, so the release is not marked Latest', (t) => { const work = mkdtempSync(join(tmpdir(), 'ds-bot-release-notes-')) t.after(() => { rmSync(work, { recursive: true, force: true }) }) @@ -128,29 +271,62 @@ test('the script stops when a package is missing, so the release is not marked L assert.match(run.stderr, /has no DS-Bot-0\.2\.3-win-x64\.exe$/mu) }) -// A releases/latest link must never reach a release whose files are still being attached, -// and no installer asset may be uploaded to the release before publish and all builds succeed. -test('the release becomes Latest last, after every build and publish job', () => { +// A releases/latest link must never reach a release before primary builds + npm publish finish, +// while macOS x64 runs asynchronously and refreshes checksums/notes after downloads succeeds. +test('release.yml marks Latest after primary builds + publish, decouples macOS x64 async upload, gates Milestone, and skips unchanged Android', () => { const workflow = YAML.parse(read('../../.github/workflows/release.yml')) const runs = job => (job.steps ?? []).map(step => step.run ?? '').join('\n') const latest = Object.entries(workflow.jobs).filter(([, job]) => /gh release edit "\$TAG" --latest/u.test(runs(job))) assert.equal(latest.length, 1) const [name, job] = latest[0] + assert.equal(name, 'downloads') + const before = (jobName, seen = new Set()) => { for (const need of [workflow.jobs[jobName].needs ?? []].flat()) if (!seen.has(need)) before(need, seen.add(need)) return seen } - const producers = Object.keys(workflow.jobs).filter((other) => { - if (other === name) return false - const steps = workflow.jobs[other].steps ?? [] - return /gh release upload/u.test(runs(workflow.jobs[other])) - || steps.some(step => typeof step.uses === 'string' && step.uses.startsWith('actions/upload-artifact@')) - }) - assert.ok(producers.length >= 5, `expected at least 5 build/publish jobs before ${name}, found ${producers.join(', ')}`) - for (const producer of producers) assert.ok(before(name).has(producer), `${name} must come after ${producer}`) + + // Primary producers must all finish before downloads marks Latest. + for (const primary of ['validate', 'publish', 'app-windows', 'app-macos-arm64', 'app-linux', 'app-android']) { + assert.ok(before(name).has(primary), `${name} must come after ${primary}`) + } + + // Intel macOS x64 must NOT block Latest; it attaches via downloads-macos-x64 after downloads completes. + assert.ok(!before(name).has('app-macos-x64'), 'app-macos-x64 must not block downloads/Latest') + assert.ok(workflow.jobs['app-macos-x64'], 'app-macos-x64 job must exist') + const x64Attach = workflow.jobs['downloads-macos-x64'] + assert.ok(x64Attach, 'downloads-macos-x64 job must exist') + assert.ok(before('downloads-macos-x64').has('downloads')) + assert.ok(before('downloads-macos-x64').has('app-macos-x64')) + assert.match(runs(x64Attach), /--merge-manifest/u) + assert.match(runs(x64Attach), /node scripts\/release-upload\.mjs /u) + assert.doesNotMatch(runs(x64Attach), /--latest/u) + + // Top-level permissions stay read-only; contents:write is scoped to publishing jobs only. + assert.equal(workflow.permissions.contents, 'read') + assert.equal(workflow.jobs.publish.permissions?.contents, 'write') + assert.equal(workflow.jobs.downloads.permissions?.contents, 'write') + assert.equal(workflow.jobs['downloads-macos-x64'].permissions?.contents, 'write') + + // validate checks Milestone (with hotfix trailer scoped to current release commits only, never HEAD^1), + // streams filtered release JSON via stdin (avoiding Linux 128 KiB MAX_ARG_STRLEN), verifies ancestor tags, + // excludes generated release-notes metadata, and computes build_android. + const validateRuns = runs(workflow.jobs.validate) + assert.match(validateRuns, /check-release-milestone\.mjs/u) + assert.match(validateRuns, /Hotfix-Release:/u) + assert.match(validateRuns, /HEAD\^1\.\.HEAD/u) + assert.doesNotMatch(validateRuns, /git log -n 2/u, 'validate must never inspect HEAD^1 history for hotfix trailers') + assert.match(validateRuns, /--jq '\[/u) + assert.match(validateRuns, /readFileSync\(0/u, 'android-scope must read filtered release JSON via stdin, not argv') + assert.match(validateRuns, /merge-base --is-ancestor/u) + assert.match(validateRuns, /release-notes\(-generated\\\.js\|\\\.json\)/u) + assert.ok(workflow.jobs.validate.outputs?.build_android) + assert.match(String(workflow.jobs['app-android'].if || ''), /needs\.validate\.outputs\.build_android == 'true'/u) + assert.ok(workflow.on.workflow_dispatch?.inputs?.force_android) + // No app build job may attach assets directly to the GitHub release before publish succeeds. for (const [other, cfg] of Object.entries(workflow.jobs)) { - if (other === name || other === 'publish') continue + if (other === name || other === 'downloads-macos-x64' || other === 'publish') continue assert.doesNotMatch(runs(cfg), /gh release upload|release-upload\.mjs/u, `${other} must not upload directly to the release before publish passes`) } assert.match(job.steps.at(-1).run, /^gh release edit "\$TAG" --latest$/u) @@ -158,6 +334,58 @@ test('the release becomes Latest last, after every build and publish job', () => assert.match(runs(job), /node scripts\/release-upload\.mjs /u) }) +test('release.yml hotfix detection scopes to current release commits and never inherits a previous hotfix on HEAD^1', (t) => { + const dir = mkdtempSync(join(tmpdir(), 'ds-bot-hotfix-scope-')) + t.after(() => { rmSync(dir, { recursive: true, force: true }) }) + const gitEnv = { + ...process.env, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_TERMINAL_PROMPT: '0', + } + const git = (args) => { + const res = spawnSync('git', ['-c', 'commit.gpgsign=false', ...args], { cwd: dir, encoding: 'utf8', env: gitEnv }) + assert.equal(res.status, 0, res.stderr) + return res.stdout.trim() + } + const detectHotfix = () => { + const isMerge = spawnSync('git', ['rev-parse', '--verify', 'HEAD^2'], { cwd: dir, env: gitEnv }).status === 0 + const msg = git(isMerge ? ['log', '--format=%B', 'HEAD^1..HEAD'] : ['log', '-1', '--format=%B', 'HEAD']) + return /(^Hotfix-Release:\s*true$|Merge pull request #[0-9]+ from [^/]+\/(hotfix\/|fix\/hot-))/mu.test(msg) + } + + // Base commit -> hotfix v0.4.1 on main with Hotfix-Release: true trailer. + git(['init', '-b', 'main']) + git(['config', 'user.email', 'test@example.com']) + git(['config', 'user.name', 'Test']) + writeFileSync(join(dir, 'file.txt'), '0.4.0\n') + git(['add', '.']) + git(['commit', '-m', 'release: v0.4.0']) + git(['checkout', '-b', 'dev']) + writeFileSync(join(dir, 'dev.txt'), 'feature for 0.4.2\n') + git(['add', '.']) + git(['commit', '-m', 'feat: planned 0.4.2 feature']) + + git(['checkout', 'main']) + writeFileSync(join(dir, 'file.txt'), '0.4.1\n') + git(['add', '.']) + git(['commit', '-m', 'release: v0.4.1', '-m', 'Hotfix-Release: true']) + assert.equal(detectHotfix(), true, 'single-parent hotfix commit with Hotfix-Release trailer must be detected') + + // Regular release v0.4.2 merges dev onto main (whose HEAD^1 is the v0.4.1 hotfix commit). + git(['merge', '--no-ff', 'dev', '-m', 'Merge pull request #2500 from Fei-Craft/chore/release-0.4.2']) + assert.equal(detectHotfix(), false, 'regular release v0.4.2 after hotfix v0.4.1 must NOT inherit hotfix exemption from HEAD^1') + + // Subsequent merge PR from a hotfix/* branch with a hotfix commit on HEAD^2 IS detected. + git(['checkout', '-b', 'hotfix/0.4.3']) + writeFileSync(join(dir, 'file.txt'), '0.4.3\n') + git(['add', '.']) + git(['commit', '-m', 'release: v0.4.3', '-m', 'Hotfix-Release: true']) + git(['checkout', 'main']) + git(['merge', '--no-ff', 'hotfix/0.4.3', '-m', 'Merge pull request #2501 from Fei-Craft/hotfix/0.4.3']) + assert.equal(detectHotfix(), true, 'hotfix merge PR must be detected via HEAD^1..HEAD') +}) + test('both READMEs link the latest release and do not hard-code release version numbers', () => { for (const file of ['../../README.md', '../../README.zh.md']) { const text = read(file) diff --git a/ds-bot/package.json b/ds-bot/package.json index 65fffb9aa..4eabd121a 100644 --- a/ds-bot/package.json +++ b/ds-bot/package.json @@ -58,6 +58,7 @@ "build": "node scripts/build-client.mjs && node scripts/build-link.mjs", "test": "node --import ./test/harness-resolve.mjs --test --test-timeout=120000 --test-force-exit \"test/*.test.js\"", "test:windows": "node --import ./test/harness-resolve.mjs --test --test-concurrency=2 --test-timeout=120000 --test-force-exit \"test/*.test.js\"", + "test:windows:shard": "node scripts/run-tests-shard.mjs", "test:browser": "node --import ./test/harness-resolve.mjs --test --test-concurrency=1 --test-timeout=120000 --test-force-exit \"test/browser/*.test.js\"", "lint": "node scripts/lint.mjs", "harness": "npm ci --prefix dev/harness --legacy-peer-deps=false --no-fund --no-audit", diff --git a/ds-bot/scripts/run-tests-shard.mjs b/ds-bot/scripts/run-tests-shard.mjs new file mode 100644 index 000000000..ecd8f1910 --- /dev/null +++ b/ds-bot/scripts/run-tests-shard.mjs @@ -0,0 +1,183 @@ +// Deterministic, size-balanced sharded runner for ds-bot unit tests. +// Usage: node scripts/run-tests-shard.mjs --shard / [--concurrency ] [--timeout ] [--list] [-- ] +import { spawnSync } from 'node:child_process' +import { readdirSync, statSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const PLUGIN_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const DEFAULT_CONCURRENCY = 2 +const DEFAULT_TIMEOUT_MS = 120_000 + +/** + * Parse a 1-based shard specifier like "1/4". + * @param {string} raw + * @returns {{ index: number, total: number }} + */ +export function parseShardSpec(raw) { + if (typeof raw !== 'string') { + throw new Error('Missing shard specifier; expected / (for example 1/4)') + } + const match = /^\s*(\d+)\s*\/\s*(\d+)\s*$/u.exec(raw) + if (match === null) { + throw new Error(`Invalid shard specifier "${raw}"; expected / (for example 1/4)`) + } + const index = Number(match[1]) + const total = Number(match[2]) + if (!Number.isSafeInteger(total) || total < 1) { + throw new Error(`Invalid shard total "${match[2]}"; must be a positive integer`) + } + if (!Number.isSafeInteger(index) || index < 1 || index > total) { + throw new Error(`Invalid shard index "${match[1]}"; must be between 1 and ${String(total)}`) + } + return { index, total } +} + +function compareAscii(a, b) { + return a < b ? -1 : a > b ? 1 : 0 +} + +/** + * Partition test entries into `total` deterministic, weight-balanced buckets using LPT scheduling. + * Each entry may be a filename string or `{ file, size }`. + * @param {Array} entries + * @param {number} total + * @returns {string[][]} + */ +export function partitionTestFiles(entries, total) { + if (!Number.isSafeInteger(total) || total < 1) { + throw new Error(`Invalid shard total ${String(total)}`) + } + const normalized = entries.map((entry) => { + if (typeof entry === 'string') return { file: entry, size: 1 } + const size = Number.isFinite(entry?.size) && entry.size >= 0 ? entry.size : 1 + return { file: String(entry.file), size } + }) + normalized.sort((a, b) => (b.size - a.size) || compareAscii(a.file, b.file)) + + const buckets = Array.from({ length: total }, () => ({ weight: 0, files: [] })) + for (const item of normalized) { + let best = 0 + for (let i = 1; i < buckets.length; i += 1) { + if (buckets[i].weight < buckets[best].weight) best = i + } + buckets[best].files.push(item.file) + buckets[best].weight += item.size + } + + return buckets.map(bucket => bucket.files.sort(compareAscii)) +} + +/** + * Select the files belonging to 1-based shard `index` of `total`. + */ +export function selectShardFiles(entries, index, total) { + const { index: validIndex, total: validTotal } = parseShardSpec(`${String(index)}/${String(total)}`) + return partitionTestFiles(entries, validTotal)[validIndex - 1] +} + +export function discoverTopLevelTests(testDir = join(PLUGIN_ROOT, 'test')) { + const entries = readdirSync(testDir, { withFileTypes: true }) + .filter(entry => entry.isFile() && entry.name.endsWith('.test.js')) + .map(entry => ({ + file: `test/${entry.name}`, + size: statSync(join(testDir, entry.name)).size, + })) + entries.sort((a, b) => compareAscii(a.file, b.file)) + return entries +} + +export function parseCliArgs(argv, env = process.env) { + let shardRaw = env.TEST_SHARD || '' + let concurrency = DEFAULT_CONCURRENCY + let timeoutMs = DEFAULT_TIMEOUT_MS + let listOnly = false + const extraArgs = [] + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--') { + extraArgs.push(...argv.slice(i + 1)) + break + } + if (arg === '--list') { + listOnly = true + } else if (arg === '--shard') { + shardRaw = argv[++i] ?? '' + } else if (arg.startsWith('--shard=')) { + shardRaw = arg.slice('--shard='.length) + } else if (arg === '--concurrency') { + concurrency = Number(argv[++i]) + } else if (arg.startsWith('--concurrency=')) { + concurrency = Number(arg.slice('--concurrency='.length)) + } else if (arg === '--timeout') { + timeoutMs = Number(argv[++i]) + } else if (arg.startsWith('--timeout=')) { + timeoutMs = Number(arg.slice('--timeout='.length)) + } else { + throw new Error(`Unknown option: ${arg}`) + } + } + + const { index, total } = parseShardSpec(shardRaw) + if (!Number.isSafeInteger(concurrency) || concurrency < 1) { + throw new Error(`Invalid concurrency: ${String(concurrency)}`) + } + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) { + throw new Error(`Invalid timeout: ${String(timeoutMs)}`) + } + return { index, total, concurrency, timeoutMs, listOnly, extraArgs } +} + +function main(argv) { + let opts + try { + opts = parseCliArgs(argv) + } catch (err) { + console.error(`run-tests-shard: ${err instanceof Error ? err.message : String(err)}`) + process.exit(2) + } + + const allTests = discoverTopLevelTests() + if (allTests.length === 0) { + console.error('run-tests-shard: no top-level test files found') + process.exit(1) + } + const selected = selectShardFiles(allTests, opts.index, opts.total) + if (opts.listOnly) { + for (const file of selected) process.stdout.write(`${file}\n`) + return + } + + console.error( + `run-tests-shard: shard ${String(opts.index)}/${String(opts.total)} — running ${String(selected.length)}/${String(allTests.length)} test files (concurrency=${String(opts.concurrency)}, timeout=${String(opts.timeoutMs)}ms)`, + ) + if (selected.length === 0) return + + const nodeArgs = [ + '--import', './test/harness-resolve.mjs', + '--test', + `--test-concurrency=${String(opts.concurrency)}`, + `--test-timeout=${String(opts.timeoutMs)}`, + '--test-force-exit', + ...opts.extraArgs, + ...selected, + ] + const res = spawnSync(process.execPath, nodeArgs, { + cwd: PLUGIN_ROOT, + stdio: 'inherit', + }) + if (res.error) { + console.error(`run-tests-shard: failed to spawn node: ${res.error.message}`) + process.exit(1) + } + if (res.signal) { + console.error(`run-tests-shard: terminated by signal ${res.signal}`) + process.exit(1) + } + process.exit(res.status ?? 1) +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main(process.argv.slice(2)) +} diff --git a/ds-bot/test/ci-workflows.test.js b/ds-bot/test/ci-workflows.test.js index 38c2caf01..a8e801887 100644 --- a/ds-bot/test/ci-workflows.test.js +++ b/ds-bot/test/ci-workflows.test.js @@ -1,9 +1,9 @@ import assert from 'node:assert/strict' import { spawnSync } from 'node:child_process' -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' +import { dirname, join, relative, resolve } from 'node:path' import { describe, it } from 'node:test' import { fileURLToPath } from 'node:url' @@ -36,7 +36,71 @@ function loadWorkflow(filename) { return parseYaml(readFileSync(join(WORKFLOWS_DIR, filename), 'utf8')) } -function runClassifier(workflowFile, filesChanged, envOverrides = {}) { +function walkFiles(dir, predicate) { + const out = [] + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'node_modules' || entry.name === '.git') continue + const full = join(dir, entry.name) + if (entry.isDirectory()) { + out.push(...walkFiles(full, predicate)) + } else if (predicate(full)) { + out.push(full) + } + } + return out +} + +/** + * Recursively discover all `ds-bot/...` repository-relative paths imported statically + * from `mobile/src/` (separating runtime sources from `*.test.ts` test files). + */ +function discoverMobileDsBotImports() { + const mobileSrcDir = join(REPO_ROOT, 'mobile', 'src') + const runtimeDsBot = new Set() + const testOnlyDsBot = new Set() + const importRe = /(?:import|export)\s+(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\)/gu + + function resolveRelative(fromFile, spec) { + if (!spec.startsWith('.')) return null + const base = resolve(dirname(fromFile), spec) + for (const candidate of [base, `${base}.js`, `${base}.ts`, `${base}.tsx`, join(base, 'index.js'), join(base, 'index.ts')]) { + if (existsSync(candidate)) return candidate + } + return null + } + + function traceFrom(startFiles, targetSet) { + const visited = new Set() + const queue = [...startFiles] + while (queue.length > 0) { + const current = queue.shift() + if (visited.has(current)) continue + visited.add(current) + const text = readFileSync(current, 'utf8') + for (const match of text.matchAll(importRe)) { + const spec = match[1] || match[2] + const resolved = resolveRelative(current, spec) + if (!resolved) continue + const rel = relative(REPO_ROOT, resolved).split('\\').join('/') + if (rel.startsWith('ds-bot/')) { + targetSet.add(rel) + queue.push(resolved) + } else if (rel.startsWith('mobile/src/')) { + queue.push(resolved) + } + } + } + } + + const allMobileFiles = walkFiles(mobileSrcDir, (f) => /\.(?:ts|tsx|js|mjs)$/u.test(f)) + const runtimeStarts = allMobileFiles.filter((f) => !/\.test\.(?:ts|tsx|js|mjs)$/u.test(f)) + const testStarts = allMobileFiles.filter((f) => /\.test\.(?:ts|tsx|js|mjs)$/u.test(f)) + traceFrom(runtimeStarts, runtimeDsBot) + traceFrom(testStarts, testOnlyDsBot) + return { runtimeDsBot: [...runtimeDsBot].sort(), testOnlyDsBot: [...testOnlyDsBot].sort() } +} + +function runClassifier(workflowFile, filesChanged, envOverrides = {}, { baseFiles = {}, headContents = {} } = {}) { const wf = loadWorkflow(workflowFile) const filterStep = wf.jobs.changes.steps.find((s) => s.id === 'filter') assert.ok(filterStep?.run, `${workflowFile}: missing filter step`) @@ -69,6 +133,11 @@ function runClassifier(workflowFile, filesChanged, envOverrides = {}) { git(['config', 'user.email', 'test@example.com']) git(['config', 'user.name', 'Test']) writeFileSync(join(dir, 'README.md'), 'init\n') + for (const [rel, content] of Object.entries(baseFiles)) { + const full = join(dir, rel) + mkdirSync(dirname(full), { recursive: true }) + writeFileSync(full, content) + } git(['add', '.']) git(['commit', '-m', 'base']) const baseSha = git(['rev-parse', 'HEAD']) @@ -78,7 +147,7 @@ function runClassifier(workflowFile, filesChanged, envOverrides = {}) { for (const rel of filesChanged) { const full = join(dir, rel) mkdirSync(dirname(full), { recursive: true }) - writeFileSync(full, `changed ${rel}\n`) + writeFileSync(full, headContents[rel] ?? `changed ${rel}\n`) } git(['add', '.']) git(['commit', '--allow-empty', '-m', 'pr change']) @@ -93,10 +162,13 @@ function runClassifier(workflowFile, filesChanged, envOverrides = {}) { EVENT: 'pull_request', REF: 'refs/pull/1/merge', BASE_REF: 'dev', + HEAD_REF: 'fix/sample', + IS_SAME_REPO: 'true', BEFORE: baseSha, SHA: headSha, PR_NUMBER: '', PR_FULL_PACKAGE: 'false', + PR_HOTFIX: 'false', GH_TOKEN: '', GH_REPO: '', ...envOverrides, @@ -117,15 +189,21 @@ function runClassifier(workflowFile, filesChanged, envOverrides = {}) { } describe('CI workflow separation and path classification', () => { - it('parses test.yml, package.yml, full-package.yml and pr-triage-labels.yml with matching result job needs', () => { + it('parses all workflow files and enforces cache isolation, sharding, macOS Intel gate, isolated PR merge guard, and release workflows', () => { const testWf = loadWorkflow('test.yml') const pkgWf = loadWorkflow('package.yml') const fullLabelWf = loadWorkflow('full-package.yml') const triageWf = loadWorkflow('pr-triage-labels.yml') + const mergeGuardWf = loadWorkflow('pr-merge-guard.yml') + const nightlyWf = loadWorkflow('nightly-release.yml') + const cutReleaseWf = loadWorkflow('cut-release.yml') assert.equal(testWf.name, 'Test') assert.equal(pkgWf.name, 'Package & Native') assert.equal(fullLabelWf.name, 'Full Package (on label)') + assert.equal(mergeGuardWf.name, 'PR Merge Guard') + assert.equal(nightlyWf.name, 'Nightly Release') + assert.equal(cutReleaseWf.name, 'Cut Release') assert.equal(triageWf.permissions.contents, 'read') assert.ok(pkgWf.on.workflow_call?.inputs?.force_full) assert.deepEqual(pkgWf.on.push.branches, ['main']) @@ -142,11 +220,32 @@ describe('CI workflow separation and path classification', () => { assert.match(String(triageWf.concurrency?.group || ''), /pr-triage-retarget-/, 'pr-triage-labels.yml must isolate base-retarget concurrency lane') const triageScript = triageWf.jobs['sync-labels'].steps.find((s) => s.with?.script)?.with?.script || '' assert.match(triageScript, /base_ref_changed/, 'pr-triage-labels.yml must durably reject approvals predating base_ref_changed') + assert.equal(triageWf.jobs['pr-merge-guard'], undefined, 'pr-merge-guard must live in its own workflow file') + + // Isolated pr-merge-guard.yml: no issue_comment/pull_request_review triggers, handles all milestone lifecycle events (including deleted), distinct job vs status context names. + assert.equal(mergeGuardWf.on.issue_comment, undefined) + assert.equal(mergeGuardWf.on.pull_request_review, undefined) + for (const evType of ['opened', 'reopened', 'synchronize', 'edited', 'labeled', 'unlabeled', 'milestoned', 'demilestoned']) { + assert.ok(mergeGuardWf.on.pull_request_target.types.includes(evType), `pr-merge-guard.yml must trigger on ${evType}`) + } + for (const msType of ['created', 'closed', 'opened', 'edited', 'deleted']) { + assert.ok(mergeGuardWf.on.milestone.types.includes(msType), `pr-merge-guard.yml must trigger on milestone:${msType}`) + } + const guardJob = mergeGuardWf.jobs['evaluate-merge-guard'] + assert.ok(guardJob, 'pr-merge-guard.yml must define evaluate-merge-guard job') + assert.notEqual(guardJob.name, 'PR merge guard', 'job name must differ from commit status context') + assert.equal(guardJob.permissions?.statuses, 'write') + const guardScript = guardJob.steps.find((s) => s.with?.script)?.with?.script || '' + assert.match(guardScript, /evaluatePrMergeGuard/u) + assert.match(guardScript, /createCommitStatus/u) + assert.match(guardScript, /context: 'PR merge guard'/u) + assert.match(guardScript, /context\.eventName === 'milestone'/u) const winNextStep = pkgWf.jobs['app-package'].steps.find((s) => s.name === 'Build the next version') assert.equal(winNextStep?.env?.ELECTRON_BUILDER_COMPRESSION_LEVEL, '1') - // test.yml shards Linux unit tests, deduplicates harness cache saves, and separates browser & Windows jobs. + // test.yml shards Linux unit tests (3 shards), shards Windows unit tests (4 shards), deduplicates harness cache saves, + // separates browser & Windows jobs, keeps release-milestone gate, and does not couple label-dependent pr-guard into Test result. assert.deepEqual(testWf.jobs.test.strategy?.matrix?.shard, [1, 2, 3]) assert.equal(testWf.jobs.test['runs-on'], 'ubuntu-latest') const shardRunStep = testWf.jobs.test.steps.find((s) => String(s.run || '').includes('--test-shard=')) @@ -158,6 +257,16 @@ describe('CI workflow separation and path classification', () => { assert.match(String(browserSaveHarness?.if || ''), /needs\.changes\.outputs\.ds_bot != 'true'/) assert.ok(testWf.jobs['test-windows']) assert.equal(testWf.jobs['test-windows']['runs-on'], 'windows-latest') + assert.deepEqual(testWf.jobs['test-windows'].strategy?.matrix?.shard, [1, 2, 3, 4]) + const winShardRun = testWf.jobs['test-windows'].steps.find((s) => String(s.run || '').includes('test:windows:shard')) + assert.match(String(winShardRun?.run || ''), /npm run test:windows:shard -- --shard/u) + const winSaveHarness = testWf.jobs['test-windows'].steps.find((s) => s.name === 'Save DSH test harness') + assert.match(String(winSaveHarness?.if || ''), /matrix\.shard == 1/u) + assert.ok(testWf.jobs['release-milestone']) + const milestoneRun = testWf.jobs['release-milestone'].steps.map((s) => s.run || '').join('\n') + assert.match(milestoneRun, /scripts\/check-release-milestone\.mjs/u) + assert.match(milestoneRun, /--head-ref HEAD/u) + assert.equal(testWf.jobs['pr-guard'], undefined, 'label/milestone merge guard must stay isolated in pr-merge-guard.yml') assert.ok(testWf.jobs['app-windows']) assert.equal(testWf.jobs['app-package'], undefined) assert.equal(testWf.jobs['app-package-macos'], undefined) @@ -165,6 +274,12 @@ describe('CI workflow separation and path classification', () => { assert.equal(testWf.jobs['mobile-ios'], undefined) assert.equal(testWf.jobs['mobile-android'], undefined) + // package.yml dynamically gates macos-26-intel behind app_package_macos_x64. + const macMatrixInclude = String(pkgWf.jobs['app-package-macos'].strategy.matrix.include || '') + assert.match(macMatrixInclude, /needs\.changes\.outputs\.app_package_macos_x64 == 'true'/u) + assert.match(macMatrixInclude, /macos-26-intel/u) + assert.match(macMatrixInclude, /macos-latest/u) + // scan must depend on changes so schedule/dispatch runs pin every job to one immutable SHA. assert.equal(testWf.jobs.scan.needs, 'changes') for (const [name, wf] of [['test.yml', testWf], ['package.yml', pkgWf]]) { @@ -239,6 +354,110 @@ describe('CI workflow separation and path classification', () => { // Every job in package.yml is checked by Package result. const pkgJobs = Object.keys(pkgWf.jobs).filter((k) => k !== 'result') assert.deepEqual([...pkgWf.jobs.result.needs].sort(), [...pkgJobs].sort()) + + // Nightly release workflow contract: minimal top-level permissions, daily 20:00 UTC cron, pre-release only, no npm publish, APK checksum consistency. + assert.equal(nightlyWf.permissions.contents, 'read') + assert.equal(nightlyWf.jobs['publish-nightly'].permissions?.contents, 'write') + assert.deepEqual(nightlyWf.on.schedule, [{ cron: '0 20 * * *' }]) + const nightlyAllRuns = Object.values(nightlyWf.jobs).flatMap((j) => (j.steps || []).map((s) => s.run || '')).join('\n') + assert.doesNotMatch(nightlyAllRuns, /npm publish/u, 'nightly-release.yml must never publish to npm') + assert.match(nightlyAllRuns, /--prerelease/u) + assert.match(nightlyAllRuns, /--latest=false/u) + assert.match(nightlyAllRuns, /Release Readiness/u) + assert.match(nightlyAllRuns, /needs-product-ok/u) + assert.match(nightlyAllRuns, /delete-asset nightly DS-Bot-nightly-android\.apk/u) + + // Cut release workflow contract: no shell interpolation of ${{ ... }} in run:, fail-fast without RELEASE_BOT_TOKEN on auto_publish, + // supports fix/hot-*, fetches tags --force, avoids self-lock via --ignore-pr, idempotently writes Fixes #N, polls checks before --watch. + const cutInputs = cutReleaseWf.on.workflow_dispatch.inputs + assert.equal(cutInputs.version.required, true) + assert.deepEqual(cutInputs.mode.options, ['stable', 'hotfix']) + assert.equal(cutInputs.auto_publish.default, false) + for (const step of cutReleaseWf.jobs['cut-release'].steps) { + if (typeof step.run === 'string') { + assert.doesNotMatch(step.run, /\$\{\{/u, `cut-release.yml step "${step.name}" must pass expressions via env:, not inline in run:`) + } + } + const cutAllRuns = Object.values(cutReleaseWf.jobs).flatMap((j) => (j.steps || []).map((s) => s.run || '')).join('\n') + assert.match(cutAllRuns, /HAS_RELEASE_BOT_TOKEN/u) + assert.match(cutAllRuns, /fix\/hot-\*/u) + assert.match(cutAllRuns, /git fetch origin main dev --tags --force/u) + assert.match(cutAllRuns, /--ignore-pr "\$existing_pr"/u) + assert.match(cutAllRuns, /git ls-remote --exit-code --heads origin "\$TARGET_BRANCH"/u) + assert.match(cutAllRuns, /git merge --no-edit "\$BASE_REF"/u) + assert.match(cutAllRuns, /Hotfix-Source:/u) + assert.match(cutAllRuns, /Hotfix-Source-Sha:/u) + assert.doesNotMatch(cutAllRuns, /git push[^\n]*--force/u, 'cut-release.yml must reuse existing release branch and never force-push') + assert.match(cutAllRuns, //u) + assert.match(cutAllRuns, /Hotfix-Release: true/u) + assert.match(cutAllRuns, /scripts\/check-release-milestone\.mjs/u) + assert.match(cutAllRuns, /--latest=false/u) + assert.match(cutAllRuns, /chore\/merge-main-/u) + }) + + it('covers every ds-bot file statically imported by mobile/src across test.yml, release.yml, and nightly-release.yml while excluding generated release-notes metadata from Android APK rebuilds', () => { + const { runtimeDsBot, testOnlyDsBot } = discoverMobileDsBotImports() + assert.ok(runtimeDsBot.includes('ds-bot/src/client/inbox-text.js'), 'expected mobile/src to import inbox-text.js') + assert.ok(runtimeDsBot.some((f) => f.startsWith('ds-bot/src/client/locales/')), 'expected transitive locale imports from i18n.js') + + const releaseText = readFileSync(join(WORKFLOWS_DIR, 'release.yml'), 'utf8') + const nightlyText = readFileSync(join(WORKFLOWS_DIR, 'nightly-release.yml'), 'utf8') + const testText = readFileSync(join(WORKFLOWS_DIR, 'test.yml'), 'utf8') + + const extractPattern = (text, label) => { + const m = /grep -qE '([^']*mobile\/[^']*)'/u.exec(text) || /has '([^']*mobile\/[^']*)'/u.exec(text) + assert.ok(m, `${label}: failed to extract mobile path regex`) + return new RegExp(m[1], 'u') + } + + const releaseExcludeRe = /^ds-bot\/src\/shared\/release-notes(-generated\.js|\.json)$/u + const releaseMobileRe = extractPattern(releaseText, 'release.yml') + const nightlyMobileRe = extractPattern(nightlyText, 'nightly-release.yml') + const testMobileRe = extractPattern(testText, 'test.yml') + + assert.match(releaseText, /grep -Ev '\^ds-bot\/src\/shared\/release-notes\(-generated\\\.js\|\\\.json\)\$'/u) + assert.match(nightlyText, /grep -Ev '\^ds-bot\/src\/shared\/release-notes\(-generated\\\.js\|\\\.json\)\$'/u) + + for (const file of runtimeDsBot) { + assert.ok(testMobileRe.test(file), `test.yml mobile filter missed imported file: ${file}`) + if (releaseExcludeRe.test(file)) continue + assert.ok(releaseMobileRe.test(file), `release.yml android-scope filter missed imported file: ${file}`) + assert.ok(nightlyMobileRe.test(file), `nightly-release.yml android filter missed imported file: ${file}`) + } + for (const file of testOnlyDsBot) { + assert.ok(testMobileRe.test(file), `test.yml mobile filter missed test-imported file: ${file}`) + } + + // Pure release metadata edits must NOT trigger Android APK rebuilds in release.yml or nightly-release.yml. + const metadataOnly = [ + 'ds-bot/package.json', + 'app/package.json', + 'CHANGELOG.md', + 'ds-bot/src/shared/release-notes.json', + 'ds-bot/src/shared/release-notes-generated.js', + ].filter((f) => !releaseExcludeRe.test(f)) + for (const file of metadataOnly) { + assert.equal(releaseMobileRe.test(file), false, `release.yml must not rebuild Android APK for ${file}`) + assert.equal(nightlyMobileRe.test(file), false, `nightly-release.yml must not rebuild Android APK for ${file}`) + } + }) + + it('extracts full CHANGELOG.md release notes across blank lines in cut-release.yml', () => { + const changelog = readFileSync(join(REPO_ROOT, 'CHANGELOG.md'), 'utf8') + const lines = changelog.split(/\r?\n/u) + const version = '0.4.1' + const startRe = new RegExp(`^## \\[${version.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}\\](?:\\s|$)`, 'u') + const startIdx = lines.findIndex((line) => startRe.test(line)) + assert.notEqual(startIdx, -1) + const collected = [] + for (let i = startIdx + 1; i < lines.length; i += 1) { + if (lines[i].startsWith('## [')) break + collected.push(lines[i]) + } + const body = collected.join('\n').trim() + assert.match(body, /^### Changed/u) + assert.match(body, /### Fixed/u) + assert.doesNotMatch(body, /^## \[0\.4\.0\]/mu) }) it('keeps everyday ds-bot host PRs to dev on the fast Linux-only gate (no Windows, Playwright, Docker, or packaging)', () => { @@ -255,6 +474,7 @@ describe('CI workflow separation and path classification', () => { assert.equal(fast.app_unit_win, 'false') assert.equal(fast.docker, 'false') assert.equal(heavy.app_package_full, 'false') + assert.equal(heavy.app_package_macos_x64, 'false') assert.equal(heavy.app_package_linux, 'false') assert.equal(heavy.mobile_ios, 'false') assert.equal(heavy.mobile_android, 'false') @@ -288,6 +508,7 @@ describe('CI workflow separation and path classification', () => { assert.equal(fast.app_unit_win, 'false', `${file} must defer app_unit_win to Nightly`) assert.equal(fast.docker, 'false', `${file} must defer docker to Nightly`) assert.equal(heavy.app_package_full, 'false', `${file} must defer 4-OS packaging to Nightly`) + assert.equal(heavy.app_package_macos_x64, 'false', `${file} must not queue macos-26-intel`) assert.equal(heavy.app_package_linux, 'false', `${file} must defer Linux packaging to Nightly`) assert.equal(heavy.app_update, 'false', `${file} must defer updater double-build to Nightly`) assert.equal(heavy.mobile_ios, 'false', `${file} must defer iOS native build to Nightly`) @@ -301,27 +522,33 @@ describe('CI workflow separation and path classification', () => { assert.equal(fast.ds_bot_win, 'false') }) - it('runs workflow contract tests in test.yml when package or triage workflows change', () => { + it('runs workflow contract tests in test.yml when workflows or milestone script change', () => { for (const file of [ '.github/workflows/package.yml', '.github/workflows/full-package.yml', '.github/workflows/pr-triage-labels.yml', + '.github/workflows/pr-merge-guard.yml', + '.github/workflows/release.yml', + '.github/workflows/nightly-release.yml', + '.github/workflows/cut-release.yml', + 'scripts/check-release-milestone.mjs', ]) { const fast = runClassifier('test.yml', [file]) assert.equal(fast.ds_bot, 'true', `${file} must run ds_bot tests in test.yml`) } }) - it('runs full matrix and pins checkout_ref on release PRs to main, workflow edits, ci/full-package label, and daily dev Nightly', () => { - for (const [files, overrides, expectPinnedSha] of [ - [['README.md'], { BASE_REF: 'main' }, false], - [['README.md'], { EVENT: 'schedule', REF: 'refs/heads/main', BASE_REF: '' }, true], - [['README.md'], { EVENT: 'workflow_dispatch', REF: 'refs/heads/dev', BASE_REF: '' }, true], - [['.github/workflows/test.yml'], {}, false], + it('runs full matrix and pins checkout_ref on release PRs to main (without macos-26-intel), workflow edits, ci/full-package label, and daily dev Nightly', () => { + for (const [files, overrides, expectPinnedSha, expectReleasePr] of [ + [['README.md'], { BASE_REF: 'main', HEAD_REF: 'chore/release-0.4.2' }, false, true], + [['README.md'], { EVENT: 'schedule', REF: 'refs/heads/main', BASE_REF: '' }, true, false], + [['README.md'], { EVENT: 'workflow_dispatch', REF: 'refs/heads/dev', BASE_REF: '' }, true, false], + [['.github/workflows/test.yml'], {}, false, false], ]) { const fast = runClassifier('test.yml', files, overrides) assert.equal(fast.checkout_ref, expectPinnedSha ? fast._headSha : '') assert.equal(fast.full, 'true') + assert.equal(fast.release_pr, expectReleasePr ? 'true' : 'false') assert.equal(fast.ds_bot, 'true') assert.equal(fast.ds_bot_browser, 'true') assert.equal(fast.ds_bot_win, 'true') @@ -333,19 +560,20 @@ describe('CI workflow separation and path classification', () => { assert.equal(fast.docker, 'true') } - for (const [files, overrides, expectPinnedSha] of [ - [['README.md'], { BASE_REF: 'main' }, false], - [['README.md'], { PR_FULL_PACKAGE: 'true' }, false], - [['README.md'], { EVENT: 'schedule', REF: 'refs/heads/main', BASE_REF: '' }, true], - [['README.md'], { EVENT: 'workflow_dispatch', REF: 'refs/heads/dev', BASE_REF: '' }, true], - [['.github/workflows/package.yml'], {}, false], - [['.github/workflows/full-package.yml'], {}, false], - [['.github/workflows/release.yml'], {}, false], + for (const [files, overrides, expectPinnedSha, expectMacX64] of [ + [['README.md'], { BASE_REF: 'main', HEAD_REF: 'chore/release-0.4.2' }, false, false], + [['README.md'], { PR_FULL_PACKAGE: 'true' }, false, true], + [['README.md'], { EVENT: 'schedule', REF: 'refs/heads/main', BASE_REF: '' }, true, true], + [['README.md'], { EVENT: 'workflow_dispatch', REF: 'refs/heads/dev', BASE_REF: '' }, true, true], + [['.github/workflows/package.yml'], {}, false, false], + [['.github/workflows/full-package.yml'], {}, false, false], + [['.github/workflows/release.yml'], {}, false, false], ]) { const heavy = runClassifier('package.yml', files, overrides) assert.equal(heavy.checkout_ref, expectPinnedSha ? heavy._headSha : '') assert.equal(heavy.full, 'true') assert.equal(heavy.app_package_full, 'true') + assert.equal(heavy.app_package_macos_x64, expectMacX64 ? 'true' : 'false') assert.equal(heavy.app_package_linux, 'true') assert.equal(heavy.app_update, 'true') assert.equal(heavy.mobile_ios, 'true') @@ -353,6 +581,97 @@ describe('CI workflow separation and path classification', () => { } }) + it('uses hotfix fast-lane on BASE_REF=main for same-repo hotfix/*, fix/hot-*, or release/hotfix PRs (ignoring version-only lockfile bumps) while blocking fork branch-name spoofing', () => { + const basePkg = JSON.stringify({ name: 'ds-bot', version: '0.4.1', dependencies: { ws: '8.18.3' } }, null, 2) + const bumpedPkg = JSON.stringify({ name: 'ds-bot', version: '0.4.2', dependencies: { ws: '8.18.3' } }, null, 2) + const baseAppPkg = JSON.stringify({ name: 'dsbot', version: '0.4.1' }, null, 2) + const bumpedAppPkg = JSON.stringify({ name: 'dsbot', version: '0.4.2' }, null, 2) + const baseAppLock = JSON.stringify({ + name: 'dsbot', + version: '0.4.1', + packages: { '': { version: '0.4.1' }, 'node_modules/ds-bot': { version: '0.4.1', resolved: 'file:../ds-bot' } }, + }, null, 2) + const bumpedAppLock = JSON.stringify({ + name: 'dsbot', + version: '0.4.2', + packages: { '': { version: '0.4.2' }, 'node_modules/ds-bot': { version: '0.4.2', resolved: 'file:../ds-bot' } }, + }, null, 2) + + for (const overrides of [ + { BASE_REF: 'main', HEAD_REF: 'hotfix/0.4.2-mail-toggle', IS_SAME_REPO: 'true' }, + { BASE_REF: 'main', HEAD_REF: 'fix/hot-mail-toggle', IS_SAME_REPO: 'true' }, + { BASE_REF: 'main', HEAD_REF: 'fix/urgent-patch', IS_SAME_REPO: 'false', PR_HOTFIX: 'true' }, + ]) { + const pkgHotfix = runClassifier( + 'package.yml', + ['ds-bot/src/host/tools.js', 'app/ui/src/session-chat.js', 'ds-bot/package.json', 'app/package.json', 'app/package-lock.json'], + overrides, + { + baseFiles: { 'ds-bot/package.json': basePkg, 'app/package.json': baseAppPkg, 'app/package-lock.json': baseAppLock }, + headContents: { 'ds-bot/package.json': bumpedPkg, 'app/package.json': bumpedAppPkg, 'app/package-lock.json': bumpedAppLock }, + }, + ) + assert.equal(pkgHotfix.hotfix, 'true') + assert.equal(pkgHotfix.full, 'false') + assert.equal(pkgHotfix.mobile_ios, 'false') + assert.equal(pkgHotfix.mobile_android, 'false') + assert.equal(pkgHotfix.app_package_full, 'false') + assert.equal(pkgHotfix.app_package_macos_x64, 'false') + assert.equal(pkgHotfix.app_package_linux, 'true') + + const testHotfix = runClassifier('test.yml', ['ds-bot/src/host/tools.js'], overrides) + assert.equal(testHotfix.hotfix, 'true') + assert.equal(testHotfix.release_pr, 'false') + assert.equal(testHotfix.full, 'false') + assert.equal(testHotfix.ds_bot, 'true') + assert.equal(testHotfix.ds_bot_win, 'true', 'hotfix PR to main changing ds-bot must run 4-shard Windows unit tests') + assert.equal(testHotfix.app_unit, 'true') + assert.equal(testHotfix.app_unit_win, 'true', 'hotfix PR to main changing app/ds-bot must run Windows desktop unit tests') + + const winHotfix = runClassifier('test.yml', ['start.ps1'], overrides) + assert.equal(winHotfix.hotfix, 'true') + assert.equal(winHotfix.ds_bot, 'true') + assert.equal(winHotfix.ds_bot_win, 'true', 'Windows-specific hotfix (start.ps1) must run Windows unit tests') + assert.equal(winHotfix.app_unit_win, 'false') + } + + // A fork PR named hotfix/* without maintainer release/hotfix label must NOT bypass full checks. + const forkSpoofPkg = runClassifier('package.yml', ['ds-bot/src/host/tools.js'], { + BASE_REF: 'main', + HEAD_REF: 'hotfix/spoofed', + IS_SAME_REPO: 'false', + PR_HOTFIX: 'false', + }) + assert.equal(forkSpoofPkg.hotfix, 'false') + assert.equal(forkSpoofPkg.full, 'true') + + const forkSpoofTest = runClassifier('test.yml', ['ds-bot/src/host/tools.js'], { + BASE_REF: 'main', + HEAD_REF: 'hotfix/spoofed', + IS_SAME_REPO: 'false', + PR_HOTFIX: 'false', + }) + assert.equal(forkSpoofTest.hotfix, 'false') + assert.equal(forkSpoofTest.release_pr, 'true') + assert.equal(forkSpoofTest.full, 'true') + + // A hotfix that genuinely changes mobile native config or adds a dependency still triggers native/full packaging. + const depChangePkg = JSON.stringify({ name: 'ds-bot', version: '0.4.2', dependencies: { ws: '8.18.4' } }, null, 2) + const depHotfix = runClassifier( + 'package.yml', + ['ds-bot/package.json', 'mobile/app.json'], + { BASE_REF: 'main', HEAD_REF: 'hotfix/0.4.2-native', IS_SAME_REPO: 'true' }, + { + baseFiles: { 'ds-bot/package.json': basePkg }, + headContents: { 'ds-bot/package.json': depChangePkg }, + }, + ) + assert.equal(depHotfix.hotfix, 'true') + assert.equal(depHotfix.app_package_full, 'true') + assert.equal(depHotfix.mobile_ios, 'true') + assert.equal(depHotfix.mobile_android, 'true') + }) + it('keeps push to dev Linux-only and fast, falls back to full when BEFORE is missing or test.yml changes, and keeps push to main off Windows/macOS runners', () => { const devTestPush = runClassifier('test.yml', ['ds-bot/index.js', 'docker/Dockerfile'], { EVENT: 'push', @@ -399,6 +718,7 @@ describe('CI workflow separation and path classification', () => { BASE_REF: '', }) assert.equal(mainPkgPush.app_package_full, 'false') + assert.equal(mainPkgPush.app_package_macos_x64, 'false') assert.equal(mainPkgPush.app_package_linux, 'true') assert.equal(mainPkgPush.mobile_ios, 'false') assert.equal(mainPkgPush.mobile_android, 'false') diff --git a/ds-bot/test/release-milestone.test.js b/ds-bot/test/release-milestone.test.js new file mode 100644 index 000000000..f50dc2268 --- /dev/null +++ b/ds-bot/test/release-milestone.test.js @@ -0,0 +1,553 @@ +import assert from 'node:assert/strict' +import { spawn, spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { describe, it } from 'node:test' +import { fileURLToPath } from 'node:url' +import { + collectClosingIssuesFromGit, + compareSemver, + evaluatePrMergeGuard, + evaluateReleaseMilestone, + extractClosingIssueNumbers, + findMilestoneForVersion, + parseSemver, + resolveActiveDevMilestone, + runPrMergeGuard, + runReleaseMilestoneCheck, +} from '../../scripts/check-release-milestone.mjs' +import { + discoverTopLevelTests, + parseShardSpec, + partitionTestFiles, + selectShardFiles, +} from '../scripts/run-tests-shard.mjs' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const PLUGIN_ROOT = join(__dirname, '..') +const REPO_ROOT = join(PLUGIN_ROOT, '..') +const MILESTONE_SCRIPT = join(REPO_ROOT, 'scripts', 'check-release-milestone.mjs') +const SHARD_SCRIPT = join(PLUGIN_ROOT, 'scripts', 'run-tests-shard.mjs') + +describe('release milestone gate', () => { + it('parses and compares semver versions numerically including v0.4.2 vs v0.4.10 and prereleases', () => { + assert.equal(parseSemver('v0.4.2').version, '0.4.2') + assert.equal(parseSemver('0.4.2').tag, 'v0.4.2') + assert.equal(parseSemver('0.4.2-rc.1').prerelease, true) + assert.equal(parseSemver('not-a-version'), null) + assert.equal(parseSemver('0.4.'), null) + + assert.equal(compareSemver('v0.4.1', 'v0.4.2'), -1) + assert.equal(compareSemver('v0.4.2', 'v0.4.10'), -1) + assert.equal(compareSemver('v0.4.10', 'v0.4.2'), 1) + assert.equal(compareSemver('0.4.2', 'v0.4.2'), 0) + assert.equal(compareSemver('0.4.2-rc.1', '0.4.2'), -1) + assert.equal(compareSemver('0.4.2-rc.2', '0.4.2-rc.10'), -1) + assert.equal(compareSemver('0.5.0', '0.4.99'), 1) + + const active = resolveActiveDevMilestone('0.4.1', [ + { number: 10, title: 'v0.4.10', state: 'open', open_issues: 1 }, + { number: 4, title: 'v0.4.2', state: 'open', open_issues: 2 }, + ]) + assert.equal(active?.parsed.tag, 'v0.4.2') + }) + + it('extracts GitHub closing keywords accurately while ignoring cross-repo issues', () => { + const text = 'Fixes #123, closes: #456, Resolves Fei-Craft/DS-Bot#789, fix other/repo#999, mentions #111' + assert.deepEqual([...extractClosingIssueNumbers(text, 'Fei-Craft/DS-Bot')].sort((a, b) => a - b), [123, 456, 789]) + }) + + it('finds milestones matching vX.Y.Z or bare X.Y.Z', () => { + const milestones = [ + { number: 1, title: 'v0.4.1', state: 'open', open_issues: 0 }, + { number: 2, title: '0.4.2', state: 'open', open_issues: 0 }, + ] + assert.equal(findMilestoneForVersion(milestones, '0.4.1')?.number, 1) + assert.equal(findMilestoneForVersion(milestones, 'v0.4.2')?.number, 2) + assert.equal(findMilestoneForVersion(milestones, 'v0.4.3'), null) + }) + + it('fails when the target Milestone does not exist or has open issues/PRs', () => { + const missing = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 1, title: 'v0.4.1', state: 'open', open_issues: 0 }], + }) + assert.equal(missing.ok, false) + assert.equal(missing.reason, 'milestone-not-found') + + const withOpen = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 2, closed_issues: 3 }], + openItems: [ + { number: 2401, title: 'Fix installer check', state: 'open', html_url: 'https://github.com/Fei-Craft/DS-Bot/issues/2401' }, + { number: 2405, title: 'Implement feature X', state: 'open', pull_request: {}, html_url: 'https://github.com/Fei-Craft/DS-Bot/pull/2405' }, + ], + }) + assert.equal(withOpen.ok, false) + assert.equal(withOpen.reason, 'open-items-remaining') + assert.equal(withOpen.blockingItems.length, 2) + assert.match(withOpen.message, /\[Issue\] #2401 Fix installer check/u) + assert.match(withOpen.message, /\[PR\] #2405 Implement feature X/u) + + // Fail-closed when open_issues > 0 and openItems is omitted. + const noList = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 1 }], + openItems: null, + }) + assert.equal(noList.ok, false) + assert.equal(noList.reason, 'open-items-remaining') + }) + + it('exempts open issues already fixed in dev (pending merge to main) while still blocking unmerged PRs and unfixed issues', () => { + const allFixedInDev = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 2, closed_issues: 3 }], + openItems: [ + { number: 2500, title: 'release: v0.4.2', state: 'open', pull_request: {} }, + { number: 2401, title: 'Already fixed on dev', state: 'open', html_url: 'https://github.com/Fei-Craft/DS-Bot/issues/2401' }, + ], + ignorePrNumber: 2500, + resolvedIssueNumbers: [2401], + }) + assert.equal(allFixedInDev.ok, true) + assert.equal(allFixedInDev.resolvedPendingMain.length, 1) + assert.match(allFixedInDev.message, /will auto-close on merge to main/u) + + // Even if a PR number appears in resolvedIssueNumbers, unmerged PRs are never exempted. + const unmergedPrStillBlocks = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 1 }], + openItems: [ + { number: 2405, title: 'Open feature PR', state: 'open', pull_request: {} }, + ], + resolvedIssueNumbers: [2405], + }) + assert.equal(unmergedPrStillBlocks.ok, false) + assert.equal(unmergedPrStillBlocks.blockingItems[0].number, 2405) + }) + + it('ignores the release PR itself via ignorePrNumber and allows clean, closed, hotfix, prerelease, or allowOpen runs', () => { + const onlySelfPr = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 1, closed_issues: 8 }], + openItems: [ + { number: 2500, title: 'release: v0.4.2', state: 'open', pull_request: {} }, + ], + ignorePrNumber: 2500, + }) + assert.equal(onlySelfPr.ok, true) + assert.equal(onlySelfPr.reason, 'milestone-clean') + + // Closed milestone with 0 open items passes. + const closedClean = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'closed', open_issues: 0, closed_issues: 12 }], + openItems: [], + }) + assert.equal(closedClean.ok, true) + + // Prerelease and hotfix skip strict milestone gate. + assert.equal(evaluateReleaseMilestone({ targetVersion: 'v0.4.2-rc.1', milestones: [] }).skipped, true) + assert.equal(evaluateReleaseMilestone({ targetVersion: 'v0.4.2', milestones: [], hotfix: true }).skipped, true) + + // allowOpen allows open items with warning. + const allowed = evaluateReleaseMilestone({ + targetVersion: 'v0.4.2', + milestones: [{ number: 4, title: 'v0.4.2', state: 'open', open_issues: 1 }], + openItems: [{ number: 2410, title: 'Unfinished bug', state: 'open' }], + allowOpen: true, + }) + assert.equal(allowed.ok, true) + assert.equal(allowed.allowedOpen, true) + }) + + it('blocks PRs with needs-product-ok and blocks dev PRs with a future Milestone ahead of the active dev Milestone', () => { + const openMilestones = [ + { number: 1, title: 'v0.3.9', state: 'open', open_issues: 0 }, + { number: 2, title: 'v0.4.0', state: 'open', open_issues: 0 }, + { number: 5, title: 'v0.4.1', state: 'open', open_issues: 0 }, + { number: 4, title: 'v0.4.2', state: 'open', open_issues: 2 }, + { number: 6, title: 'v0.4.3', state: 'open', open_issues: 1 }, + ] + + const active = resolveActiveDevMilestone('0.4.1', openMilestones) + assert.equal(active?.parsed.tag, 'v0.4.2') + + const okDev = evaluatePrMergeGuard({ + baseRef: 'dev', + labels: ['agent/antigravity', 'review/approved'], + prMilestoneTitle: 'v0.4.2', + currentVersion: '0.4.1', + milestones: openMilestones, + }) + assert.equal(okDev.ok, true) + assert.equal(okDev.activeMilestone, 'v0.4.2') + + const futureDev = evaluatePrMergeGuard({ + baseRef: 'dev', + labels: ['agent/antigravity'], + prMilestoneTitle: 'v0.4.3', + currentVersion: '0.4.1', + milestones: openMilestones, + }) + assert.equal(futureDev.ok, false) + assert.equal(futureDev.blockedByFutureMilestone, true) + assert.equal(futureDev.blockedByProductOk, false) + assert.match(futureDev.summary, /v0\.4\.3.*v0\.4\.2/u) + + const needsProductOk = evaluatePrMergeGuard({ + baseRef: 'dev', + labels: [{ name: 'needs-product-ok' }], + prMilestoneTitle: 'v0.4.2', + currentVersion: '0.4.1', + milestones: openMilestones, + }) + assert.equal(needsProductOk.ok, false) + assert.equal(needsProductOk.blockedByProductOk, true) + assert.equal(needsProductOk.blockedByFutureMilestone, false) + + const bothBlocked = evaluatePrMergeGuard({ + baseRef: 'dev', + labels: ['needs-product-ok'], + prMilestoneTitle: 'v0.4.3', + currentVersion: '0.4.1', + milestones: openMilestones, + }) + assert.equal(bothBlocked.ok, false) + assert.equal(bothBlocked.reasons.length, 2) + + const mainPrOk = evaluatePrMergeGuard({ + baseRef: 'main', + labels: [], + prMilestoneTitle: 'v0.4.3', + currentVersion: '0.4.1', + milestones: openMilestones, + }) + assert.equal(mainPrOk.ok, true) + }) + + it('verifies HTTP pagination, same-origin guard, dev-fixed issue detection, fork restricted-token fallback, and CLI exit codes', async (t) => { + // Create a tiny temp git repo with origin/main and origin/dev containing "Fixes #201" + a merged PR commit. + const gitDir = mkdtempSync(join(tmpdir(), 'dsb-milestone-git-')) + t.after(() => rmSync(gitDir, { recursive: true, force: true })) + const gitEnv = { + ...process.env, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_TERMINAL_PROMPT: '0', + } + const git = (args) => { + const res = spawnSync('git', ['-c', 'commit.gpgsign=false', ...args], { cwd: gitDir, encoding: 'utf8', env: gitEnv }) + assert.equal(res.status, 0, res.stderr) + return res.stdout.trim() + } + git(['init', '-b', 'dev']) + git(['config', 'user.email', 'test@example.com']) + git(['config', 'user.name', 'Test']) + writeFileSync(join(gitDir, 'a.txt'), 'v1\n') + git(['add', '.']) + git(['commit', '-m', 'Merge pull request #400 from Fei-Craft/fix/old-reopened']) + const oldMainPrSha = git(['rev-parse', 'HEAD']) + git(['update-ref', 'refs/remotes/origin/main', oldMainPrSha]) + writeFileSync(join(gitDir, 'a.txt'), 'v2\n') + git(['add', '.']) + git(['commit', '-m', 'fix(core): resolve bug\n\nFixes #201']) + writeFileSync(join(gitDir, 'b.txt'), 'v3\n') + git(['add', '.']) + git(['commit', '-m', 'Merge pull request #500 from Fei-Craft/fix/issue-202']) + const mergedPrSha = git(['rev-parse', 'HEAD']) + git(['update-ref', 'refs/remotes/origin/dev', mergedPrSha]) + + assert.deepEqual([...collectClosingIssuesFromGit({ baseRef: 'origin/main', headRef: 'origin/dev', cwd: gitDir })], [201]) + + const server = createServer((req, res) => { + res.setHeader('connection', 'close') + const url = new URL(req.url, 'http://127.0.0.1') + if (url.pathname === '/repos/acme/reopened/milestones') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([{ number: 7, title: 'v0.4.2', state: 'open', open_issues: 1, closed_issues: 0 }])) + return + } + if (url.pathname === '/repos/acme/reopened/issues') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([ + { number: 203, title: 'Reopened regression', state: 'open', html_url: 'https://example.test/issues/203' }, + ])) + return + } + if (url.pathname === '/repos/acme/reopened/issues/203/timeline') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([ + { + event: 'cross-referenced', + source: { + issue: { + number: 400, + state: 'closed', + pull_request: { url: 'https://example.test/pull/400' }, + repository: { full_name: 'acme/reopened' }, + }, + }, + }, + ])) + return + } + if (url.pathname === '/repos/acme/reopened/pulls/400') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ + number: 400, + merged: true, + merged_at: '2026-11-01T10:00:00Z', + merge_commit_sha: oldMainPrSha, + base: { ref: 'dev' }, + title: 'fix: earlier fix already shipped in main', + body: 'Fixes #203', + })) + return + } + if (url.pathname === '/repos/acme/rate-limited/milestones') { + res.writeHead(403, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ message: 'Resource not accessible by integration' })) + return + } + if (url.pathname === '/repos/acme/cross-origin/milestones') { + res.writeHead(200, { + 'content-type': 'application/json', + link: '; rel="next"', + }) + res.end(JSON.stringify([])) + return + } + if (url.pathname === '/repos/acme/ds-bot/milestones') { + const page = url.searchParams.get('page') || '1' + if (page === '1') { + const next = `http://127.0.0.1:${String(server.address().port)}/repos/acme/ds-bot/milestones?state=all&per_page=100&page=2` + res.writeHead(200, { 'content-type': 'application/json', link: `<${next}>; rel="next"` }) + res.end(JSON.stringify([ + { number: 1, title: 'v0.4.1', state: 'open', open_issues: 0, closed_issues: 5 }, + ])) + return + } + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([ + { number: 2, title: 'v0.4.2', state: 'open', open_issues: 3, closed_issues: 3 }, + { number: 3, title: 'v0.4.3', state: 'open', open_issues: 2, closed_issues: 0 }, + ])) + return + } + if (url.pathname === '/repos/acme/ds-bot/issues') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([ + { number: 99, title: 'release: v0.4.2', state: 'open', pull_request: {}, html_url: 'https://example.test/pull/99' }, + { number: 201, title: 'Fixed via commit in dev', state: 'open', html_url: 'https://example.test/issues/201' }, + { number: 202, title: 'Fixed via PR body merged to dev', state: 'open', html_url: 'https://example.test/issues/202' }, + ])) + return + } + if (url.pathname === '/repos/acme/ds-bot/issues/202/timeline') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify([ + { + event: 'cross-referenced', + source: { + issue: { + number: 500, + state: 'closed', + pull_request: { url: 'https://example.test/pull/500' }, + repository: { full_name: 'acme/ds-bot' }, + }, + }, + }, + ])) + return + } + if (url.pathname === '/repos/acme/ds-bot/pulls/500') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ + number: 500, + merged: true, + merged_at: '2026-11-27T10:00:00Z', + merge_commit_sha: mergedPrSha, + base: { ref: 'dev' }, + title: 'fix: resolve 202', + body: 'Fixes #202', + })) + return + } + if (url.pathname === '/repos/acme/ds-bot/pulls/123') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ + number: 123, + state: 'open', + base: { ref: 'dev' }, + head: { sha: 'deadbeef'.repeat(5) }, + labels: [{ name: 'agent/antigravity' }], + milestone: { title: 'v0.4.3' }, + })) + return + } + res.writeHead(404) + res.end('{}') + }) + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => { + server.closeAllConnections?.() + server.close() + }) + const apiBase = `http://127.0.0.1:${String(server.address().port)}` + + // Without headRef, issues #201 and #202 + PR #99 all block. + const blocked = await runReleaseMilestoneCheck({ + version: 'v0.4.2', + repo: 'acme/ds-bot', + apiBase, + }) + assert.equal(blocked.ok, false) + assert.equal(blocked.blockingItems.length, 3) + + // With headRef=origin/dev + ignorePrNumber=99: #201 is cleared via git log Fixes #201 and #202 via timeline merged PR #500. + const passedViaDevFixes = await runReleaseMilestoneCheck({ + version: 'v0.4.2', + repo: 'acme/ds-bot', + apiBase, + ignorePrNumber: 99, + baseRef: 'origin/main', + headRef: 'origin/dev', + cwd: gitDir, + }) + assert.equal(passedViaDevFixes.ok, true, passedViaDevFixes.message) + assert.deepEqual(passedViaDevFixes.resolvedPendingMain.map(i => i.number), [201, 202]) + + // Reopened issue #203 whose only merged PR (#400) is ALREADY an ancestor of origin/main must NOT be exempted. + const reopenedBlocked = await runReleaseMilestoneCheck({ + version: 'v0.4.2', + repo: 'acme/reopened', + apiBase, + baseRef: 'origin/main', + headRef: 'origin/dev', + cwd: gitDir, + }) + assert.equal(reopenedBlocked.ok, false) + assert.deepEqual(reopenedBlocked.blockingItems.map(i => i.number), [203]) + assert.deepEqual(reopenedBlocked.resolvedPendingMain, []) + + // Cross-origin pagination Link header must fail closed without forwarding Authorization. + await assert.rejects( + runReleaseMilestoneCheck({ + version: 'v0.4.2', + repo: 'acme/cross-origin', + apiBase, + token: 'placeholder-token-for-test', + }), + /cross-origin/u, + ) + + // Fork PR with non-empty restricted token skips cleanly when allowMissingToken is true and GitHub returns 403. + const forkSkip = await runReleaseMilestoneCheck({ + version: 'v0.4.2', + repo: 'acme/rate-limited', + apiBase, + token: 'restricted-fork-token-placeholder', + allowMissingToken: true, + }) + assert.equal(forkSkip.ok, true) + assert.equal(forkSkip.skipped, true) + assert.equal(forkSkip.reason, 'restricted-token') + + // PR guard via HTTP API blocks future Milestone v0.4.3 when active dev milestone is v0.4.2. + const prGuard = await runPrMergeGuard({ + prNumber: 123, + currentVersion: '0.4.1', + repo: 'acme/ds-bot', + apiBase, + }) + assert.equal(prGuard.ok, false) + assert.equal(prGuard.blockedByFutureMilestone, true) + + // CLI contract (must spawn asynchronously so the in-process mock HTTP server stays responsive). + const runCli = (args, cwd = PLUGIN_ROOT) => new Promise((resolve, reject) => { + const child = spawn(process.execPath, [MILESTONE_SCRIPT, ...args], { cwd, stdio: ['ignore', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => { stdout += chunk.toString('utf8') }) + child.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8') }) + child.once('error', reject) + child.once('close', (status) => { resolve({ status, stdout, stderr }) }) + }) + + const cliFail = await runCli(['--version', 'v0.4.2', '--repo', 'acme/ds-bot', '--api-base', apiBase]) + assert.equal(cliFail.status, 1) + assert.match(cliFail.stderr, /#99 release: v0\.4\.2/u) + + const cliOk = await runCli([ + '--version', 'v0.4.2', + '--repo', 'acme/ds-bot', + '--api-base', apiBase, + '--ignore-pr', '99', + '--base-ref', 'origin/main', + '--head-ref', 'origin/dev', + ], gitDir) + assert.equal(cliOk.status, 0, cliOk.stderr) + assert.match(cliOk.stdout, /passed/u) + }) +}) + +describe('Windows test shard runner', () => { + it('validates shard specifiers and rejects out-of-range inputs', () => { + assert.deepEqual(parseShardSpec('1/4'), { index: 1, total: 4 }) + assert.deepEqual(parseShardSpec('4/4'), { index: 4, total: 4 }) + for (const bad of ['', '0/4', '5/4', '1/0', 'abc', '1/2/3']) { + assert.throws(() => parseShardSpec(bad), /shard/i) + } + }) + + it('partitions test files deterministically with complete non-overlapping coverage and balanced weights', () => { + const entries = [ + { file: 'test/a.test.js', size: 130_000 }, + { file: 'test/b.test.js', size: 80_000 }, + { file: 'test/c.test.js', size: 70_000 }, + { file: 'test/d.test.js', size: 65_000 }, + { file: 'test/e.test.js', size: 30_000 }, + { file: 'test/f.test.js', size: 25_000 }, + { file: 'test/g.test.js', size: 20_000 }, + { file: 'test/h.test.js', size: 15_000 }, + ] + const forward = partitionTestFiles(entries, 4) + const reversed = partitionTestFiles([...entries].reverse(), 4) + assert.deepEqual(forward, reversed, 'partitioning must be invariant to input order') + + const shardOf = (name) => forward.findIndex(bucket => bucket.includes(name)) + assert.equal(new Set(['test/a.test.js', 'test/b.test.js', 'test/c.test.js', 'test/d.test.js'].map(shardOf)).size, 4) + + const union = forward.flat().sort() + assert.deepEqual(union, entries.map(e => e.file).sort()) + assert.deepEqual(selectShardFiles(entries, 2, 4), forward[1]) + }) + + it('lists all ds-bot top-level tests across 4 CLI shards with zero drops or duplicates', () => { + const all = discoverTopLevelTests().map(e => e.file).sort() + assert.ok(all.length > 50, `expected >50 top-level tests, got ${String(all.length)}`) + + const seen = new Set() + const collected = [] + for (let shard = 1; shard <= 4; shard += 1) { + const run = spawnSync(process.execPath, [SHARD_SCRIPT, '--shard', `${String(shard)}/4`, '--list'], { + cwd: PLUGIN_ROOT, + encoding: 'utf8', + }) + assert.equal(run.status, 0, run.stderr) + const files = run.stdout.trim().split(/\r?\n/).filter(Boolean) + assert.ok(files.length > 0, `shard ${String(shard)}/4 must not be empty`) + for (const file of files) { + assert.ok(!seen.has(file), `duplicate test file ${file} in shard ${String(shard)}/4`) + seen.add(file) + collected.push(file) + } + } + assert.deepEqual(collected.sort(), all) + }) +}) diff --git a/scripts/check-release-milestone.mjs b/scripts/check-release-milestone.mjs new file mode 100644 index 000000000..cdfa4a3b7 --- /dev/null +++ b/scripts/check-release-milestone.mjs @@ -0,0 +1,778 @@ +#!/usr/bin/env node +// Release milestone and PR merge-guard gate. +// Zero external dependencies (Node 24 ESM) so CI jobs can run it before npm ci. +// +// Modes: +// 1. Release milestone gate (default): +// node scripts/check-release-milestone.mjs --version v0.4.2 [--repo Fei-Craft/DS-Bot] +// [--ignore-pr ] [--base-ref origin/main] [--head-ref origin/dev] +// [--allow-open] [--hotfix] [--allow-missing-token] [--json] +// 2. PR merge guard (--mode pr-guard): +// node scripts/check-release-milestone.mjs --mode pr-guard --pr --current-version 0.4.1 +// [--repo Fei-Craft/DS-Bot] [--allow-missing-token] [--json] +import { spawnSync } from 'node:child_process' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +export const DEFAULT_REPO = 'Fei-Craft/DS-Bot' +export const DEFAULT_API_BASE = 'https://api.github.com' +export const PRODUCT_OK_LABEL = 'needs-product-ok' + +const SEMVER_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u +const CLOSING_KEYWORD_RE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)(?:\s*:\s*|\s+)(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+))?#(\d+)\b/giu + +/** Parse a semver string (with optional leading "v"). Returns null when invalid. */ +export function parseSemver(raw) { + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + const match = SEMVER_RE.exec(trimmed) + if (match === null) return null + const major = Number(match[1]) + const minor = Number(match[2]) + const patch = Number(match[3]) + if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) { + return null + } + const preRaw = match[4] ?? null + if (preRaw !== null) { + const preParts = preRaw.split('.') + if (preParts.some(part => part === '')) return null + return { + major, + minor, + patch, + pre: preParts, + prerelease: true, + version: `${String(major)}.${String(minor)}.${String(patch)}-${preRaw}`, + tag: `v${String(major)}.${String(minor)}.${String(patch)}-${preRaw}`, + } + } + const version = `${String(major)}.${String(minor)}.${String(patch)}` + return { + major, + minor, + patch, + pre: null, + prerelease: false, + version, + tag: `v${version}`, + } +} + +/** Standard semver ordering: -1 when a < b, 0 when equal, 1 when a > b. */ +export function compareSemver(aRaw, bRaw) { + const a = typeof aRaw === 'string' ? parseSemver(aRaw) : aRaw + const b = typeof bRaw === 'string' ? parseSemver(bRaw) : bRaw + if (a === null || b === null) { + throw new Error(`Cannot compare non-semver values: ${String(aRaw)} vs ${String(bRaw)}`) + } + if (a.major !== b.major) return a.major < b.major ? -1 : 1 + if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1 + if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1 + if (a.pre === null && b.pre === null) return 0 + if (a.pre === null) return 1 + if (b.pre === null) return -1 + const len = Math.max(a.pre.length, b.pre.length) + for (let i = 0; i < len; i += 1) { + const left = a.pre[i] + const right = b.pre[i] + if (left === undefined) return -1 + if (right === undefined) return 1 + if (left === right) continue + const leftNum = /^\d+$/u.test(left) + const rightNum = /^\d+$/u.test(right) + if (leftNum && rightNum) { + const diff = BigInt(left) - BigInt(right) + return diff < 0n ? -1 : 1 + } + if (leftNum !== rightNum) return leftNum ? -1 : 1 + return left < right ? -1 : 1 + } + return 0 +} + +/** + * Extract issue numbers referenced with GitHub closing keywords (Fixes/Closes/Resolves #N). + * Cross-repo references (other/repo#N) are ignored unless they match `repo`. + */ +export function extractClosingIssueNumbers(text, repo = DEFAULT_REPO) { + const numbers = new Set() + if (typeof text !== 'string' || text === '') return numbers + const targetRepo = String(repo || '').toLowerCase() + for (const match of text.matchAll(CLOSING_KEYWORD_RE)) { + const explicitRepo = match[1] ? match[1].toLowerCase() : null + if (explicitRepo && targetRepo && explicitRepo !== targetRepo) continue + const num = Number(match[2]) + if (Number.isSafeInteger(num) && num > 0) numbers.add(num) + } + return numbers +} + +/** + * Collect issue numbers closed by commits in `baseRef..headRef` in a local git checkout. + * Never throws when git history or refs are unavailable (returns an empty Set). + */ +export function collectClosingIssuesFromGit({ + baseRef = 'origin/main', + headRef = 'HEAD', + repo = DEFAULT_REPO, + cwd = process.cwd(), +} = {}) { + if (!headRef || !baseRef) return new Set() + const res = spawnSync('git', ['log', '--format=%B', `${baseRef}..${headRef}`], { + cwd, + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + }) + if (res.status !== 0 || !res.stdout) return new Set() + return extractClosingIssueNumbers(res.stdout, repo) +} + +function isCommitAncestor(commitSha, headRef, cwd = process.cwd()) { + if (!commitSha || !headRef || !/^[0-9a-f]{7,40}$/iu.test(commitSha)) return false + const res = spawnSync('git', ['merge-base', '--is-ancestor', commitSha, headRef], { + cwd, + encoding: 'utf8', + }) + return res.status === 0 +} + +/** + * Find the GitHub Milestone matching `targetVersion` (prefers exact "vX.Y.Z", accepts "X.Y.Z"). + */ +export function findMilestoneForVersion(milestones, targetVersion) { + const parsed = parseSemver(targetVersion) + if (parsed === null || !Array.isArray(milestones)) return null + const exactTag = milestones.find(m => typeof m?.title === 'string' && m.title.trim() === parsed.tag) + if (exactTag) return exactTag + const bare = milestones.find(m => typeof m?.title === 'string' && m.title.trim() === parsed.version) + return bare ?? null +} + +/** + * Pure evaluation of whether a release version passes the Milestone zero-open gate. + * Open issues already fixed in `dev` (included in `resolvedIssueNumbers`, waiting for merge to + * default branch `main` to auto-close) are listed as pending auto-close and do not block release. + * Unmerged open PRs (except `ignorePrNumber`) always block release. + */ +export function evaluateReleaseMilestone({ + targetVersion, + milestones = [], + openItems = null, + ignorePrNumber = null, + resolvedIssueNumbers = [], + allowOpen = false, + hotfix = false, + skipPrerelease = true, +}) { + const parsed = parseSemver(targetVersion) + if (parsed === null) { + return { + ok: false, + skipped: false, + reason: 'invalid-version', + message: `Invalid target release version "${String(targetVersion)}"; expected semver like v0.4.2.`, + blockingItems: [], + resolvedPendingMain: [], + milestone: null, + } + } + + if (skipPrerelease && parsed.prerelease) { + return { + ok: true, + skipped: true, + reason: 'prerelease', + message: `Skipping milestone gate for prerelease ${parsed.tag}.`, + blockingItems: [], + resolvedPendingMain: [], + milestone: null, + } + } + + const milestone = findMilestoneForVersion(milestones, parsed.tag) + + if (hotfix) { + return { + ok: true, + skipped: true, + reason: 'hotfix', + message: milestone + ? `Hotfix mode: skipping strict milestone gate for ${parsed.tag} (milestone #${String(milestone.number)} currently has ${String(milestone.open_issues ?? 0)} open item(s)).` + : `Hotfix mode: skipping strict milestone gate for ${parsed.tag} (no milestone required for hotfix).`, + blockingItems: [], + resolvedPendingMain: [], + milestone, + } + } + + if (milestone === null) { + if (allowOpen) { + return { + ok: true, + skipped: false, + allowedOpen: true, + reason: 'milestone-not-found-allowed', + message: `Warning (--allow-open): GitHub Milestone "${parsed.tag}" does not exist.`, + blockingItems: [], + resolvedPendingMain: [], + milestone: null, + } + } + return { + ok: false, + skipped: false, + reason: 'milestone-not-found', + message: `GitHub Milestone "${parsed.tag}" was not found. Create Milestone "${parsed.tag}" and close all planned issues/PRs before releasing.`, + blockingItems: [], + resolvedPendingMain: [], + milestone: null, + } + } + + const reportedOpenCount = Number(milestone.open_issues ?? 0) + const ignoreNum = Number.isSafeInteger(ignorePrNumber) && ignorePrNumber > 0 ? ignorePrNumber : null + const resolvedSet = new Set( + [...(resolvedIssueNumbers || [])].map(Number).filter(n => Number.isSafeInteger(n) && n > 0), + ) + + let blockingItems = [] + const resolvedPendingMain = [] + let ignoredSelfPrCount = 0 + + if (Array.isArray(openItems)) { + for (const item of openItems) { + if (!item || item.state === 'closed') continue + const num = Number(item.number) + const isPr = Boolean(item.pull_request) + if (ignoreNum !== null && num === ignoreNum && isPr) { + ignoredSelfPrCount += 1 + continue + } + const entry = { + number: num, + title: String(item.title || '').trim(), + type: isPr ? 'PR' : 'Issue', + url: String(item.html_url || ''), + } + // Only non-PR issues that already have a closing commit/PR in this release branch are exempted. + if (!isPr && resolvedSet.has(num)) { + resolvedPendingMain.push(entry) + continue + } + blockingItems.push(entry) + } + blockingItems.sort((a, b) => a.number - b.number) + resolvedPendingMain.sort((a, b) => a.number - b.number) + } else if (reportedOpenCount > 0) { + // Fail-closed when open_issues > 0 and caller did not supply the itemized list. + blockingItems = Array.from({ length: reportedOpenCount }, (_, idx) => ({ + number: 0, + title: `Unresolved open item #${String(idx + 1)} (item list unavailable)`, + type: 'Item', + url: '', + })) + } + + const accountedExemptions = ignoredSelfPrCount + resolvedPendingMain.length + const expectedMinBlocking = Math.max(0, reportedOpenCount - accountedExemptions) + const effectiveCount = Math.max(blockingItems.length, expectedMinBlocking) + + const formatList = (list) => list.map(item => ( + item.number > 0 + ? ` - [${item.type}] #${String(item.number)} ${item.title}${item.url ? ` (${item.url})` : ''}` + : ` - ${item.title}` + )).join('\n') + + if (effectiveCount > 0) { + const detail = blockingItems.length > 0 ? `\n${formatList(blockingItems)}` : '' + const resolvedNote = resolvedPendingMain.length > 0 + ? `\nAlready fixed in release branch (pending auto-close on merge to main):\n${formatList(resolvedPendingMain)}` + : '' + if (allowOpen) { + return { + ok: true, + skipped: false, + allowedOpen: true, + reason: 'open-items-allowed', + message: `Warning (--allow-open): Milestone "${milestone.title}" still has ${String(effectiveCount)} open item(s):${detail}${resolvedNote}`, + blockingItems, + resolvedPendingMain, + milestone, + } + } + return { + ok: false, + skipped: false, + reason: 'open-items-remaining', + message: `Milestone "${milestone.title}" still has ${String(effectiveCount)} open item(s); close or move them before releasing ${parsed.tag}:${detail}${resolvedNote}`, + blockingItems, + resolvedPendingMain, + milestone, + } + } + + const resolvedSuffix = resolvedPendingMain.length > 0 + ? `\nResolved in release branch (will auto-close on merge to main):\n${formatList(resolvedPendingMain)}` + : '' + + return { + ok: true, + skipped: false, + reason: 'milestone-clean', + message: `Milestone "${milestone.title}" passed (0 blocking open items, ${String(resolvedPendingMain.length)} fixed pending merge to main, ${String(milestone.closed_issues ?? 0)} closed).${resolvedSuffix}`, + blockingItems: [], + resolvedPendingMain, + milestone, + } +} + +/** + * Determine the active target release Milestone for `dev`: + * the lowest open stable semver milestone strictly greater than `currentVersion`. + */ +export function resolveActiveDevMilestone(currentVersion, milestones = []) { + const current = parseSemver(currentVersion) + if (current === null || !Array.isArray(milestones)) return null + const candidates = [] + for (const m of milestones) { + if (!m || m.state !== 'open') continue + const parsed = parseSemver(m.title) + if (parsed === null || parsed.prerelease) continue + if (compareSemver(parsed, current) > 0) { + candidates.push({ milestone: m, parsed }) + } + } + candidates.sort((a, b) => compareSemver(a.parsed, b.parsed)) + return candidates[0] ?? null +} + +/** + * Pure PR merge-guard evaluation: + * 1. Blocks any PR carrying the `needs-product-ok` label. + * 2. Blocks any PR targeting `dev` whose Milestone is ahead of the active `dev` release Milestone. + */ +export function evaluatePrMergeGuard({ + baseRef, + labels = [], + prMilestoneTitle = null, + currentVersion, + milestones = [], +}) { + const normalizedLabels = labels.map(l => (typeof l === 'string' ? l : String(l?.name ?? ''))).filter(Boolean) + const reasons = [] + + const hasNeedsProductOk = normalizedLabels.some(name => name.toLowerCase() === PRODUCT_OK_LABEL) + if (hasNeedsProductOk) { + reasons.push({ + code: 'needs-product-ok', + message: `PR has the "${PRODUCT_OK_LABEL}" label and requires maintainer product sign-off before merging.`, + }) + } + + let activeMilestone = null + let prMilestoneParsed = null + if (baseRef === 'dev' && typeof prMilestoneTitle === 'string' && prMilestoneTitle.trim() !== '') { + prMilestoneParsed = parseSemver(prMilestoneTitle) + const active = resolveActiveDevMilestone(currentVersion, milestones) + activeMilestone = active ? active.parsed.tag : null + if (prMilestoneParsed !== null) { + if (active !== null && compareSemver(prMilestoneParsed, active.parsed) > 0) { + reasons.push({ + code: 'future-milestone', + message: `PR targets "dev" with future Milestone "${prMilestoneParsed.tag}", ahead of active release Milestone "${active.parsed.tag}". Wait until "${active.parsed.tag}" is cut or retarget the Milestone.`, + }) + } else if (active === null) { + const current = parseSemver(currentVersion) + if (current !== null && compareSemver(prMilestoneParsed, current) > 0) { + const matchingOpen = milestones.some(m => m?.state === 'open' && parseSemver(m.title)?.version === prMilestoneParsed.version) + if (!matchingOpen) { + reasons.push({ + code: 'future-milestone', + message: `PR targets "dev" with Milestone "${prMilestoneParsed.tag}", which is ahead of current version "${current.tag}" and not an active open Milestone.`, + }) + } + } + } + } + } + + if (reasons.length > 0) { + return { + ok: false, + blockedByProductOk: hasNeedsProductOk, + blockedByFutureMilestone: reasons.some(r => r.code === 'future-milestone'), + activeMilestone, + prMilestone: prMilestoneParsed?.tag ?? prMilestoneTitle ?? null, + reasons, + summary: reasons.map(r => r.message).join(' '), + } + } + + return { + ok: true, + blockedByProductOk: false, + blockedByFutureMilestone: false, + activeMilestone, + prMilestone: prMilestoneParsed?.tag ?? prMilestoneTitle ?? null, + reasons: [], + summary: activeMilestone + ? `PR merge guard passed (active dev milestone: ${activeMilestone}).` + : 'PR merge guard passed.', + } +} + +export class GitHubApiError extends Error { + constructor(status, url, detail) { + super(`GitHub API HTTP ${String(status)} for ${url}${detail ? `: ${detail}` : ''}`) + this.name = 'GitHubApiError' + this.status = status + this.url = url + } +} + +function assertSameOrigin(targetUrl, allowedOrigin) { + const parsed = new URL(targetUrl) + if (parsed.origin !== allowedOrigin) { + throw new Error(`Refusing cross-origin GitHub pagination redirect to ${parsed.origin} (expected ${allowedOrigin})`) + } + return parsed.href +} + +async function fetchJson(url, { token, allowedOrigin, fetchImpl = globalThis.fetch } = {}) { + if (allowedOrigin) assertSameOrigin(url, allowedOrigin) + const headers = { + Accept: 'application/vnd.github+json', + 'User-Agent': 'ds-bot-release-gate', + 'X-GitHub-Api-Version': '2022-11-28', + } + if (token) headers.Authorization = `Bearer ${token}` + const res = await fetchImpl(url, { headers }) + if (!res.ok) { + const text = await res.text().catch(() => '') + throw new GitHubApiError(res.status, url, text.slice(0, 300)) + } + return { data: await res.json(), headers: res.headers } +} + +async function paginateGitHub(initialUrl, options) { + const allowedOrigin = new URL(initialUrl).origin + const out = [] + let nextUrl = initialUrl + let pages = 0 + while (nextUrl && pages < 50) { + pages += 1 + assertSameOrigin(nextUrl, allowedOrigin) + const { data, headers } = await fetchJson(nextUrl, { ...options, allowedOrigin }) + if (!Array.isArray(data)) break + out.push(...data) + const link = headers.get('link') || '' + const nextMatch = /<([^>]+)>;\s*rel="next"/u.exec(link) + if (nextMatch) { + nextUrl = assertSameOrigin(nextMatch[1], allowedOrigin) + } else { + nextUrl = null + } + } + return out +} + +/** + * Determine whether an open issue has a merged PR (targeting `dev`, carrying a closing keyword + * for `issueNumber`, and whose merge commit is an ancestor of `headRef` when checked locally) + * so it will auto-close as soon as the release merges to `main`. + */ +async function isIssueFixedInDevViaTimeline({ + issueNumber, + repo, + apiBase, + token, + fetchImpl, + baseRef, + headRef, + cwd, + checkAncestry, +}) { + const base = apiBase.replace(/\/+$/u, '') + const allowedOrigin = new URL(base).origin + const events = await paginateGitHub( + `${base}/repos/${repo}/issues/${String(issueNumber)}/timeline?per_page=100`, + { token, fetchImpl }, + ) + const candidatePrs = new Set() + for (const ev of events) { + if (ev?.event !== 'cross-referenced') continue + const src = ev?.source?.issue + if (!src?.pull_request || src.state !== 'closed') continue + if (src.repository?.full_name && src.repository.full_name.toLowerCase() !== repo.toLowerCase()) continue + const prNum = Number(src.number) + if (Number.isSafeInteger(prNum) && prNum > 0) candidatePrs.add(prNum) + } + + for (const prNum of candidatePrs) { + const { data: pr } = await fetchJson( + `${base}/repos/${repo}/pulls/${String(prNum)}`, + { token, allowedOrigin, fetchImpl }, + ) + if (!pr?.merged || !pr.merged_at) continue + const closedByBody = extractClosingIssueNumbers(`${pr.title || ''}\n${pr.body || ''}`, repo) + if (!closedByBody.has(issueNumber)) continue + if (checkAncestry) { + // Must be merged into headRef (e.g. dev) AND NOT already present on baseRef (main), + // so an issue reopened after an earlier shipped release is never falsely exempted by its old PR. + if ( + isCommitAncestor(pr.merge_commit_sha, headRef, cwd) + && (!baseRef || !isCommitAncestor(pr.merge_commit_sha, baseRef, cwd)) + ) { + return true + } + } else if (pr.base?.ref === 'dev') { + return true + } + } + return false +} + +export async function runReleaseMilestoneCheck({ + version, + repo = DEFAULT_REPO, + token = '', + apiBase = DEFAULT_API_BASE, + ignorePrNumber = null, + baseRef = 'origin/main', + headRef = '', + cwd = process.cwd(), + resolvedIssueNumbers = null, + allowOpen = false, + hotfix = false, + allowMissingToken = false, + fetchImpl = globalThis.fetch, +}) { + const parsed = parseSemver(version) + if (parsed === null || parsed.prerelease) { + return evaluateReleaseMilestone({ + targetVersion: version, + milestones: [], + openItems: [], + ignorePrNumber, + allowOpen, + hotfix, + }) + } + + const base = apiBase.replace(/\/+$/u, '') + let milestones + let openItems = [] + const resolvedSet = new Set( + [...(resolvedIssueNumbers || [])].map(Number).filter(n => Number.isSafeInteger(n) && n > 0), + ) + + try { + milestones = await paginateGitHub( + `${base}/repos/${repo}/milestones?state=all&per_page=100`, + { token, fetchImpl }, + ) + + const milestone = findMilestoneForVersion(milestones, parsed.tag) + if (milestone !== null && Number(milestone.open_issues ?? 0) > 0 && !hotfix) { + openItems = await paginateGitHub( + `${base}/repos/${repo}/issues?milestone=${String(milestone.number)}&state=open&per_page=100`, + { token, fetchImpl }, + ) + + const openNonPrIssues = openItems.filter(item => item && item.state !== 'closed' && !item.pull_request) + if (openNonPrIssues.length > 0 && headRef) { + const fromGit = collectClosingIssuesFromGit({ baseRef, headRef, repo, cwd }) + for (const num of fromGit) resolvedSet.add(num) + + const hasLocalHead = spawnSync('git', ['rev-parse', '--verify', `${headRef}^{commit}`], { cwd, encoding: 'utf8' }).status === 0 + for (const issue of openNonPrIssues) { + const num = Number(issue.number) + if (resolvedSet.has(num)) continue + const fixedInDev = await isIssueFixedInDevViaTimeline({ + issueNumber: num, + repo, + apiBase: base, + token, + fetchImpl, + baseRef, + headRef, + cwd, + checkAncestry: hasLocalHead, + }) + if (fixedInDev) resolvedSet.add(num) + } + } + } + } catch (err) { + // On fork PRs github.token may be present but restricted (401/403); gracefully skip only when allowed. + if (allowMissingToken && err instanceof GitHubApiError && (err.status === 401 || err.status === 403)) { + return { + ok: true, + skipped: true, + reason: 'restricted-token', + message: `Skipping milestone API check due to restricted/missing token (${err.message}).`, + blockingItems: [], + resolvedPendingMain: [], + milestone: null, + } + } + throw err + } + + return evaluateReleaseMilestone({ + targetVersion: version, + milestones, + openItems, + ignorePrNumber, + resolvedIssueNumbers: [...resolvedSet], + allowOpen, + hotfix, + }) +} + +export async function runPrMergeGuard({ + prNumber, + currentVersion, + repo = DEFAULT_REPO, + token = '', + apiBase = DEFAULT_API_BASE, + allowMissingToken = false, + fetchImpl = globalThis.fetch, +}) { + const base = apiBase.replace(/\/+$/u, '') + const allowedOrigin = new URL(base).origin + try { + const [{ data: pr }, milestones] = await Promise.all([ + fetchJson(`${base}/repos/${repo}/pulls/${String(prNumber)}`, { token, allowedOrigin, fetchImpl }), + paginateGitHub(`${base}/repos/${repo}/milestones?state=open&per_page=100`, { token, fetchImpl }), + ]) + return { + ...evaluatePrMergeGuard({ + baseRef: String(pr?.base?.ref || ''), + labels: Array.isArray(pr?.labels) ? pr.labels : [], + prMilestoneTitle: pr?.milestone?.title ?? null, + currentVersion, + milestones, + }), + headSha: String(pr?.head?.sha || ''), + baseRef: String(pr?.base?.ref || ''), + state: String(pr?.state || ''), + } + } catch (err) { + if (allowMissingToken && err instanceof GitHubApiError && (err.status === 401 || err.status === 403)) { + return { + ok: true, + skipped: true, + reason: 'restricted-token', + summary: `Skipping PR merge guard API check due to restricted/missing token (${err.message}).`, + reasons: [], + } + } + throw err + } +} + +export function parseCliArgs(argv, env = process.env) { + const opts = { + mode: 'release', + version: '', + prNumber: null, + currentVersion: '', + repo: env.GITHUB_REPOSITORY || DEFAULT_REPO, + ignorePrNumber: null, + baseRef: 'origin/main', + headRef: '', + allowOpen: false, + hotfix: false, + allowMissingToken: false, + json: false, + apiBase: env.GITHUB_API_URL || DEFAULT_API_BASE, + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--mode') opts.mode = argv[++i] ?? '' + else if (arg === '--version') opts.version = argv[++i] ?? '' + else if (arg === '--pr') opts.prNumber = Number(argv[++i]) + else if (arg === '--current-version') opts.currentVersion = argv[++i] ?? '' + else if (arg === '--repo') opts.repo = argv[++i] ?? '' + else if (arg === '--ignore-pr') opts.ignorePrNumber = Number(argv[++i]) + else if (arg === '--base-ref') opts.baseRef = argv[++i] ?? 'origin/main' + else if (arg === '--head-ref') opts.headRef = argv[++i] ?? '' + else if (arg === '--api-base') opts.apiBase = argv[++i] ?? DEFAULT_API_BASE + else if (arg === '--allow-open') opts.allowOpen = true + else if (arg === '--hotfix') opts.hotfix = true + else if (arg === '--allow-missing-token') opts.allowMissingToken = true + else if (arg === '--json') opts.json = true + else throw new Error(`Unknown argument: ${arg}`) + } + return opts +} + +async function main(argv) { + let opts + try { + opts = parseCliArgs(argv) + } catch (err) { + console.error(`check-release-milestone: ${err instanceof Error ? err.message : String(err)}`) + process.exit(2) + } + + const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN || '' + try { + let result + if (opts.mode === 'pr-guard') { + if (!Number.isSafeInteger(opts.prNumber) || opts.prNumber < 1 || !opts.currentVersion) { + console.error('check-release-milestone: --mode pr-guard requires --pr and --current-version ') + process.exit(2) + } + result = await runPrMergeGuard({ + prNumber: opts.prNumber, + currentVersion: opts.currentVersion, + repo: opts.repo, + token, + apiBase: opts.apiBase, + allowMissingToken: opts.allowMissingToken, + }) + } else if (opts.mode === 'release') { + if (!opts.version) { + console.error('check-release-milestone: --version is required') + process.exit(2) + } + result = await runReleaseMilestoneCheck({ + version: opts.version, + repo: opts.repo, + token, + apiBase: opts.apiBase, + ignorePrNumber: opts.ignorePrNumber, + baseRef: opts.baseRef, + headRef: opts.headRef, + allowOpen: opts.allowOpen, + hotfix: opts.hotfix, + allowMissingToken: opts.allowMissingToken, + }) + } else { + console.error(`check-release-milestone: unsupported --mode "${opts.mode}"`) + process.exit(2) + } + + if (opts.json) { + process.stdout.write(`${JSON.stringify(result, null, 2)}\n`) + } else { + const text = result.message || result.summary || '' + if (result.ok) { + console.log(text) + } else { + console.error(text) + } + } + process.exit(result.ok ? 0 : 1) + } catch (err) { + console.error(`check-release-milestone: ${err instanceof Error ? err.message : String(err)}`) + process.exit(1) + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + await main(process.argv.slice(2)) +}