⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
ci: scope BrowserStack runs
justin8af5989e84d5
diff --git a/.github/workflows/browserstack.yml b/.github/workflows/browserstack.ymlindex 0bd3fd2cf..6e415c3e3 100644--- a/.github/workflows/browserstack.yml+++ b/.github/workflows/browserstack.yml@@ -4,8 +4,11 @@ on:push:branches: [main]workflow_dispatch:+ schedule:+ - cron: '43 5 * * *'permissions:+ actions: readcontents: readconcurrency:@@ -22,7 +25,21 @@ jobs:KANEO_E2E_TLS: "true"COMPOSE_FILE: tests/e2e/compose.yml:tests/e2e/compose.tls.ymlsteps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7+ with:+ node-version: 24.19.0+ package-manager-cache: false+ - name: Classify BrowserStack changes+ id: classify+ env:+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ run: node scripts/ci/browserstack-change-classification.mjs+- name: Check BrowserStack credentials+ if: steps.classify.outputs.skip_browserstack != 'true'env:BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}@@ -32,20 +49,17 @@ jobs:exit 1fi- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- persist-credentials: false- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ if: steps.classify.outputs.skip_browserstack != 'true'with:version: 10.32.1- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7- with:- node-version: 24.19.0- package-manager-cache: false- run: pnpm --dir tests/e2e install --frozen-lockfile --ignore-scripts+ if: steps.classify.outputs.skip_browserstack != 'true'- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4+ if: steps.classify.outputs.skip_browserstack != 'true'- name: Build this revision of Kaneo+ if: steps.classify.outputs.skip_browserstack != 'true'uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7with:context: .@@ -56,31 +70,34 @@ jobs:cache-to: type=gha,mode=max,scope=browserstack- name: Create disposable test certificate+ if: steps.classify.outputs.skip_browserstack != 'true'run: |mkdir -p .cache/e2e-tlsopenssl req -x509 -newkey rsa:2048 -nodes -days 1 \-keyout .cache/e2e-tls/key.pem -out .cache/e2e-tls/cert.pem \-subj '/CN=bs-local.com' -addext 'subjectAltName=DNS:bs-local.com'- name: Start disposable test instance+ if: steps.classify.outputs.skip_browserstack != 'true'run: docker compose up --no-build --wait --wait-timeout 180- name: Run browser smoke tests+ if: steps.classify.outputs.skip_browserstack != 'true'env:BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}run: pnpm test:browserstack- name: Collect instance logs- if: failure()+ if: failure() && steps.classify.outputs.skip_browserstack != 'true'run: |mkdir -p .cache/e2edocker compose logs --no-color > .cache/e2e/instance.log- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7- if: always()+ if: always() && steps.classify.outputs.skip_browserstack != 'true'with:name: browserstack-resultspath: .cache/e2e/if-no-files-found: ignoreretention-days: 7- name: Stop disposable test instance- if: always()+ if: always() && steps.classify.outputs.skip_browserstack != 'true'run: docker compose down --volumesdiff --git a/scripts/ci/README.md b/scripts/ci/README.mdindex 4feae9f9e..41d7aacbc 100644--- a/scripts/ci/README.md+++ b/scripts/ci/README.md@@ -5,7 +5,10 @@ It checks formatting, translations, OpenAPI, types, unit/integration tests, siteThe bundled image runs against disposable PostgreSQL and MinIO services for browser, realtime, and upgrade tests.Runtime failures retain container logs, a browser screenshot, and a Playwright trace for seven days.PRs also run the independent **Chromium smoke tests** job unless change detection confirms an allowlisted docs/site-only change.-BrowserStack runs separately for main pushes and manual runs on main.+BrowserStack runs separately for main pushes, manual runs on main, and daily at 05:43 UTC.+`browserstack-change-classification.mjs` skips Docker/cloud work only for proven runtime-neutral changes since a successful full validation less than 24 hours old.+Skipped runs do not refresh that clock.+Manual runs, scheduled runs, and uncertain evidence run both engines in full.The disposable S3 fixture pins Bitnami's archived MinIO 2025.7.23 image by itsmulti-platform digest because the upstream public registries no longer servediff --git a/scripts/ci/browserstack-change-classification.mjs b/scripts/ci/browserstack-change-classification.mjsnew file mode 100644index 000000000..c683b97af--- /dev/null+++ b/scripts/ci/browserstack-change-classification.mjs@@ -0,0 +1,278 @@+import { appendFile, readFile } from "node:fs/promises";+import { pathToFileURL } from "node:url";+import { areRuntimeNeutralFiles } from "./runtime-neutral-changes.mjs";++const API = "https://api.github.com";+const WORKFLOW = ".github/workflows/browserstack.yml";+const MAX_AGE = 86_400_000;+const MAX_RUNS = 20;+const MAX_JOB_READS = 5;+const DEADLINE = 10_000;+const SHA = /^[0-9a-f]{40}$/i;+const neutral = (reason = "insufficient-evidence") => ({ skip: false, reason });+const shaValid = (value) => typeof value === "string" && SHA.test(value);+const positive = (value) =>+ (typeof value === "number" ||+ (typeof value === "string" && /^[1-9][0-9]*$/.test(value))) &&+ Number.isSafeInteger(Number(value)) &&+ Number(value) > 0;++async function body(response) {+ if (!response || response.status !== 200 || response.redirected)+ throw new Error("unavailable");+ return response.json();+}+function runValid(run, repo) {+ return (+ run &&+ positive(run.id) &&+ positive(run.run_attempt) &&+ shaValid(run.head_sha) &&+ run.head_branch === "main" &&+ [WORKFLOW, `${WORKFLOW}@refs/heads/main`].includes(run.path) &&+ ["push", "workflow_dispatch", "schedule"].includes(run.event) &&+ run.status === "completed" &&+ run.conclusion === "success" &&+ run.repository?.full_name === repo &&+ run.head_repository?.full_name === repo+ );+}+function jobValid(job, run) {+ return (+ job &&+ positive(job.id) &&+ job.run_id === run.id &&+ job.run_attempt === run.run_attempt &&+ job.head_sha === run.head_sha &&+ job.name === "smoke" &&+ job.status === "completed" &&+ job.conclusion === "success" &&+ Array.isArray(job.steps)+ );+}+function fullCompletion(job) {+ const steps = job.steps.filter(+ (step) => step?.name === "Run browser smoke tests",+ );+ if (+ steps.length !== 1 ||+ steps[0].status !== "completed" ||+ steps[0].conclusion !== "success"+ )+ return null;+ const time = Date.parse(steps[0].completed_at);+ return Number.isFinite(time) ? time : null;+}+function cheapCompletion(job) {+ const classify = job.steps.filter(+ (step) => step?.name === "Classify BrowserStack changes",+ );+ const test = job.steps.filter(+ (step) => step?.name === "Run browser smoke tests",+ );+ return (+ classify.length === 1 &&+ classify[0].status === "completed" &&+ classify[0].conclusion === "success" &&+ test.length === 1 &&+ test[0].status === "completed" &&+ test[0].conclusion === "skipped"+ );+}+function pushValid(input) {+ return (+ input.eventName === "push" &&+ input.ref === "refs/heads/main" &&+ shaValid(input.sha) &&+ positive(input.runId) &&+ positive(input.runAttempt) &&+ Number(input.runAttempt) === 1 &&+ input.event?.after === input.sha &&+ input.event.ref === input.ref &&+ input.event.forced === false &&+ input.event.deleted === false &&+ input.event.repository?.full_name === input.repository &&+ typeof input.repository === "string" &&+ /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(input.repository)+ );+}+function changes(compare, baseline, head) {+ if (+ !compare ||+ compare.truncated === true ||+ compare.incomplete_results === true ||+ compare.status !== "ahead" ||+ !Number.isSafeInteger(compare.ahead_by) ||+ compare.ahead_by < 1 ||+ compare.behind_by !== 0 ||+ !Number.isSafeInteger(compare.total_commits) ||+ compare.total_commits < 1 ||+ compare.total_commits > 250 ||+ compare.ahead_by !== compare.total_commits ||+ !Array.isArray(compare.commits) ||+ compare.commits.length !== compare.total_commits ||+ compare.base_commit?.sha !== baseline ||+ compare.merge_base_commit?.sha !== baseline ||+ compare.commits.at(-1)?.sha !== head ||+ !Array.isArray(compare.files) ||+ compare.files.length === 0 ||+ compare.files.length >= 300+ )+ return null;+ for (const file of compare.files) {+ if (+ !file ||+ typeof file.filename !== "string" ||+ !file.filename ||+ !["added", "modified", "removed", "renamed"].includes(file.status)+ )+ return null;+ if (+ file.previous_filename !== undefined &&+ (typeof file.previous_filename !== "string" || !file.previous_filename)+ )+ return null;+ if (file.status === "renamed" && typeof file.previous_filename !== "string")+ return null;+ }+ return compare.files;+}++async function classify(input) {+ if (!input || !pushValid(input)) return neutral("non-qualifying-context");+ if (+ typeof input.request !== "function" ||+ typeof input.token !== "string" ||+ !input.token ||+ !Number.isFinite(input.now)+ )+ return neutral();+ const deadline = Date.now() + DEADLINE;+ let requests = 0;+ const root = `/repos/${input.repository}`;+ const get = async (path) => {+ if (++requests > MAX_JOB_READS + 2 || Date.now() >= deadline)+ throw new Error("budget");+ const url = `${API}${path}`;+ if (new URL(url).origin !== API || !path.startsWith(`${root}/`))+ throw new Error("route");+ return body(+ await input.request(url, {+ headers: {+ authorization: `Bearer ${input.token}`,+ accept: "application/vnd.github+json",+ "x-github-api-version": "2022-11-28",+ },+ redirect: "error",+ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),+ }),+ );+ };+ try {+ const history = await get(+ `${root}/actions/workflows/browserstack.yml/runs?branch=main&per_page=${MAX_RUNS}`,+ );+ if (+ !Array.isArray(history.workflow_runs) ||+ history.workflow_runs.length === 0 ||+ history.workflow_runs.length > MAX_RUNS ||+ !Number.isSafeInteger(history.total_count) ||+ history.total_count < history.workflow_runs.length+ )+ return neutral("history-incomplete");+ const records = history.workflow_runs.filter(+ (run) => run?.id !== Number(input.runId),+ );+ if (+ records.length !==+ history.workflow_runs.length -+ (history.workflow_runs.some((run) => run?.id === Number(input.runId))+ ? 1+ : 0)+ )+ return neutral("history-malformed");+ let baseline = null;+ let jobsRead = 0;+ for (const run of records) {+ if (!runValid(run, input.repository))+ return neutral("uncertain-recent-run");+ if (++jobsRead > MAX_JOB_READS) return neutral("history-bound");+ const result = await get(+ `${root}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`,+ );+ if (+ !Array.isArray(result.jobs) ||+ result.total_count !== 1 ||+ result.jobs.length !== 1+ )+ return neutral("jobs-incomplete");+ const job = result.jobs[0];+ if (!jobValid(job, run)) return neutral("job-mismatch");+ const finished = fullCompletion(job);+ if (finished !== null) {+ if (finished > input.now || input.now - finished >= MAX_AGE)+ return neutral("stale-baseline");+ baseline = run;+ break;+ }+ if (!cheapCompletion(job)) return neutral("missing-full-proof");+ }+ if (!baseline) return neutral("baseline-unavailable");+ const comparison = await get(+ `${root}/compare/${baseline.head_sha}...${input.sha}`,+ );+ const files = changes(comparison, baseline.head_sha, input.sha);+ if (!files || !areRuntimeNeutralFiles(files))+ return neutral("changes-require-full-validation");+ return {+ skip: true,+ reason: "validated-neutral-changes",+ baselineSha: baseline.head_sha,+ };+ } catch {+ return neutral("api-or-budget-error");+ }+}++export async function classifyBrowserStack(input) {+ try {+ return await classify(input);+ } catch {+ return neutral("invalid-input");+ }+}++async function main() {+ const output = process.env.GITHUB_OUTPUT;+ if (!output) throw new Error("GITHUB_OUTPUT is required");+ let skip = false;+ try {+ const event = JSON.parse(+ await readFile(process.env.GITHUB_EVENT_PATH, "utf8"),+ );+ const result = await classifyBrowserStack({+ eventName: process.env.GITHUB_EVENT_NAME,+ ref: process.env.GITHUB_REF,+ sha: process.env.GITHUB_SHA,+ runId: process.env.GITHUB_RUN_ID,+ runAttempt: process.env.GITHUB_RUN_ATTEMPT,+ event,+ repository: process.env.GITHUB_REPOSITORY,+ token: process.env.GITHUB_TOKEN,+ now: Date.now(),+ request: globalThis.fetch,+ });+ skip = result.skip === true;+ console.log(+ `BrowserStack classification: ${skip ? "proven-neutral" : "full-validation"}`,+ );+ } catch {+ console.log("BrowserStack classification: full-validation");+ }+ await appendFile(output, `skip_browserstack=${skip}\n`);+}+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)+ await main().catch(() => {+ console.error("BrowserStack classification failed");+ process.exitCode = 1;+ });diff --git a/scripts/ci/browserstack-change-classification.test.mjs b/scripts/ci/browserstack-change-classification.test.mjsnew file mode 100644index 000000000..c570c2355--- /dev/null+++ b/scripts/ci/browserstack-change-classification.test.mjs@@ -0,0 +1,568 @@+import test from "node:test";+import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import { classifyBrowserStack } from "./browserstack-change-classification.mjs";++const sha = (char) => char.repeat(40);+const now = Date.parse("2026-10-24T12:00:00Z");+const push = {+ ref: "refs/heads/main",+ after: sha("b"),+ before: sha("a"),+ forced: false,+ deleted: false,+ repository: { full_name: "owner/repo" },+};+const base = {+ eventName: "push",+ ref: "refs/heads/main",+ sha: sha("b"),+ runId: "20",+ runAttempt: "1",+ event: push,+ repository: "owner/repo",+ token: "secret",+ now,+};+function response(value, status = 200) {+ return Response.json(value, { status });+}+function run(overrides = {}) {+ return {+ id: 10,+ run_number: 10,+ run_attempt: 1,+ name: "BrowserStack",+ event: "push",+ status: "completed",+ conclusion: "success",+ head_branch: "main",+ head_sha: sha("a"),+ path: ".github/workflows/browserstack.yml",+ repository: { full_name: "owner/repo" },+ head_repository: { full_name: "owner/repo" },+ ...overrides,+ };+}+function jobs(+ id = 10,+ attempt = 1,+ steps = [+ {+ name: "Run browser smoke tests",+ status: "completed",+ conclusion: "success",+ completed_at: new Date(now - 60_000).toISOString(),+ },+ ],+ overrides = {},+) {+ return {+ total_count: 1,+ jobs: [+ {+ id: 99,+ run_id: id,+ run_attempt: attempt,+ head_sha: sha("a"),+ status: "completed",+ conclusion: "success",+ name: "smoke",+ steps,+ ...overrides,+ },+ ],+ };+}+function neutralJobs(id, attempt) {+ return jobs(+ id,+ attempt,+ [+ {+ name: "Classify BrowserStack changes",+ status: "completed",+ conclusion: "success",+ completed_at: new Date(now - 30_000).toISOString(),+ },+ {+ name: "Run browser smoke tests",+ status: "completed",+ conclusion: "skipped",+ completed_at: null,+ },+ ],+ { conclusion: "success", head_sha: sha("b") },+ );+}+function fakeApi({+ runs = [run()],+ compare = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("a") },+ merge_base_commit: { sha: sha("a") },+ commits: [{ sha: sha("b") }],+ files: [{ filename: "docs/page.md", status: "modified" }],+ },+ jobsById = new Map([[10, jobs()]]),+ mutate = () => {},+} = {}) {+ return async (url, options = {}) => {+ mutate(url);+ assert.equal(options.redirect, "error");+ const parsed = new URL(url);+ assert.equal(parsed.origin, "https://api.github.com");+ if (parsed.pathname.endsWith("/actions/workflows/browserstack.yml/runs"))+ return response({ total_count: runs.length, workflow_runs: runs });+ const jobMatch = parsed.pathname.match(+ /\/actions\/runs\/(\d+)\/attempts\/(\d+)\/jobs$/,+ );+ if (jobMatch)+ return response(+ jobsById.get(Number(jobMatch[1])) ??+ jobs(Number(jobMatch[1]), Number(jobMatch[2])),+ );+ if (parsed.pathname.includes("/compare/")) return response(compare);+ throw new Error(`Unexpected route: ${parsed.pathname}`);+ };+}++test("fresh successful full baseline + complete docs/site/sponsor diff skips", async () => {+ assert.deepEqual(+ await classifyBrowserStack({ ...base, request: fakeApi() }),+ { skip: true, reason: "validated-neutral-changes", baselineSha: sha("a") },+ );+});++test("runtime/config/lock/mixed/hidden changes and unsafe rename run full", async () => {+ for (const filename of [+ "apps/api/main.ts",+ "package.json",+ "pnpm-lock.yaml",+ "apps/site/.npmrc",+ "apps/site/constants/other.json",+ ]) {+ const compare = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("a") },+ merge_base_commit: { sha: sha("a") },+ commits: [{ sha: sha("b") }],+ files: [{ filename, status: "modified" }],+ };+ assert.equal(+ (await classifyBrowserStack({ ...base, request: fakeApi({ compare }) }))+ .skip,+ false,+ filename,+ );+ }+ for (const file of [+ { filename: "docs/a.md", status: "renamed" },+ {+ filename: "docs/a.md",+ previous_filename: "apps/api/a.md",+ status: "renamed",+ },+ { filename: "docs/a.md", status: "copied" },+ ]) {+ const compare = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("a") },+ merge_base_commit: { sha: sha("a") },+ commits: [{ sha: sha("b") }],+ files: [file],+ };+ assert.equal(+ (await classifyBrowserStack({ ...base, request: fakeApi({ compare }) }))+ .skip,+ false,+ );+ }+});++test("manual/scheduled/rerun/forced/missing/malformed contexts run full without API", async () => {+ for (const ctx of [+ { eventName: "workflow_dispatch" },+ { eventName: "schedule" },+ { runAttempt: "2" },+ { ref: "refs/heads/other" },+ { event: { ...push, forced: true } },+ { event: { ...push, deleted: true } },+ { event: { ...push, after: "bad" } },+ { event: { ...push, repository: {} } },+ { runId: "bad" },+ ])+ assert.equal(+ (+ await classifyBrowserStack({+ ...base,+ ...ctx,+ request: async () => {+ throw Error("unexpected API");+ },+ })+ ).skip,+ false,+ JSON.stringify(ctx),+ );+});++test("prior cheap green run does not refresh full validation clock", async () => {+ const neutral = run({ id: 11, head_sha: sha("b") });+ const stale = jobs(10, 1, [+ {+ name: "Run browser smoke tests",+ status: "completed",+ conclusion: "success",+ completed_at: new Date(now - 86_400_000).toISOString(),+ },+ ]);+ const api = fakeApi({+ runs: [neutral, run()],+ jobsById: new Map([+ [11, neutralJobs(11, 1)],+ [10, stale],+ ]),+ });+ assert.equal(+ (await classifyBrowserStack({ ...base, request: api })).skip,+ false,+ );+});++test("a cheap green run can lead to a fresh actual full baseline", async () => {+ const neutral = run({ id: 11, head_sha: sha("b") });+ const request = fakeApi({+ runs: [neutral, run()],+ jobsById: new Map([+ [11, neutralJobs(11, 1)],+ [10, jobs()],+ ]),+ });+ assert.equal((await classifyBrowserStack({ ...base, request })).skip, true);+});++test("real bare workflow paths and exact main-ref paths both identify full proof", async () => {+ for (const path of [+ ".github/workflows/browserstack.yml",+ ".github/workflows/browserstack.yml@refs/heads/main",+ ])+ assert.equal(+ (+ await classifyBrowserStack({+ ...base,+ request: fakeApi({ runs: [run({ path })] }),+ })+ ).skip,+ true,+ path,+ );+});++test("cancelled scheduled and failed manual runs force a replacement full run", async () => {+ const path = ".github/workflows/browserstack.yml@refs/heads/main";+ for (const event of ["schedule", "workflow_dispatch"])+ for (const conclusion of ["cancelled", "failure"])+ assert.equal(+ (+ await classifyBrowserStack({+ ...base,+ request: fakeApi({+ runs: [run({ id: 11, event, conclusion, path }), run({ path })],+ }),+ })+ ).skip,+ false,+ `${event}:${conclusion}`,+ );+});++test("mismatched push ref and non-numeric run identity cannot authorize a skip", async () => {+ for (const context of [+ { event: { ...push, ref: "refs/heads/other" } },+ { runId: true },+ { runAttempt: true },+ ]) {+ const request = fakeApi({+ runs: [+ run({ path: ".github/workflows/browserstack.yml@refs/heads/main" }),+ ],+ });+ assert.equal(+ (await classifyBrowserStack({ ...base, ...context, request })).skip,+ false,+ );+ }+});++test("inconsistent ahead count and explicit truncation stay full", async () => {+ const compare = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("a") },+ merge_base_commit: { sha: sha("a") },+ commits: [{ sha: sha("b") }],+ files: [{ filename: "docs/a.md", status: "modified" }],+ };+ for (const change of [+ { ahead_by: 2 },+ { truncated: true },+ { incomplete_results: true },+ ]) {+ const request = fakeApi({+ runs: [+ run({ path: ".github/workflows/browserstack.yml@refs/heads/main" }),+ ],+ compare: { ...compare, ...change },+ });+ assert.equal(+ (await classifyBrowserStack({ ...base, request })).skip,+ false,+ );+ }+});++test("a missing HTTP status cannot authorize a skip", async () => {+ const api = fakeApi({+ runs: [run({ path: ".github/workflows/browserstack.yml@refs/heads/main" })],+ });+ const request = async (...args) => {+ const result = await api(...args);+ return { redirected: false, json: () => result.json() };+ };+ assert.equal((await classifyBrowserStack({ ...base, request })).skip, false);+});++test("manual and scheduled full validations can supply the actual baseline", async () => {+ for (const event of ["workflow_dispatch", "schedule"]) {+ const comparison = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("c") },+ merge_base_commit: { sha: sha("c") },+ commits: [{ sha: sha("b") }],+ files: [{ filename: "docs/a.md", status: "modified" }],+ };+ const request = fakeApi({+ runs: [run({ id: 11, event, head_sha: sha("c") }), run()],+ jobsById: new Map([[11, jobs(11, 1, undefined, { head_sha: sha("c") })]]),+ compare: comparison,+ });+ const result = await classifyBrowserStack({ ...base, request });+ assert.equal(result.skip, true);+ assert.equal(result.baselineSha, sha("c"));+ }+});++test("older run-history pages are unnecessary after complete immutable source proof", async () => {+ const records = [+ run({ id: 10000, created_at: new Date(now - 120_000).toISOString() }),+ ...Array.from({ length: 19 }, (_, index) =>+ run({+ id: 9999 - index,+ conclusion: "cancelled",+ created_at: new Date(now - 180_000 - index * 60_000).toISOString(),+ }),+ ),+ ];+ const api = fakeApi({+ runs: records,+ jobsById: new Map([[10000, jobs(10000)]]),+ });+ const request = async (url, options) => {+ const result = await api(url, options);+ if (new URL(url).pathname.endsWith("/runs")) {+ const history = await result.json();+ return response({ ...history, total_count: 2000 });+ }+ return result;+ };+ assert.equal(+ (await classifyBrowserStack({ ...base, runId: "10001", request })).skip,+ true,+ );+});++test("cancelled or failed latest attempt makes evidence uncertain and runs full", async () => {+ for (const conclusion of ["cancelled", "failure"]) {+ const latest = run({ id: 11, head_sha: sha("b"), conclusion });+ assert.equal(+ (+ await classifyBrowserStack({+ ...base,+ request: fakeApi({ runs: [latest, run()] }),+ })+ ).skip,+ false,+ conclusion,+ );+ }+});++test("old, missing, future and exactly-24-hour baseline time run full", async () => {+ for (const completedAt of [+ new Date(now - 86_400_001).toISOString(),+ new Date(now - 86_400_000).toISOString(),+ new Date(now + 1).toISOString(),+ null,+ ]) {+ const proof = jobs(10, 1, [+ {+ name: "Run browser smoke tests",+ status: "completed",+ conclusion: "success",+ completed_at: completedAt,+ },+ ]);+ assert.equal(+ (+ await classifyBrowserStack({+ ...base,+ request: fakeApi({ jobsById: new Map([[10, proof]]) }),+ })+ ).skip,+ false,+ String(completedAt),+ );+ }+});++test("API denial, malformed responses, incomplete or mismatched job and exhausted history run full", async () => {+ for (const request of [+ async () => response({}, 403),+ async () => ({+ ok: true,+ status: 200,+ json: async () => {+ throw new Error("bad JSON");+ },+ }),+ ])+ assert.equal(+ (await classifyBrowserStack({ ...base, request })).skip,+ false,+ );+ const cases = [+ { jobsById: new Map([[10, { total_count: 1, jobs: [] }]]) },+ { jobsById: new Map([[10, jobs(11, 1)]]) },+ { jobsById: new Map([[10, jobs(10, 2)]]) },+ {+ runs: Array.from({ length: 20 }, (_, i) =>+ run({ id: 100 + i, conclusion: "skipped" }),+ ),+ },+ { runs: [run({ path: ".github/workflows/other.yml@refs/heads/main" })] },+ { runs: [run({ head_repository: { full_name: "fork/repo" } })] },+ ];+ for (const input of cases)+ assert.equal(+ (await classifyBrowserStack({ ...base, request: fakeApi(input) })).skip,+ false,+ );+});++test("CLI emits explicit false and exits successfully for manual/schedule fallbacks without network", async () => {+ for (const eventName of ["workflow_dispatch", "schedule"]) {+ const directory = await mkdtemp(join(tmpdir(), "browserstack-cli-"));+ try {+ const eventPath = join(directory, "event.json");+ const outputPath = join(directory, "output.txt");+ await writeFile(eventPath, JSON.stringify({}));+ const child = spawnSync(+ process.execPath,+ [+ fileURLToPath(+ new URL(+ "./browserstack-change-classification.mjs",+ import.meta.url,+ ),+ ),+ ],+ {+ encoding: "utf8",+ env: {+ ...process.env,+ GITHUB_EVENT_NAME: eventName,+ GITHUB_REF: "refs/heads/main",+ GITHUB_SHA: sha("b"),+ GITHUB_RUN_ID: "20",+ GITHUB_RUN_ATTEMPT: "1",+ GITHUB_EVENT_PATH: eventPath,+ GITHUB_REPOSITORY: "owner/repo",+ GITHUB_OUTPUT: outputPath,+ },+ },+ );+ assert.equal(child.status, 0, child.stderr);+ assert.equal(+ await readFile(outputPath, "utf8"),+ "skip_browserstack=false\n",+ );+ assert.match(child.stdout, /full-validation/);+ } finally {+ await rm(directory, { recursive: true });+ }+ }+});++test("comparison divergence, incorrect revision/count, 300 files and empty files run full", async () => {+ const valid = {+ status: "ahead",+ ahead_by: 1,+ behind_by: 0,+ total_commits: 1,+ base_commit: { sha: sha("a") },+ merge_base_commit: { sha: sha("a") },+ commits: [{ sha: sha("b") }],+ files: [{ filename: "docs/a.md", status: "modified" }],+ };+ const cases = [+ { ...valid, status: "diverged", behind_by: 1 },+ { ...valid, base_commit: { sha: sha("c") } },+ { ...valid, merge_base_commit: { sha: sha("c") } },+ { ...valid, total_commits: 251 },+ { ...valid, total_commits: 2 },+ { ...valid, commits: [{ sha: sha("c") }] },+ {+ ...valid,+ files: Array.from({ length: 300 }, () => ({+ filename: "docs/a.md",+ status: "modified",+ })),+ },+ { ...valid, files: [] },+ {+ ...valid,+ files: [+ {+ filename: "docs/a.md",+ status: "added",+ previous_filename: "apps/api/a",+ },+ ],+ },+ ];+ for (const compare of cases)+ assert.equal(+ (await classifyBrowserStack({ ...base, request: fakeApi({ compare }) }))+ .skip,+ false,+ );+});diff --git a/scripts/ci/pr-change-classification.mjs b/scripts/ci/pr-change-classification.mjsindex 65470c10d..c0001ab79 100644--- a/scripts/ci/pr-change-classification.mjs+++ b/scripts/ci/pr-change-classification.mjs@@ -1,26 +1,9 @@import { readFile } from "node:fs/promises";import { appendFile } from "node:fs/promises";import { pathToFileURL } from "node:url";+import { areRuntimeNeutralFiles } from "./runtime-neutral-changes.mjs";const expensive = ["integration", "storage", "docker-build", "split-images"];-const configName =- /(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?|pnpm-workspace\.yaml|turbo\.json|vite\.config\.[^/]+|next\.config\.[^/]+|tsconfig[^/]*\.json|Dockerfile(?:\.[^/]*)?|docker-compose[^/]*\.ya?ml|Makefile|.*\.config\.[^/]+|.*\.ya?ml|.*\.toml|.*\.json|.*\.lock)$/i;--function allowedPath(path) {- if (- typeof path !== "string" ||- !path ||- path.startsWith("/") ||- path.split("/").includes("..")- )- return false;- if (path.split("/").some((segment) => segment.startsWith("."))) return false;- if (configName.test(path) && path !== "apps/site/constants/sponsors.json")- return false;- return (- path === "README.md" || /^(docs|apps\/docs|apps\/site)\/[^/].*$/.test(path)- );-}export function classifyChanges({ eventName, files, complete, error = false }) {const full = { skipExpensive: false };@@ -32,26 +15,7 @@ export function classifyChanges({ eventName, files, complete, error = false }) {files.length === 0)return full;- for (const file of files) {- if (typeof file === "string") {- if (!allowedPath(file)) return full;- continue;- }- if (!file || typeof file !== "object" || !allowedPath(file.filename))- return full;- if (!new Set(["added", "modified", "removed", "renamed"]).has(file.status))- return full;- if (file.status === "renamed" && !allowedPath(file.previous_filename))- return full;- if (- file.previous_filename !== undefined &&- !allowedPath(file.previous_filename)- )- return full;- if (file.status === "renamed" && typeof file.previous_filename !== "string")- return full;- }- return { skipExpensive: true };+ return areRuntimeNeutralFiles(files) ? { skipExpensive: true } : full;}export function assessGate({ eventName, skipExpensive, jobs }) {diff --git a/scripts/ci/runtime-neutral-changes.mjs b/scripts/ci/runtime-neutral-changes.mjsnew file mode 100644index 000000000..b0eee6a40--- /dev/null+++ b/scripts/ci/runtime-neutral-changes.mjs@@ -0,0 +1,49 @@+const configName =+ /(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?|pnpm-workspace\.yaml|turbo\.json|vite\.config\.[^/]+|next\.config\.[^/]+|tsconfig[^/]*\.json|Dockerfile(?:\.[^/]*)?|docker-compose[^/]*\.ya?ml|Makefile|.*\.config\.[^/]+|.*\.ya?ml|.*\.toml|.*\.json|.*\.lock)$/i;++export function isRuntimeNeutralPath(path) {+ if (+ typeof path !== "string" ||+ !path ||+ path.startsWith("/") ||+ path.split("/").includes("..")+ )+ return false;+ if (path.split("/").some((segment) => segment.startsWith("."))) return false;+ if (configName.test(path) && path !== "apps/site/constants/sponsors.json")+ return false;+ return (+ path === "README.md" || /^(docs|apps\/docs|apps\/site)\/[^/].*$/.test(path)+ );+}++export function areRuntimeNeutralFiles(files) {+ if (!Array.isArray(files) || files.length === 0) return false;+ for (const file of files) {+ if (typeof file === "string") {+ if (!isRuntimeNeutralPath(file)) return false;+ continue;+ }+ if (+ !file ||+ typeof file !== "object" ||+ !isRuntimeNeutralPath(file.filename)+ )+ return false;+ if (!new Set(["added", "modified", "removed", "renamed"]).has(file.status))+ return false;+ if (+ file.status === "renamed" &&+ !isRuntimeNeutralPath(file.previous_filename)+ )+ return false;+ if (+ file.previous_filename !== undefined &&+ !isRuntimeNeutralPath(file.previous_filename)+ )+ return false;+ if (file.status === "renamed" && typeof file.previous_filename !== "string")+ return false;+ }+ return true;+}diff --git a/tests/e2e/README.md b/tests/e2e/README.mdindex 8601fe4d4..f2e3b2a70 100644--- a/tests/e2e/README.md+++ b/tests/e2e/README.md@@ -81,7 +81,9 @@ videos appear in the Automate dashboard under **Kaneo**.The CI workflow runs the independent **Chromium smoke tests** job for PRs, including forks, without cloud credentials.It skips that job only for qualifying docs/site-only PRs.-**BrowserStack** runs Chrome on Windows and WebKit on macOS after a push to `main` or a manual dispatch on `main`.+**BrowserStack** runs Chrome on Windows and WebKit on macOS for runtime-relevant main pushes, manual runs on main, and its daily schedule at 05:43 UTC.+A main push may skip cloud work only when its complete diff since a proven full validation is runtime-neutral and that validation is less than 24 hours old.+Uncertain evidence, manual runs, and scheduled runs execute both engines in full.Cloud runs are serialized to stay within the two-session limit; obsolete PR runs are cancelled.Both workflows build the checked-out revision, use a disposable database, upload