| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const assert = require("node:assert/strict"); |
| 4 | const fs = require("node:fs"); |
| 5 | const path = require("node:path"); |
| 6 | const vm = require("node:vm"); |
| 7 | const { execFileSync } = require("node:child_process"); |
| 8 | |
| 9 | const repoRoot = path.resolve(__dirname, "..", ".."); |
| 10 | const { |
| 11 | allAssetNames, |
| 12 | allReleaseAssetNames, |
| 13 | BUNDLE_ASSET_NAMES, |
| 14 | LEGACY_TUI_BRIDGE_ASSET_NAMES, |
| 15 | } = require(path.join(repoRoot, "npm", "codewhale", "scripts", "artifacts")); |
| 16 | |
| 17 | function read(relativePath) { |
| 18 | return fs.readFileSync(path.join(repoRoot, relativePath), "utf8"); |
| 19 | } |
| 20 | |
| 21 | function valuesForKey(source, key) { |
| 22 | const expression = new RegExp(`^\\s+${key}:\\s+([^#\\s]+)\\s*$`, "gm"); |
| 23 | return [...source.matchAll(expression)].map((match) => match[1]); |
| 24 | } |
| 25 | |
| 26 | function namedStep(source, name) { |
| 27 | const marker = ` - name: ${name}\n`; |
| 28 | const start = source.indexOf(marker); |
| 29 | assert.notEqual(start, -1, `missing workflow step: ${name}`); |
| 30 | const next = source.indexOf("\n - ", start + marker.length); |
| 31 | return source.slice(start, next === -1 ? source.length : next); |
| 32 | } |
| 33 | |
| 34 | const ci = read(".github/workflows/ci.yml"); |
| 35 | const ciSuite = read(".github/workflows/ci-test-suite.yml"); |
| 36 | const nightly = read(".github/workflows/nightly.yml"); |
| 37 | const candidate = read(".github/workflows/release-candidate.yml"); |
| 38 | const artifacts = read(".github/workflows/release-artifacts.yml"); |
| 39 | const release = read(".github/workflows/release.yml"); |
| 40 | const parityWorkflow = read(".github/workflows/release-parity.yml"); |
| 41 | const republish = read(".github/workflows/release-republish.yml"); |
| 42 | const releaseDockerfile = read("packaging/docker/Dockerfile.release"); |
| 43 | const cnb = read(".cnb.yml"); |
| 44 | const cnbSync = read(".github/workflows/sync-cnb.yml"); |
| 45 | const bundles = read("scripts/release/create-release-bundles.sh"); |
| 46 | const archiveInstaller = read("scripts/release/install.sh"); |
| 47 | const cliDispatcher = read("crates/cli/src/lib.rs"); |
| 48 | const runbook = read("docs/RELEASE_RUNBOOK.md"); |
| 49 | |
| 50 | function jobBlock(source, job) { |
| 51 | const match = source.match(new RegExp(`^ ${job}:\\n([\\s\\S]*?)(?=^ \\S|(?![\\s\\S]))`, "m")); |
| 52 | assert.ok(match, `missing job: ${job}`); |
| 53 | return match[1]; |
| 54 | } |
| 55 | |
| 56 | function jobIf(source, job) { |
| 57 | const lines = jobBlock(source, job).split("\n"); |
| 58 | const at = lines.findIndex((line) => /^ if:/.test(line)); |
| 59 | assert.notEqual(at, -1, `${job} must declare an if`); |
| 60 | const first = lines[at].replace(/^ if:\s*/, ""); |
| 61 | if (first !== ">-") return first.replace(/^'(.*)'$/, "$1"); |
| 62 | const folded = []; |
| 63 | for (let i = at + 1; i < lines.length && /^ \S/.test(lines[i]); i += 1) folded.push(lines[i].trim()); |
| 64 | return folded.join(" "); |
| 65 | } |
| 66 | |
| 67 | function evaluate(expression, context) { |
| 68 | return Boolean(vm.runInNewContext(expression, context)); |
| 69 | } |
| 70 | |
| 71 | const contributionForm = read(".github/ISSUE_TEMPLATE/contribution.yml"); |
| 72 | assert.match(contributionForm, /^labels: \[.*"contribution".*\]$/m); |
| 73 | assert.equal( |
| 74 | jobIf(read(".github/workflows/spam-lockdown.yml"), "lockdown"), |
| 75 | "${{ !contains(github.event.issue.labels.*.name, 'contribution') }}", |
| 76 | "the spam workflow must exempt Contribution Issues before taking any action", |
| 77 | ); |
| 78 | |
| 79 | assert.match( |
| 80 | namedStep(ciSuite, "Archive test binaries"), |
| 81 | /cargo nextest archive --workspace --all-features --locked --profile ci/, |
| 82 | "the suite must archive the same workspace, features and profile the old single run used", |
| 83 | ); |
| 84 | assert.match( |
| 85 | namedStep(ciSuite, "Build canonical executable for acceptance tests"), |
| 86 | /sh scripts\/with-hermetic-test-home.sh cargo test --workspace --all-features --locked --no-run --test help_dispatch/, |
| 87 | "Engine acceptance must build the canonical executable first, with the test build's features", |
| 88 | ); |
| 89 | assert.match( |
| 90 | namedStep(ciSuite, "Run doctests"), |
| 91 | /cargo test --workspace --all-features --locked --doc/, |
| 92 | "nextest does not run doctests; the suite must run them once per OS", |
| 93 | ); |
| 94 | const shardRun = namedStep(ciSuite, "Run tests"); |
| 95 | assert.match(shardRun, /--partition "slice:\$\{\{ matrix\.shard \}\}\/\$\{\{ inputs\.shards \}\}"/); |
| 96 | assert.match(shardRun, /-E "not \(\$NATIVE_FILTER\)"/, "every shard must exclude the native tests that shard 1 runs apart"); |
| 97 | assert.match(namedStep(ciSuite, "Run native containment tests"), /-E "\$NATIVE_FILTER"/); |
| 98 | assert.match(ciSuite, /nextest-shard-count\.py check counts/, "the suite must prove the shards add up to the archive's list"); |
| 99 | for (const name of ["Run tests", "Run native containment tests", "Run doctests"]) { |
| 100 | const step = namedStep(ciSuite, name); |
| 101 | assert.match(step, /shell: bash/, `${name} must invoke the POSIX helper on Windows too`); |
| 102 | } |
| 103 | assert.match(ciSuite, /RUST_MIN_STACK: '16777216'/); |
| 104 | |
| 105 | const receiptScript = read("scripts/ci/compiled-host-native-receipt.py"); |
| 106 | const receiptNames = [ |
| 107 | receiptScript.match(/^COMPILED = "([^"]+)"$/m)[1], |
| 108 | receiptScript.match(/^MEMORY = "([^"]+)"$/m)[1], |
| 109 | ...[...receiptScript.match(/^WINDOWS = \[([\s\S]*?)^\]/m)[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]), |
| 110 | ]; |
| 111 | const nativeFilter = ciSuite.match(/NATIVE_FILTER: >-\n([\s\S]*?)\n steps:/)[1]; |
| 112 | assert.deepEqual( |
| 113 | [...nativeFilter.matchAll(/test\(=([^)]+)\)/g)].map((m) => m[1]).sort(), |
| 114 | receiptNames.sort(), |
| 115 | "NATIVE_FILTER must list exactly the tests scripts/ci/compiled-host-native-receipt.py requires", |
| 116 | ); |
| 117 | |
| 118 | const suiteCallers = {}; |
| 119 | for (const job of ["test-ubuntu", "test-macos", "test-windows"]) { |
| 120 | const block = jobBlock(ci, job); |
| 121 | const os = block.match(/^ os: (\S+)$/m)[1]; |
| 122 | const withValue = (key, selfHosted) => { |
| 123 | const raw = block.match(new RegExp(`^ ${key}: (.+)$`, "m"))[1]; |
| 124 | const expression = raw.match(/^\$\{\{ (.+) \}\}$/)?.[1]; |
| 125 | const context = { needs: { changes: { outputs: { macos_self_hosted: String(selfHosted) } } } }; |
| 126 | return expression ? vm.runInNewContext(expression, context) : raw.replace(/^'(.*)'$/, "$1"); |
| 127 | }; |
| 128 | for (const selfHosted of [false, true]) { |
| 129 | const shards = Number(withValue("shards", selfHosted)); |
| 130 | const list = JSON.parse(withValue("shard_list", selfHosted)); |
| 131 | assert.deepEqual(list, Array.from({ length: shards }, (_, i) => i + 1), `${job} shard_list must be 1..shards`); |
| 132 | if (!selfHosted) suiteCallers[os] = shards; |
| 133 | } |
| 134 | assert.match(block, /uses: \.\/\.github\/workflows\/ci-test-suite\.yml/); |
| 135 | assert.equal(jobIf(ci, job), jobIf(ci, "test-ubuntu"), `${job} must share the suite condition`); |
| 136 | if (job !== "test-macos") assert.doesNotMatch(block, /self_hosted/, `${job} must stay on hosted runners`); |
| 137 | } |
| 138 | assert.deepEqual(Object.keys(suiteCallers).sort(), ["macos-latest", "ubuntu-latest", "windows-latest"]); |
| 139 | assert.match(jobBlock(ci, "test-macos"), /^ self_hosted: \$\{\{ needs\.changes\.outputs\.macos_self_hosted == 'true' \}\}$/m); |
| 140 | |
| 141 | const macosRunnerStep = namedStep(ci, "Choose the macOS suite runner").match(/ run: \|\n([\s\S]*)/)[1].replace(/^ {10}/gm, ""); |
| 142 | for (const [event, repo, requested, variable, expected] of [ |
| 143 | ["pull_request", "codewhale-hq/Codewhale", "", "true", "false"], |
| 144 | ["pull_request", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 145 | ["push", "codewhale-hq/Codewhale", "", "true", "false"], |
| 146 | ["schedule", "codewhale-hq/Codewhale", "", "true", "false"], |
| 147 | ["pull_request_target", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 148 | ["workflow_dispatch", "someone/Codewhale", "self-hosted", "true", "false"], |
| 149 | ["workflow_dispatch", "codewhale-hq/Codewhale", "", "", "false"], |
| 150 | ["workflow_dispatch", "codewhale-hq/Codewhale", "default", "false", "false"], |
| 151 | ["workflow_dispatch", "codewhale-hq/Codewhale", "default", "true", "true"], |
| 152 | ["workflow_dispatch", "codewhale-hq/Codewhale", "hosted", "true", "false"], |
| 153 | ["workflow_dispatch", "codewhale-hq/Codewhale", "self-hosted", "false", "true"], |
| 154 | ]) { |
| 155 | const out = path.join(fs.mkdtempSync(path.join(require("node:os").tmpdir(), "cw-macos-runner-")), "out"); |
| 156 | execFileSync("bash", ["-c", macosRunnerStep], { |
| 157 | env: { PATH: process.env.PATH, GITHUB_OUTPUT: out, EVENT_NAME: event, THIS_REPO: repo, REQUESTED: requested, SWITCH: variable }, |
| 158 | }); |
| 159 | assert.equal(fs.readFileSync(out, "utf8"), `self_hosted=${expected}\n`, `${event} ${repo} ${requested}/${variable}`); |
| 160 | } |
| 161 | for (const [file, source] of fs.readdirSync(path.join(repoRoot, ".github/workflows")).map((f) => [f, read(`.github/workflows/${f}`)])) { |
| 162 | for (const [, value] of source.matchAll(/^[ \t]*runs-on:[ \t]*(.+)$/gm)) { |
| 163 | if (!/self-hosted|codewhale-mac/.test(value)) continue; |
| 164 | assert.ok(["ci-test-suite.yml", "release-artifacts.yml"].includes(file), `${file}: only the CI suite and the release build may name the self-hosted runner`); |
| 165 | const gate = file === "ci-test-suite.yml" |
| 166 | ? /^\$\{\{ inputs\.self_hosted && fromJSON\('\["self-hosted","macOS","ARM64","codewhale-mac"\]'\) \|\| / |
| 167 | : /^\$\{\{ startsWith\(matrix\.os, 'macos-'\) && needs\.pin\.outputs\.macos_self_hosted == 'true' && fromJSON\('\["self-hosted","macOS","ARM64","codewhale-mac"\]'\) \|\| /; |
| 168 | assert.match(value, gate, `${file}: the self-hosted label must be gated by its trusted-run decision`); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | const jobNames = (source) => [...source.matchAll(/^ [A-Za-z0-9_-]+:\n name: (.+)$/gm)].map((m) => m[1]); |
| 173 | assert.deepEqual( |
| 174 | [...jobNames(ci), ...jobNames(ciSuite)].filter((name) => /^Test \(/.test(name) || name === "Lint"), |
| 175 | ["Lint"], |
| 176 | "ci.yml has one Lint job and no separate Test job", |
| 177 | ); |
| 178 | |
| 179 | const gates = ["safety-gate", "msrv", "test-ubuntu", "test-macos", "test-windows", "portable-boundaries", "npm-wrapper-smoke", "mobile-smoke"]; |
| 180 | for (const job of gates) { |
| 181 | const guard = jobIf(ci, job); |
| 182 | const run = (scoped) => |
| 183 | evaluate(guard, { |
| 184 | inputs: { workspace_test_mode: "nextest" }, |
| 185 | needs: { changes: { outputs: { scoped } } }, |
| 186 | }); |
| 187 | assert.equal(run("false"), true, `${job} must run on a full dispatch`); |
| 188 | assert.equal(run("true"), false, `${job} must skip a scoped dispatch`); |
| 189 | } |
| 190 | for (const job of ["test-ubuntu", "test-macos", "test-windows"]) { |
| 191 | assert.equal( |
| 192 | evaluate(jobIf(ci, job), { |
| 193 | inputs: { workspace_test_mode: "shared-process-twice" }, |
| 194 | needs: { changes: { outputs: { scoped: "false" } } }, |
| 195 | }), |
| 196 | false, |
| 197 | `${job} must yield to the shared-process qualification`, |
| 198 | ); |
| 199 | } |
| 200 | const sharedGuard = jobIf(ci, "test"); |
| 201 | for (const [mode, scoped, expected] of [ |
| 202 | ["shared-process-twice", "false", true], |
| 203 | ["nextest", "false", false], |
| 204 | ["shared-process-twice", "true", false], |
| 205 | ]) { |
| 206 | assert.equal( |
| 207 | evaluate(sharedGuard, { |
| 208 | inputs: { workspace_test_mode: mode }, |
| 209 | needs: { changes: { outputs: { scoped } } }, |
| 210 | }), |
| 211 | expected, |
| 212 | `shared-process job: ${mode} scoped=${scoped}`, |
| 213 | ); |
| 214 | } |
| 215 | assert.equal( |
| 216 | evaluate(jobIf(ci, "scoped-test"), { needs: { changes: { outputs: { scoped: "true" } } } }), |
| 217 | true, |
| 218 | ); |
| 219 | assert.equal( |
| 220 | evaluate(jobIf(ci, "scoped-test"), { needs: { changes: { outputs: { scoped: "false" } } } }), |
| 221 | false, |
| 222 | ); |
| 223 | assert.match(ci, /^ expected_sha:\n description: .*\n required: true\n type: string$/m, "expected_sha stays required"); |
| 224 | for (const input of ["crate", "filter", "os"]) { |
| 225 | assert.match(ci, new RegExp(`^ ${input}:\\n description: .*\\n required: false\\n`, "m"), `scoped dispatch input ${input}`); |
| 226 | } |
| 227 | |
| 228 | const concurrency = ci.match(/^concurrency:\n group: (.+)\n cancel-in-progress: (.+)$/m); |
| 229 | assert.ok(concurrency, "ci.yml must declare its concurrency"); |
| 230 | const strip = (value) => value.replace(/^\$\{\{ /, "").replace(/ \}\}$/, ""); |
| 231 | const format = (template, ...args) => template.replace(/\{(\d)\}/g, (_, i) => args[Number(i)]); |
| 232 | const groupOf = (context) => |
| 233 | vm.runInNewContext(strip(concurrency[1]), { ...context, format }); |
| 234 | const cancelOf = (context) => vm.runInNewContext(strip(concurrency[2]), context); |
| 235 | const dispatch = (ref, sha, inputs = {}) => ({ |
| 236 | github: { ref, sha, workflow: "CI", run_id: `run-${sha}` }, |
| 237 | inputs: { crate: "", filter: "", ...inputs }, |
| 238 | }); |
| 239 | assert.equal(groupOf(dispatch("refs/heads/ci/x", "a")), groupOf(dispatch("refs/heads/ci/x", "b")), "a new dispatch on the same ci branch shares its group"); |
| 240 | assert.notEqual(groupOf(dispatch("refs/heads/ci/x", "a")), groupOf(dispatch("refs/heads/ci/y", "a"))); |
| 241 | assert.equal(cancelOf(dispatch("refs/heads/ci/x", "a")), true); |
| 242 | assert.notEqual(groupOf(dispatch("refs/heads/main", "a")), groupOf(dispatch("refs/heads/main", "b")), "runs on main never share a group"); |
| 243 | assert.equal(cancelOf(dispatch("refs/heads/main", "a")), false, "runs on main never cancel"); |
| 244 | assert.notEqual( |
| 245 | groupOf(dispatch("refs/heads/ci/x", "a", { crate: "codewhale-tui" })), |
| 246 | groupOf(dispatch("refs/heads/ci/x", "a")), |
| 247 | "a scoped dispatch never shares the full run's group", |
| 248 | ); |
| 249 | assert.equal(cancelOf(dispatch("refs/heads/ci/x", "a", { filter: "test(x)" })), false, "a scoped dispatch cancels nothing"); |
| 250 | |
| 251 | for (const [name, source] of [["ci.yml", ci], ["ci-test-suite.yml", ciSuite]]) { |
| 252 | assert.doesNotMatch(source, /pull_request_target/, `${name} must not use pull_request_target`); |
| 253 | assert.doesNotMatch(source, /\$\{\{\s*secrets\./, `${name} must not read secrets`); |
| 254 | assert.match(source, /^permissions:\n contents: read\n/m, `${name} must keep read-only default permissions`); |
| 255 | assert.doesNotMatch(source.replace(/^permissions:\n contents: read\n/m, ""), /^\s+(?:contents|actions|id-token|pull-requests|packages):\s*write/m, `${name} must not grant write permissions`); |
| 256 | for (const match of source.matchAll(/Swatinem\/rust-cache@[^\n]*\n(?:\s+(?:with|cache-bin):[^\n]*\n)*\s+save-if: ([^\n]+)/g)) { |
| 257 | assert.match(match[1], /refs\/heads\/main|false/, `${name}: rust-cache must save only on main`); |
| 258 | } |
| 259 | assert.doesNotMatch(source, /actions\/cache(?:\/save)?@/, `${name} must not write caches outside rust-cache and sccache`); |
| 260 | } |
| 261 | const npmSmokeJob = ci.match(/^ npm-wrapper-smoke:\n([\s\S]*?)(?=^ \S)/m)?.[1]; |
| 262 | assert.ok(npmSmokeJob, "CI must retain the npm-wrapper job"); |
| 263 | assert.match( |
| 264 | namedStep(npmSmokeJob, "Build wrapper binaries"), |
| 265 | /run: cargo build --release --locked -p codewhale-cli --bin codewhale/, |
| 266 | ); |
| 267 | assert.match( |
| 268 | namedStep(npmSmokeJob, "Smoke wrapper install and delegated entrypoints"), |
| 269 | /run: node scripts\/release\/npm-wrapper-smoke\.js/, |
| 270 | ); |
| 271 | const npmSmokeSteps = npmSmokeJob.split(/(?=^ - )/m).slice(1); |
| 272 | const npmSmokeCases = [ |
| 273 | ["Ubuntu", "ubuntu-latest", true], |
| 274 | ["Ubuntu cache failure", "ubuntu-latest", false], |
| 275 | ["Windows", "windows-latest", true], |
| 276 | ["Windows cache failure", "windows-latest", false], |
| 277 | ]; |
| 278 | for (const [name, source] of [["ci.yml", ci], ["ci-test-suite.yml", ciSuite]]) { |
| 279 | const enabled = source.match(/SCCACHE_GHA_ENABLED=true/g) ?? []; |
| 280 | const modes = source.match(/if \[ "\$\{GITHUB_REF\}" = refs\/heads\/main \]; then rw=READ_WRITE; else rw=READ_ONLY; fi\n(?:\s+\{\n\s+echo "SCCACHE_GHA_ENABLED=true"\n)?\s+echo "SCCACHE_GHA_RW_MODE=\$\{rw\}"/g) ?? []; |
| 281 | assert.ok(enabled.length > 0, `${name} must enable sccache`); |
| 282 | assert.equal(modes.length, enabled.length, `${name}: every sccache enable must be read-only off main`); |
| 283 | assert.doesNotMatch(source, /sccache-action[^\n]*\n(?:[^\n]*\n){0,4}\s+if: [^\n]*github\.ref == 'refs\/heads\/main'/, `${name}: sccache must install on every run`); |
| 284 | } |
| 285 | for (const [label, os, cache] of npmSmokeCases) { |
| 286 | const context = { |
| 287 | needs: { changes: { outputs: { scoped: "false" } } }, |
| 288 | github: { ref: "refs/heads/main" }, |
| 289 | matrix: { os }, |
| 290 | steps: { sccache: { outcome: cache ? "success" : "failure" } }, |
| 291 | }; |
| 292 | for (const step of npmSmokeSteps) { |
| 293 | const name = step.match(/^ - (?:name|uses): (.+)$/m)?.[1]; |
| 294 | const guard = step.match(/^ if: (.+)$/m)?.[1]; |
| 295 | assert.ok(name, "every wrapper step must have a name or uses"); |
| 296 | let expected = true; |
| 297 | if (name === "Install Linux system dependencies") expected = os === "ubuntu-latest"; |
| 298 | else if (name === "Enable sccache") expected = cache && os !== "windows-latest"; |
| 299 | else if (name === "sccache stats") expected = cache; |
| 300 | assert.equal( |
| 301 | guard ? Boolean(vm.runInNewContext(guard, context)) : true, |
| 302 | expected, |
| 303 | `${label}: ${name} must ${expected ? "execute" : "stay skipped"}`, |
| 304 | ); |
| 305 | } |
| 306 | } |
| 307 | assert.match( |
| 308 | npmSmokeJob, |
| 309 | /^ os: \[ubuntu-latest, windows-latest\]$/m, |
| 310 | "a full dispatch runs the npm wrapper smoke on Ubuntu and Windows; the release artifacts cover macOS", |
| 311 | ); |
| 312 | |
| 313 | console.log(`Wrapper CI guards OK: ${npmSmokeCases.length} cases, ${npmSmokeSteps.length} steps each.`); |
| 314 | |
| 315 | assert.match(ci, /^ workflow_dispatch:\n inputs:\n expected_sha:/m); |
| 316 | const dispatchCheck = namedStep(ci, "Check the dispatched commit"); |
| 317 | assert.match(dispatchCheck, /#EXPECTED_SHA.*-ne 40/s); |
| 318 | assert.match(dispatchCheck, /actual.*EXPECTED_SHA/s); |
| 319 | assert.doesNotMatch(ci, /github\.event_name ==|outputs\.heavy|outputs\.trusted/, "ci.yml runs only on dispatch and keeps no event or change-classification branches"); |
| 320 | const expectedNightlyTargets = [ |
| 321 | "x86_64-unknown-linux-gnu", |
| 322 | "aarch64-unknown-linux-musl", |
| 323 | "x86_64-apple-darwin", |
| 324 | "aarch64-apple-darwin", |
| 325 | "x86_64-pc-windows-msvc", |
| 326 | "aarch64-pc-windows-msvc", |
| 327 | ].sort(); |
| 328 | assert.deepEqual([...new Set(valuesForKey(nightly, "target"))].sort(), expectedNightlyTargets); |
| 329 | assert.deepEqual( |
| 330 | [ |
| 331 | ...valuesForKey(nightly, "primary_artifact"), |
| 332 | ...valuesForKey(nightly, "alias_artifact"), |
| 333 | ].sort(), |
| 334 | [ |
| 335 | "codewhale-linux-x64", |
| 336 | "codew-linux-x64", |
| 337 | "codewhale-linux-arm64", |
| 338 | "codew-linux-arm64", |
| 339 | "codewhale-macos-x64", |
| 340 | "codew-macos-x64", |
| 341 | "codewhale-macos-arm64", |
| 342 | "codew-macos-arm64", |
| 343 | "codewhale-windows-x64.exe", |
| 344 | "codew-windows-x64.exe", |
| 345 | "codewhale-windows-arm64.exe", |
| 346 | "codew-windows-arm64.exe", |
| 347 | ].sort(), |
| 348 | ); |
| 349 | assert.match( |
| 350 | nightly, |
| 351 | /cargo build --release --locked --target \$\{\{ matrix\.target \}\} -p codewhale-cli/, |
| 352 | ); |
| 353 | assert.match(nightly, /startsWith\(matrix\.target, 'x86_64-'\).*runner\.arch == 'X64'/s); |
| 354 | assert.match(nightly, /startsWith\(matrix\.target, 'aarch64-'\).*runner\.arch == 'ARM64'/s); |
| 355 | const nightlyArmMuslSetup = namedStep(nightly, "Install Linux ARM64 musl toolchain"); |
| 356 | assert.match(nightlyArmMuslSetup, /matrix\.target == 'aarch64-unknown-linux-musl'/); |
| 357 | assert.match(nightlyArmMuslSetup, /apt-get install -y binutils musl-tools/); |
| 358 | assert.match(nightlyArmMuslSetup, /rustup target add aarch64-unknown-linux-musl/); |
| 359 | const nightlyArmStaticSmoke = namedStep( |
| 360 | nightly, |
| 361 | "Verify static Linux ARM64 binary and launch", |
| 362 | ); |
| 363 | assert.match( |
| 364 | nightlyArmStaticSmoke, |
| 365 | /matrix\.target == 'aarch64-unknown-linux-musl' && runner\.arch == 'ARM64'/, |
| 366 | ); |
| 367 | assert.match(nightlyArmStaticSmoke, /readelf -l "\$\{bin_path\}"/); |
| 368 | assert.match(nightlyArmStaticSmoke, /grep -Fq 'INTERP'/); |
| 369 | assert.match(nightlyArmStaticSmoke, /"\$\{bin_path\}" --version/); |
| 370 | assert.doesNotMatch(nightly, /codewhale-tui/); |
| 371 | assert.doesNotMatch(nightly, /target\/[^\n]*\/codew(?:\.exe)?/); |
| 372 | assert.match(nightly, /cp "\$\{bin_path\}" "\$\{dir\}\/\$\{artifact\}"/); |
| 373 | assert.match(nightly, /cmp -s[\s\S]*nightly-primary[\s\S]*nightly-alias/); |
| 374 | assert.equal((nightly.match(/retention-days: 14/g) || []).length, 2); |
| 375 | |
| 376 | assert.match(candidate, /^ workflow_dispatch:\n inputs:\n expected_sha:/m); |
| 377 | assert.doesNotMatch(candidate, /^ (push|pull_request|schedule):/m); |
| 378 | assert.match(candidate, /uses: \.\/\.github\/workflows\/release-artifacts\.yml/); |
| 379 | assert.match(candidate, /source_sha: \$\{\{ needs\.resolve\.outputs\.sha \}\}/); |
| 380 | assert.match(candidate, /^ web:\n/m); |
| 381 | assert.doesNotMatch( |
| 382 | candidate, |
| 383 | /ref: \$\{\{ needs\.resolve\.outputs\.sha \}\}/, |
| 384 | "candidate jobs must checkout GITHUB_SHA, not interpolate the dispatch SHA into ref", |
| 385 | ); |
| 386 | assert.match(candidate, /cache-dependency-path: web\/package-lock\.json/); |
| 387 | assert.match(candidate, /package-manager-cache: false/); |
| 388 | assert.match(candidate, /working-directory: web/); |
| 389 | for (const workflow of [candidate, read(".github/workflows/web.yml")]) { |
| 390 | for (const command of ["npm ci", "npm test", "npm run check"]) { |
| 391 | assert.ok(workflow.includes(`run: ${command}\n`), `missing web gate: ${command}`); |
| 392 | } |
| 393 | } |
| 394 | // Both workflows use this gate. Preserve every check and its order: checking |
| 395 | // committed facts after prebuild could silently repair drift before testing it. |
| 396 | assert.deepEqual(JSON.parse(read("web/package.json")).scripts.check.split(" && "), [ |
| 397 | "npm run check:facts", |
| 398 | "npm run check:latest-release", |
| 399 | "npm run prebuild", |
| 400 | "npm run check:docs", |
| 401 | "npm run check:tokens", |
| 402 | "npm run lint", |
| 403 | "tsc --noEmit", |
| 404 | "npm run build", |
| 405 | ]); |
| 406 | assert.match(candidate, /^ needs: \[resolve, web\]$/m); |
| 407 | assert.match(candidate, /needs\.web\.result == 'success'/); |
| 408 | |
| 409 | for (const [label, workflow] of [ |
| 410 | ["release candidate", candidate], |
| 411 | ["shared artifact", artifacts], |
| 412 | ]) { |
| 413 | for (const forbidden of [ |
| 414 | /contents:\s*write/, |
| 415 | /packages:\s*write/, |
| 416 | /softprops\/action-gh-release/, |
| 417 | /docker\/login-action/, |
| 418 | /docker\/build-push-action/, |
| 419 | /\bgh release\b/, |
| 420 | /\bnpm publish\b/, |
| 421 | /\bcargo publish\b/, |
| 422 | /\bgit push\b/, |
| 423 | ]) { |
| 424 | assert.doesNotMatch(workflow, forbidden, `${label} workflow contains publication capability`); |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | for (const [label, workflow] of [ |
| 429 | ["release candidate", candidate], |
| 430 | ["shared artifact", artifacts], |
| 431 | ["public release", release], |
| 432 | ["release republish", republish], |
| 433 | ]) { |
| 434 | const remoteActions = [...workflow.matchAll(/^\s+(?:-\s+)?uses:\s+([^@\s]+)@([^#\s]+)/gm)] |
| 435 | .map((match) => ({ action: match[1], ref: match[2] })) |
| 436 | .filter(({ action }) => !action.startsWith("./")); |
| 437 | assert.ok(remoteActions.length > 0, `${label} workflow must exercise pinned actions`); |
| 438 | for (const { action, ref } of remoteActions) { |
| 439 | assert.match( |
| 440 | ref, |
| 441 | /^[0-9a-f]{40}$/, |
| 442 | `${label} action ${action} must use an audited full commit SHA`, |
| 443 | ); |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | const republishHomebrewJob = republish.match(/\n homebrew:\n([\s\S]*)$/); |
| 448 | assert.ok(republishHomebrewJob, "republish must retain a Homebrew recovery job"); |
| 449 | const republishHomebrewCheckout = namedStep( |
| 450 | republishHomebrewJob[0], |
| 451 | "Checkout release infrastructure", |
| 452 | ); |
| 453 | assert.match( |
| 454 | republishHomebrewCheckout, |
| 455 | /ref: \$\{\{ github\.event\.repository\.default_branch \}\}/, |
| 456 | "Homebrew recovery must use the repaired default-branch infrastructure", |
| 457 | ); |
| 458 | assert.doesNotMatch( |
| 459 | republishHomebrewCheckout, |
| 460 | /needs\.resolve\.outputs\.sha/, |
| 461 | "Homebrew recovery must not resurrect release-tag infrastructure", |
| 462 | ); |
| 463 | assert.match(republishHomebrewJob[0], /gh release download "\$\{\{ needs\.resolve\.outputs\.tag \}\}"/); |
| 464 | assert.match(republishHomebrewJob[0], /MANIFEST: \/tmp\/codewhale-artifacts-sha256\.txt/); |
| 465 | |
| 466 | assert.match(artifacts, /^ workflow_call:/m); |
| 467 | assert.match(artifacts, /^permissions:\n contents: read$/m); |
| 468 | const expectedTargets = [ |
| 469 | "x86_64-unknown-linux-musl", |
| 470 | "aarch64-unknown-linux-musl", |
| 471 | "aarch64-linux-android", |
| 472 | "aarch64-unknown-linux-ohos", |
| 473 | "x86_64-apple-darwin", |
| 474 | "aarch64-apple-darwin", |
| 475 | "x86_64-pc-windows-msvc", |
| 476 | "aarch64-pc-windows-msvc", |
| 477 | ].sort(); |
| 478 | assert.deepEqual([...new Set(valuesForKey(artifacts, "target"))].sort(), expectedTargets); |
| 479 | |
| 480 | const releaseMuslBuild = namedStep(artifacts, "Build static Linux binaries (musl)"); |
| 481 | assert.match(releaseMuslBuild, /endsWith\(matrix\.target, '-unknown-linux-musl'\)/); |
| 482 | assert.match(releaseMuslBuild, /apt-get install -y binutils musl-tools/); |
| 483 | assert.match(releaseMuslBuild, /rustup target add \$\{\{ matrix\.target \}\}/); |
| 484 | assert.match( |
| 485 | releaseMuslBuild, |
| 486 | /cargo build --profile dist --locked --target \$\{\{ matrix\.target \}\} -p codewhale-cli/, |
| 487 | ); |
| 488 | const releaseStaticSmoke = namedStep( |
| 489 | artifacts, |
| 490 | "Verify static Linux binaries and launch on matching native runners", |
| 491 | ); |
| 492 | assert.match(releaseStaticSmoke, /endsWith\(matrix\.target, '-unknown-linux-musl'\)/); |
| 493 | assert.match( |
| 494 | releaseStaticSmoke, |
| 495 | /startsWith\(matrix\.target, 'aarch64-'\) && runner\.arch == 'ARM64'/, |
| 496 | ); |
| 497 | assert.match(releaseStaticSmoke, /readelf -l "\$\{bin_path\}"/); |
| 498 | assert.match(releaseStaticSmoke, /grep -Fq 'INTERP'/); |
| 499 | assert.match(releaseStaticSmoke, /"\$\{bin_path\}" --version/); |
| 500 | |
| 501 | const builtAssetNames = [ |
| 502 | ...valuesForKey(artifacts, "cli_artifact"), |
| 503 | ...valuesForKey(artifacts, "shim_artifact"), |
| 504 | ...valuesForKey(artifacts, "compat_tui_artifact"), |
| 505 | ]; |
| 506 | assert.equal(builtAssetNames.length, 24); |
| 507 | assert.deepEqual( |
| 508 | [...new Set(builtAssetNames)].sort(), |
| 509 | [ |
| 510 | ...allAssetNames().filter((name) => name !== "codewhale.bat"), |
| 511 | ...LEGACY_TUI_BRIDGE_ASSET_NAMES, |
| 512 | ].sort(), |
| 513 | ); |
| 514 | assert.match( |
| 515 | artifacts, |
| 516 | /stage_binary "\$\{\{ matrix\.cli_binary \}\}" "\$\{\{ matrix\.compat_tui_artifact \}\}"/, |
| 517 | "legacy TUI bridge assets must be staged from the one compiled codewhale binary", |
| 518 | ); |
| 519 | const bundleInvocations = [...bundles.matchAll( |
| 520 | /^bundle (\S+) \\\n\s+\S+ \S+ (tar\.gz|zip) (""|portable)$/gm, |
| 521 | )].map((match) => { |
| 522 | const variant = match[3] === "portable" ? "-portable" : ""; |
| 523 | return `codewhale-${match[1]}${variant}.${match[2]}`; |
| 524 | }); |
| 525 | assert.deepEqual(bundleInvocations.sort(), [...BUNDLE_ASSET_NAMES].sort()); |
| 526 | assert.match(artifacts, /aarch64-pc-windows-msvc/); |
| 527 | assert.match(artifacts, /aarch64-linux-android/); |
| 528 | // HarmonyOS bytes cannot be shipped unsigned: the device refuses to execute an |
| 529 | // unsigned ELF, so the leg must self-sign and prove the signature before |
| 530 | // staging. Assert the order too — signing after staging would publish the |
| 531 | // unsigned copy. |
| 532 | assert.match(artifacts, /aarch64-unknown-linux-ohos/); |
| 533 | const ohosSdk = namedStep(artifacts, "Install OpenHarmony native SDK"); |
| 534 | assert.match(ohosSdk, /components: 'native;toolchains'/, "the SDK must include the binary signer"); |
| 535 | assert.match(ohosSdk, /cache: false/, "a release must download the SDK, not publish a new cache entry"); |
| 536 | // A step header glued onto the previous line because a `run:` block lost its |
| 537 | // trailing newline parses as valid YAML (the header becomes script text) and |
| 538 | // silently drops the step. Every `- name:` in these workflows must start its |
| 539 | // own line. |
| 540 | for (const [file, source] of [ |
| 541 | ["release-artifacts.yml", artifacts], |
| 542 | ["release.yml", release], |
| 543 | ["nightly.yml", nightly], |
| 544 | ]) { |
| 545 | for (const match of source.matchAll(/- name:/g)) { |
| 546 | const lineStart = source.lastIndexOf("\n", match.index) + 1; |
| 547 | assert.match( |
| 548 | source.slice(lineStart, match.index), |
| 549 | /^\s*$/, |
| 550 | `${file}: a step header must start its own line, not follow other content`, |
| 551 | ); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | const ohosBuild = namedStep(artifacts, "Cross-compile and code-sign the OpenHarmony binary"); |
| 556 | assert.match(ohosBuild, /matrix\.platform == 'ohos-arm64'/); |
| 557 | assert.match(ohosBuild, /binary-sign-tool\.jar/); |
| 558 | assert.match(ohosBuild, /-selfSign 1/); |
| 559 | assert.match(ohosBuild, /code signature is self-sign/); |
| 560 | assert.match(ohosBuild, /scripts\/ohos\/ohos-env\.sh/); |
| 561 | assert.ok( |
| 562 | ohosBuild.indexOf("codesign") === -1 || |
| 563 | ohosBuild.indexOf("binary-sign-tool.jar") < ohosBuild.indexOf("display-sign"), |
| 564 | "the signature must be applied before it is verified", |
| 565 | ); |
| 566 | assert.match(artifacts, /codew-windows-arm64\.exe/); |
| 567 | assert.match(artifacts, /CodeWhaleSetup\.exe/); |
| 568 | assert.match(artifacts, /assemble-release-assets\.js --verify release-assets/); |
| 569 | assert.match(artifacts, /CODEWHALE_SMOKE_ASSETS_DIR/); |
| 570 | assert.match(artifacts, /^ pin:\n/m); |
| 571 | assert.match(artifacts, /Require source_sha equals github\.sha/); |
| 572 | assert.doesNotMatch( |
| 573 | artifacts, |
| 574 | /ref: \$\{\{ inputs\.source_sha \}\}/, |
| 575 | "artifact jobs must checkout GITHUB_SHA, not interpolate the caller SHA into ref", |
| 576 | ); |
| 577 | assert.match(artifacts, /prefix-key: v1-\$\{\{ runner\.os \}\}-\$\{\{ runner\.arch \}\}-stable/); |
| 578 | assert.equal( |
| 579 | (artifacts.match(/package-manager-cache: false/g) || []).length, |
| 580 | 2, |
| 581 | "assemble and smoke must disable setup-node's implicit npm cache", |
| 582 | ); |
| 583 | const bundleStep = namedStep(artifacts, "Create and checksum platform archives"); |
| 584 | assert.match(bundleStep, /SOURCE_SHA: \$\{\{ github\.sha \}\}/); |
| 585 | assert.match(bundleStep, /git show -s --format=%ct "\$\{SOURCE_SHA\}"/); |
| 586 | assert.match( |
| 587 | bundleStep, |
| 588 | /SOURCE_DATE_EPOCH="\$\{source_date_epoch\}"[\s\\]+bash scripts\/release\/create-release-bundles\.sh artifacts bundles/, |
| 589 | ); |
| 590 | assert.doesNotMatch(bundleStep, /inputs\.source_sha/); |
| 591 | assert.doesNotMatch(bundleStep, /\bdate\b/, "bundle timestamps must come from the pinned source commit, not wall-clock time"); |
| 592 | |
| 593 | const rustCacheBlocks = [...artifacts.matchAll(/uses: Swatinem\/rust-cache@[\s\S]*?(?=\n - )/g)].map( |
| 594 | (match) => match[0], |
| 595 | ); |
| 596 | assert.ok(rustCacheBlocks.length >= 1, "shared artifact workflow must pin rust-cache"); |
| 597 | for (const block of rustCacheBlocks) { |
| 598 | assert.doesNotMatch(block, /github\.(event|ref|sha)|inputs\./); |
| 599 | } |
| 600 | |
| 601 | // One parity gate, called by the release candidate and the public release, |
| 602 | // and the release refuses a tag without a green RC receipt for its exact SHA. |
| 603 | // The release gate must lint at least as strictly as the merge gate. |
| 604 | function clippyAllows(source, label) { |
| 605 | const command = source.match(/cargo clippy --workspace --all-targets --all-features --locked -- \\\n([\s\S]*?)\n(?! +-)/)?.[1]; |
| 606 | assert.ok(command, `${label} must run workspace all-targets clippy`); |
| 607 | return [...command.matchAll(/-A (clippy::\w+)/g)].map((match) => match[1]).sort(); |
| 608 | } |
| 609 | assert.deepEqual( |
| 610 | clippyAllows(parityWorkflow, "release-parity.yml"), |
| 611 | clippyAllows(ci, "ci.yml"), |
| 612 | "release-parity.yml clippy allowances must match ci.yml", |
| 613 | ); |
| 614 | const parity = parityWorkflow.match(/\n parity:\n([\s\S]*)$/); |
| 615 | assert.ok(parity, "release-parity.yml must define the parity job"); |
| 616 | assert.match(parityWorkflow, /^on:\n workflow_call:\n/m, "parity must be a reusable workflow"); |
| 617 | for (const [name, source] of [["release.yml", release], ["release-candidate.yml", candidate]]) { |
| 618 | const caller = source.match(/\n parity:\n([\s\S]*?)\n\n/); |
| 619 | assert.ok(caller, `${name} must run the parity job`); |
| 620 | assert.match(caller[1], /name: Parity\n/, `${name}: the RC receipt check matches the "Parity" job name`); |
| 621 | assert.match(caller[1], /uses: \.\/\.github\/workflows\/release-parity\.yml/, `${name} must call the shared parity gate`); |
| 622 | } |
| 623 | assert.match( |
| 624 | namedStep(release, "Require a green release-candidate receipt for this exact SHA"), |
| 625 | /require-rc-receipt\.sh "\$\{GITHUB_REPOSITORY\}" "\$\{SHA\}"/, |
| 626 | ); |
| 627 | assert.match(release, /^ resolve:\n(?:.*\n)*? actions: read\n/m, "resolve needs actions: read for the RC receipt"); |
| 628 | assert.doesNotMatch( |
| 629 | parity[1], |
| 630 | /ref: \$\{\{ needs\.resolve\.outputs\.sha \}\}/, |
| 631 | "parity must checkout GITHUB_SHA after resolve, not interpolate the tag SHA into ref", |
| 632 | ); |
| 633 | assert.match(parity[1], /prefix-key: v1-\$\{\{ runner\.os \}\}-\$\{\{ runner\.arch \}\}-stable/); |
| 634 | const parityRustCache = [...parity[1].matchAll(/uses: Swatinem\/rust-cache@[\s\S]*?(?=\n - )/g)].map( |
| 635 | (match) => match[0], |
| 636 | ); |
| 637 | assert.equal(parityRustCache.length, 1, "parity must pin exactly one rust-cache"); |
| 638 | assert.doesNotMatch(parityRustCache[0], /github\.(event|ref|sha)|inputs\./); |
| 639 | |
| 640 | assert.equal(allReleaseAssetNames().length, 38); |
| 641 | assert.match(release, /^ artifacts:\n/m); |
| 642 | assert.match(release, /uses: \.\/\.github\/workflows\/release-artifacts\.yml/); |
| 643 | assert.doesNotMatch(release, /^ (build|bundle|windows-installer):/m); |
| 644 | assert.match(release, /name: codewhale-release-assets\n\s+path: artifacts/); |
| 645 | assert.match(release, /files: artifacts\/\*/); |
| 646 | assert.equal( |
| 647 | (release.match(/ensure-release-assets-absent\.js/g) || []).length, |
| 648 | 2, |
| 649 | "public release must refuse existing assets before work and immediately before upload", |
| 650 | ); |
| 651 | assert.match(release, /overwrite_files:\s*false/); |
| 652 | assert.match(release, /fail_on_unmatched_files:\s*true/); |
| 653 | // Assets land in a draft; the whole verified set becomes public at once, and |
| 654 | // derived channels (the tagged container manifest) follow the canonical release. |
| 655 | assert.match(release, /files: artifacts\/\*\n\s+draft: true\n/); |
| 656 | assert.match( |
| 657 | namedStep(release, "Verify the draft's exact asset set, then publish it at once"), |
| 658 | /verify-release-inventory\.js \\\n\s+--draft --asset-dir artifacts --publish/, |
| 659 | ); |
| 660 | const releaseJob = release.match(/\n release:\n([\s\S]*?)\n npm:\n/); |
| 661 | assert.ok(releaseJob, "public release must retain its release job"); |
| 662 | assert.match(releaseJob[1], /^ needs: \[artifacts, docker-build, resolve\]$/m); |
| 663 | const dockerJob = release.match(/\n docker:\n([\s\S]*?)\n release:\n/); |
| 664 | assert.ok(dockerJob, "public release must retain its container manifest job"); |
| 665 | assert.match(dockerJob[1], /^ needs: \[docker-build, release, resolve\]$/m); |
| 666 | assert.match(dockerJob[1], /needs\.release\.result == 'success'/); |
| 667 | const cnbJob = release.match(/\n cnb:\n([\s\S]*?)\n npm:\n/); |
| 668 | assert.ok(cnbJob, "CNB tag publication must follow the canonical release"); |
| 669 | assert.match(cnbJob[1], /^ needs: \[release, resolve\]$/m); |
| 670 | assert.match(cnbJob[1], /needs\.release\.result == 'success'/); |
| 671 | assert.match(cnbJob[1], /uses: \.\/\.github\/workflows\/sync-cnb\.yml/); |
| 672 | assert.doesNotMatch(cnbSync, /^\s+tags:/m, "a tag push alone must not start CNB publication"); |
| 673 | assert.match(cnbSync, /^ workflow_call:/m); |
| 674 | const cnbPush = namedStep(cnbSync, "Push triggering ref to CNB"); |
| 675 | const cnbPublicGate = cnbPush.indexOf("node scripts/release/verify-release-inventory.js --manifest"); |
| 676 | const cnbTagPush = cnbPush.indexOf('scripts/release/mirror-push.sh cnb "tag ${TAG}"'); |
| 677 | assert.ok(cnbPublicGate >= 0 && cnbTagPush > cnbPublicGate, |
| 678 | "manual and called tag mirrors must verify the published inventory before pushing"); |
| 679 | assert.match(cnbPush, /verify-remote-tag\.sh/); |
| 680 | assert.doesNotMatch(cnbPush, /\+refs\/tags\//, "published mirror tags must not be rewritten"); |
| 681 | assert.match( |
| 682 | namedStep(republish, "Require a complete published release"), |
| 683 | /verify-release-inventory\.js --manifest/, |
| 684 | ); |
| 685 | |
| 686 | assert.match(release, /^ docker-build:\n/m); |
| 687 | assert.match(release, /^ docker:\n/m); |
| 688 | assert.match(release, /runner: ubuntu-latest\n\s+platform: linux\/amd64/); |
| 689 | assert.match(release, /runner: ubuntu-24\.04-arm\n\s+platform: linux\/arm64/); |
| 690 | assert.match(release, /cli_artifact: codewhale-linux-x64/); |
| 691 | assert.match(release, /cli_artifact: codewhale-linux-arm64/); |
| 692 | assert.match(release, /shim_artifact: codew-linux-x64/); |
| 693 | assert.match(release, /shim_artifact: codew-linux-arm64/); |
| 694 | assert.doesNotMatch( |
| 695 | release, |
| 696 | /docker\/setup-qemu-action/, |
| 697 | "public container publication must not funnel both architectures through QEMU", |
| 698 | ); |
| 699 | const releaseDockerBytes = namedStep(release, "Verify native release bytes"); |
| 700 | assert.match(releaseDockerBytes, /CLI_ARTIFACT: \$\{\{ matrix\.cli_artifact \}\}/); |
| 701 | assert.match(releaseDockerBytes, /SHIM_ARTIFACT: \$\{\{ matrix\.shim_artifact \}\}/); |
| 702 | assert.match( |
| 703 | releaseDockerBytes, |
| 704 | /mv -- "docker-context\/bin\/\$\{CLI_ARTIFACT\}" docker-context\/bin\/codewhale/, |
| 705 | ); |
| 706 | assert.match( |
| 707 | releaseDockerBytes, |
| 708 | /mv -- "docker-context\/bin\/\$\{SHIM_ARTIFACT\}" docker-context\/bin\/codew/, |
| 709 | ); |
| 710 | assert.match(releaseDockerBytes, /cmp docker-context\/bin\/codewhale docker-context\/bin\/codew/); |
| 711 | const releaseDockerBuild = namedStep(release, "Assemble and push native image by digest"); |
| 712 | assert.match(releaseDockerBuild, /context: docker-context/); |
| 713 | assert.match(releaseDockerBuild, /file: infra\/packaging\/docker\/Dockerfile\.release/); |
| 714 | assert.match(releaseDockerBuild, /platforms: \$\{\{ matrix\.platform \}\}/); |
| 715 | assert.match(releaseDockerBuild, /provenance: mode=max/); |
| 716 | assert.match(releaseDockerBuild, /sbom: true/); |
| 717 | assert.match(releaseDockerBuild, /push-by-digest=true/); |
| 718 | const releaseDockerManifest = namedStep(release, "Publish multi-architecture manifest"); |
| 719 | assert.match(releaseDockerManifest, /Expected exactly two native image digests/); |
| 720 | assert.match(releaseDockerManifest, /docker buildx imagetools create/); |
| 721 | const releaseDockerSmoke = namedStep(release, "Verify and smoke published container"); |
| 722 | assert.match(releaseDockerSmoke, /linux\/amd64/); |
| 723 | assert.match(releaseDockerSmoke, /linux\/arm64/); |
| 724 | assert.match(releaseDockerSmoke, /--entrypoint codewhale/); |
| 725 | assert.match(releaseDockerSmoke, /--entrypoint codew/); |
| 726 | |
| 727 | const npmJob = release.match(/\n npm:\n([\s\S]*?)\n crates:\n/); |
| 728 | assert.ok(npmJob, "public release must retain a dedicated npm publication job"); |
| 729 | assert.match(npmJob[1], /^ needs: \[release, resolve\]$/m); |
| 730 | assert.match(npmJob[1], /needs\.release\.result == 'success'/); |
| 731 | assert.match(npmJob[1], /^ contents: read$/m); |
| 732 | assert.match(npmJob[1], /^ id-token: write$/m); |
| 733 | assert.match(npmJob[1], /ref: \$\{\{ needs\.resolve\.outputs\.sha \}\}/); |
| 734 | assert.match(npmJob[1], /fetch-depth: 0/); |
| 735 | assert.match(npmJob[1], /node-version: 24/); |
| 736 | assert.match(npmJob[1], /registry-url: https:\/\/registry\.npmjs\.org/); |
| 737 | assert.match(npmJob[1], /package-manager-cache: false/); |
| 738 | assert.match(npmJob[1], /npm install --global npm@12\.0\.2/); |
| 739 | const npmTagGate = namedStep(release, "Revalidate release tag before npm publish"); |
| 740 | const npmAssetGate = namedStep(release, "Revalidate public release assets"); |
| 741 | const npmPublish = namedStep(release, "Publish npm wrapper with trusted publishing"); |
| 742 | assert.match(npmTagGate, /verify-remote-tag\.sh/); |
| 743 | assert.match(npmAssetGate, /verify-release-assets\.sh/); |
| 744 | assert.match(npmAssetGate, /GH_TOKEN: \$\{\{ github\.token \}\}/); |
| 745 | assert.match(npmPublish, /working-directory: npm\/codewhale/); |
| 746 | assert.match(npmPublish, /GH_TOKEN: \$\{\{ github\.token \}\}/); |
| 747 | assert.match(npmPublish, /npm publish --access public/); |
| 748 | assert.doesNotMatch(npmJob[1], /NPM_TOKEN|NODE_AUTH_TOKEN|secrets\./); |
| 749 | assert.ok( |
| 750 | release.indexOf("Revalidate public release assets") < |
| 751 | release.indexOf("Publish npm wrapper with trusted publishing"), |
| 752 | "npm publication must follow the public exact-asset gate", |
| 753 | ); |
| 754 | |
| 755 | const cratesJob = jobBlock(release, "crates"); |
| 756 | assert.match(cratesJob, /^ environment: release$/m, "crates.io publication must wait for the protected release environment"); |
| 757 | assert.match(cratesJob, /^ needs: \[npm, release, resolve\]$/m); |
| 758 | assert.match(cratesJob, /^ permissions:\n contents: read\n env:/m, "crates.io publication needs only contents: read"); |
| 759 | assert.doesNotMatch(cratesJob, /id-token|contents: write|actions: write/); |
| 760 | assert.equal(jobTimeout(release, "crates"), 360); |
| 761 | assert.match(cratesJob, /^ concurrency:\n group: crates-io-\$\{\{ needs\.resolve\.outputs\.tag \}\}\n cancel-in-progress: false$/m); |
| 762 | assert.match(cratesJob, /persist-credentials: false/); |
| 763 | assert.doesNotMatch(cratesJob, /uses: (?:Swatinem\/rust-cache|mozilla-actions\/sccache-action)|RUSTC_WRAPPER/, "the token-holding job must not restore shared build caches"); |
| 764 | assert.doesNotMatch(cratesJob, /set -x/); |
| 765 | const cratesGuard = jobIf(release, "crates").replace(/^\$\{\{\s*(.*?)\s*\}\}$/, "$1"); |
| 766 | const cratesRuns = ({ repo = "codewhale-hq/Codewhale", ref = "refs/tags/v1.2.3", prerelease = "false", release: rel = "success", npm = "success" } = {}) => |
| 767 | evaluate(cratesGuard, { |
| 768 | cancelled: () => false, |
| 769 | format: (template, ...args) => template.replace(/\{(\d+)\}/g, (_, i) => args[Number(i)]), |
| 770 | github: { repository: repo, ref }, |
| 771 | needs: { release: { result: rel }, npm: { result: npm }, resolve: { outputs: { tag: "v1.2.3", prerelease } } }, |
| 772 | }); |
| 773 | assert.equal(cratesRuns(), true, "crates.io publication must run for a stable release of this repository"); |
| 774 | assert.equal(cratesRuns({ repo: "someone/Codewhale" }), false, "a fork must never reach the crates.io job"); |
| 775 | assert.equal(cratesRuns({ ref: "refs/heads/main" }), false, "a dispatch from a branch must never reach the crates.io job"); |
| 776 | assert.equal(cratesRuns({ ref: "refs/tags/v9.9.9" }), false, "the ref must be the resolved release tag"); |
| 777 | assert.equal(cratesRuns({ prerelease: "true" }), false, "prereleases publish no crates"); |
| 778 | assert.equal(cratesRuns({ npm: "failure" }), false, "crates.io publication follows npm"); |
| 779 | assert.equal(cratesRuns({ release: "failure" }), false, "crates.io publication follows the GitHub Release"); |
| 780 | assert.equal( |
| 781 | (release.match(/secrets\.CARGO_REGISTRY_TOKEN/g) || []).length, |
| 782 | 1, |
| 783 | "the crates.io token must be referenced exactly once", |
| 784 | ); |
| 785 | const cratesPublish = namedStep(release, "Publish crates to crates.io"); |
| 786 | assert.match(cratesPublish, /^ env:\n CARGO_REGISTRY_TOKEN: \$\{\{ secrets\.CARGO_REGISTRY_TOKEN \}\}$/m, "the token reaches only the publish step's environment"); |
| 787 | assert.doesNotMatch(cratesPublish.split("run: |")[1], /\$\{\{/, "the publish script must not interpolate expressions into its command line"); |
| 788 | assert.match(cratesPublish, /if \[\[ -z "\$\{CARGO_REGISTRY_TOKEN:-\}" \]\]; then\n\s+echo "::error::Secret CARGO_REGISTRY_TOKEN is not set in the 'release' environment/); |
| 789 | assert.match(cratesPublish, /CARGO_HOME="\$\{root\}\/cargo-home" CARGO_TARGET_DIR="\$\{root\}\/target" \\\n\s+\.\/scripts\/release\/publish-crates\.sh publish/); |
| 790 | const cratesOrder = [ |
| 791 | "Require the clean release tag checkout before crates.io publish", |
| 792 | "Publish crates to crates.io", |
| 793 | "Verify crates.io and npm serve the release", |
| 794 | ].map((name) => release.indexOf(` - name: ${name}\n`)); |
| 795 | assert.ok(cratesOrder.every((at, i) => at > 0 && (i === 0 || at > cratesOrder[i - 1])), "crates job: tag gate, publish, then registry check"); |
| 796 | assert.match(namedStep(release, "Require the clean release tag checkout before crates.io publish"), /require-release-tag-checkout\.sh "\$\{VERSION\}"/); |
| 797 | assert.match(namedStep(release, "Verify crates.io and npm serve the release"), /check-published\.sh "\$\{VERSION\}"/); |
| 798 | assert.doesNotMatch(namedStep(release, "Verify crates.io and npm serve the release"), /secrets\./); |
| 799 | assert.match(read("scripts/release/publish-crates.sh"), /env -u CARGO_REGISTRY_TOKEN cargo publish "\$\{package_args\[@\]\}"/, "the pre-upload verification build must not see the token"); |
| 800 | |
| 801 | assert.match(releaseDockerfile, /^FROM debian:bookworm-slim$/m); |
| 802 | assert.match(releaseDockerfile, /ca-certificates/); |
| 803 | assert.match(releaseDockerfile, /libdbus-1-3/); |
| 804 | assert.match(releaseDockerfile, /COPY .*bin\/codewhale \/usr\/local\/bin\/codewhale/); |
| 805 | assert.match(releaseDockerfile, /COPY .*bin\/codew \/usr\/local\/bin\/codew/); |
| 806 | assert.match(releaseDockerfile, /^USER codewhale$/m); |
| 807 | assert.doesNotMatch( |
| 808 | releaseDockerfile, |
| 809 | /\bcargo\s+build\b|^FROM\s+rust:/m, |
| 810 | "release container assembly must reuse the already-verified release binaries", |
| 811 | ); |
| 812 | |
| 813 | assert.match(runbook, /release[- ]candidate/i); |
| 814 | assert.match(runbook, /expected_sha/); |
| 815 | assert.match(runbook, /38/); |
| 816 | assert.match(runbook, /does not create a tag/i); |
| 817 | assert.match(runbook, /explicit.*approval/i); |
| 818 | assert.match(runbook, /last[- ]useful[- ]log/i, "runbook must document the last-useful-log rule (#5496)"); |
| 819 | assert.match(runbook, /404 logs/i, "runbook must document the 404-log cancellation rule (#5496)"); |
| 820 | |
| 821 | const cnbRustGates = cnb.match( |
| 822 | /\.rust_workspace_gates_stage: &rust_workspace_gates_stage([\s\S]*?)\n\.linux_rust_gates:/, |
| 823 | ); |
| 824 | assert.ok(cnbRustGates, "CNB must retain the shared Rust workspace gate"); |
| 825 | assert.match( |
| 826 | cnbRustGates[1], |
| 827 | /timeout: 45m[\s\S]*export CARGO_BUILD_JOBS=1[\s\S]*export CARGO_PROFILE_TEST_DEBUG=0[\s\S]*cargo check --workspace --all-targets --locked[\s\S]*cargo clippy --workspace --all-targets --all-features --locked -- -D warnings[\s\S]*RUST_MIN_STACK=16777216 sh scripts\/with-hermetic-test-home.sh cargo test --workspace --all-features --locked/, |
| 828 | "CNB must serialize the memory-heavy Rust gate and preserve the workspace test stack contract", |
| 829 | ); |
| 830 | assert.doesNotMatch( |
| 831 | cnbRustGates[1], |
| 832 | /export (?:HOME|USERPROFILE|CODEWHALE_HOME)=/, |
| 833 | "CNB must reuse the shared test-home boundary without overriding legacy migration fixtures", |
| 834 | ); |
| 835 | |
| 836 | // Cover every test invocation, including named parity and narrow crate gates. |
| 837 | // These launchers protect production dependencies as well as cfg(test) code. |
| 838 | // `release parity` is 4 rather than 3: parity runs the workspace under nextest |
| 839 | // for the same one-process-per-test isolation CI's lanes use, and keeps a |
| 840 | // separate doctest invocation because nextest does not run doctests. release.yml |
| 841 | // itself runs none: its parity job calls release-parity.yml. |
| 842 | let hermeticInvocations = 0; |
| 843 | for (const [label, workflow, expected] of [ |
| 844 | ["CI", ci, 5], |
| 845 | ["CI test suite", ciSuite, 5], |
| 846 | ["release", release, 0], |
| 847 | ["release parity", parityWorkflow, 4], |
| 848 | ["CNB", cnb, 3], |
| 849 | ]) { |
| 850 | const commands = workflow.split("\n").filter((line) => |
| 851 | !line.trimStart().startsWith("#") && |
| 852 | // Exclude only this standalone quoted receipt argument. A printf line |
| 853 | // with command substitution or any appended execution still counts. |
| 854 | line.trim() !== "'command=sh scripts/with-hermetic-test-home.sh cargo test --workspace --all-features --locked -- --format=pretty'" && |
| 855 | /\bcargo (?:test|nextest run)\b/.test(line), |
| 856 | ); |
| 857 | assert.equal(commands.length, expected, `${label} must retain every Rust test invocation`); |
| 858 | for (const command of commands) { |
| 859 | assert.match(command, /sh scripts\/with-hermetic-test-home.sh cargo (?:test|nextest run)\b/, |
| 860 | `${label} Rust tests must use the shared test-home boundary`); |
| 861 | } |
| 862 | hermeticInvocations += commands.length; |
| 863 | } |
| 864 | console.log(`Hermetic Rust workflow invocations OK: ${hermeticInvocations} checks passed.`); |
| 865 | |
| 866 | const nextest = read(".config/nextest.toml"); |
| 867 | const integrationGroup = nextest.search(/^filter = 'package\(codewhale-tui\) & binary\(integration\)'$/m); |
| 868 | const telemetryGroup = nextest.indexOf( |
| 869 | "filter = 'package(codewhale-tui) & binary(integration) & test(/^telemetry_contract::/)'", |
| 870 | ); |
| 871 | const execGroup = nextest.indexOf( |
| 872 | "filter = 'package(codewhale-tui) & binary(integration) & test(/^exec_persistent_service::/)'", |
| 873 | ); |
| 874 | assert.ok(integrationGroup >= 0, "nextest must bound the integration binary"); |
| 875 | assert.ok( |
| 876 | telemetryGroup >= 0 && telemetryGroup < integrationGroup, |
| 877 | "telemetry-contract override must precede binary(integration); first matching group wins", |
| 878 | ); |
| 879 | assert.ok( |
| 880 | execGroup >= 0 && execGroup < integrationGroup, |
| 881 | "exec_persistent_service override must precede binary(integration); first matching group wins", |
| 882 | ); |
| 883 | assert.match(nextest, /exec-persistent-service = \{ max-threads = 1 \}/); |
| 884 | assert.equal( |
| 885 | (cnb.match(/^\s+- \*rust_workspace_gates_stage$/gm) || []).length, |
| 886 | 2, |
| 887 | "both CNB Rust pipelines must reuse the constrained workspace gate", |
| 888 | ); |
| 889 | |
| 890 | const cnbPreflight = cnb.match( |
| 891 | /\.linux_release_preflight: &linux_release_preflight([\s\S]*?)\nmain:/, |
| 892 | ); |
| 893 | assert.ok(cnbPreflight, "CNB must retain a dedicated release preflight"); |
| 894 | const cnbBuild = cnbPreflight[1].indexOf( |
| 895 | "cargo build --jobs 2 --release --locked -p codewhale-cli", |
| 896 | ); |
| 897 | const cnbAlias = cnbPreflight[1].indexOf( |
| 898 | "cp target/release/codewhale target/release/codew", |
| 899 | ); |
| 900 | const cnbSmoke = cnbPreflight[1].indexOf("node scripts/release/npm-wrapper-smoke.js"); |
| 901 | assert.ok(cnbBuild >= 0, "CNB release preflight must build the consolidated runtime"); |
| 902 | assert.ok(cnbAlias > cnbBuild, "CNB release preflight must materialize codew after the build"); |
| 903 | assert.ok(cnbSmoke > cnbAlias, "CNB release preflight must materialize codew before smoke"); |
| 904 | |
| 905 | const cnbTagRelease = cnb.match(/\$:\n tag_push:\n([\s\S]*)$/); |
| 906 | assert.ok(cnbTagRelease, "CNB must retain a tag release pipeline"); |
| 907 | const cnbTagStamp = cnbTagRelease[1].indexOf( |
| 908 | 'export CODEWHALE_BUILD_SHA="$commit_sha"', |
| 909 | ); |
| 910 | const cnbTagBuild = cnbTagRelease[1].indexOf( |
| 911 | "cargo build --jobs 2 --release --locked \\", |
| 912 | ); |
| 913 | const cnbTagVersionCheck = cnbTagRelease[1].indexOf( |
| 914 | "./scripts/release/check-versions.sh --require-dated-release", |
| 915 | ); |
| 916 | assert.ok(cnbTagVersionCheck >= 0, "CNB publication must reject undated source candidates"); |
| 917 | for (const [label, workflow] of [["release-candidate.yml", candidate], ["release.yml", release]]) { |
| 918 | assert.match( |
| 919 | workflow, |
| 920 | /\.\/scripts\/release\/check-versions\.sh --require-dated-release/, |
| 921 | `${label} must reject undated source candidates before building`, |
| 922 | ); |
| 923 | } |
| 924 | assert.ok(cnbTagVersionCheck < cnbTagBuild, "CNB must validate release notes before building public assets"); |
| 925 | assert.match(cnbTagRelease[1], /checkout_sha="\$\(git rev-parse 'HEAD\^\{commit\}'\)"/); |
| 926 | assert.match(cnbTagRelease[1], /commit_sha="\$\{CNB_COMMIT:-\$\{checkout_sha\}\}"/); |
| 927 | assert.match(cnbTagRelease[1], /CNB_COMMIT[\s\S]*does not match checkout[\s\S]*exit 1/); |
| 928 | assert.ok(cnbTagStamp >= 0, "CNB tag releases must stamp the consolidated runtime"); |
| 929 | assert.ok(cnbTagBuild > cnbTagStamp, "CNB tag releases must stamp before compiling"); |
| 930 | |
| 931 | assert.doesNotMatch( |
| 932 | archiveInstaller, |
| 933 | /cargo install codewhale --locked/, |
| 934 | "glibc recovery must name the published codewhale-cli crate", |
| 935 | ); |
| 936 | assert.equal( |
| 937 | (archiveInstaller.match(/cargo install codewhale-cli --locked/g) || []).length, |
| 938 | 2, |
| 939 | "both glibc recovery branches must name codewhale-cli", |
| 940 | ); |
| 941 | assert.doesNotMatch( |
| 942 | archiveInstaller, |
| 943 | /install_binary "\$SCRIPT_DIR\/[^"]+" "\$BIN_DIR\/codewhale-tui"/, |
| 944 | "archive installs must not write the retired codewhale-tui command", |
| 945 | ); |
| 946 | assert.doesNotMatch( |
| 947 | cliDispatcher, |
| 948 | /codewhale_config::auto_model::classify/, |
| 949 | "the CLI dispatcher must leave auto routing to the provider-aware runtime", |
| 950 | ); |
| 951 | |
| 952 | // #5496: every release-lane job carries an explicit `timeout-minutes`. |
| 953 | // |
| 954 | // GitHub's default is 360 minutes, so an assigned-but-dead runner sits for six |
| 955 | // hours before anything reclaims it — observed on the v0.9.9 train as a job |
| 956 | // stuck `in_progress` with 404 logs. Timeouts are containment, not recovery: |
| 957 | // the runbook keeps the 404-log cancel/rerun rule for infrastructure failures. |
| 958 | // |
| 959 | // A job that calls a reusable workflow (`uses:`) cannot carry the key at all — |
| 960 | // GitHub rejects it — so the callee owns its own caps. That is why the artifact |
| 961 | // bounds live in release-artifacts.yml rather than in its callers. |
| 962 | function timeoutMinutes(value) { |
| 963 | const literal = /^\d+$/.test(value); |
| 964 | const conditional = value.match( |
| 965 | /^\$\{\{\s*startsWith\(matrix\.os,\s*'macos-'\)\s*&&\s*(\d+)\s*\|\|\s*(\d+)\s*\}\}$/, |
| 966 | ); |
| 967 | if (!literal && !conditional) return null; |
| 968 | const macos = Number(literal ? value : conditional[1]); |
| 969 | const other = Number(literal ? value : conditional[2]); |
| 970 | if (![macos, other].every((cap) => Number.isInteger(cap) && cap > 0 && cap <= 360)) { |
| 971 | return null; |
| 972 | } |
| 973 | return { macos, other }; |
| 974 | } |
| 975 | |
| 976 | function jobsWithoutTimeout(source) { |
| 977 | const lines = source.split("\n"); |
| 978 | const jobsAt = lines.findIndex((line) => /^jobs:\s*$/.test(line)); |
| 979 | assert.notEqual(jobsAt, -1, "workflow must declare jobs"); |
| 980 | const offenders = []; |
| 981 | for (let i = jobsAt + 1; i < lines.length; i += 1) { |
| 982 | const header = lines[i].match(/^ ([A-Za-z0-9_-]+):\s*$/); |
| 983 | if (!header) continue; |
| 984 | let reusable = false; |
| 985 | let capped = false; |
| 986 | for (let j = i + 1; j < lines.length; j += 1) { |
| 987 | if (/^ [A-Za-z0-9_-]+:\s*$/.test(lines[j])) break; |
| 988 | if (/^ uses:/.test(lines[j])) reusable = true; |
| 989 | const timeout = lines[j].match(/^ timeout-minutes:\s*(.+?)\s*$/); |
| 990 | if (timeout && timeoutMinutes(timeout[1])) capped = true; |
| 991 | } |
| 992 | if (!reusable && !capped) offenders.push(header[1]); |
| 993 | } |
| 994 | return offenders; |
| 995 | } |
| 996 | |
| 997 | assert.deepEqual( |
| 998 | jobsWithoutTimeout("jobs:\n uncapped:\n runs-on: ubuntu-latest\n"), |
| 999 | ["uncapped"], |
| 1000 | "jobsWithoutTimeout must detect an uncapped job", |
| 1001 | ); |
| 1002 | assert.deepEqual( |
| 1003 | jobsWithoutTimeout("jobs:\n reusable:\n uses: ./.github/workflows/reusable.yml\n"), |
| 1004 | [], |
| 1005 | "jobsWithoutTimeout must skip reusable workflow callers", |
| 1006 | ); |
| 1007 | assert.deepEqual( |
| 1008 | jobsWithoutTimeout("jobs:\n capped:\n runs-on: ubuntu-latest\n timeout-minutes: 15\n"), |
| 1009 | [], |
| 1010 | "jobsWithoutTimeout must accept a capped job", |
| 1011 | ); |
| 1012 | |
| 1013 | for (const [name, source] of [ |
| 1014 | ["release-candidate.yml", candidate], |
| 1015 | ["release-artifacts.yml", artifacts], |
| 1016 | ["release.yml", release], |
| 1017 | ["release-parity.yml", parityWorkflow], |
| 1018 | ["release-republish.yml", republish], |
| 1019 | ["ci.yml", ci], |
| 1020 | ["ci-test-suite.yml", ciSuite], |
| 1021 | ["nightly.yml", nightly], |
| 1022 | ]) { |
| 1023 | assert.deepEqual( |
| 1024 | jobsWithoutTimeout(source), |
| 1025 | [], |
| 1026 | `${name}: every job must set timeout-minutes (#5496)`, |
| 1027 | ); |
| 1028 | } |
| 1029 | |
| 1030 | function jobTimeout(source, job, platform = "other") { |
| 1031 | const match = source.match( |
| 1032 | new RegExp(`^ ${job}:\\n(?:.*\\n)*? timeout-minutes: (.+)$`, "m"), |
| 1033 | ); |
| 1034 | assert.ok(match, `${job} must declare timeout-minutes`); |
| 1035 | const caps = timeoutMinutes(match[1].trim()); |
| 1036 | assert.ok(caps, `${job} must declare a bounded timeout`); |
| 1037 | return caps[platform]; |
| 1038 | } |
| 1039 | |
| 1040 | const macosTimeout = "${{ startsWith(matrix.os, 'macos-') && 360 || 210 }}"; |
| 1041 | assert.deepEqual(timeoutMinutes(macosTimeout), { macos: 360, other: 210 }); |
| 1042 | for (const invalid of [ |
| 1043 | "0", "361", "Infinity", "${{ matrix.timeout }}", |
| 1044 | "${{ startsWith(matrix.os, 'macos-') && 361 || 210 }}", |
| 1045 | "${{ startsWith(matrix.os, 'macos-') && 360 || 0 }}", |
| 1046 | ]) { |
| 1047 | assert.equal(timeoutMinutes(invalid), null, `${invalid} must not count as a bounded cap`); |
| 1048 | } |
| 1049 | assert.deepEqual( |
| 1050 | jobsWithoutTimeout(`jobs:\n capped:\n timeout-minutes: ${macosTimeout}\n`), |
| 1051 | [], |
| 1052 | ); |
| 1053 | assert.equal(jobTimeout(artifacts, "build", "macos"), 360); |
| 1054 | assert.equal(jobTimeout(artifacts, "build"), 210); |
| 1055 | const artifactCacheSetup = artifacts.match( |
| 1056 | / - uses: mozilla-actions\/sccache-action@[^\n]+\n(?:(?! - ).*\n)*/, |
| 1057 | ); |
| 1058 | assert.ok(artifactCacheSetup, "artifact compiler cache setup must be explicit"); |
| 1059 | assert.match(artifactCacheSetup[0], /^ if: runner\.os == 'Linux'$/m); |
| 1060 | assert.match( |
| 1061 | namedStep(artifacts, "Enable sccache"), |
| 1062 | /^ if: steps\.sccache\.outcome == 'success' && runner\.os == 'Linux'$/m, |
| 1063 | ); |
| 1064 | |
| 1065 | assert.equal(jobTimeout(candidate, "resolve"), 10); |
| 1066 | assert.equal(jobTimeout(candidate, "web"), 15); |
| 1067 | assert.equal(jobTimeout(artifacts, "pin"), 10); |
| 1068 | assert.ok( |
| 1069 | jobTimeout(artifacts, "build") >= jobTimeout(ci, "test"), |
| 1070 | "native artifacts must allow the full CI cold-build budget", |
| 1071 | ); |
| 1072 | for (const job of ["bundle", "windows-installer", "assemble", "smoke"]) { |
| 1073 | assert.equal(jobTimeout(artifacts, job), 15, `${job} must keep the 15m packaging cap`); |
| 1074 | } |
| 1075 | assert.equal( |
| 1076 | jobTimeout(nightly, "build"), jobTimeout(artifacts, "build"), |
| 1077 | "nightly and non-macOS release builds must share the cold-build allowance", |
| 1078 | ); |
| 1079 | assert.equal(jobTimeout(release, "resolve"), 10); |
| 1080 | // The 0.10.1 cold parity build exhausted 45 minutes before tests started. |
| 1081 | // Reuse the full CI suite's budget rather than pinning an older release's cap. |
| 1082 | assert.ok( |
| 1083 | jobTimeout(parityWorkflow, "parity") >= jobTimeout(ci, "test"), |
| 1084 | "release parity must allow the full CI suite's cold-build budget", |
| 1085 | ); |
| 1086 | |
| 1087 | const pinnedToolchain = read("rust-toolchain.toml").match(/^channel\s*=\s*"([^"]+)"/m)[1]; |
| 1088 | assert.match(pinnedToolchain, /^\d+\.\d+\.\d+$/, "rust-toolchain.toml must pin an exact Rust release"); |
| 1089 | const msrv = read("Cargo.toml").match(/^rust-version\s*=\s*"([^"]+)"/m)[1]; |
| 1090 | assert.match(msrv, /^\d+\.\d+$/, "Cargo.toml must declare a minor MSRV"); |
| 1091 | const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 1092 | const stripWorkflowComments = (source) => |
| 1093 | source |
| 1094 | .split("\n") |
| 1095 | .map((line) => line.replace(/(^|\s)#.*$/, "")) |
| 1096 | .join("\n"); |
| 1097 | const workflowDir = path.join(repoRoot, ".github", "workflows"); |
| 1098 | const workflowSources = new Map(); |
| 1099 | for (const file of fs.readdirSync(workflowDir).filter((name) => /\.ya?ml$/.test(name)).sort()) { |
| 1100 | workflowSources.set(file, stripWorkflowComments(read(`.github/workflows/${file}`))); |
| 1101 | } |
| 1102 | const ciSource = workflowSources.get("ci.yml"); |
| 1103 | const msrvHeader = /^ msrv:[ \t]*$/m.exec(ciSource); |
| 1104 | assert.ok(msrvHeader, "ci.yml must keep an MSRV job"); |
| 1105 | const msrvStart = msrvHeader.index; |
| 1106 | const afterMsrvHeader = msrvStart + msrvHeader[0].length; |
| 1107 | const nextJob = /^ \S/m.exec(ciSource.slice(afterMsrvHeader)); |
| 1108 | const msrvEnd = nextJob ? afterMsrvHeader + nextJob.index : ciSource.length; |
| 1109 | const selectorValue = (value) => value.trim().replace(/^(["'])(.*)\1$/, "$2"); |
| 1110 | const inMsrvJob = (index) => index >= msrvStart && index < msrvEnd; |
| 1111 | for (const [file, source] of workflowSources) { |
| 1112 | const selectors = [ |
| 1113 | ...[...source.matchAll(/dtolnay\/rust-toolchain@([^\s]+)/g)].map((m) => ["action ref", m[1], m.index]), |
| 1114 | ...[...source.matchAll(/^[ \t]+toolchain:[ \t]*([^\r\n]*)$/gm)].map((m) => ["toolchain input", selectorValue(m[1]), m.index]), |
| 1115 | ...[...source.matchAll(/^[ \t]+rust-version:[ \t]*([^\r\n]*)$/gm)].map((m) => ["rust-version input", selectorValue(m[1]), m.index]), |
| 1116 | ...[...source.matchAll(/^[ \t]+RUSTUP_TOOLCHAIN:[ \t]*([^\r\n]*)$/gm)].map((m) => ["RUSTUP_TOOLCHAIN", selectorValue(m[1]), m.index]), |
| 1117 | ...[...source.matchAll(/\bcargo\s+\+\s*["']?([^\s"']+)/g)].map((m) => ["cargo + selector", m[1], m.index]), |
| 1118 | ]; |
| 1119 | for (const [kind, value, index] of selectors) { |
| 1120 | if (kind === "action ref" && (/^[0-9a-f]{40}$/.test(value) || value === "master")) continue; |
| 1121 | const expected = file === "ci.yml" && inMsrvJob(index) ? msrv : file === "toolchain-drift.yml" ? "stable" : pinnedToolchain; |
| 1122 | assert.equal(value, expected, `${file}: ${kind} ${value} must equal ${expected}`); |
| 1123 | } |
| 1124 | assert.doesNotMatch(source, /rustup (?:target|component) add --toolchain/, `${file}: rustup adds must follow rust-toolchain.toml`); |
| 1125 | } |
| 1126 | const msrvJob = ciSource.slice(msrvStart, msrvEnd); |
| 1127 | assert.match(msrvJob, new RegExp(`RUSTUP_TOOLCHAIN: "${escapeRegExp(msrv)}"`), "the MSRV job must override rust-toolchain.toml for every step"); |
| 1128 | assert.match(msrvJob, new RegExp(`toolchain: "?${escapeRegExp(msrv)}"?`)); |
| 1129 | assert.match(msrvJob, new RegExp(`cargo \\+${escapeRegExp(msrv)} check --workspace --locked`)); |
| 1130 | assert.doesNotMatch(msrvJob, new RegExp(`\\b${escapeRegExp(pinnedToolchain)}\\b`), "the MSRV job must not select the pinned release toolchain"); |
| 1131 | |
| 1132 | const rootDockerfile = read("Dockerfile"); |
| 1133 | const devcontainerDockerfile = read(".devcontainer/Dockerfile"); |
| 1134 | const devcontainerConfig = read(".devcontainer/devcontainer.json"); |
| 1135 | const tencentCnb = read("deploy/tencent-lighthouse/cnb/cnb.yml.example"); |
| 1136 | const pinnedTag = `${pinnedToolchain}-bookworm`; |
| 1137 | for (const [label, source] of [ |
| 1138 | ["Dockerfile", rootDockerfile], |
| 1139 | [".devcontainer/Dockerfile", devcontainerDockerfile], |
| 1140 | ]) { |
| 1141 | assert.match(source, new RegExp(`^ARG RUST_VERSION=${escapeRegExp(pinnedToolchain)}$`, "m"), `${label} must default RUST_VERSION to the pinned toolchain`); |
| 1142 | assert.match(source, /^FROM .*\brust:\$\{RUST_VERSION\}/m, `${label} must build from the RUST_VERSION image`); |
| 1143 | } |
| 1144 | assert.match(devcontainerConfig, new RegExp(`"RUST_VERSION":\\s*"${escapeRegExp(pinnedToolchain)}"`), ".devcontainer/devcontainer.json must pass the pinned RUST_VERSION build arg"); |
| 1145 | for (const [label, source] of [ |
| 1146 | [".cnb.yml", cnb], |
| 1147 | ["deploy/tencent-lighthouse/cnb/cnb.yml.example", tencentCnb], |
| 1148 | ]) { |
| 1149 | const tags = [...stripWorkflowComments(source).matchAll(/^[ \t]*image:[ \t]*([^\r\n]*)$/gm)] |
| 1150 | .map((m) => selectorValue(m[1])) |
| 1151 | .filter((value) => value.startsWith("rust:")) |
| 1152 | .map((value) => value.slice("rust:".length)); |
| 1153 | assert.ok(tags.length > 0, `${label} must declare a Rust build image`); |
| 1154 | assert.deepEqual([...new Set(tags)], [pinnedTag], `${label}: Rust build images must match rust-toolchain.toml`); |
| 1155 | } |
| 1156 | |
| 1157 | const releaseMacosStep = namedStep(artifacts, "Choose the macOS build runner").match(/ run: \|\n([\s\S]*)/)[1].replace(/^ {10}/gm, ""); |
| 1158 | for (const [event, ref, repo, requested, variable, expected] of [ |
| 1159 | ["pull_request", "refs/pull/1/merge", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 1160 | ["pull_request_target", "refs/heads/main", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 1161 | ["push", "refs/heads/main", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 1162 | ["push", "refs/tags/nightly", "codewhale-hq/Codewhale", "self-hosted", "true", "false"], |
| 1163 | ["schedule", "refs/heads/main", "codewhale-hq/Codewhale", "default", "true", "false"], |
| 1164 | ["workflow_dispatch", "refs/heads/ci/x", "someone/Codewhale", "self-hosted", "true", "false"], |
| 1165 | ["push", "refs/tags/v0.10.4", "someone/Codewhale", "default", "true", "false"], |
| 1166 | ["push", "refs/tags/v0.10.4", "codewhale-hq/Codewhale", "default", "false", "false"], |
| 1167 | ["push", "refs/tags/v0.10.4", "codewhale-hq/Codewhale", "default", "true", "true"], |
| 1168 | ["push", "refs/tags/v0.10.4", "codewhale-hq/Codewhale", "hosted", "true", "false"], |
| 1169 | ["workflow_dispatch", "refs/heads/ci/x", "codewhale-hq/Codewhale", "", "", "false"], |
| 1170 | ["workflow_dispatch", "refs/heads/ci/x", "codewhale-hq/Codewhale", "self-hosted", "false", "true"], |
| 1171 | ]) { |
| 1172 | const out = path.join(fs.mkdtempSync(path.join(require("node:os").tmpdir(), "cw-release-macos-")), "out"); |
| 1173 | execFileSync("bash", ["-c", releaseMacosStep], { |
| 1174 | env: { PATH: process.env.PATH, GITHUB_OUTPUT: out, EVENT_NAME: event, EVENT_REF: ref, THIS_REPO: repo, REQUESTED: requested, SWITCH: variable }, |
| 1175 | }); |
| 1176 | assert.equal(fs.readFileSync(out, "utf8"), `self_hosted=${expected}\n`, `release macOS runner: ${event} ${ref} ${repo} ${requested}/${variable}`); |
| 1177 | } |
| 1178 | const releaseBuildRunsOn = jobBlock(artifacts, "build").match(/^ runs-on: (.+)$/m)[1]; |
| 1179 | assert.equal( |
| 1180 | releaseBuildRunsOn, |
| 1181 | `\${{ startsWith(matrix.os, 'macos-') && needs.pin.outputs.macos_self_hosted == 'true' && fromJSON('["self-hosted","macOS","ARM64","codewhale-mac"]') || (matrix.os == 'ubuntu-latest' && 'ubuntu-24.04' || matrix.os) }}`, |
| 1182 | "only macOS release builds may use the self-hosted Mac, and only when pin chose it", |
| 1183 | ); |
| 1184 | const releaseBuild = jobBlock(artifacts, "build"); |
| 1185 | const freshReleaseHome = namedStep(releaseBuild, "Fresh rustup, Cargo home and temp for a self-hosted release build"); |
| 1186 | assert.match(freshReleaseHome, /rm -rf "\$\{fresh\}"/); |
| 1187 | for (const remap of [/"\$\{CARGO_HOME\}=\/cargo"/, /"\$\(cd "\$\{fresh\}" && pwd -P\)\/\.cargo=\/cargo"/, /"\$\{GITHUB_WORKSPACE\}=\/codewhale"/, /"\$\(cd "\$\{GITHUB_WORKSPACE\}" && pwd -P\)=\/codewhale"/]) { |
| 1188 | assert.match(freshReleaseHome, remap, "self-hosted shipping binaries must not embed the build machine's home or workspace paths"); |
| 1189 | } |
| 1190 | assert.match(freshReleaseHome, /CARGO_ENCODED_RUSTFLAGS=/); |
| 1191 | assert.match(namedStep(releaseBuild, "Start the self-hosted release build from an empty target"), /rm -rf target\n\s+test -z "\$\(git status --porcelain --ignored\)"/); |
| 1192 | assert.match(releaseBuild, /uses: Swatinem\/rust-cache@[^\n]+\n if: runner\.environment != 'self-hosted'\n/, "self-hosted shipping builds must not restore or save a shared cache"); |
| 1193 | assert.match(candidate, /^ macos_runner: \$\{\{ inputs\.macos_runner \}\}$/m); |
| 1194 | |
| 1195 | let pinnedRunsOn = 0; |
| 1196 | for (const [file, source] of workflowSources) { |
| 1197 | for (const [, value] of source.matchAll(/^[ \t]*runs-on:[ \t]*(.+)$/gm)) { |
| 1198 | pinnedRunsOn += 1; |
| 1199 | assert.doesNotMatch( |
| 1200 | value.replace(/==\s*'ubuntu-latest'/g, ""), |
| 1201 | /ubuntu-latest/, |
| 1202 | `${file}: runs-on must name ubuntu-24.04, never ubuntu-latest: ${value}`, |
| 1203 | ); |
| 1204 | for (const [, key] of value.matchAll(/matrix\.(\w+)/g)) { |
| 1205 | const listsUbuntuLatest = new RegExp(`^[ \\t-]*${key}:.*ubuntu-latest`, "m").test(source); |
| 1206 | if (listsUbuntuLatest) { |
| 1207 | assert.match( |
| 1208 | value, |
| 1209 | new RegExp(`matrix\\.${key} == 'ubuntu-latest' && 'ubuntu-24\\.04'`), |
| 1210 | `${file}: runs-on must map matrix.${key} ubuntu-latest to ubuntu-24.04: ${value}`, |
| 1211 | ); |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | } |
| 1216 | assert.ok(pinnedRunsOn > 50, "runs-on pin contract must scan every workflow"); |
| 1217 | |
| 1218 | const nightlyCandidate = read(".github/workflows/nightly-candidate.yml"); |
| 1219 | const fullCiReceipt = read("scripts/release/require-full-ci-receipt.sh"); |
| 1220 | assert.match(nightlyCandidate, /^ schedule:\n - cron: '\d+ \d+ \* \* \*'\n workflow_dispatch:\n/m); |
| 1221 | assert.match(nightlyCandidate, /^concurrency:\n group: nightly-candidate\n cancel-in-progress: false\n/m); |
| 1222 | assert.deepEqual(jobsWithoutTimeout(nightlyCandidate), [], "nightly-candidate.yml: every job must set timeout-minutes"); |
| 1223 | assert.doesNotMatch(nightlyCandidate, /secrets\./, "the nightly dispatcher must hold no secret"); |
| 1224 | for (const forbidden of [/contents:\s*write/, /packages:\s*write/, /\bgh release\b/, /\bnpm publish\b/, /\bcargo publish\b/, /\bgit push\b/, /\bgit tag\b/, /release\.yml/]) { |
| 1225 | assert.doesNotMatch(nightlyCandidate, forbidden, "the nightly dispatcher must not publish or start a release"); |
| 1226 | } |
| 1227 | const nightlyDecide = namedStep(nightlyCandidate, "Decide whether main needs a candidate"); |
| 1228 | assert.match(nightlyDecide, /commits\/main/, "the nightly builds main's tip"); |
| 1229 | assert.match(nightlyDecide, /release-candidate\.yml\/runs\?head_sha=\$\{sha\}/, "skip a SHA that already has a candidate"); |
| 1230 | assert.match(nightlyDecide, /select\(\.status != "completed"\)/, "never stack a candidate on one still building"); |
| 1231 | assert.match(nightlyDecide, /require-full-ci-receipt\.sh "\$\{GITHUB_REPOSITORY\}" "\$\{sha\}"/, "build only a main with green full CI"); |
| 1232 | const nightlyDispatch = namedStep(nightlyCandidate, "Dispatch release-candidate.yml for main"); |
| 1233 | assert.match(nightlyDispatch, /if: steps\.decide\.outputs\.decision == 'dispatch' && !inputs\.dry_run/); |
| 1234 | assert.match( |
| 1235 | nightlyDispatch, |
| 1236 | /gh workflow run release-candidate\.yml --repo "\$\{GITHUB_REPOSITORY\}" --ref main \\\n\s+-f expected_sha="\$\{SHA\}" -f nightly=true/, |
| 1237 | "the nightly must dispatch (not call) the candidate so release.yml finds a workflow_dispatch receipt", |
| 1238 | ); |
| 1239 | assert.match( |
| 1240 | candidate, |
| 1241 | /CODEWHALE_RELEASE_SIGNING_KEY: \$\{\{ !inputs\.nightly && secrets\.CODEWHALE_RELEASE_SIGNING_KEY \|\| '' \}\}/, |
| 1242 | "a nightly candidate must never receive the release signing key", |
| 1243 | ); |
| 1244 | assert.match( |
| 1245 | release, |
| 1246 | /retention_days: 14\n\s+require_signature: true\n\s+secrets:\n\s+CODEWHALE_RELEASE_SIGNING_KEY: \$\{\{ secrets\.CODEWHALE_RELEASE_SIGNING_KEY \}\}/, |
| 1247 | "the tag release must require a signed checksum manifest", |
| 1248 | ); |
| 1249 | assert.match( |
| 1250 | namedStep(artifacts, "Sign the checksum manifest when the release key is configured"), |
| 1251 | /if \[\[ -z "\$\{CODEWHALE_RELEASE_SIGNING_KEY\}" \]\]; then\n\s+if \[\[ "\$\{REQUIRE_SIGNATURE\}" == "true" \]\]; then\n[^\n]+\n\s+exit 1\n/, |
| 1252 | "a release that requires a signature must fail when the key is absent", |
| 1253 | ); |
| 1254 | assert.match( |
| 1255 | namedStep(candidate, "Check version and OHOS release contracts"), |
| 1256 | /if \[\[ "\$\{NIGHTLY\}" == "true" \]\]; then\n\s+\.\/scripts\/release\/check-versions\.sh\n\s+else\n\s+\.\/scripts\/release\/check-versions\.sh --require-dated-release\n/, |
| 1257 | "only the nightly may build an undated main; every other candidate keeps the dated-release gate", |
| 1258 | ); |
| 1259 | for (const job of ["Change detection", "Lint", "Shared-process tests"]) { |
| 1260 | assert.ok(ci.split("\n").includes(` name: ${job}`), `ci.yml must still name the "${job}" job`); |
| 1261 | assert.ok(fullCiReceipt.includes(`"${job}"`), `require-full-ci-receipt.sh must check "${job}"`); |
| 1262 | } |
| 1263 | assert.match(ci, /^ name: Scoped test \(/m, "ci.yml must still name the Scoped test job"); |
| 1264 | assert.match(ciSuite, /^ name: Suite check\n/m, "ci-test-suite.yml must still name the Suite check job"); |
| 1265 | for (const os of ["ubuntu-latest", "macos-latest", "windows-latest"]) { |
| 1266 | assert.match(ci, new RegExp(`^ name: Sharded tests \\(${os}\\)\\n`, "m"), `ci.yml must still run Sharded tests (${os})`); |
| 1267 | assert.ok( |
| 1268 | fullCiReceipt.includes(`"Sharded tests (${os}) / Suite check"`), |
| 1269 | `require-full-ci-receipt.sh must require the ${os} Suite check`, |
| 1270 | ); |
| 1271 | } |
| 1272 | assert.ok( |
| 1273 | ci.includes("bash scripts/release/require-full-ci-receipt.test.sh\n"), |
| 1274 | "ci.yml must run the full-CI receipt tests", |
| 1275 | ); |
| 1276 | |
| 1277 | const mainLanding = read(".github/workflows/main-landing.yml"); |
| 1278 | const landingPreflight = jobBlock(mainLanding, "preflight"); |
| 1279 | assert.match(mainLanding, /^ push:\n branches: \[main\]\n/m, "the landing gate must run on every push to main"); |
| 1280 | assert.doesNotMatch(landingPreflight, /scripts\/preflight\.sh/, "the landing preflight must invoke direct checks instead of retired scripts/preflight.sh"); |
| 1281 | for (const cmd of [ |
| 1282 | "bash scripts/sync-changelog.sh --check", |
| 1283 | "node web/scripts/check-facts.mjs", |
| 1284 | "node web/scripts/check-cloud-facts.mjs", |
| 1285 | "node web/scripts/check-release-docs.mjs", |
| 1286 | "node web/scripts/check-runtime-routes.mjs", |
| 1287 | 'python3 scripts/check-behaviour-line.py --guards-only "${base}" HEAD', |
| 1288 | 'bash scripts/release/check-feature-release-notes.sh "${base}" HEAD', |
| 1289 | ]) { |
| 1290 | assert.ok(landingPreflight.includes(cmd), `the landing preflight must run ${cmd}`); |
| 1291 | } |
| 1292 | assert.doesNotMatch(landingPreflight, /^ if:/m, "the landing preflight must never be skipped"); |
| 1293 | const landingDispatch = namedStep(mainLanding, "Run ci.yml with every gate on the pushed commit"); |
| 1294 | const landingReceipt = landingDispatch.indexOf( |
| 1295 | 'if receipt="$(bash scripts/release/require-full-ci-receipt.sh "${GITHUB_REPOSITORY}" "${GITHUB_SHA}" 2>&1)"; then', |
| 1296 | ); |
| 1297 | const landingFullRun = landingDispatch.indexOf( |
| 1298 | 'gh workflow run ci.yml --repo "${GITHUB_REPOSITORY}" --ref main -f expected_sha="${GITHUB_SHA}"', |
| 1299 | ); |
| 1300 | assert.ok(landingReceipt >= 0, "the landing gate may skip only on a full-CI receipt for the exact pushed SHA"); |
| 1301 | assert.ok(landingFullRun > landingReceipt, "without that receipt the landing gate must dispatch the full suite"); |
| 1302 | assert.equal((landingDispatch.match(/exit 0/g) || []).length, 1, "the only early exit is the receipt branch"); |
| 1303 | assert.match(landingDispatch, /set -euo pipefail\n/); |
| 1304 | |
| 1305 | assert.deepEqual(jobsWithoutTimeout(mainLanding), [], "main-landing.yml: every job must set timeout-minutes"); |
| 1306 | assert.doesNotMatch( |
| 1307 | mainLanding, |
| 1308 | /secrets\.|CLOUDFLARE_|npm run deploy|cf deploy/, |
| 1309 | "the landing gate must never hold Cloudflare credentials or deploy", |
| 1310 | ); |
| 1311 | const landingWeb = jobBlock(mainLanding, "web"); |
| 1312 | assert.match(landingWeb, /^ needs: web_changes$/m); |
| 1313 | assert.equal( |
| 1314 | evaluate(jobIf(mainLanding, "web"), { needs: { web_changes: { outputs: { web: "true" } } } }), |
| 1315 | true, |
| 1316 | "landing web gates must run when a website input changed", |
| 1317 | ); |
| 1318 | assert.equal( |
| 1319 | evaluate(jobIf(mainLanding, "web"), { needs: { web_changes: { outputs: { web: "false" } } } }), |
| 1320 | false, |
| 1321 | "landing web gates must skip unrelated commits", |
| 1322 | ); |
| 1323 | assert.match(landingWeb, /^ run:\n working-directory: web$/m); |
| 1324 | assert.match(landingWeb, /fetch-depth: 0/); |
| 1325 | assert.match(landingWeb, /cache-dependency-path: web\/package-lock\.json/); |
| 1326 | for (const [label, source] of [ |
| 1327 | ["main-landing.yml", landingWeb], |
| 1328 | ["web.yml", jobBlock(read(".github/workflows/web.yml"), "lint")], |
| 1329 | ]) { |
| 1330 | const order = ["npm ci", "npm test", "npm run check"].map((cmd) => source.indexOf(`run: ${cmd}\n`)); |
| 1331 | assert.ok( |
| 1332 | order.every((at, i) => at >= 0 && (i === 0 || at > order[i - 1])), |
| 1333 | `${label} must run npm ci, npm test, and npm run check in order`, |
| 1334 | ); |
| 1335 | } |
| 1336 | for (const match of [...jobBlock(mainLanding, "web_changes").matchAll(/uses:\s+([^@\s]+)@([^#\s]+)/g), ...landingWeb.matchAll(/uses:\s+([^@\s]+)@([^#\s]+)/g)]) { |
| 1337 | assert.match(match[2], /^[0-9a-f]{40}$/, `main-landing.yml ${match[1]} must pin a full commit SHA`); |
| 1338 | } |
| 1339 | const landingWebDetect = namedStep(jobBlock(mainLanding, "web_changes"), "Detect website input changes"); |
| 1340 | assert.match(landingWebDetect, /EVENT_NAME.*==.*"workflow_dispatch"/); |
| 1341 | const landingWebCase = landingWebDetect.match(/\n( +)case "\$\{path\}" in\n[\s\S]*?\n\1esac\n/)?.[0]; |
| 1342 | assert.ok(landingWebCase, "main-landing.yml must declare the website input path case block"); |
| 1343 | function classifyLandingWeb(paths) { |
| 1344 | const script = `while IFS= read -r path; do web=false\n${landingWebCase}\nprintf '%s\\t%s\\n' "$web" "$path"; done`; |
| 1345 | const out = execFileSync("bash", ["-c", script], { input: `${paths.join("\n")}\n`, encoding: "utf8" }); |
| 1346 | return new Map(out.trim().split("\n").map((line) => line.split("\t").reverse())); |
| 1347 | } |
| 1348 | const docsMapSources = [...read("web/lib/docs-map.ts").matchAll(/repoSource:\s*(\[[^\]]+\]|"[^"]+")/g)].flatMap( |
| 1349 | (m) => [...m[1].matchAll(/"([^"#]+)(?:#[^"]*)?"/g)].map((hit) => hit[1]), |
| 1350 | ); |
| 1351 | const featureDocSources = [...read("docs/features.toml").matchAll(/^\s*docs\s*=\s*"([^"#]+)(?:#[^"]*)?"/gm)].map( |
| 1352 | (m) => m[1], |
| 1353 | ); |
| 1354 | const publicSurfaceMatrix = JSON.parse(read("docs/public-surface-facts.json")); |
| 1355 | const matrixSources = []; |
| 1356 | (function collectSources(value) { |
| 1357 | if (Array.isArray(value)) value.forEach(collectSources); |
| 1358 | else if (value && typeof value === "object") { |
| 1359 | for (const [k, v] of Object.entries(value)) { |
| 1360 | if (k === "sources" || k === "creditSources") matrixSources.push(...v); |
| 1361 | else collectSources(v); |
| 1362 | } |
| 1363 | } |
| 1364 | })(publicSurfaceMatrix); |
| 1365 | const mustTriggerWebGates = [ |
| 1366 | ...new Set([ |
| 1367 | "web/package.json", |
| 1368 | "web/app/[locale]/page.tsx", |
| 1369 | "web/data/latest-published-release.json", |
| 1370 | "web/scripts/derive-facts.mjs", |
| 1371 | "docs/features.toml", |
| 1372 | "docs/contributors.json", |
| 1373 | "docs/public-surface-facts.json", |
| 1374 | "docs/cloud-facts/stable.json", |
| 1375 | "docs/cloud-facts/fixtures/envelope-stable-v7.json", |
| 1376 | "docs/i18n/README.zh-CN.md", |
| 1377 | "docs/zh_hans/INSTALL.md", |
| 1378 | "docs/zh_hans/GUIDE.md", |
| 1379 | "docs/zh_hans/MODES.md", |
| 1380 | "docs/RUNTIME_ROUTES.md", |
| 1381 | "CHANGELOG.md", |
| 1382 | "Cargo.toml", |
| 1383 | "CONTRIBUTING.md", |
| 1384 | "LICENSE", |
| 1385 | "README.md", |
| 1386 | "npm/codewhale/package.json", |
| 1387 | "npm/codewhale/README.md", |
| 1388 | "npm/codewhale/scripts/artifacts.js", |
| 1389 | "crates/config/assets/provider_descriptors.json", |
| 1390 | "crates/config/assets/models_dev.bundled.json", |
| 1391 | "crates/config/src/cloud_facts/keys.rs", |
| 1392 | "crates/config/src/app_mode.rs", |
| 1393 | "crates/sandbox/src/lib.rs", |
| 1394 | "crates/engine/src/tools/registry.rs", |
| 1395 | "crates/engine/src/core/engine/tool_catalog.rs", |
| 1396 | "crates/app-server/src/runtime_api.rs", |
| 1397 | "crates/app-server/src/runtime_web/target.mjs", |
| 1398 | "crates/palette/src/rgb.rs", |
| 1399 | "crates/cli/Cargo.toml", |
| 1400 | "crates/execpolicy/src/approval_mode.rs", |
| 1401 | "crates/runtime/src/config.rs", |
| 1402 | "crates/runtime/src/config/subagent_limits.rs", |
| 1403 | "crates/tui/src/tui/app.rs", |
| 1404 | "crates/tui/src/tui/app/init.rs", |
| 1405 | "scripts/export-design-tokens.py", |
| 1406 | "vendor/codewhale-design/tokens.json", |
| 1407 | "telemetry-ingest/src/schema.ts", |
| 1408 | ".github/workflows/web.yml", |
| 1409 | ".github/workflows/main-landing.yml", |
| 1410 | ...docsMapSources, |
| 1411 | ...featureDocSources, |
| 1412 | ...matrixSources, |
| 1413 | ]), |
| 1414 | ]; |
| 1415 | const webVerdicts = classifyLandingWeb(mustTriggerWebGates); |
| 1416 | for (const target of mustTriggerWebGates) { |
| 1417 | assert.equal(webVerdicts.get(target), "true", `${target} feeds the website or its tests and must trigger landing web gates`); |
| 1418 | } |
| 1419 | const nonWebPaths = [ |
| 1420 | "crates/core/src/lib.rs", |
| 1421 | "crates/engine/src/core/engine/turn_loop.rs", |
| 1422 | "crates/tui/src/main.rs", |
| 1423 | "scripts/sync-changelog.sh", |
| 1424 | ".github/workflows/ci.yml", |
| 1425 | "packaging/aur/PKGBUILD.in", |
| 1426 | ]; |
| 1427 | const nonWebVerdicts = classifyLandingWeb(nonWebPaths); |
| 1428 | for (const target of nonWebPaths) { |
| 1429 | assert.equal(nonWebVerdicts.get(target), "false", `${target} is unrelated to the website and must skip landing web gates`); |
| 1430 | } |
| 1431 | console.log(`Landing web gate path filter OK: ${mustTriggerWebGates.length} web inputs trigger, ${nonWebPaths.length} unrelated paths skip.`); |
| 1432 | |
| 1433 | const webWorkflow = read(".github/workflows/web.yml"); |
| 1434 | const webTriggerBlock = webWorkflow.slice( |
| 1435 | webWorkflow.indexOf("on:\n"), |
| 1436 | webWorkflow.indexOf("\n\npermissions:"), |
| 1437 | ); |
| 1438 | assert.match(webTriggerBlock, /^on:\n workflow_dispatch:(?:\n .*)*$/, "web.yml must stay workflow_dispatch-only"); |
| 1439 | assert.doesNotMatch(jobBlock(webWorkflow, "lint"), /^ if:/m, "web.yml lint job must run unconditionally on dispatch"); |
| 1440 | const webDeployBlock = jobBlock(webWorkflow, "deploy"); |
| 1441 | assert.match(webDeployBlock, /^ needs: lint$/m); |
| 1442 | assert.equal( |
| 1443 | evaluate(jobIf(webWorkflow, "deploy"), { |
| 1444 | github: { event_name: "workflow_dispatch", ref: "refs/heads/main" }, |
| 1445 | }), |
| 1446 | true, |
| 1447 | ); |
| 1448 | assert.equal( |
| 1449 | evaluate(jobIf(webWorkflow, "deploy"), { |
| 1450 | github: { event_name: "push", ref: "refs/heads/main" }, |
| 1451 | }), |
| 1452 | false, |
| 1453 | ); |
| 1454 | assert.equal( |
| 1455 | evaluate(jobIf(webWorkflow, "deploy"), { |
| 1456 | github: { event_name: "workflow_dispatch", ref: "refs/heads/release" }, |
| 1457 | }), |
| 1458 | false, |
| 1459 | ); |
| 1460 | assert.match(webDeployBlock, /^ concurrency:\n group: deploy-codewhale-web\n cancel-in-progress: false$/m); |
| 1461 | assert.match(webDeployBlock, /ref: \$\{\{ github\.sha \}\}\n\s+fetch-depth: 0/); |
| 1462 | assert.ok(webDeployBlock.indexOf("actions/checkout@") < webDeployBlock.indexOf("Verify expected commit")); |
| 1463 | assert.ok(webDeployBlock.indexOf("Verify expected commit") < webDeployBlock.indexOf("actions/setup-node@")); |
| 1464 | assert.match(webDeployBlock, /run: npm run check:deploy-env\n/); |
| 1465 | assert.match(webDeployBlock, /run: npm run deploy\n/); |
| 1466 | assert.doesNotMatch(webDeployBlock, /npm run build/); |
| 1467 | assert.match(webDeployBlock, /run: npm run check:deployed-facts -- --expected-revision "\$GITHUB_SHA"/); |
| 1468 | const webRefreshStep = namedStep(webDeployBlock, "Refresh published release facts"); |
| 1469 | assert.match(webRefreshStep, /CLOUDFLARE_API_TOKEN: ''/); |
| 1470 | assert.match(webRefreshStep, /node scripts\/sync-latest-release\.mjs/); |
| 1471 | assert.ok( |
| 1472 | webDeployBlock.indexOf("Refresh published release facts") < webDeployBlock.indexOf("run: npm run deploy\n"), |
| 1473 | "web.yml deploy must sync the published release record before building the OpenNext bundle", |
| 1474 | ); |
| 1475 | |
| 1476 | const releaseWebDeploy = jobBlock(release, "web_deploy"); |
| 1477 | assert.match(releaseWebDeploy, /^ needs: \[npm, release, resolve\]$/m); |
| 1478 | assert.equal(jobTimeout(release, "web_deploy"), 45); |
| 1479 | assert.match( |
| 1480 | releaseWebDeploy, |
| 1481 | /^ permissions:\n actions: write\n contents: read\n steps:/m, |
| 1482 | "release web_deploy needs only actions: write and contents: read", |
| 1483 | ); |
| 1484 | assert.doesNotMatch( |
| 1485 | releaseWebDeploy, |
| 1486 | /secrets\.|CLOUDFLARE_|contents:\s*write|packages:\s*write|id-token:\s*write|set -x/, |
| 1487 | "release web_deploy must hold no Cloudflare or release secrets and no extra write scopes", |
| 1488 | ); |
| 1489 | assert.match( |
| 1490 | releaseWebDeploy, |
| 1491 | /^ concurrency:\n group: release-web-deploy-\$\{\{ needs\.resolve\.outputs\.tag \}\}\n cancel-in-progress: false$/m, |
| 1492 | ); |
| 1493 | const webDeployGuard = jobIf(release, "web_deploy").replace(/^\$\{\{\s*(.*?)\s*\}\}$/, "$1"); |
| 1494 | const webDeployRuns = ({ |
| 1495 | repo = "codewhale-hq/Codewhale", |
| 1496 | ref = "refs/tags/v1.2.3", |
| 1497 | prerelease = "false", |
| 1498 | release: rel = "success", |
| 1499 | npm = "success", |
| 1500 | isCancelled = false, |
| 1501 | } = {}) => |
| 1502 | evaluate(webDeployGuard, { |
| 1503 | cancelled: () => isCancelled, |
| 1504 | format: (template, ...args) => template.replace(/\{(\d+)\}/g, (_, i) => args[Number(i)]), |
| 1505 | github: { repository: repo, ref }, |
| 1506 | needs: { release: { result: rel }, npm: { result: npm }, resolve: { outputs: { tag: "v1.2.3", prerelease } } }, |
| 1507 | }); |
| 1508 | assert.equal(webDeployRuns(), true, "release website deploy must run for a stable release of this repository"); |
| 1509 | assert.equal(webDeployRuns({ repo: "someone/Codewhale" }), false, "a fork must never trigger the website deploy"); |
| 1510 | assert.equal(webDeployRuns({ prerelease: "true" }), false, "a prerelease must never trigger the website deploy"); |
| 1511 | assert.equal(webDeployRuns({ ref: "refs/heads/main" }), false, "a branch ref must never trigger the website deploy"); |
| 1512 | assert.equal(webDeployRuns({ ref: "refs/tags/v9.9.9" }), false, "a mismatched tag ref must never trigger the website deploy"); |
| 1513 | assert.equal(webDeployRuns({ release: "failure" }), false, "website deploy requires a successful GitHub Release job"); |
| 1514 | assert.equal(webDeployRuns({ npm: "failure" }), false, "website deploy requires a successful npm job"); |
| 1515 | assert.equal(webDeployRuns({ isCancelled: true }), false, "cancelled runs must not trigger the website deploy"); |
| 1516 | |
| 1517 | const webDispatchStep = namedStep(releaseWebDeploy, "Dispatch web.yml on main and wait for deploy"); |
| 1518 | const webLiveVerifyStep = namedStep(releaseWebDeploy, "Verify live site names the released version"); |
| 1519 | assert.ok( |
| 1520 | releaseWebDeploy.indexOf(" - name: Dispatch web.yml on main and wait for deploy\n") < |
| 1521 | releaseWebDeploy.indexOf(" - name: Verify live site names the released version\n"), |
| 1522 | "live site check must follow the web.yml deploy wait", |
| 1523 | ); |
| 1524 | assert.doesNotMatch(webDispatchStep.split("run: |")[1], /\$\{\{/, "dispatch script must pass workflow values via env"); |
| 1525 | assert.match(webDispatchStep, /gh workflow run web\.yml --repo "\$\{GITHUB_REPOSITORY\}" --ref main -f expected_sha="\$\{main_sha\}"/); |
| 1526 | assert.match(webDispatchStep, /compare\/\$\{RELEASE_SHA\}\.\.\.\$\{main_sha\}/); |
| 1527 | assert.match( |
| 1528 | webDispatchStep, |
| 1529 | /\.name == "Lint & Type Check" and \.conclusion == "success"[\s\S]*\.name == "Deploy to Cloudflare" and \.conclusion == "success"/, |
| 1530 | ); |
| 1531 | assert.doesNotMatch(webLiveVerifyStep.split("run: |")[1], /\$\{\{/, "live version check must pass VERSION via env"); |
| 1532 | assert.match(webLiveVerifyStep, /VERSION: \$\{\{ needs\.resolve\.outputs\.version \}\}/); |
| 1533 | assert.match(webLiveVerifyStep, /expected="Version \$\{VERSION\} is released"/); |
| 1534 | assert.match(webLiveVerifyStep, /https:\/\/codewhale\.net\/en/); |
| 1535 | assert.match(webLiveVerifyStep, /grep -Fq "\$\{expected\}"/); |
| 1536 | assert.match(webLiveVerifyStep, /for attempt in \$\(seq 1 24\); do/); |
| 1537 | assert.match(webLiveVerifyStep, /exit 1\s*$/); |
| 1538 | |
| 1539 | const catalogRefresh = read(".github/workflows/catalog-refresh.yml"); |
| 1540 | const discoverStep = namedStep(catalogRefresh, "Propose new models, re-lock and render"); |
| 1541 | assert.match( |
| 1542 | discoverStep, |
| 1543 | /run: \|\n\s+set -euo pipefail\n[\s\S]*seed discover[\s\S]*\| tee /, |
| 1544 | "catalog-refresh must enable pipefail before piping seed discover into tee", |
| 1545 | ); |
| 1546 | |
| 1547 | console.log( |
| 1548 | "Workflow contracts OK: 6-target/12-asset single-runtime nightly and exact-head 8-target/38-asset release candidate.", |
| 1549 | ); |
| 1550 |