From 4d80e68f465b954f201f8d1f9f12aa354e56f557 Mon Sep 17 00:00:00 2001 From: kvnloo <7121943+kvnloo@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:56:23 -0600 Subject: [PATCH 01/18] ci(factory): prepare nightly CI and upstream mirror guard --- .github/workflows/ci.yml | 34 ++++++++++- .github/workflows/factory-main-sync.yml | 53 ++++++++++++++++ CONTRIBUTING-FACTORY.md | 12 ++++ scripts/upstream-port.py | 81 +++++++++++++++++++++++++ 4 files changed, 177 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/factory-main-sync.yml create mode 100644 CONTRIBUTING-FACTORY.md create mode 100644 scripts/upstream-port.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 412bf5da862..6623d96cc62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,8 @@ name: CI on: pull_request: push: - branches: [main] + branches: [main, nightly, staging] + workflow_dispatch: permissions: contents: read @@ -13,6 +14,19 @@ concurrency: cancel-in-progress: true jobs: + factory-base: + name: Fork branch policy + if: github.repository == 'kvnloo/gods-eye-view' && github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - name: Refuse feature PRs to mirror and stable branches + env: + BASE: ${{ github.base_ref }} + run: | + case "$BASE" in + main|staging) echo '::error::Target nightly. Main mirrors upstream; staging is fast-forward promotion only.'; exit 1 ;; + esac + verify: name: Node ${{ matrix.node }} runs-on: ubuntu-latest @@ -51,11 +65,21 @@ jobs: - name: Check published layer-token allocations if: github.event_name == 'pull_request' - run: npm run layer-token:check -- --base-ref origin/main + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: npm run layer-token:check -- --base-ref "$BASE_SHA" - name: Check Data Library manifests and share tokens if: github.event_name == 'pull_request' - run: npm run library:check -- --base-ref origin/main + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: npm run library:check -- --base-ref "$BASE_SHA" + + - name: Check translations + run: npm run i18n + + - name: Typecheck renderer declarations + run: npx --no-install tsc --noEmit --strict --module NodeNext --target es2022 $(git ls-files 'src/render/**/*.d.ts') - name: Run unit tests run: npm test @@ -63,6 +87,10 @@ jobs: - name: Build production bundle run: npm run build + - name: Run performance microbenchmarks (Node 24) + if: matrix.node == '24.22.2' + run: npm run test:perf + street-level-browser: # Hermetic: every Mapillary request is answered from fixtures, so the # dummy token below never leaves the page. diff --git a/.github/workflows/factory-main-sync.yml b/.github/workflows/factory-main-sync.yml new file mode 100644 index 00000000000..ad9a62d60ff --- /dev/null +++ b/.github/workflows/factory-main-sync.yml @@ -0,0 +1,53 @@ +name: Factory main mirror +on: + schedule: + - cron: '17 * * * *' + workflow_dispatch: + inputs: + apply: + description: Apply the fast-forward (false only checks readiness) + type: boolean + default: false + +permissions: + contents: write + +concurrency: + group: factory-main-mirror + cancel-in-progress: false + +jobs: + mirror: + if: github.repository == 'kvnloo/gods-eye-view' && (github.ref == 'refs/heads/staging' || (github.ref == 'refs/heads/ci/factory-foundation' && github.event_name == 'workflow_dispatch' && !inputs.apply)) + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Compare and fast-forward main without checking out code + env: + GH_TOKEN: ${{ github.token }} + APPLY: ${{ github.event_name == 'schedule' || inputs.apply }} + shell: bash + run: | + set -euo pipefail + fork=kvnloo/gods-eye-view + upstream=bilawalsidhu/gods-eye-view + before=$(gh api "repos/$fork/git/ref/heads/main" --jq .object.sha) + target=$(gh api "repos/$upstream/git/ref/heads/main" --jq .object.sha) + printf 'Fork main: `%s`\n\nUpstream main: `%s`\n\n' "$before" "$target" | tee -a "$GITHUB_STEP_SUMMARY" + if [[ "$before" == "$target" ]]; then + printf 'Already in sync.\n' | tee -a "$GITHUB_STEP_SUMMARY" + exit 0 + fi + ancestor=$(gh api "repos/$upstream/compare/$before...$target" --jq .merge_base_commit.sha) + if [[ "$ancestor" != "$before" ]]; then + printf '::error::Fork main is not an ancestor of upstream main; refusing to update.\n' + exit 1 + fi + if [[ "$APPLY" != true ]]; then + printf 'Fast-forward available (dry run).\n' | tee -a "$GITHUB_STEP_SUMMARY" + exit 0 + fi + gh api -X PATCH "repos/$fork/git/refs/heads/main" -f sha="$target" -F force=false --jq .object.sha + after=$(gh api "repos/$fork/git/ref/heads/main" --jq .object.sha) + [[ "$after" == "$target" ]] + printf 'Fast-forwarded to `%s`.\n' "$after" | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/CONTRIBUTING-FACTORY.md b/CONTRIBUTING-FACTORY.md new file mode 100644 index 00000000000..2077a26d34a --- /dev/null +++ b/CONTRIBUTING-FACTORY.md @@ -0,0 +1,12 @@ +# Fork factory contribution guide + +- `main` mirrors upstream; no fork PRs or fork commits belong there. +- `staging` is stable. Existing PRs moved from `main` are historical intake; do not merge them directly to staging. Port their feature commits to a branch targeting `nightly` before new work lands. +- `nightly` is preview. Start new branches from stable `origin/staging`, as specified by the factory plan, and explicitly set `gh pr create --base nightly`. If a feature needs preview-only work, declare the dependency instead of silently incorporating unrelated commits. +- One feature per PR. Give each feature a default-off query/config flag, document how to enable it and test both paths. Docs, gate fixes and regressions that restore existing behavior do not need runtime flags. +- Put feature code and tests in focused new files. Use the established application contracts for the smallest possible wiring change. Keep mechanical formatting and unrelated cleanup out of behavior commits. Use `type(scope): subject`; every commit should build on its own. +- Use a unique `feature:` PR label. Keep exact commit provenance and avoid bundling dependencies that are not part of the feature. See `CONTRIBUTING.md` for the project’s runtime and testing conventions (its `main` instructions are for upstream). + +## Upstream rehearsal + +Run `python3 scripts/upstream-port.py feature:` from this fork checkout. It selects exactly one merged nightly PR with that exact label, pins its merge and source commits, fetches current upstream `main`, and tries the feature commits in order in a separate local checkout. It prints each attempted commit and any conflicted paths. The scratch branch is retained for inspection. It never pushes or opens an upstream PR; the upstream contribution process owns publication. diff --git a/scripts/upstream-port.py b/scripts/upstream-port.py new file mode 100644 index 00000000000..8490cdfe849 --- /dev/null +++ b/scripts/upstream-port.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Rehearse exactly one merged fork feature on today's upstream main, locally.""" +import argparse +import json +from pathlib import Path +import re +import subprocess +import tempfile + +FORK = 'kvnloo/gods-eye-view' +UPSTREAM = 'https://github.com/bilawalsidhu/gods-eye-view.git' + + +def output(*args, cwd=None): + return subprocess.check_output(args, cwd=cwd, text=True).strip() + + +def rehearse(label): + pages = json.loads(output('gh', 'api', '--paginate', '--slurp', + f'repos/{FORK}/pulls?state=closed&base=nightly&per_page=100')) + matches = [pr for page in pages for pr in page if + any(item['name'] == label for item in pr['labels'])] + merged = [] + for pr in matches: + detail = json.loads(output('gh', 'api', f'repos/{FORK}/pulls/{pr["number"]}')) + if detail['merged']: + merged.append(detail) + if len(merged) != 1: + raise RuntimeError(f'{label}: expected one merged nightly PR, got {len(merged)}') + pr = merged[0] + merge = pr['merge_commit_sha'] + source = pr['head']['sha'] + for sha in (merge, source): + if not re.fullmatch(r'[0-9a-f]{40}', sha or ''): + raise RuntimeError('GitHub did not return pinned merge and source commits') + scratch = Path(tempfile.mkdtemp(prefix='gev-upstream-port-')) + print(f'PR {pr["html_url"]}; rehearsal retained at {scratch}', flush=True) + + def git(*args): + return output('git', *args, cwd=scratch) + + git('init', '--quiet') + git('fetch', '--quiet', '--no-tags', UPSTREAM, 'refs/heads/main:refs/remotes/upstream/main') + git('fetch', '--quiet', '--no-tags', f'https://github.com/{FORK}.git', merge) + _, *parents = git('rev-list', '--parents', '-n', '1', merge).split() + if len(parents) != 2 or parents[1] != source: + raise RuntimeError('Expected a merge commit preserving the exact PR source head') + commits = git('rev-list', '--reverse', f'{parents[0]}..{source}').splitlines() + if not commits or git('rev-list', '--merges', f'{parents[0]}..{source}'): + raise RuntimeError('Cannot isolate a nonempty linear feature; inspect dependencies manually') + check = git('merge-tree', '--write-tree', parents[0], source).splitlines()[0] + if check != git('rev-parse', f'{merge}^{{tree}}'): + raise RuntimeError('Merge has extra resolutions; do not silently omit them') + git('switch', '--quiet', '-c', 'upstream-port/' + label.split(':', 1)[1], 'upstream/main') + print(f'Upstream base: {git("rev-parse", "HEAD")}', flush=True) + for sha in commits: + print(f'Cherry-pick {sha}', flush=True) + result = subprocess.run(['git', '-c', 'user.name=GEV port rehearsal', '-c', + 'user.email=gev-port@users.noreply.github.com', '-c', 'commit.gpgsign=false', + '-c', 'core.hooksPath=/dev/null', 'cherry-pick', '-x', sha], cwd=scratch) + if result.returncode: + print('Unmerged paths:\n' + git('diff', '--name-only', '--diff-filter=U')) + return 1 + print(f'Clean rehearsal: {git("rev-parse", "HEAD")}; no remote writes') + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('label') + args = parser.parse_args() + if not re.fullmatch(r'feature:[a-z0-9]+(?:-[a-z0-9]+)*', args.label): + parser.error('expected an exact feature: label') + try: + return rehearse(args.label) + except (RuntimeError, subprocess.CalledProcessError) as error: + parser.exit(1, f'{error}\n') + + +if __name__ == '__main__': + raise SystemExit(main()) From 383e7975068cc407b811347c1329502418268661 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 17:41:46 -0600 Subject: [PATCH 02/18] ci(factory): gate driver with a baseline-differential unit gate --- scripts/factory-ci.mjs | 420 +++++++++++++++++++++++++++++ scripts/factory-ci/test-events.mjs | 23 ++ src/factoryCi.test.mjs | 116 ++++++++ 3 files changed, 559 insertions(+) create mode 100644 scripts/factory-ci.mjs create mode 100644 scripts/factory-ci/test-events.mjs create mode 100644 src/factoryCi.test.mjs diff --git a/scripts/factory-ci.mjs b/scripts/factory-ci.mjs new file mode 100644 index 00000000000..22ece2afa3a --- /dev/null +++ b/scripts/factory-ci.mjs @@ -0,0 +1,420 @@ +// Factory CI gates for nightly and staging. One driver for GitHub Actions +// (.github/workflows/factory-ci-sha.yml) and for disposable Boat VMs, so both +// report the same commit-status contexts: gev-ci/ and gev-ci/full. +// +// node scripts/factory-ci.mjs ... [--out DIR] [--base-ref SHA] +// node scripts/factory-ci.mjs unit --write-baseline refresh the baseline +// node scripts/factory-ci.mjs statuses DIR contexts as TSV +// +// Every gate writes DIR/.json ({gate, state, description, ...}) and +// DIR/.log. state is success, failure (the code under test failed) or +// error (the gate itself could not run). Docs: docs/factory-ci.md. +import { spawn, execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { createWriteStream, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + allocationTestArgs, + buildUnitTestPlan, + discoverUnitTestFiles, + isCalibratedAllocationRuntime, + UNIT_TEST_NODE_FLAGS, +} from './run-unit-tests.mjs'; +import { discoverPerfTestFiles, perfTestArgs } from './run-perf-tests.mjs'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const REPORTER = path.join(ROOT, 'scripts/factory-ci/test-events.mjs'); +export const BASELINE_PATH = 'ci/factory/unit-baseline.json'; +export const PERF_SMOKE = Object.freeze({ runs: 5, failQuorum: 3 }); +export const GATES = Object.freeze([ + 'lint', 'typecheck', 'translations', 'unit', 'build', 'bundle-budget', 'globe-smoke', 'perf-smoke', +]); +const MINUTE = 60_000; + +// ---------------------------------------------------------------- processes + +/** Run one command, teeing output to the gate log. Never throws. */ +function run(command, args, { log, env = {}, timeoutMs = 30 * MINUTE } = {}) { + return new Promise((resolve) => { + const started = Date.now(); + log.write(`\n$ ${[command, ...args].join(' ')}\n`); + let child; + try { + child = spawn(command, args, { cwd: ROOT, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (error) { + resolve({ code: null, signal: null, error: String(error), ms: 0 }); + return; + } + const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs); + for (const stream of [child.stdout, child.stderr]) { + stream.on('data', (chunk) => { + log.write(chunk); + process.stdout.write(chunk); + }); + } + child.on('error', (error) => { + clearTimeout(timer); + resolve({ code: null, signal: null, error: String(error), ms: Date.now() - started }); + }); + child.on('close', (code, signal) => { + clearTimeout(timer); + resolve({ code, signal, error: signal === 'SIGKILL' ? `timed out after ${timeoutMs} ms` : null, ms: Date.now() - started }); + }); + }); +} + +/** A gate made of commands: failure on a non-zero exit, error if one could not run. */ +async function commandGate(log, steps) { + for (const [label, command, args, options] of steps) { + const result = await run(command, args, { log, ...options }); + if (result.error || result.signal) return { state: 'error', description: `${label}: ${result.error ?? result.signal}` }; + if (result.code !== 0) return { state: 'failure', description: `${label} exited ${result.code}` }; + } + return { state: 'success', description: steps.map(([label]) => label).join(', ') + ' passed' }; +} + +const npm = (script, ...rest) => ['npm', ['run', '--silent', script, ...(rest.length ? ['--', ...rest] : [])]]; + +// ---------------------------------------------------------------- test events + +/** + * Turn reporter lines into one entry per test, named by its file and every + * enclosing suite. node:test reports children before their parent, so each + * finished node adopts the pending nodes one level deeper in the same file. + */ +export function collectTests(lines) { + const pending = new Map(); // file -> Map(nesting -> nodes) + const roots = []; + const summaries = []; + for (const line of lines) { + if (!line.trim()) continue; + const event = JSON.parse(line); + if (event.event === 'summary') { + summaries.push(event); + continue; + } + if (event.event !== 'pass' && event.event !== 'fail') continue; + const file = event.file ? path.relative(ROOT, event.file).split(path.sep).join('/') : '(no file)'; + const levels = pending.get(file) ?? new Map(); + pending.set(file, levels); + // A file that fails outside any test is reported under its own path. + const wholeFile = event.file && path.resolve(ROOT, event.name) === event.file; + const node = { + file, + name: wholeFile ? '(file)' : event.name, + kind: event.kind, + // A todo test may fail without failing the run, so todo/skip win. + status: event.todo ? 'todo' : event.skip ? 'skip' + : event.event === 'pass' ? 'pass' + : event.failureType === 'cancelledByParent' ? 'cancelled' : 'fail', + failureType: event.failureType, + durationMs: event.durationMs, + children: levels.get(event.nesting + 1) ?? [], + }; + levels.delete(event.nesting + 1); + if (event.nesting === 0) roots.push(node); + else levels.set(event.nesting, [...(levels.get(event.nesting) ?? []), node]); + } + const orphaned = [...pending.values()].some((levels) => levels.size > 0); + const tests = new Map(); + const visit = (node, prefix) => { + const name = [...prefix, node.name]; + // A suite that failed only because a child failed adds nothing; a failing + // hook or a file that failed to load is a failure of its own. + const counts = node.kind === 'test' || (node.status === 'fail' && node.failureType !== 'subtestsFailed'); + if (counts) { + let id = `${node.file} > ${name.join(' > ')}`; + for (let n = 2; tests.has(id); n++) id = `${node.file} > ${name.join(' > ')} #${n}`; + tests.set(id, { status: node.status, kind: node.kind, file: node.file, durationMs: node.durationMs }); + } + for (const child of node.children) visit(child, name); + }; + for (const root of roots) visit(root, []); + return { tests, summary: summaries.find((s) => s.file === null) ?? null, orphaned }; +} + +/** Run node --test with the event reporter. Returns the process outcome and parsed tests. */ +async function runNodeTests(args, { log, eventsFile, env, timeoutMs }) { + const reporterArgs = [ + '--test-reporter=dot', '--test-reporter-destination=stdout', + `--test-reporter=${REPORTER}`, `--test-reporter-destination=${eventsFile}`, + ]; + const result = await run(process.execPath, [...UNIT_TEST_NODE_FLAGS, ...reporterArgs, ...args], { log, env, timeoutMs }); + const lines = existsSync(eventsFile) ? readFileSync(eventsFile, 'utf8').split('\n') : []; + return { ...result, ...collectTests(lines) }; +} + +/** Why a test process's own report cannot be trusted, or null. */ +export function processProblem({ code, signal, error, tests, summary, orphaned }) { + if (error || signal) return error ?? `killed by ${signal}`; + if (!summary) return 'the test runner produced no summary'; + if (orphaned) return 'some test results had no enclosing test'; + const counted = [...tests.values()].filter((t) => t.kind === 'test').length; + if (counted !== summary.counts.tests) return `reported ${summary.counts.tests} tests but emitted ${counted}`; + const failed = [...tests.values()].some((t) => t.status === 'fail' || t.status === 'cancelled'); + if (code !== 0 && !failed) return `exited ${code} with no failing test`; + if (code === 0 && failed) return 'exited 0 despite failing tests'; + return null; +} + +// ---------------------------------------------------------------- unit gate + +function git(...args) { + return execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }).trim(); +} + +export function environment() { + return { + node: process.versions.node, + npm: execFileSync('npm', ['--version'], { encoding: 'utf8' }).trim(), + platform: process.platform, + arch: process.arch, + osRelease: os.release(), + cpus: os.availableParallelism(), + memoryGiB: Math.round(os.totalmem() / 2 ** 30), + runner: process.env.GEV_CI_RUNNER ?? (process.env.GITHUB_ACTIONS ? 'github-actions' : 'local'), + }; +} + +/** Compare a run with the recorded baseline. Pure; the gate decision lives here. */ +export function compareWithBaseline(baseline, tests, perFile, discovered) { + const failures = new Set(baseline.failures); + const skipped = new Set(baseline.skipped); + const out = { newFailures: [], stillFailing: [], fixed: [], newlySkipped: [], emptiedFiles: [], missingFiles: [] }; + for (const [id, { status }] of tests) { + if (status === 'fail' || status === 'cancelled') (failures.has(id) ? out.stillFailing : out.newFailures).push(id); + else if ((status === 'skip' || status === 'todo') && !skipped.has(id)) out.newlySkipped.push(id); + } + for (const id of failures) if (tests.get(id)?.status === 'pass') out.fixed.push(id); + const present = new Set(discovered); + for (const [file, count] of Object.entries(baseline.testsPerFile)) { + if (!present.has(file)) out.missingFiles.push(file); + else if (count > 0 && !perFile[file]) out.emptiedFiles.push(file); + } + const blocking = out.newFailures.length + out.newlySkipped.length + out.emptiedFiles.length; + return { ...out, blocking }; +} + +function perFileCounts(tests) { + const counts = {}; + for (const { file, kind } of tests.values()) if (kind === 'test') counts[file] = (counts[file] ?? 0) + 1; + return Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))); +} + +async function unitGate({ log, out, writeBaseline }) { + // Policy tests diff against origin/main; a shallow checkout is a setup error, not a test failure. + try { + git('rev-parse', '--verify', 'origin/main^{commit}'); + git('merge-base', 'HEAD', 'origin/main'); + } catch { + return { state: 'error', description: 'origin/main history is missing; fetch full history first' }; + } + if (!isCalibratedAllocationRuntime()) { + return { state: 'error', description: `Node ${process.versions.node} has no calibrated allocation budgets` }; + } + const discovered = discoverUnitTestFiles(ROOT); + const plan = buildUnitTestPlan(discovered); + // Every process runs even when an earlier one failed, so no suite is silently skipped. + const processes = [ + ['parallel', ['--test', ...plan.parallel]], + ...plan.serializedAllocations.map((file) => [file, allocationTestArgs(file)]), + ]; + const tests = new Map(); + const runs = []; + for (const [index, [label, args]] of processes.entries()) { + const eventsFile = path.join(out, `unit-events-${index}.ndjson`); + const result = await runNodeTests(args, { log, eventsFile, env: { GEV_REQUIRE_ALLOCATION_GATE: '1' }, timeoutMs: 40 * MINUTE }); + const problem = processProblem(result); + runs.push({ label, exitCode: result.code, signal: result.signal, ms: result.ms, counts: result.summary?.counts ?? null, problem }); + for (const [id, test] of result.tests) tests.set(tests.has(id) ? `${id} (${label})` : id, test); + } + const counts = { tests: 0, passed: 0, failed: 0, cancelled: 0, skipped: 0, todo: 0 }; + for (const { kind, status } of tests.values()) { + if (kind !== 'test') continue; + counts.tests++; + counts[{ pass: 'passed', fail: 'failed', cancelled: 'cancelled', skip: 'skipped', todo: 'todo' }[status]]++; + } + const failing = [...tests].filter(([, t]) => t.status === 'fail' || t.status === 'cancelled').map(([id]) => id).sort(); + const skipped = [...tests].filter(([, t]) => t.status === 'skip' || t.status === 'todo').map(([id]) => id).sort(); + const perFile = perFileCounts(tests); + const problems = runs.filter((r) => r.problem).map((r) => `${r.label}: ${r.problem}`); + const record = { runs, counts, failing, skipped }; + if (problems.length) return { state: 'error', description: problems.join('; '), ...record }; + + if (writeBaseline) { + const baseline = { + schema: 1, + commit: git('rev-parse', 'HEAD'), + tree: git('rev-parse', 'HEAD^{tree}'), + dirty: git('status', '--porcelain', '--untracked-files=no') !== '', + packageLockSha256: createHash('sha256').update(readFileSync(path.join(ROOT, 'package-lock.json'))).digest('hex'), + // The driver may be newer than the commit (a baseline is recorded before the gate lands). + harnessSha256: createHash('sha256').update(readFileSync(fileURLToPath(import.meta.url))).update(readFileSync(REPORTER)).digest('hex'), + environment: environment(), + generatedAt: new Date().toISOString(), + command: 'node scripts/factory-ci.mjs unit --write-baseline', + counts, + failures: failing, + skipped, + testsPerFile: perFile, + }; + mkdirSync(path.dirname(path.join(ROOT, BASELINE_PATH)), { recursive: true }); + writeFileSync(path.join(ROOT, BASELINE_PATH), `${JSON.stringify(baseline, null, 2)}\n`); + return { state: 'success', description: `baseline written: ${counts.tests} tests, ${failing.length} failing, ${skipped.length} skipped`, ...record }; + } + + const baselineFile = path.join(ROOT, BASELINE_PATH); + if (!existsSync(baselineFile)) return { state: 'error', description: `${BASELINE_PATH} is missing`, ...record }; + const baseline = JSON.parse(readFileSync(baselineFile, 'utf8')); + const env = environment(); + if (baseline.environment.node !== env.node || baseline.environment.platform !== env.platform) { + return { state: 'error', description: `baseline was recorded on Node ${baseline.environment.node}/${baseline.environment.platform}, this is ${env.node}/${env.platform}`, ...record }; + } + const diff = compareWithBaseline(baseline, tests, perFile, discovered); + const description = diff.blocking + ? `${diff.newFailures.length} new failures, ${diff.newlySkipped.length} newly skipped, ${diff.emptiedFiles.length} emptied files vs ${baseline.commit.slice(0, 12)}` + : `${counts.tests} tests; ${diff.stillFailing.length} baseline failures, 0 new; ${diff.fixed.length} fixed`; + return { state: diff.blocking ? 'failure' : 'success', description, baselineCommit: baseline.commit, ...diff, ...record }; +} + +// ---------------------------------------------------------------- perf smoke + +/** + * The repository's wall-clock benchmarks (*.perf.test.mjs), run PERF_SMOKE.runs + * times serially. A benchmark fails the gate when it misses its own budget in + * failQuorum runs or more; every run's numbers are kept. Budgets themselves are + * never changed here. + */ +async function perfSmokeGate({ log, out }) { + const files = discoverPerfTestFiles(ROOT); + if (!files.length) return { state: 'error', description: 'no *.perf.test.mjs benchmarks found' }; + const misses = new Map(); + const runs = []; + for (let i = 0; i < PERF_SMOKE.runs; i++) { + const eventsFile = path.join(out, `perf-events-${i}.ndjson`); + const args = perfTestArgs(files).slice(UNIT_TEST_NODE_FLAGS.length); + const result = await runNodeTests(args, { log, eventsFile, env: { GEV_PERF_BUDGETS: '1' }, timeoutMs: 10 * MINUTE }); + const problem = processProblem(result); + if (problem) return { state: 'error', description: `run ${i + 1}: ${problem}`, runs }; + const tests = Object.fromEntries([...result.tests].map(([id, t]) => [id, { status: t.status, durationMs: t.durationMs }])); + for (const [id, t] of Object.entries(tests)) { + if (t.status === 'skip' || t.status === 'todo') return { state: 'failure', description: `${id} was skipped`, runs }; + if (t.status !== 'pass') misses.set(id, (misses.get(id) ?? 0) + 1); + } + runs.push({ run: i + 1, ms: result.ms, tests }); + } + const failed = [...misses].filter(([, n]) => n >= PERF_SMOKE.failQuorum); + const missed = [...misses].map(([id, n]) => `${id.split(' > ').pop().slice(0, 40)} ${n}/${PERF_SMOKE.runs}`); + return { + state: failed.length ? 'failure' : 'success', + description: failed.length + ? `${failed.length} benchmark(s) missed budget in >=${PERF_SMOKE.failQuorum}/${PERF_SMOKE.runs} runs` + : `${Object.keys(runs[0].tests).length} benchmarks within budget${missed.length ? `; isolated misses: ${missed.join(', ')}` : ''}`, + policy: PERF_SMOKE, + misses: Object.fromEntries(misses), + runs, + }; +} + +// ---------------------------------------------------------------- gates + +async function runGate(gate, { out, baseRef, writeBaseline }) { + const log = createWriteStream(path.join(out, `${gate}.log`)); + const started = Date.now(); + let result; + try { + switch (gate) { + case 'lint': { + const steps = [ + ['format', ...npm('format:check')], + ['boundaries', ...npm('check:boundaries')], + ['library', ...npm('library:check', ...(baseRef ? ['--base-ref', baseRef] : []))], + ]; + if (baseRef) steps.push(['layer tokens', ...npm('layer-token:check', '--base-ref', baseRef)]); + result = await commandGate(log, steps); + break; + } + case 'typecheck': { + // Declarations only: the app is JavaScript bundled by Vite, so Bundler resolution. + const files = git('ls-files', 'src/render/**/*.d.ts').split('\n').filter(Boolean); + if (!files.length) { result = { state: 'error', description: 'no declaration files found' }; break; } + result = await commandGate(log, [['tsc (renderer declarations)', path.join(ROOT, 'node_modules/.bin/tsc'), + ['--noEmit', '--strict', '--module', 'ESNext', '--moduleResolution', 'Bundler', '--target', 'es2022', ...files]]]); + break; + } + case 'translations': + result = await commandGate(log, [['i18n', ...npm('i18n')]]); + break; + case 'build': + result = await commandGate(log, [['vite build', ...npm('build')]]); + break; + case 'bundle-budget': + result = existsSync(path.join(ROOT, 'dist/index.html')) + ? await commandGate(log, [['budget', process.execPath, ['scripts/factory-bundle-budget.mjs', 'dist', path.join(out, 'bundle.json')]]]) + : { state: 'error', description: 'dist/ is missing; run the build gate first' }; + break; + case 'globe-smoke': + result = existsSync(path.join(ROOT, 'dist/index.html')) + ? await commandGate(log, [['globe', process.execPath, ['scripts/factory-globe-smoke.mjs', path.join(out, 'globe.png'), 'dist', path.join(out, 'globe.json')], { timeoutMs: 5 * MINUTE }]]) + : { state: 'error', description: 'dist/ is missing; run the build gate first' }; + break; + case 'unit': + result = await unitGate({ log, out, writeBaseline }); + break; + case 'perf-smoke': + result = await perfSmokeGate({ log, out }); + break; + default: + result = { state: 'error', description: `unknown gate ${gate}` }; + } + } catch (error) { + result = { state: 'error', description: String(error?.message ?? error).slice(0, 200), stack: String(error?.stack ?? '') }; + } + await new Promise((resolve) => log.end(resolve)); + const record = { gate, ...result, description: result.description.slice(0, 140), durationMs: Date.now() - started }; + writeFileSync(path.join(out, `${gate}.json`), `${JSON.stringify(record, null, 2)}\n`); + console.log(`[factory-ci] ${gate}: ${record.state} (${(record.durationMs / 1000).toFixed(1)}s) ${record.description}`); + return record; +} + +/** Commit statuses for a results directory: one per gate and gev-ci/full. Missing results are errors. */ +export function statusesFor(dir) { + const rows = GATES.map((gate) => { + const file = path.join(dir, `${gate}.json`); + if (!existsSync(file)) return { context: `gev-ci/${gate}`, state: 'error', description: 'no result recorded' }; + const { state, description } = JSON.parse(readFileSync(file, 'utf8')); + return { context: `gev-ci/${gate}`, state: ['success', 'failure', 'error'].includes(state) ? state : 'error', description }; + }); + const red = rows.filter((r) => r.state !== 'success').map((r) => r.context.slice(7)); + rows.push({ context: 'gev-ci/full', state: red.length ? 'failure' : 'success', description: red.length ? `not green: ${red.join(', ')}` : `all ${GATES.length} gates passed` }); + return rows; +} + +async function main(argv) { + if (argv[0] === 'statuses') { + for (const row of statusesFor(argv[1] ?? 'ci-results')) console.log([row.context, row.state, row.description.replace(/\s+/g, ' ')].join('\t')); + return 0; + } + const option = (name) => { + const i = argv.indexOf(name); + if (i === -1) return null; + const [value] = argv.splice(i, 2).slice(1); + return value; + }; + const writeBaseline = argv.includes('--write-baseline'); + if (writeBaseline) argv.splice(argv.indexOf('--write-baseline'), 1); + const out = path.resolve(option('--out') ?? 'ci-results'); + const baseRef = option('--base-ref'); + const gates = argv.length ? argv : GATES; + if (writeBaseline && gates.join() !== 'unit') throw new Error('--write-baseline only applies to the unit gate'); + mkdirSync(out, { recursive: true }); + let ok = true; + for (const gate of gates) ok = (await runGate(gate, { out, baseRef, writeBaseline })).state === 'success' && ok; + return ok ? 0 : 1; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + process.exitCode = await main(process.argv.slice(2)); +} diff --git a/scripts/factory-ci/test-events.mjs b/scripts/factory-ci/test-events.mjs new file mode 100644 index 00000000000..297085d55ba --- /dev/null +++ b/scripts/factory-ci/test-events.mjs @@ -0,0 +1,23 @@ +// node:test reporter that writes one JSON line per finished test or suite, plus +// summaries. scripts/factory-ci.mjs rebuilds each test's full name from these. +export default async function* testEvents(source) { + for await (const { type, data } of source) { + if (type === 'test:pass' || type === 'test:fail') { + yield `${JSON.stringify({ + event: type === 'test:pass' ? 'pass' : 'fail', + file: data.file ?? null, + name: data.name, + nesting: data.nesting, + kind: data.details?.type ?? 'test', + skip: data.skip !== undefined && data.skip !== false, + todo: data.todo !== undefined && data.todo !== false, + failureType: data.details?.error?.failureType ?? null, + durationMs: data.details?.duration_ms ?? null, + })}\n`; + } else if (type === 'test:diagnostic' && data.nesting > 0) { + yield `${JSON.stringify({ event: 'diagnostic', file: data.file ?? null, nesting: data.nesting, message: data.message })}\n`; + } else if (type === 'test:summary') { + yield `${JSON.stringify({ event: 'summary', file: data.file ?? null, counts: data.counts, success: data.success })}\n`; + } + } +} diff --git a/src/factoryCi.test.mjs b/src/factoryCi.test.mjs new file mode 100644 index 00000000000..bba3c7a9589 --- /dev/null +++ b/src/factoryCi.test.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { + collectTests, + compareWithBaseline, + GATES, + processProblem, + statusesFor, +} from '../scripts/factory-ci.mjs'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const REPORTER = path.join(ROOT, 'scripts/factory-ci/test-events.mjs'); + +// A nested runner inherits NODE_TEST_CONTEXT and would report to this one instead. +const { NODE_TEST_CONTEXT, ...withoutTestContext } = process.env; + +/** Run real node:test files through the factory reporter, as the unit gate does. */ +function runFixture(files) { + const dir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'factory-ci-fixture-'))); + try { + for (const [name, body] of Object.entries(files)) writeFileSync(path.join(dir, name), body); + const events = path.join(dir, 'events.ndjson'); + const result = spawnSync(process.execPath, [ + '--test', `--test-reporter=${REPORTER}`, `--test-reporter-destination=${events}`, + ...Object.keys(files).map((name) => path.join(dir, name)), + ], { cwd: ROOT, encoding: 'utf8', env: withoutTestContext }); + const prefix = path.relative(ROOT, dir).split(path.sep).join('/'); + const run = { code: result.status, signal: result.signal, error: null, ...collectTests(readFileSync(events, 'utf8').split('\n')) }; + return { run, prefix }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +const SUITE = ` +import { describe, it, test } from 'node:test'; +describe('outer', () => { + it('same', () => {}); + it('breaks', () => { throw new Error('no'); }); + describe('inner', () => { it('same', () => {}); it.skip('later', () => {}); }); +}); +test('parent', async (t) => { await t.test('child', () => {}); }); +it.todo('todo that fails', () => { throw new Error('todo'); }); +`; + +test('every test is named by its file and enclosing suites, with its own status', () => { + const { run, prefix } = runFixture({ 'a.test.mjs': SUITE, 'b.test.mjs': "throw new Error('does not load');\n" }); + const status = Object.fromEntries([...run.tests].map(([id, t]) => [id.slice(prefix.length + 1), t.status])); + assert.deepEqual(status, { + 'a.test.mjs > outer > same': 'pass', + 'a.test.mjs > outer > breaks': 'fail', + 'a.test.mjs > outer > inner > same': 'pass', + 'a.test.mjs > outer > inner > later': 'skip', + 'a.test.mjs > parent': 'pass', + 'a.test.mjs > parent > child': 'pass', + 'a.test.mjs > todo that fails': 'todo', + 'b.test.mjs > (file)': 'fail', + }); + assert.equal(processProblem(run), null, 'a failing run that reported every test is trustworthy'); +}); + +test('a run whose report cannot be trusted is an error, not a test failure', () => { + const { run } = runFixture({ 'a.test.mjs': "import { it } from 'node:test';\nit('ok', () => {});\n" }); + assert.equal(processProblem(run), null); + assert.match(processProblem({ ...run, signal: 'SIGKILL' }), /SIGKILL/); + assert.match(processProblem({ ...run, summary: null }), /no summary/); + assert.match(processProblem({ ...run, code: 1 }), /no failing test/); + assert.match(processProblem({ ...run, tests: new Map() }), /reported 1 tests but emitted 0/); +}); + +test('only new failures, newly skipped tests and emptied files block', () => { + const baseline = { + failures: ['a > known'], + skipped: ['a > parked'], + testsPerFile: { a: 4, gone: 1, emptied: 2 }, + }; + const tests = new Map([ + ['a > known', { status: 'fail' }], + ['a > fresh', { status: 'fail' }], + ['a > parked', { status: 'skip' }], + ['a > hidden', { status: 'skip' }], + ['a > fine', { status: 'pass' }], + ]); + const diff = compareWithBaseline(baseline, tests, { a: 5 }, ['a', 'emptied']); + assert.deepEqual(diff.newFailures, ['a > fresh']); + assert.deepEqual(diff.stillFailing, ['a > known']); + assert.deepEqual(diff.newlySkipped, ['a > hidden']); + assert.deepEqual(diff.emptiedFiles, ['emptied']); + assert.deepEqual(diff.missingFiles, ['gone']); + assert.equal(diff.blocking, 3); + + const clean = compareWithBaseline(baseline, new Map([['a > known', { status: 'pass' }]]), { a: 1, emptied: 2 }, ['a', 'emptied']); + assert.deepEqual(clean.fixed, ['a > known']); + assert.equal(clean.blocking, 0); +}); + +test('gev-ci/full is green only when every gate recorded success', () => { + const dir = mkdtempSync(path.join(os.tmpdir(), 'factory-ci-statuses-')); + try { + for (const gate of GATES) writeFileSync(path.join(dir, `${gate}.json`), JSON.stringify({ state: 'success', description: 'ok' })); + assert.deepEqual(statusesFor(dir).at(-1), { context: 'gev-ci/full', state: 'success', description: `all ${GATES.length} gates passed` }); + rmSync(path.join(dir, 'globe-smoke.json')); + writeFileSync(path.join(dir, 'unit.json'), JSON.stringify({ state: 'weird', description: 'x' })); + const rows = Object.fromEntries(statusesFor(dir).map((r) => [r.context, r.state])); + assert.equal(rows['gev-ci/globe-smoke'], 'error'); + assert.equal(rows['gev-ci/unit'], 'error'); + assert.equal(rows['gev-ci/full'], 'failure'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); From 52ba9375b42fc4493266bab8a91b3d6426116fba Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 17:41:46 -0600 Subject: [PATCH 03/18] ci(factory): measured bundle budget and headless globe smoke --- scripts/factory-bundle-budget.mjs | 51 +++++++++++++++++ scripts/factory-globe-smoke.mjs | 92 +++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 scripts/factory-bundle-budget.mjs create mode 100644 scripts/factory-globe-smoke.mjs diff --git a/scripts/factory-bundle-budget.mjs b/scripts/factory-bundle-budget.mjs new file mode 100644 index 00000000000..8b6c5483bab --- /dev/null +++ b/scripts/factory-bundle-budget.mjs @@ -0,0 +1,51 @@ +// Production asset budget. Raising a limit is a reviewed change to this file. +// node scripts/factory-bundle-budget.mjs [dist] [result.json] +import assert from 'node:assert/strict'; +import { readdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { join, relative } from 'node:path'; +import { gzipSync } from 'node:zlib'; + +// Measured at nightly 53f0caa6 (Node 24.22.2, Linux x64): total 80,939,371; +// JS gzip 7,456,194; largest JS gzip 2,796,702; entry JS gzip 4,498,737. +// Two builds of the same tree gave identical bytes. Limits are about 5% over. +export const LIMITS = Object.freeze({ + totalBytes: 85_000_000, + jsGzipBytes: 7_850_000, + largestJsGzipBytes: 3_000_000, + entryJsGzipBytes: 4_750_000, +}); + +const out = process.argv[2] ?? 'dist'; +const result = { totalBytes: 0, files: 0, jsFiles: 0, jsGzipBytes: 0, largestJsGzipBytes: 0, largestJs: null, entryJsGzipBytes: 0 }; +assert.ok((await stat(join(out, 'index.html'))).isFile(), 'Missing production HTML'); +const html = await readFile(join(out, 'index.html'), 'utf8'); +const entries = new Set([...html.matchAll(/]*\bsrc="\/?([^"]+\.m?js)"/g)].map((m) => m[1])); +async function walk(dir) { + for (const item of await readdir(dir, { withFileTypes: true })) { + const file = join(dir, item.name); + if (item.isDirectory()) await walk(file); + else if (item.isFile()) { + result.totalBytes += (await stat(file)).size; + result.files++; + if (!/\.m?js$/.test(item.name)) continue; + const bytes = gzipSync(await readFile(file)).length; + result.jsFiles++; + result.jsGzipBytes += bytes; + if (entries.has(relative(out, file).split('\\').join('/'))) result.entryJsGzipBytes += bytes; + if (bytes > result.largestJsGzipBytes) { + result.largestJsGzipBytes = bytes; + result.largestJs = relative(out, file); + } + } else throw new Error(`Unexpected non-file artifact: ${file}`); + } +} +await walk(out); +const report = { ...result, entries: [...entries], limits: LIMITS }; +console.log(JSON.stringify(report, null, 2)); +if (process.argv[3]) await writeFile(process.argv[3], `${JSON.stringify(report, null, 2)}\n`); +assert.ok(result.largestJs, 'No JavaScript found in production output'); +assert.ok(entries.size > 0, 'No entry script in dist/index.html'); +for (const [name, limit] of Object.entries(LIMITS)) { + assert.ok(limit > 0, `${name} has no budget`); + assert.ok(result[name] <= limit, `${name}: ${result[name]} > ${limit}`); +} diff --git a/scripts/factory-globe-smoke.mjs b/scripts/factory-globe-smoke.mjs new file mode 100644 index 00000000000..1e501fa7859 --- /dev/null +++ b/scripts/factory-globe-smoke.mjs @@ -0,0 +1,92 @@ +// Render the real production build headless, with every external request +// blocked and no API keys, and prove the Cesium globe drew pixels. +// node scripts/factory-globe-smoke.mjs [screenshot.png] [dist] [result.json] +import assert from 'node:assert/strict'; +import { writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import puppeteer from 'puppeteer'; +import sharp from 'sharp'; +import { preview } from 'vite'; + +// The globe must change this share of the central crop against the same frame +// with the globe hidden, and the crop must not be one flat colour. +export const THRESHOLDS = Object.freeze({ changedFraction: 0.2, channelDelta: 24, minLumaStdDev: 4 }); + +const output = resolve(process.argv[2] ?? 'factory-globe.png'); +const server = await preview({ + build: { outDir: process.argv[3] ?? 'dist' }, + preview: { host: '127.0.0.1', port: 0, strictPort: true }, +}); +let browser; +const pageErrors = []; +try { + const origin = `http://127.0.0.1:${server.httpServer.address().port}`; + browser = await puppeteer.launch({ + headless: true, + args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + defaultViewport: { width: 1024, height: 768 }, + }); + const page = await browser.newPage(); + page.on('pageerror', (error) => pageErrors.push(String(error?.message ?? error))); + await page.setRequestInterception(true); + page.on('request', (request) => { + const url = new URL(request.url()); + return url.origin === origin || ['blob:', 'data:'].includes(url.protocol) + ? request.continue() + : request.abort(); + }); + const started = Date.now(); + const response = await page.goto(`${origin}/?welcome=0#lat=35&lon=-90&alt=22000000&heading=0&pitch=-90`); + assert.equal(response?.status(), 200, 'production home page'); + await page.waitForFunction(() => { + const scene = window.__godsEyeView?.viewer?.scene; + const loader = document.getElementById('loading-screen'); + return scene?.globe?.show && scene.canvas.width > 512 && (!loader || loader.classList.contains('hidden')); + }, { timeout: 90_000 }); + const readyMs = Date.now() - started; + const render = async (show) => page.evaluate(async (visible) => { + const scene = window.__godsEyeView.viewer.scene; + scene.globe.show = visible; + await new Promise((done) => { + const unsubscribe = scene.postRender.addEventListener(() => { + unsubscribe(); + done(); + }); + // If the render governor owns the loop, invalidate it too. + window.__godsEyeView.requestRender?.('factory-globe-smoke'); + scene.requestRender(); + }); + }, show); + // Compare a fixed central crop against a real negative control (globe hidden). + // Chrome compositing includes the HUD, which also appears in the control. + const clip = { x: 384, y: 256, width: 256, height: 256 }; + await render(true); + const withGlobe = await page.screenshot({ clip }); + await page.screenshot({ path: output }); + await render(false); + const withoutGlobe = await page.screenshot({ clip }); + const pixels = async (image) => sharp(Buffer.from(image)).removeAlpha().raw().toBuffer(); + const a = await pixels(withGlobe); + const b = await pixels(withoutGlobe); + assert.equal(a.length, b.length); + let changed = 0; + let sum = 0; + let sumSquares = 0; + for (let i = 0; i < a.length; i += 3) { + if (Math.max(Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2])) > THRESHOLDS.channelDelta) changed++; + const luma = 0.2126 * a[i] + 0.7152 * a[i + 1] + 0.0722 * a[i + 2]; + sum += luma; + sumSquares += luma * luma; + } + const n = a.length / 3; + const changedFraction = changed / n; + const lumaStdDev = Math.sqrt(Math.max(0, sumSquares / n - (sum / n) ** 2)); + const report = { readyMs, changedPixels: changed, croppedPixels: n, changedFraction, lumaStdDev, pageErrors, thresholds: THRESHOLDS, screenshot: output }; + console.log(JSON.stringify(report, null, 2)); + if (process.argv[4]) await writeFile(process.argv[4], `${JSON.stringify(report, null, 2)}\n`); + assert.ok(changedFraction >= THRESHOLDS.changedFraction, `globe changed ${changedFraction} of the central crop`); + assert.ok(lumaStdDev >= THRESHOLDS.minLumaStdDev, `globe crop is flat (luma std dev ${lumaStdDev})`); +} finally { + await browser?.close(); + await new Promise((done) => server.httpServer.close(done)); +} From 7656e3903187ed9a175210923aa829f3d9c4e188 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 17:41:46 -0600 Subject: [PATCH 04/18] ci(factory): record the unit baseline at nightly 53f0caa6 --- ci/factory/unit-baseline.json | 1250 +++++++++++++++++++++++++++++++++ 1 file changed, 1250 insertions(+) create mode 100644 ci/factory/unit-baseline.json diff --git a/ci/factory/unit-baseline.json b/ci/factory/unit-baseline.json new file mode 100644 index 00000000000..044f28bff98 --- /dev/null +++ b/ci/factory/unit-baseline.json @@ -0,0 +1,1250 @@ +{ + "schema": 1, + "commit": "53f0caa6e54d9769740d69424e8bf26364b00a6a", + "tree": "0629f67b790b64e62a0e66aaf8f14d52c8e589bb", + "dirty": false, + "packageLockSha256": "82038ae6fab86ffecf3d70cd04108c3552aca7bc6e90213d2773c982bea7a6b5", + "harnessSha256": "bec734239bc71d8941e9962874cfe79bdc107b5634695778c448b1dd9a96ae5c", + "environment": { + "node": "24.22.2", + "npm": "11.19.1", + "platform": "linux", + "arch": "x64", + "osRelease": "6.8.0-117-generic", + "cpus": 4, + "memoryGiB": 8, + "runner": "boat-default-4vcpu" + }, + "generatedAt": "2026-11-25T23:37:55.062Z", + "command": "node scripts/factory-ci.mjs unit --write-baseline", + "counts": { + "tests": 14427, + "passed": 14424, + "failed": 0, + "cancelled": 0, + "skipped": 3, + "todo": 0 + }, + "failures": [], + "skipped": [ + "src/keySetupHardening.test.mjs > Windows production hardener applies its exact DACL with native tools", + "src/layers/wildlifeSightings/model.perf.test.mjs > 500 / 2,000 / 5,000 icon model updates stay within their named timing budgets", + "src/layers/wildlifeSightings/render.perf.test.mjs > dense continental production moveEnd pipeline yields every 4ms, including cold tiles and real Cesium billboard updates" + ], + "testsPerFile": { + "server/providers/acartia.test.mjs": 12, + "server/providers/aircraft/openskyCredentials.test.mjs": 4, + "server/providers/cctv/ontario511.test.mjs": 9, + "server/providers/common/rateLimitKeys.test.mjs": 2, + "server/providers/common/request.test.mjs": 7, + "server/providers/ghostMaps.test.mjs": 6, + "server/providers/inaturalist/client.test.mjs": 5, + "server/providers/inaturalist/grid.test.mjs": 11, + "server/providers/inaturalist/observations.test.mjs": 25, + "server/providers/inaturalist/queue.test.mjs": 4, + "server/providers/inaturalist/speed.test.mjs": 7, + "server/providers/library.test.mjs": 11, + "server/providers/news.test.mjs": 10, + "server/providers/news/gdeltEvents.test.mjs": 15, + "server/providers/news/keyed.test.mjs": 42, + "server/providers/overpass/requestAdmission.test.mjs": 13, + "server/providers/transitHistory.test.mjs": 20, + "src/agent/worldPacket.test.mjs": 7, + "src/annotations/adminOutline.test.mjs": 12, + "src/annotations/annotationEngine.test.mjs": 49, + "src/annotations/annotationResolver.test.mjs": 24, + "src/annotations/drawMarks.test.mjs": 6, + "src/annotations/drawMode.test.mjs": 17, + "src/annotations/drawTool.test.mjs": 8, + "src/annotations/drawToolBehaviour.test.mjs": 20, + "src/annotations/hybridAnnotationRenderer.test.mjs": 10, + "src/annotations/outlineIdentity.test.mjs": 4, + "src/annotations/outlineRungs.test.mjs": 21, + "src/annotations/outlineRungsFallback.test.mjs": 6, + "src/annotations/placeOutline.test.mjs": 18, + "src/annotations/regionRing.test.mjs": 9, + "src/annotations/screenAnnotationRenderer.test.mjs": 11, + "src/annotations/worldAnnotationRenderer.test.mjs": 7, + "src/app/application.test.mjs": 40, + "src/app/atmosphereCompat.test.mjs": 15, + "src/app/catalog.test.mjs": 5, + "src/app/constructCatalog.test.mjs": 4, + "src/app/controls.test.mjs": 1, + "src/app/embed.test.mjs": 28, + "src/app/embedTerrainTakeover.test.mjs": 2, + "src/app/globePanelRuntime.test.mjs": 1, + "src/app/layers/streetLevel.test.mjs": 3, + "src/app/layers/transit.test.mjs": 3, + "src/app/mapLifecycle.test.mjs": 2, + "src/app/operations.test.mjs": 4, + "src/app/panelRendering.test.mjs": 3, + "src/app/renderFailureInlineRetry.test.mjs": 3, + "src/app/scene.test.mjs": 4, + "src/app/sourceComposition.test.mjs": 10, + "src/app/startupCamera.test.mjs": 2, + "src/app/stateChannel.test.mjs": 5, + "src/awarenessEcho.test.mjs": 5, + "src/browserModuleBoundary.test.mjs": 1, + "src/cameraGlobeRotation.test.mjs": 144, + "src/cameraGroundGuard.test.mjs": 23, + "src/cameraHandoff.test.mjs": 15, + "src/cameraTilt.test.mjs": 60, + "src/cctvFocusPolicy.test.mjs": 4, + "src/cctvFocusRequest.test.mjs": 3, + "src/celestialRing.test.mjs": 14, + "src/celestialRingView.test.mjs": 10, + "src/cityPresets.test.mjs": 8, + "src/cockpitCloudEffects.test.mjs": 5, + "src/cockpitLook.test.mjs": 11, + "src/cockpitMarkup.test.mjs": 39, + "src/cockpitMath.test.mjs": 38, + "src/cockpitOrbital.test.mjs": 27, + "src/cockpitOrbitalFocus.test.mjs": 7, + "src/cockpitOrbitalSatellites.test.mjs": 3, + "src/cockpitProgress.test.mjs": 6, + "src/cockpitRadar.test.mjs": 9, + "src/cockpitSignalFocus.test.mjs": 11, + "src/cockpitSubjectProviders.test.mjs": 18, + "src/cockpitSubjects.test.mjs": 8, + "src/cockpitTracking.test.mjs": 10, + "src/cockpitUtilityLayout.test.mjs": 15, + "src/cockpitVisionPolicy.test.mjs": 6, + "src/codexOauthRealtime.test.mjs": 8, + "src/contactsDetectionPolicy.test.mjs": 18, + "src/contextModePolicy.test.mjs": 33, + "src/contextSessionOrdering.test.mjs": 21, + "src/contextTabKeyboard.test.mjs": 7, + "src/costEndpointThrottle.test.mjs": 11, + "src/creditAttribution.test.mjs": 16, + "src/cyberSonar.test.mjs": 15, + "src/cyberSonarScene.test.mjs": 9, + "src/data/adminBoundaries.test.mjs": 19, + "src/data/adsbLolFallback.test.mjs": 3, + "src/data/aircraftClass.test.mjs": 6, + "src/data/aircraftEmergency.test.mjs": 6, + "src/data/aircraftEmergencyAnalyst.test.mjs": 10, + "src/data/aircraftIconLayer.test.mjs": 4, + "src/data/aircraftMeta.test.mjs": 2, + "src/data/aircraftModelLayer.test.mjs": 7, + "src/data/aircraftModelLighting.test.mjs": 4, + "src/data/aircraftNearbyPolicy.test.mjs": 1, + "src/data/aircraftRecession.test.mjs": 8, + "src/data/aisLiveVessels.analyst.test.mjs": 5, + "src/data/aisLiveVessels.test.mjs": 88, + "src/data/aisStreamAdapter.test.mjs": 38, + "src/data/aisStreamSentinels.test.mjs": 15, + "src/data/aisWatchdog.test.mjs": 49, + "src/data/aisWatchdogTransport.test.mjs": 3, + "src/data/alprCameras.test.mjs": 42, + "src/data/ambiguous-camera-direction.test.mjs": 2, + "src/data/analystEngine.test.mjs": 68, + "src/data/areaGeometry.test.mjs": 10, + "src/data/areaResolver.test.mjs": 36, + "src/data/bhoteKoshiEmbeddedMedia.test.mjs": 20, + "src/data/bhoteKoshiEvent.test.mjs": 50, + "src/data/bhoteKoshiEvidenceFit.test.mjs": 3, + "src/data/bhoteKoshiEvidencePublisher.test.mjs": 2, + "src/data/bhoteKoshiLocator.test.mjs": 21, + "src/data/bhoteKoshiPanelView.test.mjs": 3, + "src/data/bhoteKoshiShotPaths.test.mjs": 4, + "src/data/bikeshare.test.mjs": 2, + "src/data/boundaryLabels.test.mjs": 4, + "src/data/bundledJson.test.mjs": 6, + "src/data/cameraFraming.test.mjs": 4, + "src/data/cctv.test.mjs": 59, + "src/data/cctvA22.test.mjs": 8, + "src/data/cctvCalgary.test.mjs": 13, + "src/data/cctvCards.test.mjs": 23, + "src/data/cctvCatalogCap.test.mjs": 16, + "src/data/cctvCataloniaSource.test.mjs": 16, + "src/data/cctvDisplayCode.test.mjs": 2, + "src/data/cctvDriveBcSource.test.mjs": 6, + "src/data/cctvEstonia.test.mjs": 12, + "src/data/cctvFintraffic.test.mjs": 8, + "src/data/cctvFlorida.test.mjs": 13, + "src/data/cctvFootprint.test.mjs": 3, + "src/data/cctvGizmo.test.mjs": 16, + "src/data/cctvGroundHeights.test.mjs": 2, + "src/data/cctvHk.test.mjs": 15, + "src/data/cctvHlsStream.test.mjs": 12, + "src/data/cctvHouston.test.mjs": 14, + "src/data/cctvIceland.test.mjs": 13, + "src/data/cctvKingCountySource.test.mjs": 9, + "src/data/cctvLithuania.test.mjs": 11, + "src/data/cctvLod.test.mjs": 29, + "src/data/cctvMediaFeedType.test.mjs": 12, + "src/data/cctvMediaRange.test.mjs": 21, + "src/data/cctvMissingNumbers.test.mjs": 6, + "src/data/cctvNswSource.test.mjs": 6, + "src/data/cctvNyc.test.mjs": 17, + "src/data/cctvOttawa.test.mjs": 7, + "src/data/cctvProxy.test.mjs": 22, + "src/data/cctvSourcePins.test.mjs": 3, + "src/data/cctvTaiwan.test.mjs": 18, + "src/data/cctvToronto.test.mjs": 15, + "src/data/cctvTxdotSource.test.mjs": 10, + "src/data/cctvVegvesen.test.mjs": 31, + "src/data/cctvViewshed.test.mjs": 8, + "src/data/cctvViewThinning.test.mjs": 9, + "src/data/cctvWarendorf.test.mjs": 3, + "src/data/cctvWorldQuebec.test.mjs": 10, + "src/data/cctvWsdotSource.test.mjs": 8, + "src/data/cockpitAirLod.test.mjs": 3, + "src/data/cockpitDetectionSubjects.test.mjs": 4, + "src/data/cockpitModels.test.mjs": 15, + "src/data/contactMatch.test.mjs": 10, + "src/data/contactPlayback.test.mjs": 16, + "src/data/contactTrailRenderer.test.mjs": 10, + "src/data/contextStore.test.mjs": 12, + "src/data/courseFromFixes.test.mjs": 2, + "src/data/cyclonesProxy.test.mjs": 13, + "src/data/dataCredits.test.mjs": 18, + "src/data/detectionAwarenessEcho.test.mjs": 3, + "src/data/detectionCohort.test.mjs": 3, + "src/data/detectionDraw.test.mjs": 22, + "src/data/detectionHost.test.mjs": 30, + "src/data/detectionOcclusion.test.mjs": 32, + "src/data/detectionPolicy.test.mjs": 15, + "src/data/detectionPresentation.test.mjs": 2, + "src/data/detectionRenderDemand.test.mjs": 11, + "src/data/detectionSonarAdmission.test.mjs": 1, + "src/data/directions.test.mjs": 28, + "src/data/directionText.test.mjs": 5, + "src/data/displayDelay.test.mjs": 12, + "src/data/distanceFormat.test.mjs": 5, + "src/data/droneAirspaceProxy.test.mjs": 13, + "src/data/earthquakes.test.mjs": 12, + "src/data/entityContext.test.mjs": 18, + "src/data/entityRecords.test.mjs": 5, + "src/data/fireAnchors.test.mjs": 6, + "src/data/firePerimetersProxy.test.mjs": 17, + "src/data/firms-calendar-validity.test.mjs": 1, + "src/data/firms-coordinate-evidence.test.mjs": 2, + "src/data/firmsAdapt.test.mjs": 10, + "src/data/firmsCards.test.mjs": 13, + "src/data/firmsCsv.test.mjs": 20, + "src/data/firmsHeatmap.test.mjs": 6, + "src/data/firmsHeatRaster.test.mjs": 8, + "src/data/firmsHorizonCull.test.mjs": 19, + "src/data/firmsIntensity.test.mjs": 11, + "src/data/firmsInteraction.test.mjs": 22, + "src/data/firmsLabels.test.mjs": 5, + "src/data/firmsProxy.test.mjs": 17, + "src/data/fixCurve.test.mjs": 6, + "src/data/fleetModelInstances.test.mjs": 14, + "src/data/fleetModels.test.mjs": 20, + "src/data/flights.test.mjs": 62, + "src/data/flowMatch.test.mjs": 17, + "src/data/focusAllocations.test.mjs": 1, + "src/data/focusDeemphasis.test.mjs": 13, + "src/data/focusResumeGate.test.mjs": 3, + "src/data/followed.test.mjs": 7, + "src/data/gbfsProxy.test.mjs": 14, + "src/data/gbfsProxyRateLimit.test.mjs": 4, + "src/data/geoFileImport.test.mjs": 42, + "src/data/geoid.test.mjs": 12, + "src/data/geoImportFeatures.test.mjs": 10, + "src/data/geoImportPins.test.mjs": 8, + "src/data/geojsonPins.test.mjs": 7, + "src/data/gnssIntegrityProxy.test.mjs": 18, + "src/data/groundFloor.test.mjs": 61, + "src/data/gtfsRealtime.test.mjs": 14, + "src/data/headingDegrees.test.mjs": 5, + "src/data/iconOrientation.test.mjs": 23, + "src/data/iconSegment.test.mjs": 12, + "src/data/iconSet.test.mjs": 20, + "src/data/infrastructure.test.mjs": 5, + "src/data/inputOwnership.test.mjs": 14, + "src/data/installationFeedback.test.mjs": 4, + "src/data/installationProxy.test.mjs": 17, + "src/data/irishRail.test.mjs": 5, + "src/data/labelArbiter.test.mjs": 26, + "src/data/labelArbiterDifferential.test.mjs": 1, + "src/data/layerSnapshot.test.mjs": 13, + "src/data/layerState.test.mjs": 78, + "src/data/layerStateTokenLedger.test.mjs": 8, + "src/data/libraryRegistration.test.mjs": 1, + "src/data/localGeojson.analyst.test.mjs": 6, + "src/data/localGeojson.test.mjs": 42, + "src/data/localGeojsonDraw.test.mjs": 7, + "src/data/localGeojsonLifecycle.test.mjs": 7, + "src/data/localGeojsonLod.test.mjs": 32, + "src/data/localReceiversProxy.test.mjs": 12, + "src/data/manager.test.mjs": 103, + "src/data/managerPanel.test.mjs": 16, + "src/data/meshFloorSampler.test.mjs": 19, + "src/data/militaryAwareness.test.mjs": 86, + "src/data/militaryAwarenessEngine.test.mjs": 10, + "src/data/militaryFlights.test.mjs": 17, + "src/data/militaryInstallationData.test.mjs": 12, + "src/data/militaryInstallations.test.mjs": 28, + "src/data/militaryNames.test.mjs": 7, + "src/data/militaryRegistry.test.mjs": 3, + "src/data/modelEligibility.test.mjs": 3, + "src/data/modelMatrix.test.mjs": 3, + "src/data/modelRecord.test.mjs": 2, + "src/data/modelScale.test.mjs": 12, + "src/data/motionModel.test.mjs": 30, + "src/data/naturalEarthRegions.test.mjs": 20, + "src/data/nearbyModelHandoff.test.mjs": 6, + "src/data/neighborhoodPolygons.test.mjs": 5, + "src/data/openVesselPhoto.test.mjs": 7, + "src/data/osmOverlays.test.mjs": 9, + "src/data/overpassProxy.test.mjs": 10, + "src/data/packGeometry.test.mjs": 3, + "src/data/pickedContext.test.mjs": 5, + "src/data/pickRegistry.test.mjs": 13, + "src/data/placeBelow.test.mjs": 16, + "src/data/placeBoundaries.test.mjs": 17, + "src/data/placementProvider.test.mjs": 3, + "src/data/placePacksLoading.test.mjs": 5, + "src/data/planespottersPhoto.test.mjs": 11, + "src/data/radio.test.mjs": 55, + "src/data/radioCountry.test.mjs": 4, + "src/data/radioNextState.test.mjs": 16, + "src/data/radioProxy.test.mjs": 34, + "src/data/railFeeds.test.mjs": 16, + "src/data/railFeedsAsia.test.mjs": 3, + "src/data/railFeedsDocs.test.mjs": 4, + "src/data/railFeedsFrance.test.mjs": 5, + "src/data/railFeedsNational.test.mjs": 3, + "src/data/railFeedsUs.test.mjs": 2, + "src/data/railFeedsUsNoTerms.test.mjs": 3, + "src/data/railFeedsUsUrban.test.mjs": 4, + "src/data/railIreland.test.mjs": 4, + "src/data/railNoPositions.test.mjs": 8, + "src/data/railPaths.test.mjs": 7, + "src/data/railProxy.test.mjs": 23, + "src/data/railSchedule.test.mjs": 16, + "src/data/railSiriVm.test.mjs": 8, + "src/data/railTripUpdates.test.mjs": 7, + "src/data/regional-calendar-evidence.test.mjs": 1, + "src/data/regionalBrief.test.mjs": 6, + "src/data/regionalProxy.test.mjs": 9, + "src/data/renderAltitude.test.mjs": 19, + "src/data/renderedFrames.test.mjs": 2, + "src/data/retryableLoad.test.mjs": 8, + "src/data/rocketLaunches.test.mjs": 67, + "src/data/route-cap-truthfulness.test.mjs": 1, + "src/data/routePlausible.test.mjs": 6, + "src/data/routeSegment.test.mjs": 8, + "src/data/routeSteps.test.mjs": 5, + "src/data/satelliteClass.test.mjs": 18, + "src/data/satellitePass.test.mjs": 11, + "src/data/satellites.analyst.test.mjs": 9, + "src/data/satellitesTrackedRefresh.test.mjs": 7, + "src/data/satellitesVisibility.test.mjs": 2, + "src/data/scenePick.test.mjs": 6, + "src/data/sharedOsmDisplays.test.mjs": 7, + "src/data/shipwrecksProxy.test.mjs": 11, + "src/data/spriteOrder.test.mjs": 3, + "src/data/tapAddress.test.mjs": 12, + "src/data/telegeographySubmarineCables.test.mjs": 27, + "src/data/terrainHeights.test.mjs": 16, + "src/data/terrainHeightsProxy.test.mjs": 10, + "src/data/tileBudget.test.mjs": 1, + "src/data/timelineHistory.test.mjs": 7, + "src/data/tomtomTiles.test.mjs": 18, + "src/data/tr3bRegistry.test.mjs": 13, + "src/data/trackedAircraftIcon.test.mjs": 4, + "src/data/trackedCamera.test.mjs": 7, + "src/data/trackedCardLocale.test.mjs": 2, + "src/data/trackedModelForm.test.mjs": 28, + "src/data/trackedReadout.test.mjs": 10, + "src/data/trackingClickGesture.test.mjs": 5, + "src/data/traffic.test.mjs": 14, + "src/data/trafficBounds.test.mjs": 10, + "src/data/trafficFlowStyle.test.mjs": 14, + "src/data/trafficPresetStyle.test.mjs": 10, + "src/data/trafficQueue.test.mjs": 10, + "src/data/trafficTiming.test.mjs": 3, + "src/data/trailGroundJoin.test.mjs": 6, + "src/data/trailRenderer.test.mjs": 10, + "src/data/trailReports.test.mjs": 6, + "src/data/transit.test.mjs": 8, + "src/data/transitFeeds.test.mjs": 50, + "src/data/transitIcons.test.mjs": 7, + "src/data/transitPresetStyle.test.mjs": 6, + "src/data/transitProxy.test.mjs": 18, + "src/data/ucsSatellites.test.mjs": 4, + "src/data/vesselLabels.test.mjs": 6, + "src/data/vesselTypeCardLabel.test.mjs": 3, + "src/data/vesselTypes.test.mjs": 2, + "src/data/weather-missing-observations.test.mjs": 1, + "src/data/weatherProxy.test.mjs": 35, + "src/data/wikidataCities.test.mjs": 8, + "src/data/windDecode.test.mjs": 1, + "src/data/windGfs.test.mjs": 5, + "src/data/windGrid.test.mjs": 4, + "src/data/windIfs.test.mjs": 3, + "src/data/windProxy.test.mjs": 17, + "src/devCctv.test.mjs": 4, + "src/devFreshDotenv.test.mjs": 6, + "src/director/camera.test.mjs": 4, + "src/director/clock.test.mjs": 7, + "src/director/director-dateline-seek.test.mjs": 3, + "src/director/document.test.mjs": 8, + "src/director/interactions/interactions.test.mjs": 8, + "src/director/packs/asset-stream-cancellation.test.mjs": 2, + "src/director/packs/packs.test.mjs": 12, + "src/director/playback.test.mjs": 31, + "src/director/sharing/sharing.test.mjs": 10, + "src/director/timeline.test.mjs": 3, + "src/dockerLauncher.test.mjs": 4, + "src/dockerTrustedPeers.test.mjs": 4, + "src/firstRunExperience.test.mjs": 34, + "src/firstRunLauncherView.test.mjs": 7, + "src/geminiChatServer.test.mjs": 5, + "src/geminiComposition.test.mjs": 4, + "src/geminiServer.test.mjs": 40, + "src/geo/celestial.test.mjs": 7, + "src/geo/frustum.test.mjs": 2, + "src/geo/geo.test.mjs": 10, + "src/geo/geodesic.test.mjs": 3, + "src/geo/horizon.test.mjs": 2, + "src/geo/julian.test.mjs": 4, + "src/geo/polyline.test.mjs": 3, + "src/geo/quaternion.test.mjs": 7, + "src/geo/rectangle.test.mjs": 2, + "src/geo/rhumb.test.mjs": 2, + "src/geo/screenCluster.test.mjs": 6, + "src/geo/sphere.test.mjs": 2, + "src/geoDistance.test.mjs": 6, + "src/googleGeocodeProxy.test.mjs": 5, + "src/googlePlacesCoordinates.test.mjs": 3, + "src/googlePlacesKeyless.test.mjs": 2, + "src/googleServerKey.test.mjs": 6, + "src/hudA11y.test.mjs": 3, + "src/hudAltitudeDatum.test.mjs": 14, + "src/hudDms.test.mjs": 4, + "src/hudLocality.test.mjs": 9, + "src/hudPageVisibility.test.mjs": 1, + "src/hudSummaryGate.test.mjs": 7, + "src/hudSummaryLine.test.mjs": 26, + "src/hudSummaryResponse.test.mjs": 31, + "src/i18n/ar-display.test.mjs": 5, + "src/i18n/catalog.test.mjs": 25, + "src/i18n/empty-translation.test.mjs": 4, + "src/i18n/firms-live-zh.test.mjs": 3, + "src/i18n/i18n.test.mjs": 19, + "src/i18n/ja-display.test.mjs": 1, + "src/i18n/ja-hud-units.test.mjs": 1, + "src/i18n/kartaviewMessages.test.mjs": 3, + "src/i18n/layerStatusText.test.mjs": 63, + "src/i18n/messageOverrides.test.mjs": 5, + "src/i18n/page.test.mjs": 4, + "src/i18n/plural-english.test.mjs": 10, + "src/i18n/stale-index.test.mjs": 1, + "src/i18n/zh-CN-display.test.mjs": 5, + "src/i18n/zh-Hant-display.test.mjs": 3, + "src/input/dispatcher.test.mjs": 37, + "src/keyboardFocusStyles.test.mjs": 5, + "src/keylessGeocoder.test.mjs": 44, + "src/keySetup.test.mjs": 8, + "src/keySetupCore.test.mjs": 24, + "src/keySetupErrorLocale.test.mjs": 6, + "src/keySetupHardening.test.mjs": 17, + "src/keySetupOAuthFailure.test.mjs": 2, + "src/keySetupOAuthI18n.test.mjs": 3, + "src/layers/aircraft/classification.test.mjs": 6, + "src/layers/airQuality/airQualityLocale.test.mjs": 9, + "src/layers/airQuality/model.test.mjs": 18, + "src/layers/airQuality/ownership.test.mjs": 16, + "src/layers/airQuality/source.test.mjs": 9, + "src/layers/alpr/overlay.test.mjs": 13, + "src/layers/alpr/source.test.mjs": 13, + "src/layers/awareness/anchor.test.mjs": 1, + "src/layers/awareness/directionOverlay.test.mjs": 3, + "src/layers/awareness/panel.test.mjs": 6, + "src/layers/awareness/presentation.test.mjs": 1, + "src/layers/awareness/queries.test.mjs": 3, + "src/layers/awareness/rangeRing.test.mjs": 40, + "src/layers/awareness/selectedVessel.test.mjs": 3, + "src/layers/awareness/staleAfterLoading.test.mjs": 2, + "src/layers/bikeshare/barcelonaSystems.test.mjs": 5, + "src/layers/bikeshare/brPbscCities.test.mjs": 2, + "src/layers/bikeshare/failureReporting.test.mjs": 12, + "src/layers/bikeshare/latamPbscCities.test.mjs": 5, + "src/layers/bikeshare/proxyRoute.test.mjs": 11, + "src/layers/bikeshare/registry.test.mjs": 3, + "src/layers/bikeshare/rowRepaint.test.mjs": 10, + "src/layers/bikeshare/source.test.mjs": 2, + "src/layers/bikeshare/spainCitiesSystems.test.mjs": 7, + "src/layers/bikeshare/usPbscCities.test.mjs": 3, + "src/layers/cctv/drawSets.test.mjs": 3, + "src/layers/cctv/frames.test.mjs": 7, + "src/layers/cctv/geometry.test.mjs": 2, + "src/layers/cctv/headingConfidence.test.mjs": 8, + "src/layers/cctv/lifecycle.test.mjs": 1, + "src/layers/cctv/modelSpecs.test.mjs": 23, + "src/layers/cctv/presentation.i18n.test.mjs": 2, + "src/layers/cctv/presentation.test.mjs": 2, + "src/layers/cctv/rendering.test.mjs": 7, + "src/layers/cctv/selection.test.mjs": 2, + "src/layers/cctv/source.test.mjs": 7, + "src/layers/cctv/videoPlayback.test.mjs": 6, + "src/layers/cyclones/coverage.test.mjs": 4, + "src/layers/cyclones/index.test.mjs": 16, + "src/layers/cyclones/labels.test.mjs": 4, + "src/layers/cyclones/rendering.test.mjs": 10, + "src/layers/cyclones/source.test.mjs": 5, + "src/layers/directions/source.test.mjs": 5, + "src/layers/directions/statusLocale.test.mjs": 5, + "src/layers/droneAirspace/cards.test.mjs": 3, + "src/layers/droneAirspace/docs.test.mjs": 3, + "src/layers/droneAirspace/ownership.test.mjs": 7, + "src/layers/droneAirspace/records.test.mjs": 5, + "src/layers/droneAirspace/source.test.mjs": 5, + "src/layers/earthquakes/ownership.test.mjs": 8, + "src/layers/earthquakes/records.test.mjs": 7, + "src/layers/feedDegradationI18n.test.mjs": 3, + "src/layers/firms/cells.test.mjs": 3, + "src/layers/firms/heatImagery.test.mjs": 6, + "src/layers/firms/heatVisibility.test.mjs": 1, + "src/layers/firms/model.test.mjs": 2, + "src/layers/firms/source.test.mjs": 3, + "src/layers/firms/windowLabel.test.mjs": 2, + "src/layers/flights/clockFollow.test.mjs": 9, + "src/layers/flights/controller.test.mjs": 2, + "src/layers/flights/icons.test.mjs": 7, + "src/layers/flights/ingestion.test.mjs": 2, + "src/layers/flights/motion.test.mjs": 9, + "src/layers/flights/ownership.test.mjs": 17, + "src/layers/flights/queries.test.mjs": 4, + "src/layers/flights/recordPolicy.test.mjs": 1, + "src/layers/flights/records.test.mjs": 11, + "src/layers/flights/snapshotStale.test.mjs": 4, + "src/layers/flights/staleHold.test.mjs": 10, + "src/layers/flights/trail.test.mjs": 11, + "src/layers/flights/trailRecord.test.mjs": 14, + "src/layers/ghostMaps/catalog.test.mjs": 6, + "src/layers/ghostMaps/lifecycle.test.mjs": 35, + "src/layers/ghostMaps/records.test.mjs": 11, + "src/layers/gnss/ownership.test.mjs": 23, + "src/layers/gnss/records.test.mjs": 22, + "src/layers/gnss/source.test.mjs": 3, + "src/layers/gnss/sourceErrorLocale.test.mjs": 2, + "src/layers/installations/classLabel.packClasses.test.mjs": 2, + "src/layers/installations/ingestion.test.mjs": 3, + "src/layers/installations/installationFeedbackLocale.test.mjs": 3, + "src/layers/installations/lifecycle.test.mjs": 4, + "src/layers/installations/namedMarkers.test.mjs": 7, + "src/layers/installations/namesLoading.test.mjs": 5, + "src/layers/installations/navigation.test.mjs": 3, + "src/layers/installations/selection.test.mjs": 10, + "src/layers/installations/selectionFill.test.mjs": 3, + "src/layers/installations/source.test.mjs": 10, + "src/layers/installations/unnamedInstallationTitle.test.mjs": 4, + "src/layers/launches/failedEntry.test.mjs": 12, + "src/layers/launches/hover.test.mjs": 7, + "src/layers/launches/ingestion.test.mjs": 9, + "src/layers/launches/missionStatus.i18n.test.mjs": 2, + "src/layers/launches/panel.test.mjs": 4, + "src/layers/launches/replay.test.mjs": 1, + "src/layers/launches/replayOverlay.test.mjs": 3, + "src/layers/launches/source.test.mjs": 3, + "src/layers/launches/worldTime.test.mjs": 4, + "src/layers/localAdsb/card.i18n.test.mjs": 5, + "src/layers/localAdsb/card.test.mjs": 1, + "src/layers/localAdsb/feeds.test.mjs": 9, + "src/layers/localAdsb/index.test.mjs": 28, + "src/layers/localAdsb/motion.test.mjs": 10, + "src/layers/localAdsb/statusLocale.test.mjs": 8, + "src/layers/military/clockFollow.test.mjs": 3, + "src/layers/military/ingestion.test.mjs": 2, + "src/layers/military/ownership.test.mjs": 8, + "src/layers/military/records.test.mjs": 10, + "src/layers/military/snapshotRenderer.test.mjs": 4, + "src/layers/military/snapshotStale.test.mjs": 4, + "src/layers/military/staleHold.test.mjs": 4, + "src/layers/military/trail.test.mjs": 5, + "src/layers/military/trailRecord.test.mjs": 10, + "src/layers/news/cards.test.mjs": 3, + "src/layers/news/layer.test.mjs": 29, + "src/layers/news/model.test.mjs": 21, + "src/layers/news/source.test.mjs": 5, + "src/layers/osmPlaces/index.test.mjs": 5, + "src/layers/perimeters/cards.i18n.test.mjs": 7, + "src/layers/perimeters/cards.test.mjs": 13, + "src/layers/perimeters/inciweb.test.mjs": 9, + "src/layers/perimeters/ownership.test.mjs": 20, + "src/layers/perimeters/records.test.mjs": 7, + "src/layers/perimeters/source.test.mjs": 8, + "src/layers/radio/ingestionErrors.i18n.test.mjs": 4, + "src/layers/radio/interaction.test.mjs": 2, + "src/layers/radio/lifecycle.test.mjs": 2, + "src/layers/radio/rendering.test.mjs": 2, + "src/layers/radio/source.test.mjs": 3, + "src/layers/rail/cockpitSubject.test.mjs": 13, + "src/layers/rail/dedupe.test.mjs": 16, + "src/layers/rail/follow.test.mjs": 15, + "src/layers/rail/groundHeight.test.mjs": 17, + "src/layers/rail/layerStats.test.mjs": 3, + "src/layers/rail/liveOnly.test.mjs": 13, + "src/layers/rail/pathBinding.test.mjs": 12, + "src/layers/rail/policy.test.mjs": 25, + "src/layers/rail/routeLines.test.mjs": 15, + "src/layers/rail/schedules.test.mjs": 16, + "src/layers/rail/source.test.mjs": 10, + "src/layers/rail/stopLabels.test.mjs": 10, + "src/layers/recentImagery/catalog.test.mjs": 5, + "src/layers/recentImagery/cmr-raw-page-budget.test.mjs": 4, + "src/layers/recentImagery/imagery-box-missing-edge.test.mjs": 2, + "src/layers/recentImagery/index.test.mjs": 46, + "src/layers/recentImagery/model.test.mjs": 15, + "src/layers/recentImagery/rendering.test.mjs": 8, + "src/layers/recentImagery/source.test.mjs": 2, + "src/layers/recentImagery/thumbnail-presence-proof.test.mjs": 1, + "src/layers/recentImagery/thumbnails.test.mjs": 9, + "src/layers/satellites/classes.test.mjs": 23, + "src/layers/satellites/cockpitSubject.test.mjs": 14, + "src/layers/satellites/ingestion.test.mjs": 9, + "src/layers/satellites/motion.test.mjs": 5, + "src/layers/satellites/nearestPositions.test.mjs": 1, + "src/layers/satellites/offCesium.test.mjs": 6, + "src/layers/satellites/reckon.test.mjs": 4, + "src/layers/satellites/sensors.test.mjs": 5, + "src/layers/satellites/source.test.mjs": 4, + "src/layers/satellites/stale.test.mjs": 9, + "src/layers/shipwrecks/cards.test.mjs": 3, + "src/layers/shipwrecks/eras.test.mjs": 1, + "src/layers/shipwrecks/index.test.mjs": 12, + "src/layers/shipwrecks/period.test.mjs": 3, + "src/layers/shipwrecks/records.test.mjs": 9, + "src/layers/shipwrecks/source.test.mjs": 1, + "src/layers/streetLevel/cameraFraming.test.mjs": 8, + "src/layers/streetLevel/filter.test.mjs": 5, + "src/layers/streetLevel/groundClick.test.mjs": 4, + "src/layers/streetLevel/imageSize.test.mjs": 3, + "src/layers/streetLevel/index.test.mjs": 77, + "src/layers/streetLevel/limiter.test.mjs": 4, + "src/layers/streetLevel/lineCoverage.test.mjs": 24, + "src/layers/streetLevel/marker.test.mjs": 7, + "src/layers/streetLevel/panorama.test.mjs": 7, + "src/layers/streetLevel/params.test.mjs": 3, + "src/layers/streetLevel/photoViewer.test.mjs": 15, + "src/layers/streetLevel/pickRouter.test.mjs": 3, + "src/layers/streetLevel/providers/google/mapsLoader.test.mjs": 8, + "src/layers/streetLevel/providers/google/provider.test.mjs": 15, + "src/layers/streetLevel/providers/google/viewer.test.mjs": 22, + "src/layers/streetLevel/providers/kartaview/decode.test.mjs": 8, + "src/layers/streetLevel/providers/kartaview/policy.test.mjs": 13, + "src/layers/streetLevel/providers/kartaview/provider.test.mjs": 31, + "src/layers/streetLevel/providers/kartaview/source.test.mjs": 23, + "src/layers/streetLevel/providers/kartaview/viewer.test.mjs": 32, + "src/layers/streetLevel/providers/mapillary/decode.test.mjs": 3, + "src/layers/streetLevel/providers/mapillary/mapillary.test.mjs": 3, + "src/layers/streetLevel/providers/mapillary/provider.test.mjs": 8, + "src/layers/streetLevel/providers/mapillary/replacePlay.test.mjs": 1, + "src/layers/streetLevel/providers/mapillary/source.test.mjs": 12, + "src/layers/streetLevel/providers/panoramax/decode.test.mjs": 10, + "src/layers/streetLevel/providers/panoramax/policy.test.mjs": 13, + "src/layers/streetLevel/providers/panoramax/provider.test.mjs": 42, + "src/layers/streetLevel/providers/panoramax/source.test.mjs": 21, + "src/layers/streetLevel/providers/panoramax/viewer.test.mjs": 10, + "src/layers/streetLevel/providerSwitches.test.mjs": 5, + "src/layers/streetLevel/registry.test.mjs": 7, + "src/layers/streetLevel/selection.test.mjs": 8, + "src/layers/streetLevel/sequenceCones.test.mjs": 8, + "src/layers/streetLevel/street-level-unique-tiles.test.mjs": 2, + "src/layers/streetLevel/tileMath.test.mjs": 10, + "src/layers/streetLevel/uiState.test.mjs": 10, + "src/layers/streetLevel/view.test.mjs": 16, + "src/layers/streetLevel/viewerHost.test.mjs": 27, + "src/layers/submarineCables/bundledSource.test.mjs": 2, + "src/layers/traffic/deadline.test.mjs": 15, + "src/layers/traffic/footprint.test.mjs": 5, + "src/layers/traffic/heatLines.test.mjs": 7, + "src/layers/traffic/hostModes.test.mjs": 11, + "src/layers/traffic/motion.test.mjs": 23, + "src/layers/traffic/navigation.test.mjs": 19, + "src/layers/traffic/renderDemand.test.mjs": 1, + "src/layers/traffic/roadModes.test.mjs": 26, + "src/layers/traffic/roadStatus.i18n.test.mjs": 10, + "src/layers/traffic/source.test.mjs": 44, + "src/layers/traffic/streaming.test.mjs": 4, + "src/layers/traffic/style.test.mjs": 4, + "src/layers/traffic/surface.test.mjs": 10, + "src/layers/traffic/timing.test.mjs": 2, + "src/layers/transit/lifecycle.test.mjs": 99, + "src/layers/transit/movement.test.mjs": 10, + "src/layers/transit/qaMetrics.test.mjs": 16, + "src/layers/transit/queries.test.mjs": 1, + "src/layers/transit/refreshErrorRepaint.test.mjs": 1, + "src/layers/transit/selectionCopy.i18n.test.mjs": 4, + "src/layers/transit/source.test.mjs": 2, + "src/layers/transit/vocabulary.test.mjs": 9, + "src/layers/vessels/cameraArea.test.mjs": 4, + "src/layers/vessels/clockFollow.test.mjs": 6, + "src/layers/vessels/cockpitSubject.test.mjs": 10, + "src/layers/vessels/ingestion.test.mjs": 5, + "src/layers/vessels/motion.test.mjs": 9, + "src/layers/vessels/motionSegments.test.mjs": 11, + "src/layers/vessels/ownership.test.mjs": 22, + "src/layers/vessels/photos.test.mjs": 3, + "src/layers/vessels/placement.test.mjs": 3, + "src/layers/vessels/radarContacts.test.mjs": 5, + "src/layers/vessels/records.test.mjs": 8, + "src/layers/vessels/renderGovernor.test.mjs": 16, + "src/layers/vessels/tracking.test.mjs": 8, + "src/layers/vessels/viewArea.test.mjs": 2, + "src/layers/weather/clock.test.mjs": 23, + "src/layers/weather/display.test.mjs": 22, + "src/layers/weather/imageryHost.test.mjs": 2, + "src/layers/weather/imageryOrder.test.mjs": 1, + "src/layers/weather/infraredAlpha.test.mjs": 3, + "src/layers/weather/infraredImage.test.mjs": 8, + "src/layers/weather/rasterTiles.test.mjs": 8, + "src/layers/weather/shellRendering.test.mjs": 29, + "src/layers/weather/source.test.mjs": 10, + "src/layers/weather/weather.test.mjs": 86, + "src/layers/wildlifeSightings/acartiaTaxa.test.mjs": 2, + "src/layers/wildlifeSightings/acquisition.test.mjs": 32, + "src/layers/wildlifeSightings/cache.integration.test.mjs": 1, + "src/layers/wildlifeSightings/cards.test.mjs": 19, + "src/layers/wildlifeSightings/density.test.mjs": 14, + "src/layers/wildlifeSightings/docs.test.mjs": 7, + "src/layers/wildlifeSightings/gridViewport.test.mjs": 6, + "src/layers/wildlifeSightings/model.perf.test.mjs": 1, + "src/layers/wildlifeSightings/model.test.mjs": 7, + "src/layers/wildlifeSightings/ownership.test.mjs": 45, + "src/layers/wildlifeSightings/performance.test.mjs": 8, + "src/layers/wildlifeSightings/photos.test.mjs": 4, + "src/layers/wildlifeSightings/records.test.mjs": 18, + "src/layers/wildlifeSightings/render.perf.test.mjs": 1, + "src/layers/wildlifeSightings/rendering.test.mjs": 11, + "src/layers/wildlifeSightings/selection.test.mjs": 8, + "src/layers/wildlifeSightings/source.test.mjs": 30, + "src/layers/wildlifeSightings/sprites.test.mjs": 5, + "src/layers/wildlifeSightings/viewport.test.mjs": 6, + "src/layers/wind/fields.test.mjs": 5, + "src/layers/wind/fieldUnavailableLocale.test.mjs": 3, + "src/layers/wind/gpuRendering.test.mjs": 5, + "src/layers/wind/index.test.mjs": 16, + "src/layers/wind/inspection.test.mjs": 2, + "src/layers/wind/inspectionMarker.test.mjs": 2, + "src/layers/wind/model.test.mjs": 3, + "src/layers/wind/presentation.test.mjs": 1, + "src/layers/wind/relief.test.mjs": 4, + "src/layers/wind/rendering.test.mjs": 37, + "src/layers/wind/source.test.mjs": 8, + "src/layers/wind/staleInfo.test.mjs": 1, + "src/layers/wind/streamlines.test.mjs": 5, + "src/layers/wind/windProblemLocale.test.mjs": 3, + "src/layers/wind/windUpstreamReason.test.mjs": 5, + "src/library/camera.test.mjs": 3, + "src/library/catalog.test.mjs": 3, + "src/library/controller.test.mjs": 19, + "src/library/datasetLayer.test.mjs": 12, + "src/library/extent.test.mjs": 3, + "src/library/formats.test.mjs": 13, + "src/library/manifest.test.mjs": 15, + "src/library/outlines.test.mjs": 4, + "src/library/parquet.test.mjs": 12, + "src/library/relief.test.mjs": 5, + "src/library/selection.test.mjs": 4, + "src/library/tileLayer.test.mjs": 9, + "src/library/viewLayer.test.mjs": 7, + "src/loadingFeedback.test.mjs": 43, + "src/localRequestGate.test.mjs": 14, + "src/locationReadouts.test.mjs": 7, + "src/locations.test.mjs": 41, + "src/locationStatus.test.mjs": 8, + "src/logoGaze.test.mjs": 6, + "src/maps/controller.test.mjs": 44, + "src/maps/globeEngine.test.mjs": 14, + "src/maps/googleTokens.test.mjs": 5, + "src/maps/imageryHost.test.mjs": 4, + "src/maps/map-subscription-ownership.test.mjs": 4, + "src/maps/terrainRetry.test.mjs": 9, + "src/mapSourceFocus.test.mjs": 29, + "src/mapStackChips.test.mjs": 9, + "src/mapStackUnavailableReason.test.mjs": 3, + "src/mapStartup.test.mjs": 14, + "src/materialSymbolsSubset.test.mjs": 2, + "src/navigationPolicy.test.mjs": 21, + "src/navigationPolicyFrame.test.mjs": 3, + "src/noCesiumLabels.test.mjs": 4, + "src/nominatimGeocode.test.mjs": 8, + "src/overlays/wildlifeSightingOverlay.test.mjs": 3, + "src/overlays/worldOverlay.test.mjs": 57, + "src/overlays/worldOverlayActionsView.test.mjs": 3, + "src/overlays/worldOverlayAllocation.test.mjs": 14, + "src/overlays/worldOverlayDraw.test.mjs": 25, + "src/overlays/worldOverlayTokens.test.mjs": 1, + "src/overpassOffload.test.mjs": 12, + "src/overpassProxy.test.mjs": 10, + "src/panelEscape.test.mjs": 12, + "src/panelStackLayout.test.mjs": 21, + "src/perfTestRunner.test.mjs": 2, + "src/pinokioEnvironment.test.mjs": 7, + "src/pinokioLauncherContract.test.mjs": 9, + "src/pinokioPreflight.test.mjs": 6, + "src/pinokioUpdatePreview.test.mjs": 25, + "src/proxyErrorResponses.test.mjs": 20, + "src/qaChrome.test.mjs": 5, + "src/qaL9MatrixVerdicts.test.mjs": 29, + "src/qaVesselCardsHarness.test.mjs": 5, + "src/queries/heights.test.mjs": 16, + "src/radioMarkup.test.mjs": 12, + "src/reasonableDefaults.test.mjs": 10, + "src/render/camera/events.test.mjs": 3, + "src/render/camera/poseSignature.test.mjs": 3, + "src/render/cesium/applicationViewer.test.mjs": 5, + "src/render/cesium/appRenderer.test.mjs": 11, + "src/render/cesium/cameraControls.test.mjs": 13, + "src/render/cesium/cameraGoldens.test.mjs": 1, + "src/render/cesium/cameraInput.test.mjs": 2, + "src/render/cesium/cameraPort.test.mjs": 13, + "src/render/cesium/common.test.mjs": 6, + "src/render/cesium/controlledCamera.test.mjs": 12, + "src/render/cesium/creditKeyboard.test.mjs": 11, + "src/render/cesium/credits.test.mjs": 18, + "src/render/cesium/draw.test.mjs": 144, + "src/render/cesium/drawFields.test.mjs": 17, + "src/render/cesium/drawIconMoves.test.mjs": 1, + "src/render/cesium/drawStreamlines.test.mjs": 14, + "src/render/cesium/effects.test.mjs": 16, + "src/render/cesium/follow.test.mjs": 14, + "src/render/cesium/frame.test.mjs": 7, + "src/render/cesium/globe.test.mjs": 31, + "src/render/cesium/gpuIcons.test.mjs": 32, + "src/render/cesium/heights.test.mjs": 13, + "src/render/cesium/iconSetPrimitive.test.mjs": 2, + "src/render/cesium/imageryFrames.test.mjs": 10, + "src/render/cesium/imageryLookAhead.test.mjs": 7, + "src/render/cesium/input.test.mjs": 18, + "src/render/cesium/internals.test.mjs": 5, + "src/render/cesium/mapSources.test.mjs": 11, + "src/render/cesium/nativeClick.test.mjs": 18, + "src/render/cesium/ports.test.mjs": 43, + "src/render/cesium/quality.test.mjs": 21, + "src/render/cesium/query.test.mjs": 7, + "src/render/cesium/renderFailure.test.mjs": 9, + "src/render/cesium/renderFailureEventRetry.test.mjs": 18, + "src/render/cesium/renderFailureLoopErrors.test.mjs": 2, + "src/render/cesium/renderFailureSecondLoop.test.mjs": 4, + "src/render/cesium/sceneCommandRelease.test.mjs": 3, + "src/render/cesium/sceneOcclusionProbe.test.mjs": 22, + "src/render/cesium/screenModulation.test.mjs": 12, + "src/render/cesium/setBlend.test.mjs": 8, + "src/render/cesium/starrySky.test.mjs": 13, + "src/render/cesium/tileRequests.test.mjs": 3, + "src/render/cesium/uploadProbe.test.mjs": 3, + "src/render/cesium/vectorBase.test.mjs": 5, + "src/render/cesium/zoomOutGuard.test.mjs": 35, + "src/render/color.test.mjs": 4, + "src/render/conformance/cameraRunner.test.mjs": 2, + "src/render/conformance/scenes.test.mjs": 8, + "src/render/contract/contract.test.mjs": 7, + "src/render/creditMarkup.test.mjs": 4, + "src/render/input/router.test.mjs": 8, + "src/render/motion/iconBook.test.mjs": 5, + "src/render/motion/iconMotion.test.mjs": 6, + "src/render/neutralExports.test.mjs": 5, + "src/render/noCesiumOutsideRender.test.mjs": 9, + "src/render/occlusion/depthProbe.test.mjs": 6, + "src/render/recession.test.mjs": 5, + "src/render/rendererOf.test.mjs": 12, + "src/render/stub/stub.test.mjs": 16, + "src/render/unboundCamera.test.mjs": 10, + "src/render/vectorBase/vectorBase.test.mjs": 17, + "src/render/viewerAccess.test.mjs": 5, + "src/render/weather.test.mjs": 3, + "src/renderGovernor.test.mjs": 17, + "src/rightRailPolicy.test.mjs": 5, + "src/routeCinematics.test.mjs": 30, + "src/sceneCommandRelease.test.mjs": 2, + "src/scenes/bootstrapTitleProvenance.test.mjs": 1, + "src/scenes/cameraMotion.test.mjs": 4, + "src/scenes/dataPacks/presentation.test.mjs": 6, + "src/scenes/dataPacks/presentationView.test.mjs": 3, + "src/scenes/director.test.mjs": 92, + "src/scenes/directorStorageNotices.test.mjs": 182, + "src/scenes/interactionsView.test.mjs": 6, + "src/scenes/packs/registry.test.mjs": 1, + "src/scenes/scenePolicy.test.mjs": 15, + "src/scenes/sceneSaveError.test.mjs": 4, + "src/scenes/sceneTitleDisplay.test.mjs": 6, + "src/scenes/sharingDialogs.test.mjs": 4, + "src/scenes/storyThumb.test.mjs": 7, + "src/scopeMask.test.mjs": 25, + "src/sdr/adsbDecoder.test.mjs": 20, + "src/sdr/controller.test.mjs": 32, + "src/sdr/decoderDiagnostics.test.mjs": 8, + "src/sdr/gain.test.mjs": 4, + "src/sdr/readPipeline.diag.test.mjs": 6, + "src/sdr/sdrAudioWorklet.test.mjs": 11, + "src/sdr/sdrLocaleSwitch.test.mjs": 3, + "src/sdr/sdrSeekLocalized.test.mjs": 5, + "src/sdr/spectrum.test.mjs": 3, + "src/sdr/usbDevices.test.mjs": 7, + "src/sdr/workerAdmission.test.mjs": 14, + "src/search/coordinate-empty-components.test.mjs": 1, + "src/search/coordinateParser.test.mjs": 10, + "src/search/geospatial.test.mjs": 8, + "src/search/gridReference.test.mjs": 9, + "src/search/nominatim.test.mjs": 6, + "src/search/offlineGeocoders.test.mjs": 10, + "src/search/photonSetting.test.mjs": 3, + "src/search/placeSearch.test.mjs": 10, + "src/services/boundary-probe-recovery.test.mjs": 1, + "src/services/groundSnap.test.mjs": 11, + "src/services/requests.test.mjs": 8, + "src/services/terrainHeights.test.mjs": 7, + "src/setupDoctor.test.mjs": 17, + "src/share/legacyShareState.test.mjs": 9, + "src/share/shareLinkPath.test.mjs": 3, + "src/share/viewCodec.test.mjs": 48, + "src/share/wire.test.mjs": 9, + "src/sharelink.camera.test.mjs": 3, + "src/sharelink.celestial.test.mjs": 41, + "src/sharelink.lang.test.mjs": 2, + "src/sharelink.navigation.test.mjs": 17, + "src/sky/stars.test.mjs": 7, + "src/sources/adsbFields.test.mjs": 3, + "src/sources/adsbRecords.test.mjs": 12, + "src/sources/featureGeometry.test.mjs": 1, + "src/sources/gbfsStations.test.mjs": 21, + "src/sources/httpBody.test.mjs": 10, + "src/sources/live/contract.test.mjs": 23, + "src/sources/live/standalone.test.mjs": 1, + "src/sources/militaryTileGeometry.test.mjs": 10, + "src/sources/nominatimOutlines.test.mjs": 10, + "src/sources/openFreeMap.test.mjs": 14, + "src/sources/openFreeMapOutlines.test.mjs": 13, + "src/sources/openFreeMapOutlinesEdges.test.mjs": 10, + "src/sources/osmFeatures.test.mjs": 4, + "src/sources/overpassFeatures.test.mjs": 9, + "src/sources/phaseTiming.test.mjs": 2, + "src/sources/protocols.test.mjs": 5, + "src/sources/rateLimit.test.mjs": 1, + "src/sources/reference.test.mjs": 1, + "src/sources/vectorTiles.test.mjs": 19, + "src/splitFlap.test.mjs": 28, + "src/standalone/layerSources.test.mjs": 1, + "src/standalone/startupChrome.test.mjs": 4, + "src/stories/boot.test.mjs": 7, + "src/stories/controller.test.mjs": 50, + "src/stories/gevPlayer.test.mjs": 14, + "src/stories/keyboard.test.mjs": 3, + "src/stories/thumbs.test.mjs": 4, + "src/streetLevelLifecycle.test.mjs": 6, + "src/streetLevelMarkup.test.mjs": 7, + "src/streetLevelReplacement.test.mjs": 16, + "src/terrainHeightsBounds.test.mjs": 12, + "src/testSupport/aircraftFeedLatency.mjs": 14, + "src/textChatServer.test.mjs": 40, + "src/time/frameWait.test.mjs": 3, + "src/time/snapshotTimeline.test.mjs": 18, + "src/time/timelineFixes.test.mjs": 4, + "src/time/viewerClock.test.mjs": 1, + "src/time/worldClock.test.mjs": 26, + "src/tooling/allowedHosts.test.mjs": 7, + "src/tooling/applicationHtml.test.mjs": 2, + "src/tooling/boundedCache.test.mjs": 3, + "src/tooling/buildRailPaths.test.mjs": 15, + "src/tooling/buildRailPathsCli.test.mjs": 10, + "src/tooling/buildRailPathsLocal.test.mjs": 3, + "src/tooling/buildRailPathsRoutes.test.mjs": 3, + "src/tooling/buildRailPathsTripEnds.test.mjs": 3, + "src/tooling/buildRailPathsUnlocated.test.mjs": 3, + "src/tooling/buildRailPathsWrite.test.mjs": 10, + "src/tooling/changelogFragments.test.mjs": 17, + "src/tooling/environmentProviders.test.mjs": 14, + "src/tooling/fixtureRoot.test.mjs": 1, + "src/tooling/format.test.mjs": 6, + "src/tooling/googleTokenUnavailable.test.mjs": 4, + "src/tooling/importDirections.test.mjs": 16, + "src/tooling/liveProviders.test.mjs": 22, + "src/tooling/ll2Integration.test.mjs": 10, + "src/tooling/localServices.test.mjs": 31, + "src/tooling/mapillaryProvider.test.mjs": 32, + "src/tooling/mediaProviders.test.mjs": 5, + "src/tooling/nominatimGuardLifecycle.test.mjs": 23, + "src/tooling/nominatimLockOwnership.test.mjs": 2, + "src/tooling/nominatimOutlineRoute.test.mjs": 31, + "src/tooling/nominatimSearchRoute.test.mjs": 10, + "src/tooling/osmFeaturesRoute.test.mjs": 17, + "src/tooling/packageBoundaries.test.mjs": 7, + "src/tooling/panelBuild.test.mjs": 4, + "src/tooling/panelStorageDocs.test.mjs": 2, + "src/tooling/placeProviders.test.mjs": 18, + "src/tooling/precomputeCctvHeights.test.mjs": 15, + "src/tooling/previewServing.test.mjs": 2, + "src/tooling/railCatalogPacks.test.mjs": 8, + "src/tooling/railService.test.mjs": 22, + "src/tooling/railServiceFaults.test.mjs": 4, + "src/tooling/railServicePacks.test.mjs": 6, + "src/tooling/responseCompression.test.mjs": 3, + "src/tooling/skyAssets.paintOut.test.mjs": 1, + "src/tooling/skyAssets.test.mjs": 7, + "src/tooling/spaceProviders.test.mjs": 13, + "src/tooling/streetLevelQa.test.mjs": 7, + "src/tooling/trackArrivalObservation.test.mjs": 24, + "src/tooling/trafficFixtures.test.mjs": 5, + "src/tooling/transitProvider.test.mjs": 10, + "src/tooling/transitQa.test.mjs": 10, + "src/tooling/transitService.test.mjs": 4, + "src/tooling/viteBuild.test.mjs": 9, + "src/tooling/voiceBench.test.mjs": 19, + "src/tooling/vueLoader.test.mjs": 5, + "src/tooling/webAppIcons.test.mjs": 5, + "src/toolProjectRoot.test.mjs": 3, + "src/tools/area.test.mjs": 13, + "src/tools/catalog-cancellation.test.mjs": 2, + "src/tools/catalog.test.mjs": 9, + "src/tools/functions.test.mjs": 2, + "src/tools/globePanel.test.mjs": 7, + "src/tools/localRoute.test.mjs": 5, + "src/tools/localServer.test.mjs": 7, + "src/tools/mcp/mcp.test.mjs": 8, + "src/tools/mcpPanelKey.test.mjs": 8, + "src/tools/places.test.mjs": 3, + "src/tools/queries/atmosphere.test.mjs": 4, + "src/tools/queries/aviation.test.mjs": 18, + "src/tools/queries/cables.test.mjs": 3, + "src/tools/queries/environment.test.mjs": 19, + "src/tools/queries/events.test.mjs": 2, + "src/tools/queries/hazards.test.mjs": 6, + "src/tools/queries/hud-caption-feed-state.test.mjs": 2, + "src/tools/queries/imagery.test.mjs": 2, + "src/tools/queries/infrastructure.test.mjs": 3, + "src/tools/queries/maritime.test.mjs": 15, + "src/tools/queries/media.test.mjs": 11, + "src/tools/queries/mobility.test.mjs": 16, + "src/tools/queries/panelRequest.test.mjs": 13, + "src/tools/queries/places.test.mjs": 7, + "src/tools/queries/queries.test.mjs": 4, + "src/tools/queries/share.test.mjs": 8, + "src/tools/queries/space.test.mjs": 17, + "src/tools/queries/surveillance.test.mjs": 3, + "src/tools/results.test.mjs": 4, + "src/tools/surfaces.test.mjs": 5, + "src/tools/tool-schema-codepoints.test.mjs": 2, + "src/tools/tool-timestamp-range.test.mjs": 1, + "src/tools/views.test.mjs": 4, + "src/ui/awarenessPanel.test.mjs": 11, + "src/ui/cameraOrientationControls.test.mjs": 20, + "src/ui/cctvBadges.test.mjs": 3, + "src/ui/cctvControls.test.mjs": 6, + "src/ui/cctvPanel.test.mjs": 24, + "src/ui/cctvPicker.test.mjs": 11, + "src/ui/cctvVideo.test.mjs": 1, + "src/ui/cockpitBodyClasses.test.mjs": 2, + "src/ui/cockpitBridge.test.mjs": 49, + "src/ui/cockpitBriefing.test.mjs": 14, + "src/ui/cockpitContext.test.mjs": 15, + "src/ui/cockpitController.test.mjs": 9, + "src/ui/cockpitDisplayPortal.test.mjs": 6, + "src/ui/cockpitDoubleClick.test.mjs": 9, + "src/ui/cockpitEntryGate.test.mjs": 29, + "src/ui/cockpitInstruments.test.mjs": 13, + "src/ui/cockpitOrbital.test.mjs": 10, + "src/ui/cockpitOrbitalFocus.test.mjs": 20, + "src/ui/cockpitOrbitalView.test.mjs": 46, + "src/ui/cockpitPresence.test.mjs": 8, + "src/ui/cockpitPresentation.test.mjs": 3, + "src/ui/cockpitRollingValue.test.mjs": 7, + "src/ui/cockpitSubjectView.test.mjs": 26, + "src/ui/cockpitUtilityControls.test.mjs": 15, + "src/ui/commandDock.test.mjs": 11, + "src/ui/contextControls.test.mjs": 8, + "src/ui/contextLayerChanges.i18n.test.mjs": 8, + "src/ui/contextPanel.test.mjs": 4, + "src/ui/creditsView.test.mjs": 6, + "src/ui/cssContentCaption.test.mjs": 2, + "src/ui/cyberSonarControls.test.mjs": 8, + "src/ui/cyberTheme.test.mjs": 36, + "src/ui/displayGroups.test.mjs": 1, + "src/ui/displayPanel.test.mjs": 18, + "src/ui/displayPanelActions.test.mjs": 9, + "src/ui/feedErrorI18n.test.mjs": 3, + "src/ui/flyToDataSource.test.mjs": 6, + "src/ui/frameRateMonitor.test.mjs": 4, + "src/ui/frameRateView.test.mjs": 1, + "src/ui/geoFileImport.test.mjs": 24, + "src/ui/globeActions.test.mjs": 7, + "src/ui/i18n.test.mjs": 3, + "src/ui/imageryBoxTool.test.mjs": 6, + "src/ui/imagerySplit.test.mjs": 6, + "src/ui/imagerySplitView.test.mjs": 4, + "src/ui/kit/UiBadge.test.mjs": 2, + "src/ui/kit/UiButton.test.mjs": 6, + "src/ui/kit/UiChip.test.mjs": 1, + "src/ui/kit/UiRail.test.mjs": 6, + "src/ui/kit/UiSegmented.test.mjs": 9, + "src/ui/kit/UiSelect.test.mjs": 6, + "src/ui/kit/UiSlider.test.mjs": 9, + "src/ui/layerFinder.test.mjs": 7, + "src/ui/layerKeyRequirement.test.mjs": 5, + "src/ui/layerNames.test.mjs": 5, + "src/ui/layerPanel.test.mjs": 14, + "src/ui/layerPanel/layerRows.test.mjs": 5, + "src/ui/layerStatusLocale.test.mjs": 3, + "src/ui/libraryBrowser.test.mjs": 6, + "src/ui/localAdsbGuidanceI18n.test.mjs": 1, + "src/ui/localePicker.test.mjs": 11, + "src/ui/localePickerView.test.mjs": 12, + "src/ui/localeSwitch.test.mjs": 3, + "src/ui/localSdrAudioState.i18n.test.mjs": 2, + "src/ui/localSdrControls.test.mjs": 5, + "src/ui/localSdrFeedLine.i18n.test.mjs": 4, + "src/ui/localSdrFmStopMessage.i18n.test.mjs": 3, + "src/ui/localSdrMarkup.test.mjs": 3, + "src/ui/localSdrNumbers.i18n.test.mjs": 3, + "src/ui/localSdrPresentation.test.mjs": 6, + "src/ui/locationControls.test.mjs": 12, + "src/ui/locationSearch.test.mjs": 8, + "src/ui/locationSearchRecovery.test.mjs": 5, + "src/ui/mapSourceControls.test.mjs": 9, + "src/ui/missionPanels.test.mjs": 9, + "src/ui/mobileShell.test.mjs": 30, + "src/ui/newsPanel.test.mjs": 9, + "src/ui/ownerFlag.test.mjs": 9, + "src/ui/panelChromeButtons.test.mjs": 14, + "src/ui/panelNavigation.test.mjs": 5, + "src/ui/panelPositionControls.test.mjs": 1, + "src/ui/panelRails.test.mjs": 43, + "src/ui/placeNames.test.mjs": 5, + "src/ui/placePacksLoading.test.mjs": 3, + "src/ui/providerSettings.test.mjs": 11, + "src/ui/quebecCctvOverlay.test.mjs": 6, + "src/ui/radioControls.test.mjs": 5, + "src/ui/radioPanel.test.mjs": 10, + "src/ui/radioPanelActions.test.mjs": 3, + "src/ui/radioPanelPlacement.test.mjs": 2, + "src/ui/radioPresentation.playbackError.test.mjs": 3, + "src/ui/radioPresentationTransition.test.mjs": 2, + "src/ui/radioTuner.test.mjs": 11, + "src/ui/rail/fieldValue.test.mjs": 2, + "src/ui/railCards.test.mjs": 7, + "src/ui/railEdgeScroll.test.mjs": 9, + "src/ui/railPanelChrome.test.mjs": 10, + "src/ui/railScrollers.test.mjs": 1, + "src/ui/recentImagery.test.mjs": 16, + "src/ui/recentImageryNotice.test.mjs": 3, + "src/ui/renderFailureView.test.mjs": 7, + "src/ui/revealPanel.test.mjs": 2, + "src/ui/rtlLayout.test.mjs": 6, + "src/ui/safeFrameView.test.mjs": 1, + "src/ui/sceneControls.test.mjs": 21, + "src/ui/sceneSharingView.test.mjs": 6, + "src/ui/sdrCardActions.test.mjs": 3, + "src/ui/setMapStackReason.test.mjs": 1, + "src/ui/shareButton.test.mjs": 11, + "src/ui/shareFollow.test.mjs": 5, + "src/ui/shareLinks.test.mjs": 16, + "src/ui/shareRestorationNotice.test.mjs": 3, + "src/ui/shellFacade.test.mjs": 2, + "src/ui/shellFeedbackStatusLocalization.test.mjs": 11, + "src/ui/shellLifecycle.test.mjs": 7, + "src/ui/shellLifetime.test.mjs": 6, + "src/ui/shellToasts.i18n.test.mjs": 144, + "src/ui/sidePanelDisclosure.test.mjs": 5, + "src/ui/stateOwners.test.mjs": 3, + "src/ui/statusChipOwners.test.mjs": 3, + "src/ui/statusChipsView.test.mjs": 9, + "src/ui/statusText.test.mjs": 16, + "src/ui/stores/owners.test.mjs": 4, + "src/ui/stores/panels.test.mjs": 1, + "src/ui/storiesCredit.test.mjs": 5, + "src/ui/storiesView.test.mjs": 1, + "src/ui/streetLevelControls.test.mjs": 41, + "src/ui/streetLevelMetaLocale.test.mjs": 3, + "src/ui/streetLevelPresentation.test.mjs": 19, + "src/ui/styleParameters.test.mjs": 8, + "src/ui/styles/english-css-parity.test.mjs": 13, + "src/ui/surface-tab-order.test.mjs": 1, + "src/ui/surfaceKeyboard.test.mjs": 8, + "src/ui/tileErrorI18n.test.mjs": 6, + "src/ui/toastView.test.mjs": 3, + "src/ui/unitLabels.test.mjs": 3, + "src/ui/untranslatedErrors.test.mjs": 6, + "src/ui/views/intelHudView.test.mjs": 4, + "src/ui/views/mountApplicationViews.test.mjs": 4, + "src/ui/views/panels/DataLibraryDialog.test.mjs": 6, + "src/ui/views/panels/DrawMarkList.test.mjs": 9, + "src/ui/views/panels/GeoImport.test.mjs": 7, + "src/ui/views/panels/WorldTimeline.test.mjs": 17, + "src/ui/visualEffects.test.mjs": 17, + "src/ui/visualInput.test.mjs": 9, + "src/ui/weatherPanel.test.mjs": 18, + "src/ui/wildlifeSightingCard.test.mjs": 28, + "src/unitTestRunner.test.mjs": 4, + "src/view/index.test.mjs": 13, + "src/viewSky.test.mjs": 3, + "src/voice/actionSchemas.test.mjs": 12, + "src/voice/aircraftIdentityNarration.test.mjs": 1, + "src/voice/analystAccessors.test.mjs": 5, + "src/voice/analystCardLocale.test.mjs": 3, + "src/voice/analystEmptyNotes.test.mjs": 14, + "src/voice/areaActions.test.mjs": 26, + "src/voice/cctvRouting.test.mjs": 19, + "src/voice/chatAttachments.test.mjs": 8, + "src/voice/chatControlView.test.mjs": 10, + "src/voice/chatPreferences.test.mjs": 4, + "src/voice/cloudVoiceAuth.test.mjs": 1, + "src/voice/deixis.test.mjs": 13, + "src/voice/geminiAcquisition.test.mjs": 7, + "src/voice/geminiAudio.test.mjs": 31, + "src/voice/geminiAutomaticVad.test.mjs": 32, + "src/voice/geminiDeferredInput.test.mjs": 5, + "src/voice/geminiIntegration.test.mjs": 8, + "src/voice/geminiNativeCaptionEvents.test.mjs": 2, + "src/voice/geminiNativeOwnership.test.mjs": 19, + "src/voice/geminiNativeRadio.test.mjs": 23, + "src/voice/geminiNativeRecovery.test.mjs": 6, + "src/voice/geminiPacketOwnership.test.mjs": 11, + "src/voice/geminiSession.test.mjs": 127, + "src/voice/geminiTextChat.test.mjs": 14, + "src/voice/gevActions.test.mjs": 185, + "src/voice/gevRealtime.test.mjs": 164, + "src/voice/globeResetConfirmation.test.mjs": 31, + "src/voice/hudPlaceLabels.test.mjs": 12, + "src/voice/imageryActions.test.mjs": 15, + "src/voice/integrationContract.test.mjs": 29, + "src/voice/layerManifest.test.mjs": 5, + "src/voice/narration.test.mjs": 8, + "src/voice/osmActions.test.mjs": 14, + "src/voice/panel/actionObserver.test.mjs": 13, + "src/voice/panel/host.test.mjs": 45, + "src/voice/panel/inactivity.test.mjs": 5, + "src/voice/panel/manualPanel.test.mjs": 6, + "src/voice/panel/nativeActivity.test.mjs": 22, + "src/voice/panel/preferences.test.mjs": 12, + "src/voice/panel/preferencesView.test.mjs": 1, + "src/voice/pointAndAsk.test.mjs": 12, + "src/voice/pointAndAskReview.test.mjs": 8, + "src/voice/pointerContext.test.mjs": 13, + "src/voice/pointerCrop.test.mjs": 7, + "src/voice/pointerReticle.test.mjs": 4, + "src/voice/pointerReticleView.test.mjs": 2, + "src/voice/providerCommands.test.mjs": 25, + "src/voice/realtimeBackend.test.mjs": 7, + "src/voice/realtimeCostIncompleteNote.i18n.test.mjs": 3, + "src/voice/realtimeCostPanel.test.mjs": 3, + "src/voice/realtimeCostTierStatus.test.mjs": 3, + "src/voice/realtimeNarration.test.mjs": 13, + "src/voice/realtimeOwners.test.mjs": 7, + "src/voice/realtimeProtocol.test.mjs": 7, + "src/voice/realtimeRadio.test.mjs": 3, + "src/voice/realtimeTypedSend.test.mjs": 9, + "src/voice/realtimeViewportPolicy.test.mjs": 18, + "src/voice/session.test.mjs": 25, + "src/voice/speech.test.mjs": 19, + "src/voice/textChat.test.mjs": 36, + "src/voice/turnMetrics.test.mjs": 7, + "src/voice/viewportCapture.test.mjs": 3, + "src/voice/voiceCard.test.mjs": 11, + "src/voice/voiceCardErrorLines.i18n.test.mjs": 7, + "src/voice/voiceCardLocale.test.mjs": 10, + "src/voice/voiceCardPlaceNames.i18n.test.mjs": 2, + "src/voice/voiceCardPlanSteps.i18n.test.mjs": 16, + "src/voice/voiceControlView.test.mjs": 3, + "src/voice/voiceCost.test.mjs": 60, + "src/voice/voiceMiniPreview.test.mjs": 4, + "src/weatherEffectsMath.test.mjs": 6, + "src/worldFocus.test.mjs": 10 + } +} From 2196aa0a2fe73e8a97b510c4d83aaf1d75e56f03 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 17:41:46 -0600 Subject: [PATCH 05/18] ci(factory): reusable exact-SHA workflow with lockfile-keyed caches --- .github/actions/factory-node/action.yml | 50 ++++++++ .github/workflows/ci.yml | 27 +++-- .github/workflows/factory-ci-sha.yml | 149 ++++++++++++++++++++++++ 3 files changed, 215 insertions(+), 11 deletions(-) create mode 100644 .github/actions/factory-node/action.yml create mode 100644 .github/workflows/factory-ci-sha.yml diff --git a/.github/actions/factory-node/action.yml b/.github/actions/factory-node/action.yml new file mode 100644 index 00000000000..a1e2677ae06 --- /dev/null +++ b/.github/actions/factory-node/action.yml @@ -0,0 +1,50 @@ +name: Factory Node toolchain +description: >- + Pinned Node plus node_modules restored only on an exact match of OS image, + architecture, Node, npm and package-lock.json. A miss runs npm ci; a partial + or older tree is never reused. +inputs: + browser: + description: Also install and cache the Chrome build Puppeteer pins. + default: 'false' +runs: + using: composite + steps: + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24.22.2 + + - name: Cache key + id: key + shell: bash + run: | + lock=$(sha256sum package-lock.json | cut -c1-64) + echo "modules=factory-nm-v1-${ImageOS}-${RUNNER_ARCH}-node$(node -v)-npm$(npm -v)-${lock}" >> "$GITHUB_OUTPUT" + echo "browser=factory-chrome-v1-${ImageOS}-${RUNNER_ARCH}-${lock}" >> "$GITHUB_OUTPUT" + + - name: Restore node_modules + id: modules + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: node_modules + key: ${{ steps.key.outputs.modules }} + + - name: Restore Puppeteer Chrome + if: inputs.browser == 'true' + id: chrome + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.cache/puppeteer + key: ${{ steps.key.outputs.browser }} + + - name: Install locked dependencies + if: steps.modules.outputs.cache-hit != 'true' + shell: bash + env: + PUPPETEER_SKIP_DOWNLOAD: ${{ inputs.browser == 'true' && '0' || '1' }} + run: npm ci --no-audit --no-fund + + - name: Install Puppeteer Chrome + if: inputs.browser == 'true' && steps.chrome.outputs.cache-hit != 'true' + shell: bash + run: npx --no-install puppeteer browsers install chrome diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6623d96cc62..3c30874f265 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ name: CI on: pull_request: push: - branches: [main, nightly, staging] + branches: [nightly, staging] workflow_dispatch: permissions: @@ -27,6 +27,21 @@ jobs: main|staging) echo '::error::Target nightly. Main mirrors upstream; staging is fast-forward promotion only.'; exit 1 ;; esac + factory: + # Required on the fork: the gev-ci/* statuses this posts on the exact head. + name: Factory gates + if: >- + github.repository == 'kvnloo/gods-eye-view' && ( + (github.event_name == 'pull_request' && contains(fromJSON('["nightly","staging"]'), github.base_ref)) || + (github.event_name == 'push' && contains(fromJSON('["refs/heads/nightly","refs/heads/staging"]'), github.ref))) + permissions: + contents: read + statuses: write + uses: ./.github/workflows/factory-ci-sha.yml + with: + sha: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + base-sha: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || '' }} + verify: name: Node ${{ matrix.node }} runs-on: ubuntu-latest @@ -75,22 +90,12 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} run: npm run library:check -- --base-ref "$BASE_SHA" - - name: Check translations - run: npm run i18n - - - name: Typecheck renderer declarations - run: npx --no-install tsc --noEmit --strict --module NodeNext --target es2022 $(git ls-files 'src/render/**/*.d.ts') - - name: Run unit tests run: npm test - name: Build production bundle run: npm run build - - name: Run performance microbenchmarks (Node 24) - if: matrix.node == '24.22.2' - run: npm run test:perf - street-level-browser: # Hermetic: every Mapillary request is answered from fixtures, so the # dummy token below never leaves the page. diff --git a/.github/workflows/factory-ci-sha.yml b/.github/workflows/factory-ci-sha.yml new file mode 100644 index 00000000000..a0ed8a12347 --- /dev/null +++ b/.github/workflows/factory-ci-sha.yml @@ -0,0 +1,149 @@ +# Full validation of one exact commit. Called by ci.yml for PRs and pushes, and +# by the nightly-integration and staging-promotion workflows for the SHA they +# are about to publish. Contract: docs/factory-ci.md. +# +# Every gate posts a commit status on inputs.sha: gev-ci/ plus +# gev-ci/full. A Boat run of scripts/factory-ci.mjs posts the same contexts, so +# consumers read statuses, not job names. +name: Factory CI (exact SHA) + +on: + workflow_call: + inputs: + sha: + description: Full 40-character commit SHA to validate. + required: true + type: string + base-sha: + description: Optional full SHA the append-only ledgers are checked against. + required: false + type: string + default: '' + outputs: + full: + description: success or failure, the state posted as gev-ci/full. + value: ${{ jobs.report.outputs.full }} + workflow_dispatch: + inputs: + sha: + description: Full 40-character commit SHA to validate. + required: true + base-sha: + description: Optional full SHA the append-only ledgers are checked against. + required: false + default: '' + +permissions: + contents: read + +concurrency: + group: factory-ci-sha-${{ inputs.sha }} + cancel-in-progress: false + +jobs: + gates: + name: gev-ci ${{ matrix.group }} + runs-on: ubuntu-24.04 + timeout-minutes: ${{ matrix.timeout }} + strategy: + fail-fast: false + matrix: + include: + - group: checks + gates: lint typecheck translations + browser: 'false' + timeout: 20 + - group: unit + gates: unit + browser: 'false' + timeout: 45 + - group: build + gates: build bundle-budget globe-smoke + browser: 'true' + timeout: 25 + - group: perf + gates: perf-smoke + browser: 'false' + timeout: 20 + env: + SHA: ${{ inputs.sha }} + BASE_SHA: ${{ inputs.base-sha }} + GEV_CI_RUNNER: github-actions + steps: + - name: Refuse anything but a full SHA + run: | + [[ $SHA =~ ^[0-9a-f]{40}$ ]] || { echo "::error::sha must be 40 lowercase hex characters"; exit 1; } + [[ -z $BASE_SHA || $BASE_SHA =~ ^[0-9a-f]{40}$ ]] || { echo "::error::base-sha must be empty or a full SHA"; exit 1; } + + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Confirm the checked-out commit + run: test "$(git rev-parse HEAD)" = "$SHA" + + - uses: ./.github/actions/factory-node + with: + browser: ${{ matrix.browser }} + + - name: Run gates + run: node scripts/factory-ci.mjs ${{ matrix.gates }} --out ci-results ${BASE_SHA:+--base-ref "$BASE_SHA"} + + - name: Upload results + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: gev-ci-${{ matrix.group }}-${{ inputs.sha }} + path: | + ci-results/*.json + ci-results/*.log + ci-results/*.png + if-no-files-found: error + retention-days: 30 + + report: + name: gev-ci report + needs: gates + if: always() + runs-on: ubuntu-24.04 + permissions: + contents: read + statuses: write + outputs: + full: ${{ steps.post.outputs.full }} + env: + SHA: ${{ inputs.sha }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ inputs.sha }} + persist-credentials: false + + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: gev-ci-*-${{ inputs.sha }} + path: ci-results + merge-multiple: true + + - name: Post commit statuses + id: post + env: + GH_TOKEN: ${{ github.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + node scripts/factory-ci.mjs statuses ci-results > statuses.tsv + { + echo "### gev-ci for \`$SHA\`" + echo '| Context | State | Detail |' + echo '|---|---|---|' + while IFS=$'\t' read -r context state description; do + gh api -X POST "repos/$GITHUB_REPOSITORY/statuses/$SHA" \ + -f state="$state" -f context="$context" -f description="$description" -f target_url="$RUN_URL" > /dev/null + echo "| $context | $state | $description |" + done < statuses.tsv + } >> "$GITHUB_STEP_SUMMARY" + full=$(awk -F'\t' '$1 == "gev-ci/full" { print $2 }' statuses.tsv) + echo "full=$full" >> "$GITHUB_OUTPUT" + test "$full" = success From d95cc718a64005973b3634174ffb736d6f56b703 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 17:41:46 -0600 Subject: [PATCH 06/18] ci(factory): run the gates on a disposable Boat VM and post statuses --- scripts/factory-ci-boat.sh | 78 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 scripts/factory-ci-boat.sh diff --git a/scripts/factory-ci-boat.sh b/scripts/factory-ci-boat.sh new file mode 100644 index 00000000000..4ad7c1a2da9 --- /dev/null +++ b/scripts/factory-ci-boat.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Run every factory gate on one exact commit in a disposable Boat VM and post +# the gev-ci/* commit statuses from this (trusted) host. The VM gets no +# credentials; it only reads the public repository. Contract: docs/factory-ci.md. +# +# scripts/factory-ci-boat.sh [base-sha] +# +# Needs: boat (signed in), gh (signed in with statuses + contents write on the +# fork), git, jq. Evidence goes to the factory/ci-evidence branch and each +# status links to it. Exit 0 only when gev-ci/full is success. +set -euo pipefail +repo=${GEV_CI_REPO:-kvnloo/gods-eye-view} +sha=${1:?usage: factory-ci-boat.sh [base-sha]} +base=${2:-} +[[ $sha =~ ^[0-9a-f]{40}$ ]] || { echo "sha must be 40 lowercase hex characters" >&2; exit 2; } +[[ -z $base || $base =~ ^[0-9a-f]{40}$ ]] || { echo "base-sha must be a full SHA" >&2; exit 2; } +gh api "repos/$repo/commits/$sha" --jq .sha | grep -qx "$sha" || { echo "$sha is not a commit of $repo" >&2; exit 2; } + +stamp=$(date -u +%Y%m%dT%H%M%SZ) +local_out=${GEV_CI_OUT:-$PWD/ci-runs}/$sha/$stamp +mkdir -p "$local_out" +box=$(boat new --no-update --no-env --type default --ttl 7200 --name "gev-ci-${sha:0:12}" --json | jq -r 'select(.event == "ready") | .id') +[[ $box == bx_* ]] || { echo "could not start a Boat VM" >&2; exit 3; } +trap 'boat delete --no-update "$box" --yes > /dev/null 2>&1 || true' EXIT + +remote=$(cat <<'REMOTE' +set -euo pipefail +export GIT_TERMINAL_PROMPT=0 GEV_CI_RUNNER=boat-default-4vcpu +unset GH_TOKEN GITHUB_TOKEN +cd /home/user +npm install --silent --no-audit --no-fund --prefix runtime node@24.22.2 +export PATH=/home/user/runtime/node_modules/.bin:$PATH +git init -q src && cd src +git fetch -q "https://github.com/$REPO.git" "$SHA" '+refs/heads/main:refs/remotes/origin/main' +[[ -z $BASE ]] || git fetch -q "https://github.com/$REPO.git" "$BASE" +git checkout -q --detach "$SHA" +[[ $(git rev-parse HEAD) == "$SHA" ]] +mkdir -p ci-results +start=$SECONDS +# A failed install records no gate results, so every status reads error. +if npm ci --no-audit --no-fund > ci-results/npm-ci.log 2>&1; then + echo "$((SECONDS - start))" > ci-results/install-seconds.txt + node scripts/factory-ci.mjs --out ci-results ${BASE:+--base-ref "$BASE"} || true +fi +printf '%s\n' "$SHA" > ci-results/sha.txt +node --version > ci-results/node-version.txt +tar -czf /home/user/ci-results.tgz --exclude='*.ndjson' ci-results +REMOTE +) +boat exec --no-update "$box" --timeout 0 env REPO="$repo" SHA="$sha" BASE="$base" bash -c "$remote" | tee "$local_out/remote.log" +boat exec --no-update --json "$box" --timeout 120 base64 -w0 /home/user/ci-results.tgz > "$local_out/fetch.json" +[[ $(jq -r '.exitCode' "$local_out/fetch.json") == 0 && $(jq -r '.stdoutTruncated' "$local_out/fetch.json") == false ]] \ + || { echo "could not retrieve results" >&2; exit 3; } +jq -r .stdout "$local_out/fetch.json" | base64 -d | tar -xzf - -C "$local_out" +rm "$local_out/fetch.json" +[[ $(cat "$local_out/ci-results/sha.txt") == "$sha" ]] + +# Publish evidence to factory/ci-evidence, then link every status to it. +evidence=$(mktemp -d) +git -C "$evidence" init -q +git -C "$evidence" fetch -q --depth=1 "https://github.com/$repo.git" factory/ci-evidence 2>/dev/null \ + && git -C "$evidence" checkout -q FETCH_HEAD || git -C "$evidence" checkout -q --orphan factory/ci-evidence +mkdir -p "$evidence/$sha/$stamp" +cp "$local_out"/ci-results/*.{json,log,png,txt} "$evidence/$sha/$stamp/" 2>/dev/null || true +git -C "$evidence" add -A +git -C "$evidence" -c user.name=gev-factory -c user.email=gev-factory@users.noreply.github.com commit -qm "ci(evidence): gev-ci for $sha ($stamp)" +GIT_TERMINAL_PROMPT=0 git -C "$evidence" -c credential.helper= -c 'credential.https://github.com.helper=!gh auth git-credential' \ + push -q "https://github.com/$repo.git" HEAD:refs/heads/factory/ci-evidence +url="https://github.com/$repo/tree/factory/ci-evidence/$sha/$stamp" + +node "$(dirname "$0")/factory-ci.mjs" statuses "$local_out/ci-results" > "$local_out/statuses.tsv" +while IFS=$'\t' read -r context state description; do + gh api -X POST "repos/$repo/statuses/$sha" -f state="$state" -f context="$context" \ + -f description="$description" -f target_url="$url" > /dev/null + printf '%s\t%s\t%s\n' "$context" "$state" "$description" +done < "$local_out/statuses.tsv" +echo "evidence: $url" +[[ $(awk -F'\t' '$1 == "gev-ci/full" { print $2 }' "$local_out/statuses.tsv") == success ]] From aab4f38dcc496bfd49943fe488bc4fe62a77a666 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 18:07:54 -0600 Subject: [PATCH 07/18] ci(factory): record benchmarks already over budget at the baseline --- ci/factory/perf-baseline.json | 22 ++++++++++++++++++++++ scripts/factory-ci.mjs | 27 +++++++++++++++++++++------ 2 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 ci/factory/perf-baseline.json diff --git a/ci/factory/perf-baseline.json b/ci/factory/perf-baseline.json new file mode 100644 index 00000000000..86029ff284b --- /dev/null +++ b/ci/factory/perf-baseline.json @@ -0,0 +1,22 @@ +{ + "schema": 1, + "commit": "53f0caa6e54d9769740d69424e8bf26364b00a6a", + "environment": { + "node": "24.22.2", + "platform": "linux", + "arch": "x64", + "cpus": 4, + "cpuModel": "AMD EPYC 4585PX 16-Core Processor", + "runner": "boat-default-4vcpu" + }, + "measuredAt": "2026-11-25", + "overBudget": { + "src/layers/wildlifeSightings/render.perf.test.mjs > dense continental production moveEnd pipeline yields every 4ms, including cold tiles and real Cesium billboard updates": { + "budgetMs": 4, + "missedRuns": 11, + "runs": 20, + "observedSliceMs": [4.16, 8.26], + "note": "Four 5-run perf-smoke passes at this commit missed 1, 4, 2 and 4 times; four passes on d95cc718 (same src/ apart from one new test file) missed 4, 3, 4 and 3. Run alone on that tree the file missed 16/20, with thread CPU about equal to wall time and near-zero steal: the slice is CPU work, not preemption. The observed range spans both trees. Remove this entry once the layer meets 4 ms here; GEV-F3 owns device budgets." + } + } +} diff --git a/scripts/factory-ci.mjs b/scripts/factory-ci.mjs index 22ece2afa3a..6b62b922fd8 100644 --- a/scripts/factory-ci.mjs +++ b/scripts/factory-ci.mjs @@ -27,6 +27,7 @@ import { discoverPerfTestFiles, perfTestArgs } from './run-perf-tests.mjs'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const REPORTER = path.join(ROOT, 'scripts/factory-ci/test-events.mjs'); export const BASELINE_PATH = 'ci/factory/unit-baseline.json'; +export const PERF_BASELINE_PATH = 'ci/factory/perf-baseline.json'; export const PERF_SMOKE = Object.freeze({ runs: 5, failQuorum: 3 }); export const GATES = Object.freeze([ 'lint', 'typecheck', 'translations', 'unit', 'build', 'bundle-budget', 'globe-smoke', 'perf-smoke', @@ -305,14 +306,28 @@ async function perfSmokeGate({ log, out }) { } runs.push({ run: i + 1, ms: result.ms, tests }); } - const failed = [...misses].filter(([, n]) => n >= PERF_SMOKE.failQuorum); - const missed = [...misses].map(([id, n]) => `${id.split(' > ').pop().slice(0, 40)} ${n}/${PERF_SMOKE.runs}`); + // Benchmarks already over budget at the baseline commit on this runner class + // are listed in PERF_BASELINE_PATH with their measured miss rate. They are + // reported every run but cannot block; any other benchmark over quorum blocks. + const baselineFile = path.join(ROOT, PERF_BASELINE_PATH); + if (!existsSync(baselineFile)) return { state: 'error', description: `${PERF_BASELINE_PATH} is missing`, runs }; + const baseline = JSON.parse(readFileSync(baselineFile, 'utf8')); + const env = environment(); + if (baseline.environment.node !== env.node || baseline.environment.platform !== env.platform) { + return { state: 'error', description: `perf baseline is for Node ${baseline.environment.node}/${baseline.environment.platform}`, runs }; + } + const short = (id) => id.split(' > ').pop().slice(0, 32); + const overQuorum = [...misses].filter(([, n]) => n >= PERF_SMOKE.failQuorum).map(([id]) => id); + const blocking = overQuorum.filter((id) => !(id in baseline.overBudget)); + const known = Object.keys(baseline.overBudget).map((id) => `${short(id)} ${misses.get(id) ?? 0}/${PERF_SMOKE.runs}`); return { - state: failed.length ? 'failure' : 'success', - description: failed.length - ? `${failed.length} benchmark(s) missed budget in >=${PERF_SMOKE.failQuorum}/${PERF_SMOKE.runs} runs` - : `${Object.keys(runs[0].tests).length} benchmarks within budget${missed.length ? `; isolated misses: ${missed.join(', ')}` : ''}`, + state: blocking.length ? 'failure' : 'success', + description: blocking.length + ? `over budget in >=${PERF_SMOKE.failQuorum}/${PERF_SMOKE.runs} runs: ${blocking.map(short).join(', ')}` + : `${Object.keys(runs[0].tests).length} benchmarks, none newly over budget${known.length ? `; known over at ${baseline.commit.slice(0, 8)}: ${known.join(', ')}` : ''}`, policy: PERF_SMOKE, + baselineCommit: baseline.commit, + blocking, misses: Object.fromEntries(misses), runs, }; From 588f86d619a3cfcf8f444eca662ef547a865af9c Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 18:07:54 -0600 Subject: [PATCH 08/18] docs(factory): exact-SHA CI contract, baselines and thresholds --- docs/factory-ci.md | 161 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 docs/factory-ci.md diff --git a/docs/factory-ci.md b/docs/factory-ci.md new file mode 100644 index 00000000000..4c39ddaf3d7 --- /dev/null +++ b/docs/factory-ci.md @@ -0,0 +1,161 @@ +# Factory CI: exact-SHA gates for nightly and staging + +Every commit that lands on `nightly` or is promoted to `staging` must carry green +`gev-ci/*` commit statuses **on that exact SHA**. Two runners produce the same +statuses from the same driver, `scripts/factory-ci.mjs`: + +- **GitHub Actions:** `.github/workflows/factory-ci-sha.yml` (`workflow_call` and + `workflow_dispatch`, input `sha`). `ci.yml` calls it for PRs into `nightly` or + `staging` and for pushes to them. Actions is currently paused on this fork by + GitHub; only the owner can re-enable it at `/actions`. +- **Boat:** `scripts/factory-ci-boat.sh [base-sha]` runs the gates in a + disposable Boat VM with no credentials. It then posts statuses from the + trusted host. This is the working path while Actions is paused. + +## Contract for nightly integration and staging promotion + +| Item | Value | +|---|---| +| Input | `sha`: 40 lowercase hex characters. Anything else is refused before checkout. Optional `base-sha` (full SHA) turns on the append-only ledger checks against that base. | +| Checkout | `fetch-depth: 0` at `sha`, then `git rev-parse HEAD == sha` is asserted. The unit gate needs `origin/main` because two policy tests diff against it. | +| Output | Commit statuses on `sha`, one per gate, plus `gev-ci/full`. The Actions run also exposes `outputs.full` (`success` or `failure`). | +| Required check | `gev-ci/full`. It is `success` only when all eight gate results exist and are `success`. A missing result counts as `error`. | +| Evidence link | Each status's `target_url`: the Actions run, or `factory/ci-evidence///` for Boat runs (gate JSON, logs, `globe.png`). | +| States | `success`. `failure` means the code under test failed. `error` means the gate could not produce a trustworthy result, for example a crash, a timeout, missing history, an environment mismatch or a missing build. Never treat `error` as a pass. | + +Consumers must read statuses for the exact SHA they are about to publish, and +must re-read the branch ref right before the update. A status on any other SHA, +including the PR head when the integration commit is a merge, authorizes +nothing. + +## Gates (stable context names) + +| Context | What runs | Fails when | +|---|---|---| +| `gev-ci/lint` | `format:check`, `check:boundaries`, `library:check`, plus `layer-token:check --base-ref` when `base-sha` is given | any command exits non-zero | +| `gev-ci/typecheck` | `tsc --strict --module ESNext --moduleResolution Bundler` over `src/render/**/*.d.ts` | a type error. This covers the renderer declarations only. The app is JavaScript, so there is no whole-app typecheck. | +| `gev-ci/translations` | `npm run i18n` (13 catalogs) | a catalog is out of step | +| `gev-ci/unit` | every `*.test.mjs` under `src/` and `server/`, compared with the baseline (below) | a new failure, a newly skipped test, or a test file that emptied | +| `gev-ci/build` | `vite build` | the build fails | +| `gev-ci/bundle-budget` | `scripts/factory-bundle-budget.mjs` | a size is over its limit (below) | +| `gev-ci/globe-smoke` | `scripts/factory-globe-smoke.mjs` on the production `dist/` | the globe does not draw (below) | +| `gev-ci/perf-smoke` | the repository's `*.perf.test.mjs` budgets, 5 serial runs | one benchmark misses its own budget in 3 or more of the 5 runs | + +### Unit baseline + +`ci/factory/unit-baseline.json` is the reviewable baseline. It records the commit, +tree, lockfile hash, driver hash and environment (Node, npm, OS, CPUs). It also +holds the exact IDs of failing and skipped tests and the test count per file. +A test ID is ` > > ... > `. A file that fails outside any +test is ` > (file)`. + +The current baseline is `53f0caa6e54d9769740d69424e8bf26364b00a6a` (nightly and +staging tip on 2026-11-25), Node 24.22.2 on Linux x64. It has 14,427 tests: +**0 failing**, 3 skipped. The skipped tests are a Windows-only DACL test and the +two timing benchmarks, which normal runs skip on purpose; perf-smoke runs them. + +The gate is strict about what it trusts: + +- Every test process runs, including the two GC-bracketed allocation probes, even + when an earlier process failed. `npm test` stops at the first red process, so it + would skip them. +- A run is an `error` when the process was killed or timed out, or when the + runner's own count of tests differs from the results it emitted. It is also an + `error` when the exit code disagrees with the results: non-zero with no failing + test, or zero with one. +- If the baseline was recorded on a different Node version or platform, the gate + returns `error` and does not compare. +- Baseline failures that now pass are listed as `fixed`. Remove them in the next + baseline refresh so they cannot regress silently. +- Deleted test files are listed and do not block. A file that still exists but + now runs zero tests blocks. + +To refresh the baseline, run this on the pinned environment and commit the file +as its own reviewed change: + +```sh +node scripts/factory-ci.mjs unit --write-baseline +``` + +Never refresh the baseline just to turn a red PR green. Fix the test, or explain +the new failure in the PR that adds it to the baseline. + +### Bundle budget + +These limits were measured at `53f0caa6` and sit about 5% above the measured +sizes. Raising one is a reviewed edit to `LIMITS` in +`scripts/factory-bundle-budget.mjs`. + +| Metric | Measured | Limit | +|---|---:|---:| +| `dist/` total bytes | 80,939,371 | 85,000,000 | +| All JS, gzip | 7,456,194 | 7,850,000 | +| Largest JS file, gzip (`assets/index-*.js`) | 2,796,702 | 3,000,000 | +| Entry scripts in `index.html`, gzip | 4,498,737 | 4,750,000 | + +### Globe smoke + +The smoke serves the production build with `vite preview`. It blocks every +non-local request, so no keys or tiles are used. It opens `/` in headless Chrome +(SwiftShader WebGL) and waits for the Cesium scene. It then renders a 256×256 +central crop twice, with the globe shown and hidden. It passes when: + +- at least **20%** of the crop changes (a channel delta above 24), and +- the luma standard deviation of the globe crop is at least **4**, so a flat + fill fails. + +Measured at `53f0caa6`: 98.27% of pixels changed, luma standard deviation 9.49, +ready in 6.7 s. The full-page screenshot is uploaded as `globe.png`. The +screenshot shows globe geometry and atmosphere only. Map imagery and Google 3D +tiles are not tested. + +### Performance smoke (limits pending GEV-F3) + +This gate runs the repository's two wall-clock benchmarks with their own +budgets, and never changes those budgets: + +- icon model updates within 4 ms, 8 ms and 20 ms at N = 500, 2,000 and 5,000 +- the dense continental moveEnd pipeline yielding every 4 ms + +The gate runs 5 separate serial runs. A benchmark is over budget when it misses +in 3 or more of them. That benchmark fails the gate unless +`ci/factory/perf-baseline.json` lists it as already over budget at the baseline +commit on this runner class. Each listed entry carries its measured miss rate. +Listed benchmarks still appear in every description and JSON result. The gate +also returns `error` when the baseline's Node version or platform differs from +the runner's. + +There is one listed entry today, measured on Boat `default` VMs with the +moveEnd pipeline: + +- At `53f0caa6` it missed its 4 ms budget in 11 of 20 runs. +- On identical `src/` at the candidate head it missed in 14 of 20. +- Run alone, it missed in 16 of 20. +- The slowest slices measured 4.2 to 8.3 ms. Thread CPU time was about the + same as wall time and steal was near zero, so the overrun is CPU work on this + hardware, not noise. + +The budget stays at 4 ms. Remove the entry once the layer meets it. + +Limitations: + +- This is a Node microbenchmark smoke on a shared x64 VM. It does not measure + frame rate, GPU time, input latency or device resolution. Those belong to + GEV-F3 (real-device hill climbs, for example on an S25). +- A listed benchmark is not checked for further regression. Until F3 lands, a + green perf-smoke means only that no other CPU hot path went over its budget. + +## Caching + +- **Actions:** `.github/actions/factory-node` restores `node_modules` only on an + exact key: `factory-nm-v1---node-npm-`. + It sets no `restore-keys`, so a partial or older tree is never reused. A miss + runs `npm ci`. Puppeteer's Chrome is cached under its own key, built from the + same lockfile hash. +- **Boat:** every run starts from a fresh VM and runs `npm ci`. The measurements + below show why a cache would save little there. + +## Measured cost + +Boat `default` VM: 4 vCPU (AMD EPYC 4585PX), 8 GiB, Ubuntu 24.04, Node 24.22.2, +npm 11.19.1. See `REPORT` in the PR for single-run numbers and their spread. From 389d3286e3d7c9d935a3c3f6fbe6216a476102b1 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 18:44:58 -0600 Subject: [PATCH 09/18] fix(factory-ci): report external kills and test-less files truthfully --- scripts/factory-ci.mjs | 16 +++++++++++----- src/factoryCi.test.mjs | 8 ++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/scripts/factory-ci.mjs b/scripts/factory-ci.mjs index 6b62b922fd8..e76c23647c3 100644 --- a/scripts/factory-ci.mjs +++ b/scripts/factory-ci.mjs @@ -48,7 +48,11 @@ function run(command, args, { log, env = {}, timeoutMs = 30 * MINUTE } = {}) { resolve({ code: null, signal: null, error: String(error), ms: 0 }); return; } - const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill('SIGKILL'); + }, timeoutMs); for (const stream of [child.stdout, child.stderr]) { stream.on('data', (chunk) => { log.write(chunk); @@ -61,7 +65,7 @@ function run(command, args, { log, env = {}, timeoutMs = 30 * MINUTE } = {}) { }); child.on('close', (code, signal) => { clearTimeout(timer); - resolve({ code, signal, error: signal === 'SIGKILL' ? `timed out after ${timeoutMs} ms` : null, ms: Date.now() - started }); + resolve({ code, signal, error: timedOut ? `timed out after ${timeoutMs} ms` : null, ms: Date.now() - started }); }); }); } @@ -105,6 +109,7 @@ export function collectTests(lines) { const node = { file, name: wholeFile ? '(file)' : event.name, + wholeFile: Boolean(wholeFile), kind: event.kind, // A todo test may fail without failing the run, so todo/skip win. status: event.todo ? 'todo' : event.skip ? 'skip' @@ -128,7 +133,7 @@ export function collectTests(lines) { if (counts) { let id = `${node.file} > ${name.join(' > ')}`; for (let n = 2; tests.has(id); n++) id = `${node.file} > ${name.join(' > ')} #${n}`; - tests.set(id, { status: node.status, kind: node.kind, file: node.file, durationMs: node.durationMs }); + tests.set(id, { status: node.status, kind: node.kind, file: node.file, wholeFile: node.wholeFile, durationMs: node.durationMs }); } for (const child of node.children) visit(child, name); }; @@ -198,9 +203,10 @@ export function compareWithBaseline(baseline, tests, perFile, discovered) { return { ...out, blocking }; } -function perFileCounts(tests) { +/** Real tests per file. A file with no tests is reported as one passing whole-file entry; it counts as zero. */ +export function perFileCounts(tests) { const counts = {}; - for (const { file, kind } of tests.values()) if (kind === 'test') counts[file] = (counts[file] ?? 0) + 1; + for (const { file, kind, wholeFile } of tests.values()) if (kind === 'test' && !wholeFile) counts[file] = (counts[file] ?? 0) + 1; return Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))); } diff --git a/src/factoryCi.test.mjs b/src/factoryCi.test.mjs index bba3c7a9589..defe08ad62a 100644 --- a/src/factoryCi.test.mjs +++ b/src/factoryCi.test.mjs @@ -9,6 +9,7 @@ import { collectTests, compareWithBaseline, GATES, + perFileCounts, processProblem, statusesFor, } from '../scripts/factory-ci.mjs'; @@ -73,6 +74,13 @@ test('a run whose report cannot be trusted is an error, not a test failure', () assert.match(processProblem({ ...run, tests: new Map() }), /reported 1 tests but emitted 0/); }); +test('a file that no longer defines tests counts as zero tests', () => { + const { run, prefix } = runFixture({ 'a.test.mjs': "import { it } from 'node:test';\nit('ok', () => {});\n", 'empty.test.mjs': 'export {};\n' }); + assert.equal(processProblem(run), null); + const counts = Object.fromEntries(Object.entries(perFileCounts(run.tests)).map(([file, n]) => [file.slice(prefix.length + 1), n])); + assert.deepEqual(counts, { 'a.test.mjs': 1 }); +}); + test('only new failures, newly skipped tests and emptied files block', () => { const baseline = { failures: ['a > known'], From d0dfe3217a8c346086f751b4a639e50ac7c1a7b4 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 18:44:58 -0600 Subject: [PATCH 10/18] ci(factory): re-record the unit baseline with the fixed driver --- ci/factory/unit-baseline.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ci/factory/unit-baseline.json b/ci/factory/unit-baseline.json index 044f28bff98..8057a774654 100644 --- a/ci/factory/unit-baseline.json +++ b/ci/factory/unit-baseline.json @@ -4,7 +4,7 @@ "tree": "0629f67b790b64e62a0e66aaf8f14d52c8e589bb", "dirty": false, "packageLockSha256": "82038ae6fab86ffecf3d70cd04108c3552aca7bc6e90213d2773c982bea7a6b5", - "harnessSha256": "bec734239bc71d8941e9962874cfe79bdc107b5634695778c448b1dd9a96ae5c", + "harnessSha256": "8c8fbf0ded7e5ff2a66f4537fe6c09fc92e35fbf12d64bfeb4f4627162650bd1", "environment": { "node": "24.22.2", "npm": "11.19.1", @@ -15,7 +15,7 @@ "memoryGiB": 8, "runner": "boat-default-4vcpu" }, - "generatedAt": "2026-11-25T23:37:55.062Z", + "generatedAt": "2026-11-26T00:25:18.587Z", "command": "node scripts/factory-ci.mjs unit --write-baseline", "counts": { "tests": 14427, From da15c7b875391e0843c10e572c66a5918175bd83 Mon Sep 17 00:00:00 2001 From: kevin Date: Wed, 25 Nov 2026 18:44:58 -0600 Subject: [PATCH 11/18] docs(factory): measured costs and required checks --- docs/factory-ci.md | 47 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/docs/factory-ci.md b/docs/factory-ci.md index 4c39ddaf3d7..baaeda887d9 100644 --- a/docs/factory-ci.md +++ b/docs/factory-ci.md @@ -105,9 +105,10 @@ central crop twice, with the globe shown and hidden. It passes when: fill fails. Measured at `53f0caa6`: 98.27% of pixels changed, luma standard deviation 9.49, -ready in 6.7 s. The full-page screenshot is uploaded as `globe.png`. The -screenshot shows globe geometry and atmosphere only. Map imagery and Google 3D -tiles are not tested. +ready in 6.7 s. The full-page screenshot is uploaded as `globe.png`. It shows +the globe as a solid base-colour sphere with the starfield and HUD. Map imagery +and Google 3D tiles are not tested. The blocked icon font makes HUD icons render +as their ligature names, for example `layers`. ### Performance smoke (limits pending GEV-F3) @@ -158,4 +159,42 @@ Limitations: ## Measured cost Boat `default` VM: 4 vCPU (AMD EPYC 4585PX), 8 GiB, Ubuntu 24.04, Node 24.22.2, -npm 11.19.1. See `REPORT` in the PR for single-run numbers and their spread. +npm 11.19.1. Each line is measured on that VM class. `n` is the number of runs. + +| Step | Wall time | CPU (user+sys) | Peak RSS | n | +|---|---:|---:|---:|---:| +| `npm ci`, empty npm cache (includes Puppeteer's Chrome) | 13 s, 23 s | 31 s | 0.4 GB | 2 | +| `node_modules` restore from a tarball (warm) | 2.0 s | | | 1 | +| lint | 73 to 96 s | 125 s | 3.0 GB | 3 | +| typecheck, translations | 1.5 s, 0.7 s | | 0.4 GB | 3 | +| unit (all processes) | 304 to 393 s, median 340 s | 799 s | 0.9 GB | 6 | +| build | 13 to 15 s | 25 s | 2.2 GB | 3 | +| bundle-budget | 0.3 s | | | 3 | +| globe-smoke | 9 to 10 s | 2 s | 0.2 GB | 3 | +| perf-smoke (5 runs) | 6 to 8 s | 9 s | 0.3 GB | 9 | +| Whole Boat run, VM start to statuses posted | 7 min 24 s | | | 1 | + +The unit gate dominates, and most of it is the parallel test process: 311 s of +the 393 s baseline run. The serialized allocation probe takes 81 s more. CPU use +was about 200% of 400%, so the run is not CPU-bound on 4 vCPUs. Caching +`node_modules` saves 11 to 21 s per job (about 5% of a Boat run) and keeps +`npm ci` off the network. The cache sizes are 117 MB for the `node_modules` +tarball and 299 MB for Chrome. On Actions, the four gate jobs run in parallel, +so wall time is the unit job. + +Mirroring to Boat is not an optimisation here. While Actions is paused it is +the only working runner. A Boat CI app for `runs-on: boat` exists, but it is not +installed on this account, and installing it needs the owner in a browser. + +## Required checks + +- On every SHA that `nightly` or `staging` points to: `gev-ci/full`, which + implies all eight `gev-ci/*` gates above. +- On PRs into `nightly` (owned by the modularity card, `factory-modularity.yml`): + `factory-modularity/hot-files`, `factory-modularity/commit-builds` and + `factory-modularity/tooling-tests`. +- `Fork branch policy` (in `ci.yml`) refuses PRs into `main` and `staging`. + Staging only moves by fast-forward promotion. +- Upstream's own jobs (`Node 24.22.2`, `Node 26.x`, `Street Level browser gate`, + `Windows onboarding`) still run on Actions. They are not part of the factory + contract. From bae4f4588688286bd857ad9a6a949f451c010010 Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 12/18] feat(factory): exact-SHA status and soak evaluation for branch gates Policy file plus shared logic: latest-per-context status verdicts (trusted success only, red from anyone), soak computed from GitHub-stamped commit-status history with reset, gap and staleness rules, and plain-push git helpers. --- ci/factory/branch-policy.json | 33 +++ scripts/factory/branch_gates.py | 507 ++++++++++++++++++++++++++++++++ 2 files changed, 540 insertions(+) create mode 100644 ci/factory/branch-policy.json create mode 100644 scripts/factory/branch_gates.py diff --git a/ci/factory/branch-policy.json b/ci/factory/branch-policy.json new file mode 100644 index 00000000000..99e013c73fb --- /dev/null +++ b/ci/factory/branch-policy.json @@ -0,0 +1,33 @@ +{ + "$comment": "Policy for nightly integration, soak observation and staging promotion. Read from the trusted checkout (default branch), never from a PR. Contract: docs/factory/NIGHTLY-PROMOTION.md. Changing a value is a reviewed edit.", + "repo": "kvnloo/gods-eye-view", + "nightly_branch": "nightly", + "staging_branch": "staging", + "nightly_label": "nightly", + "integrable_bases": ["nightly", "staging"], + "candidate_ref_prefix": "factory/nightly-candidate/", + "ci_full_context": "gev-ci/full", + "ci_gate_contexts": [ + "gev-ci/lint", + "gev-ci/typecheck", + "gev-ci/translations", + "gev-ci/unit", + "gev-ci/build", + "gev-ci/bundle-budget", + "gev-ci/globe-smoke", + "gev-ci/perf-smoke" + ], + "ci_red_prefix": "gev-ci/", + "pr_extra_required_contexts": [], + "$pr_extra_required_contexts": "factory-modularity/{hot-files,commit-builds,tooling-tests} (t_9a4af6d7) only run on GitHub Actions, which is paused on this fork. Add them here once Actions runs them; until then they cannot exist on any head.", + "trusted_status_creators": ["kvnloo", "github-actions[bot]"], + "soak_context": "gev-soak/nightly", + "promotion_context": "gev-promote/staging", + "min_soak_hours": 24, + "max_observation_gap_hours": 6, + "min_soak_observations": 4, + "ci_wait_minutes": 90, + "max_ci_runs_per_integration": 8, + "committer_name": "gev-factory", + "committer_email": "gev-factory@users.noreply.github.com" +} diff --git a/scripts/factory/branch_gates.py b/scripts/factory/branch_gates.py new file mode 100644 index 00000000000..9ac7ef03133 --- /dev/null +++ b/scripts/factory/branch_gates.py @@ -0,0 +1,507 @@ +"""Shared logic for nightly integration, soak observation and staging promotion. + +Contract and runbook: docs/factory/NIGHTLY-PROMOTION.md. CI contract consumed: +docs/factory-ci.md (exact-SHA `gev-ci/*` commit statuses, `gev-ci/full`). + +Design rules this module enforces: + +* Evidence is read from GitHub commit statuses on the *exact* SHA being + published. A status on any other SHA (a PR head, an older tip) authorizes + nothing. +* Only the latest status per context counts. A latest `failure`/`error` from + any creator is red. A latest `success` counts only from a trusted creator. + Missing or `pending` is not green. Every unknown is a refusal. +* Time comes from GitHub's own `created_at` on statuses. Nothing in this module + accepts a caller-supplied timestamp for soak evidence, so soak cannot be + backdated. Statuses cannot be deleted through the API, so the history is + append-only. +* Branch updates are plain (non-forced) pushes of an already-validated SHA, + after re-reading the ref. Git refuses a non-fast-forward, and the post-push + read-back must equal the validated SHA. + +Python 3.9+, standard library only. +""" +from __future__ import annotations + +import datetime as dt +import json +import os +import re +import subprocess +import tempfile +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple + +SHA_RE = re.compile(r"^[0-9a-f]{40}$") +HERE = Path(__file__).resolve().parent +DEFAULT_POLICY = HERE.parent.parent / "ci" / "factory" / "branch-policy.json" + + +class Refusal(Exception): + """A fail-closed refusal. `code` is the process exit status.""" + + def __init__(self, reason: str, code: int = 1): + super().__init__(reason) + self.reason = reason + self.code = code + + +def load_policy(path: Optional[Path] = None) -> dict: + with open(path or DEFAULT_POLICY, encoding="utf-8") as fh: + policy = json.load(fh) + for key in ("nightly_branch", "staging_branch", "ci_full_context", "ci_gate_contexts", + "trusted_status_creators", "soak_context", "min_soak_hours", + "max_observation_gap_hours", "min_soak_observations"): + if key not in policy: + raise Refusal(f"policy is missing {key!r}", 2) + if float(policy["min_soak_hours"]) < 24: + # The owner's bar is >= 24 h. A policy edit cannot lower it below that. + raise Refusal("policy min_soak_hours is below the 24 h floor", 2) + return policy + + +def require_sha(value: str, what: str = "sha") -> str: + if not isinstance(value, str) or not SHA_RE.match(value): + raise Refusal(f"{what} must be 40 lowercase hex characters (got {value!r})", 2) + return value + + +def parse_time(stamp: str) -> dt.datetime: + return dt.datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc) + + +def fmt_time(t: Optional[dt.datetime]) -> str: + return t.strftime("%Y-%m-%dT%H:%M:%SZ") if t else "-" + + +# -------------------------------------------------------------------------- +# Status evaluation (pure) +# -------------------------------------------------------------------------- + +@dataclass +class Status: + id: int + context: str + state: str + created_at: dt.datetime + creator: str + description: str = "" + target_url: str = "" + + @classmethod + def from_api(cls, raw: dict) -> "Status": + return cls( + id=int(raw.get("id") or 0), + context=raw["context"], + state=raw["state"], + created_at=parse_time(raw["created_at"]), + creator=((raw.get("creator") or {}).get("login") or ""), + description=raw.get("description") or "", + target_url=raw.get("target_url") or "", + ) + + +def _order(s: Status) -> Tuple[dt.datetime, int]: + return (s.created_at, s.id) + + +def latest_by_context(statuses: Iterable[Status]) -> Dict[str, Status]: + out: Dict[str, Status] = {} + for s in statuses: + cur = out.get(s.context) + if cur is None or _order(s) > _order(cur): + out[s.context] = s + return out + + +@dataclass +class CiVerdict: + state: str # green | red | pending + detail: List[Tuple[str, str, str]] = field(default_factory=list) # (context, state, note) + + @property + def green(self) -> bool: + return self.state == "green" + + def summary(self) -> str: + bad = [f"{c}={s}{' (' + n + ')' if n else ''}" for c, s, n in self.detail if s != "success" or n] + return self.state + (": " + ", ".join(bad) if bad else "") + + +def evaluate_ci(statuses: Sequence[Status], contexts: Sequence[str], trusted: Sequence[str], + red_prefix: Optional[str] = None) -> CiVerdict: + """Green only if every context's latest status is a trusted success and no + context under `red_prefix` has a latest failure/error.""" + latest = latest_by_context(statuses) + detail: List[Tuple[str, str, str]] = [] + red = pending = False + for ctx in contexts: + s = latest.get(ctx) + if s is None: + detail.append((ctx, "missing", "")) + pending = True + elif s.state in ("failure", "error"): + detail.append((ctx, s.state, s.description[:80])) + red = True + elif s.state != "success": + detail.append((ctx, s.state, "")) + pending = True + elif s.creator not in trusted: + detail.append((ctx, "untrusted", f"posted by {s.creator or '?'}")) + pending = True + else: + detail.append((ctx, "success", "")) + if red_prefix: + for ctx, s in sorted(latest.items()): + if ctx.startswith(red_prefix) and ctx not in contexts and s.state in ("failure", "error"): + detail.append((ctx, s.state, s.description[:80])) + red = True + return CiVerdict("red" if red else "pending" if pending else "green", detail) + + +def ci_contexts(policy: dict) -> List[str]: + return list(policy["ci_gate_contexts"]) + [policy["ci_full_context"]] + + +def evaluate_exact_ci(statuses: Sequence[Status], policy: dict) -> CiVerdict: + return evaluate_ci(statuses, ci_contexts(policy), policy["trusted_status_creators"], + policy.get("ci_red_prefix")) + + +@dataclass +class SoakReport: + ok: bool + reason: str + start: Optional[dt.datetime] = None + end: Optional[dt.datetime] = None + observations: int = 0 + last_reset: Optional[Status] = None + ci_green_since: Optional[dt.datetime] = None + gaps: List[Tuple[str, str, float]] = field(default_factory=list) + ignored_untrusted: int = 0 + + @property + def hours(self) -> float: + if not (self.start and self.end): + return 0.0 + return (self.end - self.start).total_seconds() / 3600 + + def as_dict(self) -> dict: + return { + "ok": self.ok, "reason": self.reason, "soak_start": fmt_time(self.start), + "soak_end": fmt_time(self.end), "soak_hours": round(self.hours, 3), + "observations": self.observations, + "last_reset": None if not self.last_reset else { + "context": self.last_reset.context, "state": self.last_reset.state, + "created_at": fmt_time(self.last_reset.created_at), "id": self.last_reset.id, + "creator": self.last_reset.creator}, + "ci_green_since": fmt_time(self.ci_green_since), + "gaps_over_limit": [{"from": a, "to": b, "hours": round(h, 3)} for a, b, h in self.gaps], + "ignored_untrusted_observations": self.ignored_untrusted, + } + + +def compute_soak(statuses: Sequence[Status], policy: dict, now: dt.datetime) -> SoakReport: + """Soak of one SHA from its own commit-status history. + + * Reset: the newest `failure`/`error` (any creator) in any `gev-ci/*` + context or the soak context. Soak evidence before it does not count. + * Observations: trusted `success` statuses in the soak context, posted + after the reset and after the first trusted `gev-ci/full` success that + follows it. + * The observations are split wherever two consecutive ones (or the last one + and `now`) are more than `max_observation_gap_hours` apart. Only the + final unbroken run counts. It must span `min_soak_hours` and contain at + least `min_soak_observations` observations. + """ + soak_ctx = policy["soak_context"] + trusted = set(policy["trusted_status_creators"]) + red_prefix = policy.get("ci_red_prefix", "gev-ci/") + full_ctx = policy["ci_full_context"] + min_soak = dt.timedelta(hours=float(policy["min_soak_hours"])) + max_gap = dt.timedelta(hours=float(policy["max_observation_gap_hours"])) + min_obs = int(policy["min_soak_observations"]) + + ordered = sorted(statuses, key=_order) + resets = [s for s in ordered + if s.state in ("failure", "error") and (s.context == soak_ctx or s.context.startswith(red_prefix))] + last_reset = resets[-1] if resets else None + after = [s for s in ordered if last_reset is None or _order(s) > _order(last_reset)] + + green_full = [s for s in after if s.context == full_ctx and s.state == "success" and s.creator in trusted] + rep = SoakReport(False, "", last_reset=last_reset) + if not green_full: + rep.reason = ("no trusted gev-ci/full success since the last red" + if last_reset else "no trusted gev-ci/full success on this SHA") + return rep + rep.ci_green_since = green_full[0].created_at + + obs_all = [s for s in after if s.context == soak_ctx and s.state == "success"] + rep.ignored_untrusted = sum(1 for s in obs_all if s.creator not in trusted) + obs = [s for s in obs_all if s.creator in trusted and s.created_at >= rep.ci_green_since] + if not obs: + rep.reason = "no recorded soak observations since CI went green" + return rep + + segment: List[Status] = [obs[0]] + for prev, cur in zip(obs, obs[1:]): + if cur.created_at - prev.created_at > max_gap: + rep.gaps.append((fmt_time(prev.created_at), fmt_time(cur.created_at), + (cur.created_at - prev.created_at).total_seconds() / 3600)) + segment = [cur] + else: + segment.append(cur) + rep.start, rep.end, rep.observations = segment[0].created_at, segment[-1].created_at, len(segment) + + if now - rep.end > max_gap: + rep.gaps.append((fmt_time(rep.end), fmt_time(now), (now - rep.end).total_seconds() / 3600)) + rep.reason = f"last soak observation is {(now - rep.end).total_seconds() / 3600:.1f} h old (limit {max_gap.total_seconds() / 3600:g} h)" + return rep + if rep.end - rep.start < min_soak: + rep.reason = f"soaked {rep.hours:.2f} h of the required {min_soak.total_seconds() / 3600:g} h" + return rep + if rep.observations < min_obs: + rep.reason = f"{rep.observations} soak observations, need at least {min_obs}" + return rep + rep.ok = True + rep.reason = f"soaked {rep.hours:.2f} h with {rep.observations} observations and no red" + return rep + + +def observation_for(sha: str, in_nightly: bool, tip: str, ci_sha: CiVerdict, + ci_tip: Optional[CiVerdict]) -> Tuple[str, str]: + """(state, description) of one soak observation of `sha`.""" + short = tip[:12] + if not in_nightly: + return "failure", f"not in nightly history (tip {short})" + if ci_sha.state == "red": + return "failure", "own gev-ci red: " + ci_sha.summary()[:100] + if not ci_sha.green: + return "pending", "own gev-ci not green: " + ci_sha.summary()[:100] + if sha != tip and ci_tip is not None: + if ci_tip.state == "red": + return "failure", f"nightly tip {short} is red" + if not ci_tip.green: + return "pending", f"nightly tip {short} not validated" + return "success", f"green in nightly@{short}" + + +# -------------------------------------------------------------------------- +# Adapters +# -------------------------------------------------------------------------- + +def run(cmd: Sequence[str], cwd: Optional[str] = None, check: bool = True, env: Optional[dict] = None, + input_text: Optional[str] = None) -> subprocess.CompletedProcess: + proc = subprocess.run(list(cmd), cwd=cwd, env=env, input=input_text, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if check and proc.returncode != 0: + raise RuntimeError(f"{' '.join(cmd[:4])}... exited {proc.returncode}: {proc.stderr.strip()[:600]}") + return proc + + +class GitHubCli: + """GitHub REST through `gh api` (GH_TOKEN in Actions, the gh login on a host).""" + + def __init__(self, repo: str): + if not re.match(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", repo): + raise Refusal(f"bad repo {repo!r}", 2) + self.repo = repo + + def _api(self, args: Sequence[str]) -> object: + proc = run(["gh", "api", *args]) + return json.loads(proc.stdout) if proc.stdout.strip() else None + + def _paginate(self, path: str) -> list: + proc = run(["gh", "api", "--paginate", "--slurp", path]) + pages = json.loads(proc.stdout) + return [item for page in pages for item in page] + + def now(self) -> dt.datetime: + return dt.datetime.now(dt.timezone.utc) + + def open_prs(self) -> List[dict]: + return self._paginate(f"repos/{self.repo}/pulls?state=open&per_page=100") + + def pr(self, number: int) -> dict: + return self._api([f"repos/{self.repo}/pulls/{int(number)}"]) # type: ignore[return-value] + + def statuses(self, sha: str) -> List[Status]: + require_sha(sha) + return [Status.from_api(r) for r in self._paginate(f"repos/{self.repo}/commits/{sha}/statuses?per_page=100")] + + def post_status(self, sha: str, state: str, context: str, description: str, target_url: str = "") -> Status: + require_sha(sha) + args = ["-X", "POST", f"repos/{self.repo}/statuses/{sha}", "-f", f"state={state}", + "-f", f"context={context}", "-f", f"description={description[:140]}"] + if target_url: + args += ["-f", f"target_url={target_url}"] + return Status.from_api(self._api(args)) # type: ignore[arg-type] + + def dispatch(self, workflow: str, ref: str, inputs: Dict[str, str]) -> None: + args = ["-X", "POST", f"repos/{self.repo}/actions/workflows/{workflow}/dispatches", "-f", f"ref={ref}"] + for k, v in inputs.items(): + args += ["-f", f"inputs[{k}]={v}"] + self._api(args) + + +class GitRepo: + """A private scratch repository that talks to one remote.""" + + def __init__(self, remote_url: str, workdir: Optional[str] = None, use_gh_credentials: bool = True): + self.remote_url = remote_url + self.dir = workdir or tempfile.mkdtemp(prefix="gev-branch-gate-") + Path(self.dir).mkdir(parents=True, exist_ok=True) + self.env = dict(os.environ, GIT_TERMINAL_PROMPT="0") + self.cred: List[str] = ["-c", "credential.helper="] + if use_gh_credentials and remote_url.startswith("https://github.com/"): + if os.environ.get("FACTORY_PUSH_TOKEN"): + # Actions: a GitHub App token that may push workflow files; the API keeps GITHUB_TOKEN. + helper = '!f() { echo username=x-access-token; echo "password=$FACTORY_PUSH_TOKEN"; }; f' + else: + helper = "!gh auth git-credential" + self.cred += ["-c", f"credential.https://github.com.helper={helper}"] + if not (Path(self.dir) / "HEAD").exists(): + self.git("init", "-q", "--bare") + self.git("remote", "add", "origin", remote_url) + if remote_url.startswith("https://"): + self.git("config", "remote.origin.promisor", "true") + self.git("config", "remote.origin.partialclonefilter", "blob:none") + + def git(self, *args: str, check: bool = True, input_text: Optional[str] = None) -> str: + proc = run(["git", "-C", self.dir, *self.cred, *args], check=check, env=self.env, input_text=input_text) + return proc.stdout.strip() if check else proc # type: ignore[return-value] + + def ok(self, *args: str) -> bool: + return run(["git", "-C", self.dir, *self.cred, *args], check=False, env=self.env).returncode == 0 + + def remote_ref(self, branch: str) -> Optional[str]: + out = self.git("ls-remote", "origin", f"refs/heads/{branch}") + for line in out.splitlines(): + sha, ref = line.split("\t", 1) + if ref == f"refs/heads/{branch}": + return require_sha(sha, f"remote {branch}") + return None + + def fetch(self, *refspecs: str) -> None: + extra = ["--filter=blob:none"] if self.remote_url.startswith("https://") else [] + self.git("fetch", "-q", "--no-tags", *extra, "origin", *refspecs) + + def fetch_sha(self, sha: str) -> bool: + require_sha(sha) + if self.ok("cat-file", "-e", f"{sha}^{{commit}}"): + return True + extra = ["--filter=blob:none"] if self.remote_url.startswith("https://") else [] + return self.ok("fetch", "-q", "--no-tags", *extra, "origin", sha) and \ + self.ok("cat-file", "-e", f"{sha}^{{commit}}") + + def is_ancestor(self, a: str, b: str) -> bool: + return self.ok("merge-base", "--is-ancestor", a, b) + + def first_parent_range(self, base: str, tip: str) -> List[str]: + out = self.git("rev-list", "--first-parent", f"{base}..{tip}") + return [l for l in out.splitlines() if l] + + def merge(self, ours: str, theirs: str, message: str, name: str, email: str) -> Optional[str]: + """Merge commit of `theirs` into `ours` without a worktree; None on conflict.""" + proc = run(["git", "-C", self.dir, *self.cred, "merge-tree", "--write-tree", "--no-messages", ours, theirs], + check=False, env=self.env) + if proc.returncode == 1: + return None + if proc.returncode != 0: + raise RuntimeError(f"merge-tree failed: {proc.stderr.strip()[:400]}") + tree = proc.stdout.split()[0] + env = dict(self.env, GIT_AUTHOR_NAME=name, GIT_AUTHOR_EMAIL=email, + GIT_COMMITTER_NAME=name, GIT_COMMITTER_EMAIL=email) + out = run(["git", "-C", self.dir, "commit-tree", tree, "-p", ours, "-p", theirs, "-F", "-"], + env=env, input_text=message).stdout.strip() + return require_sha(out, "merge commit") + + def push(self, sha: str, branch: str) -> subprocess.CompletedProcess: + """Plain push: no force flag of any kind, so the remote refuses a + non-fast-forward. Returns the process so callers can report stderr.""" + require_sha(sha) + return run(["git", "-C", self.dir, *self.cred, "push", "--porcelain", "--no-verify", "origin", + f"{sha}:refs/heads/{branch}"], check=False, env=self.env) + + +# -------------------------------------------------------------------------- +# Reporting +# -------------------------------------------------------------------------- + +class Summary: + """Markdown report: stdout plus $GITHUB_STEP_SUMMARY when set.""" + + def __init__(self, path: Optional[str] = None): + self.path = path if path is not None else os.environ.get("GITHUB_STEP_SUMMARY") + self.lines: List[str] = [] + + def add(self, *lines: str) -> None: + for line in lines: + self.lines.append(line) + print(line, flush=True) + if self.path: + with open(self.path, "a", encoding="utf-8") as fh: + fh.write(line + "\n") + + def table(self, header: Sequence[str], rows: Iterable[Sequence[str]]) -> None: + self.add("| " + " | ".join(header) + " |", "|" + "---|" * len(header)) + for r in rows: + self.add("| " + " | ".join(str(c).replace("|", "\\|").replace("\n", " ") for c in r) + " |") + self.add("") + + +def max_status_id(gh, sha: str) -> int: + return max((s.id for s in gh.statuses(sha)), default=0) + + +def wait_for_full(gh, sha: str, policy: dict, minutes: float, poll_seconds: float = 30, + sleep: Callable[[float], None] = time.sleep, min_id: int = 0) -> CiVerdict: + """Poll statuses on `sha` until a gev-ci/full newer than status id `min_id` + is final, or time runs out. Status ids grow monotonically on GitHub, so an + older verdict on the same SHA cannot satisfy the wait.""" + deadline = time.monotonic() + minutes * 60 + while True: + statuses = gh.statuses(sha) + verdict = evaluate_exact_ci(statuses, policy) + full = latest_by_context(statuses).get(policy["ci_full_context"]) + if full is not None and full.id > min_id and full.state in ("success", "failure", "error"): + return verdict + if time.monotonic() >= deadline: + return CiVerdict("pending", verdict.detail + [(policy["ci_full_context"], "timeout", f"{minutes:g} min")]) + sleep(poll_seconds) + + +def run_url() -> str: + server, repo, rid = (os.environ.get(k) for k in ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_RUN_ID")) + return f"{server}/{repo}/actions/runs/{rid}" if server and repo and rid else "" + + +class HostLock: + """Serializes runs on one host (Actions uses a concurrency group).""" + + def __init__(self, path: Optional[str]): + self.path = path + self.fh = None + + def __enter__(self): + if not self.path: + return self + import fcntl + Path(self.path).parent.mkdir(parents=True, exist_ok=True) + self.fh = open(self.path, "a+") + try: + fcntl.flock(self.fh, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + raise Refusal(f"another branch mutation holds {self.path}", 75) + return self + + def __exit__(self, *exc): + if self.fh: + self.fh.close() + return False + + +def default_lock_path() -> str: + return os.path.join(os.path.expanduser("~"), ".cache", "gev-factory", "branch-mutation.lock") From c24a29b9a289dccf3c3e462669ace3984aff117e Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 13/18] feat(factory): hourly soak observations as commit statuses Posts gev-soak/nightly on every validated nightly tip ahead of staging. The append-only status history is the soak ledger. --- .github/workflows/factory-soak-observe.yml | 40 ++++++++++ scripts/factory/soak_observe.py | 85 ++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 .github/workflows/factory-soak-observe.yml create mode 100644 scripts/factory/soak_observe.py diff --git a/.github/workflows/factory-soak-observe.yml b/.github/workflows/factory-soak-observe.yml new file mode 100644 index 00000000000..6613892b386 --- /dev/null +++ b/.github/workflows/factory-soak-observe.yml @@ -0,0 +1,40 @@ +# Hourly soak observation: one `gev-soak/nightly` commit status on every +# validated nightly tip that is not on staging yet. The status history on each +# SHA is the soak ledger that staging promotion reads. +# Owner card: t_cf66fac4. Runbook: docs/factory/NIGHTLY-PROMOTION.md. +name: Factory soak observation + +on: + schedule: + - cron: '53 * * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: factory-soak-observe + cancel-in-progress: false + +jobs: + observe: + name: Observe nightly soak + if: github.repository == 'kvnloo/gods-eye-view' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + statuses: write + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + scripts/factory + ci/factory/branch-policy.json + sparse-checkout-cone-mode: false + persist-credentials: false + - name: Observe + env: + GH_TOKEN: ${{ github.token }} + run: python3 scripts/factory/soak_observe.py diff --git a/scripts/factory/soak_observe.py b/scripts/factory/soak_observe.py new file mode 100644 index 00000000000..f9104e09f24 --- /dev/null +++ b/scripts/factory/soak_observe.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Record one soak observation on every validated nightly tip not yet on staging. + + python3 scripts/factory/soak_observe.py [--sha ] + +Tracked SHAs are the first-parent commits of `staging..nightly` that carry a +`gev-ci/full` status (the tips nightly integration published). For each one it +posts a `gev-soak/nightly` commit status: + +* success the SHA is in nightly history, its own gev-ci/* are green, and the + current nightly tip is green; +* failure it left nightly history, its own gev-ci/* turned red, or the + nightly tip is red. A failure resets that SHA's soak; +* pending inconclusive (own CI or tip not validated). It neither extends nor + resets soak; long runs of it break soak through the gap limit. + +GitHub stamps `created_at` and the creator on every status and offers no delete, +so this status history is the persisted, append-only soak ledger. +Exit: 0 observed, 1 could not observe, 2 usage. +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path +from typing import List, Optional, Tuple + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import branch_gates as bg # noqa: E402 + + +def observe(gh, git: bg.GitRepo, policy: dict, summary: bg.Summary, only: Optional[str] = None, + target_url: str = "") -> Tuple[int, List[Tuple[str, str, str]]]: + nightly, staging, ctx = policy["nightly_branch"], policy["staging_branch"], policy["soak_context"] + tip, stage = git.remote_ref(nightly), git.remote_ref(staging) + if not tip or not stage: + summary.add(f"❌ cannot read `{nightly}`/`{staging}`; nothing observed") + return 1, [] + git.fetch(f"+refs/heads/{nightly}:refs/gate/nightly", f"+refs/heads/{staging}:refs/gate/staging") + ci_tip = bg.evaluate_exact_ci(gh.statuses(tip), policy) + + if only: + bg.require_sha(only) + if not git.fetch_sha(only): + summary.add(f"❌ `{only}` is not a commit of the repository; nothing observed") + return 1, [] + tracked = [only] + else: + tracked = [s for s in git.first_parent_range(stage, tip) + if any(st.context == policy["ci_full_context"] for st in gh.statuses(s))][:50] + + rows: List[Tuple[str, str, str]] = [] + for sha in tracked: + in_nightly = git.is_ancestor(sha, tip) + ci_sha = bg.evaluate_exact_ci(gh.statuses(sha), policy) + state, desc = bg.observation_for(sha, in_nightly, tip, ci_sha, None if sha == tip else ci_tip) + posted = gh.post_status(sha, state, ctx, desc, target_url) + rows.append((sha, state, f"{desc} (status {posted.id} at {bg.fmt_time(posted.created_at)})")) + + summary.add(f"## Soak observation (`{ctx}`)", "", + f"nightly `{tip}` ({ci_tip.state}), staging `{stage}`", "") + if rows: + summary.table(["SHA", "observation", "detail"], [[f"`{s}`", st, d] for s, st, d in rows]) + else: + summary.add("No validated nightly tips are ahead of staging.") + return 0, rows + + +def main(argv: Optional[List[str]] = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--sha", help="observe only this SHA") + args = ap.parse_args(argv) + try: + policy = bg.load_policy() + gh = bg.GitHubCli(policy["repo"]) + git = bg.GitRepo(f"https://github.com/{policy['repo']}.git") + code, _ = observe(gh, git, policy, bg.Summary(), args.sha, bg.run_url()) + return code + except bg.Refusal as exc: + print(f"refused: {exc.reason}", file=sys.stderr) + return exc.code + + +if __name__ == "__main__": + sys.exit(main()) From 2212fe3cc87069239041b94315a71ce8b89a1eaa Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 14/18] feat(factory): nightly integration of green PRs labeled nightly Merges eligible nightly- and staging-based PRs, validates the exact integration SHA with full CI on a candidate ref, falls back to one PR at a time, and publishes only a re-verified green SHA by fast-forward. --- .../workflows/factory-nightly-integrate.yml | 78 +++++ scripts/factory/nightly_integrate.py | 327 ++++++++++++++++++ 2 files changed, 405 insertions(+) create mode 100644 .github/workflows/factory-nightly-integrate.yml create mode 100644 scripts/factory/nightly_integrate.py diff --git a/.github/workflows/factory-nightly-integrate.yml b/.github/workflows/factory-nightly-integrate.yml new file mode 100644 index 00000000000..46b6dce3f6d --- /dev/null +++ b/.github/workflows/factory-nightly-integrate.yml @@ -0,0 +1,78 @@ +# Nightly integration: merge green PRs labeled `nightly` into `nightly`, but only +# publish an integration SHA whose own gev-ci/* statuses are green. +# Owner card: t_cf66fac4. Runbook: docs/factory/NIGHTLY-PROMOTION.md. +# +# `schedule` fires only from the default branch (`staging`), so this runs once +# the file has been promoted there. Until then use the host runner in the runbook. +name: Factory nightly integration + +on: + schedule: + - cron: '41 8 * * *' # 08:41 UTC, 02:41 US Central + workflow_dispatch: + inputs: + dry-run: + description: Assess and merge locally; push nothing + type: boolean + default: false + +permissions: + contents: read + +# One branch mutator at a time: shared with factory-promote-staging.yml. +concurrency: + group: factory-branch-mutation + cancel-in-progress: false + +jobs: + integrate: + name: Integrate labeled PRs into nightly + if: github.repository == 'kvnloo/gods-eye-view' + runs-on: ubuntu-24.04 + timeout-minutes: 350 + environment: factory-branches + permissions: + contents: read + pull-requests: read + statuses: read + actions: write # dispatches factory-ci-sha.yml for each integration SHA + steps: + - name: Check out the trusted gate scripts (default branch, never a PR) + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + scripts/factory + ci/factory/branch-policy.json + sparse-checkout-cone-mode: false + persist-credentials: false + + # GITHUB_TOKEN cannot push commits that touch .github/workflows, and many + # integrations do. The App token is used only by `git push`. + - name: Branch push token + id: app + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ vars.FACTORY_APP_CLIENT_ID }} + private-key: ${{ secrets.FACTORY_APP_PRIVATE_KEY }} + permission-contents: write + permission-workflows: write + + - name: Integrate (exact-SHA CI via factory-ci-sha.yml) + env: + GH_TOKEN: ${{ github.token }} + FACTORY_PUSH_TOKEN: ${{ steps.app.outputs.token }} + DRY_RUN: ${{ inputs.dry-run && '--dry-run' || '' }} + run: | + python3 scripts/factory/nightly_integrate.py --validator dispatch \ + --ci-workflow factory-ci-sha.yml --ci-ref '${{ github.event.repository.default_branch }}' \ + --lock '' --report integration.json $DRY_RUN + + - name: Keep the JSON record + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: nightly-integration-${{ github.run_id }} + path: integration.json + if-no-files-found: warn + retention-days: 90 diff --git a/scripts/factory/nightly_integrate.py b/scripts/factory/nightly_integrate.py new file mode 100644 index 00000000000..11742950bfe --- /dev/null +++ b/scripts/factory/nightly_integrate.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Integrate green PRs labeled `nightly` into `nightly`, validated by exact-SHA CI. + + python3 scripts/factory/nightly_integrate.py --validator boat|dispatch|external [--dry-run] + +1. Read `nightly` (B) and `staging`; refuse unless staging is an ancestor of B. +2. List open PRs with the `nightly` label. Eligible: not draft, base `nightly` + or `staging`, head on this repo, already not in B, and every gev-ci/* + context green on the exact head SHA from a trusted creator. +3. Merge eligible heads onto B in PR-number order (merge commits, first parent + = the previous nightly tip). A conflicting PR is skipped. +4. Push the result to a new `factory/nightly-candidate/-` branch + and run full CI on that exact SHA (Boat, workflow dispatch, or an external + runner). Read the verdict back from commit statuses on that SHA. +5. If the batch is red, rebuild one PR at a time on top of the last green tip, + validating each, within `max_ci_runs_per_integration`. +6. Publish only a SHA whose own statuses are green: re-read `nightly` (must + still be B) and every merged PR head (must be unchanged), re-read the + statuses, plain-push (fast-forward only), and read the ref back. + +Exit: 0 published or nothing to do, 1 refused or red, 2 usage, 75 locked. +""" +from __future__ import annotations + +import argparse +import datetime as dt +import json +import os +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, List, Optional + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import branch_gates as bg # noqa: E402 + + +@dataclass +class Candidate: + number: int + base: str + head: str + title: str + url: str + outcome: str = "" + included: bool = False + + +@dataclass +class Attempt: + sha: str + prs: List[int] + ref: str + verdict: str = "" + + +@dataclass +class Result: + exit_code: int + nightly_before: str = "" + nightly_after: str = "" + published: Optional[str] = None + candidates: List[Candidate] = field(default_factory=list) + attempts: List[Attempt] = field(default_factory=list) + reason: str = "" + + def as_dict(self) -> dict: + return { + "exit_code": self.exit_code, "reason": self.reason, + "nightly_before": self.nightly_before, "nightly_after": self.nightly_after, + "published": self.published, + "prs": [c.__dict__ for c in self.candidates], + "attempts": [a.__dict__ for a in self.attempts], + } + + +class BoatValidator: + """Runs scripts/factory-ci-boat.sh synchronously; it posts the statuses.""" + + def __init__(self, script: Path): + self.script = script + + def start(self, sha: str, base: str) -> None: + bg.run(["bash", str(self.script), sha, base], check=False) + + +class DispatchValidator: + """Dispatches factory-ci-sha.yml; its report job posts the statuses.""" + + def __init__(self, gh, workflow: str, ref: str): + self.gh, self.workflow, self.ref = gh, workflow, ref + + def start(self, sha: str, base: str) -> None: + self.gh.dispatch(self.workflow, self.ref, {"sha": sha, "base-sha": base}) + + +class ExternalValidator: + """Another runner validates candidate refs; just wait for its statuses.""" + + def start(self, sha: str, base: str) -> None: + return None + + +def assess(pr: dict, policy: dict, gh, repo: str) -> Candidate: + head = (pr.get("head") or {}).get("sha") or "" + c = Candidate(int(pr["number"]), (pr.get("base") or {}).get("ref") or "", head, + pr.get("title") or "", pr.get("html_url") or "") + if pr.get("draft"): + c.outcome = "skipped: draft" + return c + if c.base not in policy["integrable_bases"]: + c.outcome = (f"skipped: base `{c.base}` is not integrated (only " + f"{', '.join(policy['integrable_bases'])}); retarget once its parent lands") + return c + head_repo = ((pr.get("head") or {}).get("repo") or {}).get("full_name") + if head_repo != repo: + c.outcome = f"skipped: head is on `{head_repo}`, not `{repo}`" + return c + if not bg.SHA_RE.match(head): + c.outcome = "skipped: head SHA unreadable" + return c + contexts = bg.ci_contexts(policy) + list(policy.get("pr_extra_required_contexts", [])) + verdict = bg.evaluate_ci(gh.statuses(head), contexts, policy["trusted_status_creators"], + policy.get("ci_red_prefix")) + if not verdict.green: + c.outcome = f"skipped: head not green ({verdict.summary()})" + return c + c.outcome = "eligible" + return c + + +def merge_message(c: Candidate, nightly: str) -> str: + return (f"Merge PR #{c.number} into {nightly}\n\n{c.title}\n\nPR: {c.url}\nHead: {c.head}\n" + f"PR-Base: {c.base}\nIntegrated-By: scripts/factory/nightly_integrate.py\n") + + +def integrate(gh, git: bg.GitRepo, policy: dict, validator, summary: bg.Summary, dry_run: bool = False, + poll_seconds: float = 30, sleep: Callable[[float], None] = time.sleep, + stamp: Optional[str] = None) -> Result: + repo, nightly, staging = policy["repo"], policy["nightly_branch"], policy["staging_branch"] + name, email = policy["committer_name"], policy["committer_email"] + stamp = stamp or dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + res = Result(1) + summary.add(f"## Nightly integration ({'dry run' if dry_run else 'apply'})", "") + + base = git.remote_ref(nightly) + stage = git.remote_ref(staging) + if not base or not stage: + res.reason = f"cannot read `{nightly}` or `{staging}`" + return _finish(res, summary) + res.nightly_before = res.nightly_after = base + git.fetch(f"+refs/heads/{nightly}:refs/gate/nightly", f"+refs/heads/{staging}:refs/gate/staging") + if not git.is_ancestor(stage, base): + res.reason = (f"`{staging}` {stage} is not an ancestor of `{nightly}` {base}; the ff-only promotion " + "invariant is broken. Nothing was integrated") + return _finish(res, summary) + summary.table(["ref", "sha"], [[f"`{nightly}` (B)", f"`{base}`"], [f"`{staging}`", f"`{stage}`"]]) + + label = policy["nightly_label"] + prs = [p for p in gh.open_prs() if label in {l.get("name") for l in p.get("labels") or []}] + for pr in sorted(prs, key=lambda p: int(p["number"])): + c = assess(pr, policy, gh, repo) + if c.outcome == "eligible": + if not git.fetch_sha(c.head): + c.outcome = "skipped: head commit not fetchable" + elif git.is_ancestor(c.head, base): + c.outcome = "skipped: already in nightly" + res.candidates.append(c) + eligible = [c for c in res.candidates if c.outcome == "eligible"] + + def build(on: str, items: List[Candidate]) -> tuple: + tip, used = on, [] + for c in items: + merged = git.merge(tip, c.head, merge_message(c, nightly), name, email) + if merged is None: + c.outcome = f"skipped: conflicts with nightly after {', '.join('#%d' % u.number for u in used) or 'B'}" + continue + tip = merged + used.append(c) + return tip, used + + tip, used = build(base, eligible) + if not used: + res.exit_code = 0 + res.reason = "nothing to integrate" + return _finish(res, summary) + + if dry_run: + for c in used: + c.outcome = "would integrate" + res.exit_code = 0 + res.reason = f"dry run: would validate `{tip}` (not pushed)" + res.attempts.append(Attempt(tip, [c.number for c in used], "(local only)", "not run")) + return _finish(res, summary) + + runs_left = int(policy.get("max_ci_runs_per_integration", 8)) + + def validate(sha: str, prs_in: List[Candidate], on: str) -> bg.CiVerdict: + nonlocal runs_left + runs_left -= 1 + ref = f"{policy['candidate_ref_prefix']}{stamp}-{sha[:12]}" + att = Attempt(sha, [c.number for c in prs_in], ref) + res.attempts.append(att) + push = git.push(sha, ref) + if push.returncode != 0: + att.verdict = "candidate push failed" + return bg.CiVerdict("pending", [("push", "error", push.stderr.strip()[:200])]) + min_id = bg.max_status_id(gh, sha) + validator.start(sha, on) + verdict = bg.wait_for_full(gh, sha, policy, float(policy.get("ci_wait_minutes", 90)), + poll_seconds, sleep, min_id=min_id) + att.verdict = verdict.summary() + return verdict + + accepted: List[Candidate] = [] + verdict = validate(tip, used, base) + if verdict.green: + accepted, good = list(used), tip + else: + good = base + if len(used) > 1: + # Find which PRs are green on their own, one at a time on top of the last green tip. + for c in used: + if runs_left <= 0: + c.outcome = "not retried: CI run budget spent" + continue + single, ok = build(good, [c]) + if not ok: + continue + v = validate(single, [c], good) + if v.green: + good = single + accepted.append(c) + else: + c.outcome = f"rejected: red on top of nightly ({v.summary()[:160]})" + else: + used[0].outcome = f"rejected: integration red ({verdict.summary()[:160]})" + + if good == base: + res.reason = "no candidate produced a green integration SHA; nightly unchanged" + return _finish(res, summary) + + # Publish `good`. Every check is re-done against live state right before the push. + now_base = git.remote_ref(nightly) + if now_base != base: + res.reason = f"`{nightly}` moved during the run ({base} -> {now_base}); refusing to publish" + return _finish(res, summary) + for c in accepted: + live = gh.pr(c.number) + live_head = (live.get("head") or {}).get("sha") + if live.get("state") != "open" or live_head != c.head: + res.reason = (f"PR #{c.number} changed during the run (state {live.get('state')}, head " + f"{live_head}); refusing to publish {good}") + return _finish(res, summary) + final = bg.evaluate_exact_ci(gh.statuses(good), policy) + if not final.green: + res.reason = f"statuses on `{good}` are no longer green ({final.summary()}); refusing to publish" + return _finish(res, summary) + if not git.is_ancestor(base, good): + res.reason = "internal: integration SHA does not descend from nightly" + return _finish(res, summary) + push = git.push(good, nightly) + after = git.remote_ref(nightly) + if push.returncode != 0 or after != good: + res.nightly_after = after or "" + res.reason = (f"push of `{good}` to `{nightly}` was refused or not visible (exit {push.returncode}, " + f"remote now {after}): {push.stderr.strip()[:300]}") + return _finish(res, summary) + for c in accepted: + c.included = True + c.outcome = "integrated" + (" (base staging: stays open until staging is promoted past it)" + if c.base == staging else "") + res.exit_code, res.published, res.nightly_after = 0, good, good + res.reason = f"`{nightly}` fast-forwarded {base[:12]} -> {good[:12]}" + return _finish(res, summary) + + +def _finish(res: Result, summary: bg.Summary) -> Result: + if res.candidates: + summary.add("### Labeled PRs", "") + summary.table(["PR", "base", "head SHA", "outcome"], + [[f"#{c.number}", f"`{c.base}`", f"`{c.head}`", c.outcome] for c in res.candidates]) + else: + summary.add("No open PRs carry the `nightly` label.", "") + if res.attempts: + summary.add("### Integration SHAs validated by full CI", "") + summary.table(["integration SHA", "PRs", "candidate ref", "gev-ci verdict (exact SHA)"], + [[f"`{a.sha}`", ", ".join(f"#{n}" for n in a.prs), f"`{a.ref}`", a.verdict] + for a in res.attempts]) + icon = "✅" if res.exit_code == 0 else "❌" + summary.add(f"{icon} **{res.reason}**", "", + f"nightly before `{res.nightly_before}`, after `{res.nightly_after}`") + return res + + +def main(argv: Optional[List[str]] = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--validator", choices=["boat", "dispatch", "external"], required=True) + ap.add_argument("--ci-workflow", default="factory-ci-sha.yml") + ap.add_argument("--ci-ref", default="staging", help="ref whose factory-ci-sha.yml is dispatched") + ap.add_argument("--dry-run", action="store_true", help="assess and merge locally; push nothing") + ap.add_argument("--report", help="also write the JSON result here") + ap.add_argument("--lock", default=bg.default_lock_path(), help="host lock file ('' to rely on Actions concurrency)") + args = ap.parse_args(argv) + try: + policy = bg.load_policy() + gh = bg.GitHubCli(policy["repo"]) + git = bg.GitRepo(f"https://github.com/{policy['repo']}.git") + if args.validator == "boat": + validator = BoatValidator(Path(__file__).resolve().parent.parent / "factory-ci-boat.sh") + elif args.validator == "dispatch": + validator = DispatchValidator(gh, args.ci_workflow, args.ci_ref) + else: + validator = ExternalValidator() + with bg.HostLock(args.lock or None): + res = integrate(gh, git, policy, validator, bg.Summary(), dry_run=args.dry_run) + except bg.Refusal as exc: + print(f"refused: {exc.reason}", file=sys.stderr) + return exc.code + if args.report: + Path(args.report).write_text(json.dumps(res.as_dict(), indent=2) + "\n", encoding="utf-8") + return res.exit_code + + +if __name__ == "__main__": + sys.exit(main()) From 62cbd88af18e32e159ef92dec465f88775becd90 Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 15/18] feat(factory): fail-closed fast-forward staging promotion Requires nightly membership, staging ancestry, exact-SHA gev-ci green and a recorded 24 h green soak; re-reads refs and statuses before a plain push. --- .github/workflows/factory-promote-staging.yml | 74 ++++++++ scripts/factory/promote_staging.py | 173 ++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 .github/workflows/factory-promote-staging.yml create mode 100644 scripts/factory/promote_staging.py diff --git a/.github/workflows/factory-promote-staging.yml b/.github/workflows/factory-promote-staging.yml new file mode 100644 index 00000000000..de148c068e9 --- /dev/null +++ b/.github/workflows/factory-promote-staging.yml @@ -0,0 +1,74 @@ +# Staging promotion: fast-forward `staging` to one explicitly chosen nightly SHA +# after exact-SHA CI is green and it has a recorded >= 24 h green soak. +# Owner card: t_cf66fac4. Runbook: docs/factory/NIGHTLY-PROMOTION.md. +name: Factory staging promotion + +on: + workflow_dispatch: + inputs: + sha: + description: Full 40-character nightly SHA to promote (no branch names, no short SHAs) + required: true + type: string + dry-run: + description: Run every check; push nothing + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: factory-branch-mutation + cancel-in-progress: false + +jobs: + promote: + name: Promote ${{ inputs.sha }} to staging + if: github.repository == 'kvnloo/gods-eye-view' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + environment: factory-branches + permissions: + contents: read + statuses: write # one soak observation + the gev-promote/staging record + env: + SHA: ${{ inputs.sha }} + steps: + - name: Refuse anything but a full SHA + run: '[[ $SHA =~ ^[0-9a-f]{40}$ ]] || { echo "::error::sha must be 40 lowercase hex characters"; exit 2; }' + + - name: Check out the trusted gate scripts (default branch) + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + scripts/factory + ci/factory/branch-policy.json + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Branch push token + id: app + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ vars.FACTORY_APP_CLIENT_ID }} + private-key: ${{ secrets.FACTORY_APP_PRIVATE_KEY }} + permission-contents: write + permission-workflows: write + + - name: Promote (fails closed) + env: + GH_TOKEN: ${{ github.token }} + FACTORY_PUSH_TOKEN: ${{ steps.app.outputs.token }} + DRY_RUN: ${{ inputs.dry-run && '--dry-run' || '' }} + run: python3 scripts/factory/promote_staging.py --sha "$SHA" --lock '' --report promotion.json $DRY_RUN + + - name: Keep the JSON record + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: staging-promotion-${{ github.run_id }} + path: promotion.json + if-no-files-found: warn + retention-days: 400 diff --git a/scripts/factory/promote_staging.py b/scripts/factory/promote_staging.py new file mode 100644 index 00000000000..8aa9e5f2027 --- /dev/null +++ b/scripts/factory/promote_staging.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Fast-forward `staging` to one explicitly chosen nightly SHA, or refuse. + + python3 scripts/factory/promote_staging.py --sha <40-hex nightly sha> [--dry-run] + +Every condition is required; any unknown is a refusal: + +1. `sha` is a full 40-hex SHA of a commit in the repository. +2. `sha` is in `nightly` history (ancestor of, or equal to, the nightly tip). +3. `staging` is an ancestor of `sha`, so the update is a fast-forward. +4. Every gev-ci/* context on that exact SHA is a trusted success. +5. A fresh soak observation is recorded, then the SHA's own status history + shows >= 24 h of trusted soak observations, no gap over the limit, and no + red (any gev-ci/* or gev-soak failure/error) since the soak started. +6. `staging` and `nightly` still point where they did at step 2, and the + statuses are still green, immediately before the push. +7. Plain push (no force; git refuses a non-fast-forward), then read back. + +Exit: 0 promoted (or already there), 1 refused, 2 usage, 75 locked. +""" +from __future__ import annotations + +import argparse +import datetime as dt +import json +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import List, Optional + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import branch_gates as bg # noqa: E402 +import soak_observe # noqa: E402 + + +@dataclass +class Promotion: + exit_code: int + sha: str + reason: str = "" + staging_before: str = "" + staging_after: str = "" + nightly: str = "" + checks: List[List[str]] = field(default_factory=list) + soak: Optional[dict] = None + + def as_dict(self) -> dict: + return dict(self.__dict__) + + +def promote(gh, git: bg.GitRepo, policy: dict, sha: str, summary: bg.Summary, dry_run: bool = False, + observe: bool = True, target_url: str = "") -> Promotion: + staging, nightly = policy["staging_branch"], policy["nightly_branch"] + p = Promotion(1, sha) + summary.add(f"## Staging promotion of `{sha}` ({'dry run' if dry_run else 'apply'})", "") + + def check(name: str, ok: bool, detail: str) -> bool: + p.checks.append([name, "pass" if ok else "FAIL", detail]) + return ok + + def refuse(reason: str) -> Promotion: + p.reason = "refused: " + reason + return finish(p, summary) + + try: + bg.require_sha(sha) + except bg.Refusal as exc: + p.exit_code = 2 + check("full SHA", False, exc.reason) + return refuse(exc.reason) + check("full SHA", True, "40 hex") + + s0, n0 = git.remote_ref(staging), git.remote_ref(nightly) + if not s0 or not n0: + return refuse(f"cannot read `{staging}`/`{nightly}`") + p.staging_before, p.nightly, p.staging_after = s0, n0, s0 + git.fetch(f"+refs/heads/{nightly}:refs/gate/nightly", f"+refs/heads/{staging}:refs/gate/staging") + if sha == s0: + p.exit_code = 0 + p.reason = f"`{staging}` is already at `{sha}`; nothing to do" + return finish(p, summary) + if not check("commit exists", git.fetch_sha(sha), "fetched by SHA"): + return refuse(f"`{sha}` is not a commit of {policy['repo']}") + if not check("in nightly history", git.is_ancestor(sha, n0), f"ancestor of nightly `{n0}`"): + return refuse(f"`{sha}` is not in `{nightly}` history (tip `{n0}`)") + if not check("staging is ancestor", git.is_ancestor(s0, sha), f"`{s0}` ⊑ sha (fast-forward)"): + return refuse(f"`{staging}` `{s0}` is not an ancestor of `{sha}`; promotion would not be a fast-forward") + + ci = bg.evaluate_exact_ci(gh.statuses(sha), policy) + if not check("exact-SHA CI", ci.green, ci.summary()): + return refuse(f"gev-ci on `{sha}` is {ci.summary()}") + + if observe: + code, rows = soak_observe.observe(gh, git, policy, bg.Summary(path=""), sha, target_url) + fresh_ok = code == 0 and bool(rows) and rows[0][1] == "success" + if not check("fresh soak observation", fresh_ok, rows[0][2] if rows else "not recorded"): + return refuse("the fresh soak observation is not green: " + (rows[0][2] if rows else "not recorded")) + statuses = gh.statuses(sha) + # Staleness is judged against the later of the API client's clock and the + # newest server-stamped observation. Soak length uses server stamps only. + soak_now = gh.now() + latest_obs = [s.created_at for s in statuses if s.context == policy["soak_context"]] + if latest_obs: + soak_now = max(soak_now, max(latest_obs)) + soak = bg.compute_soak(statuses, policy, soak_now) + p.soak = soak.as_dict() + if not check("soak", soak.ok, soak.reason): + return refuse(soak.reason) + + # Re-read everything that could have changed, right before the push. + s1, n1 = git.remote_ref(staging), git.remote_ref(nightly) + if not check("refs unchanged", s1 == s0 and n1 == n0, f"staging `{s1}`, nightly `{n1}`"): + return refuse(f"refs changed during promotion (staging {s0} -> {s1}, nightly {n0} -> {n1})") + ci2 = bg.evaluate_exact_ci(gh.statuses(sha), policy) + if not check("exact-SHA CI (re-read)", ci2.green, ci2.summary()): + return refuse(f"gev-ci on `{sha}` changed to {ci2.summary()}") + + if dry_run: + p.exit_code = 0 + p.reason = f"dry run: every check passed; would fast-forward `{staging}` {s0[:12]} -> {sha[:12]}" + return finish(p, summary) + + push = git.push(sha, staging) + after = git.remote_ref(staging) + p.staging_after = after or "" + if push.returncode != 0 or after != sha: + return refuse(f"push refused or not visible (exit {push.returncode}, staging now {after}): " + f"{push.stderr.strip()[:300]}") + try: + gh.post_status(sha, "success", policy["promotion_context"], + f"promoted to {staging} from {s0[:12]}; soak {soak.hours:.1f} h", target_url) + except Exception as exc: # the ref moved; the audit status is best-effort and reported + check("promotion record", False, str(exc)[:200]) + p.exit_code = 0 + p.reason = f"`{staging}` fast-forwarded {s0[:12]} -> {sha[:12]}" + return finish(p, summary) + + +def finish(p: Promotion, summary: bg.Summary) -> Promotion: + if p.checks: + summary.table(["check", "result", "detail"], p.checks) + if p.soak: + summary.add("
soak evidence", "", "```json", + json.dumps(p.soak, indent=2), "```", "
", "") + summary.add(f"{'✅' if p.exit_code == 0 else '❌'} **{p.reason}**", "", + f"staging before `{p.staging_before}`, after `{p.staging_after}`; nightly `{p.nightly}`") + return p + + +def main(argv: Optional[List[str]] = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--sha", required=True, help="full 40-hex nightly SHA to promote") + ap.add_argument("--dry-run", action="store_true", help="run every check; push nothing") + ap.add_argument("--report", help="also write the JSON result here") + ap.add_argument("--lock", default=bg.default_lock_path(), help="host lock file ('' to rely on Actions concurrency)") + args = ap.parse_args(argv) + try: + policy = bg.load_policy() + gh = bg.GitHubCli(policy["repo"]) + git = bg.GitRepo(f"https://github.com/{policy['repo']}.git") + with bg.HostLock(args.lock or None): + p = promote(gh, git, policy, args.sha.strip(), bg.Summary(), dry_run=args.dry_run, + target_url=bg.run_url()) + except bg.Refusal as exc: + print(f"refused: {exc.reason}", file=sys.stderr) + return exc.code + if args.report: + Path(args.report).write_text(json.dumps(p.as_dict(), indent=2) + "\n", encoding="utf-8") + return p.exit_code + + +if __name__ == "__main__": + sys.exit(main()) From 402c5a7f809b4bd54fe9e2d3ec101f44935193dd Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 16/18] test(factory): acceptance and refusal paths for integration and promotion --- scripts/factory/tests/test_branch_gates.py | 605 +++++++++++++++++++++ 1 file changed, 605 insertions(+) create mode 100644 scripts/factory/tests/test_branch_gates.py diff --git a/scripts/factory/tests/test_branch_gates.py b/scripts/factory/tests/test_branch_gates.py new file mode 100644 index 00000000000..b75b74c9ad2 --- /dev/null +++ b/scripts/factory/tests/test_branch_gates.py @@ -0,0 +1,605 @@ +"""End-to-end tests for nightly integration, soak observation and staging promotion. + +Real git: a local bare `origin` with receive.denyNonFastForwards and a +pre-receive hook that refuses a nightly/staging update whose new SHA lacks a +trusted gev-ci/full success (what the GitHub ruleset does). Fake GitHub: an +in-memory PR list and commit-status store whose clock is owned by the fake +server, exactly as `created_at` is owned by GitHub. The production code paths +are called unchanged; no production flag exists to inject time or statuses. + + python3 -m unittest discover -s scripts/factory/tests -p 'test_branch_gates.py' -v +""" +from __future__ import annotations + +import datetime as dt +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) +import branch_gates as bg # noqa: E402 +import nightly_integrate as ni # noqa: E402 +import promote_staging as ps # noqa: E402 +import soak_observe as so # noqa: E402 + +REPO = "kvnloo/gods-eye-view" +POLICY = bg.load_policy() +GATES = bg.ci_contexts(POLICY) +T0 = dt.datetime(2026, 11, 20, 0, 0, 0, tzinfo=dt.timezone.utc) + +HOOK = r'''#!/usr/bin/env python3 +import json, sys +STATUSES = %r +data = json.load(open(STATUSES)) +for line in sys.stdin: + old, new, ref = line.split() + if ref not in ("refs/heads/nightly", "refs/heads/staging"): + continue + if new == "0" * 40: + print("deletion refused"); sys.exit(1) + full = [s for s in data.get(new, []) if s["context"] == "gev-ci/full"] + full.sort(key=lambda s: (s["created_at"], s["id"])) + if not full or full[-1]["state"] != "success" or full[-1]["creator"]["login"] not in ("kvnloo", "github-actions[bot]"): + print("required status gev-ci/full is not success on " + new); sys.exit(1) +''' + + +def git(cwd, *args, env=None): + out = subprocess.run(["git", "-C", str(cwd), *args], text=True, capture_output=True, env=env) + if out.returncode: + raise AssertionError(f"git {' '.join(args)}: {out.stderr}") + return out.stdout.strip() + + +class FakeGitHub: + def __init__(self, origin: Path, store: Path): + self.origin, self.store = origin, store + self.clock = T0 + self.next_id = 1000 + self.data: dict = {} + self.prs: dict = {} + self.on_statuses = None # callable(sha) for race injection + self.dispatched: list = [] + self._save() + + # clock owned by the "server" + def now(self): + return self.clock + + def advance(self, hours: float): + self.clock += dt.timedelta(hours=hours) + + def _save(self): + self.store.write_text(json.dumps(self.data)) + + def post_status(self, sha, state, context, description, target_url="", creator="kvnloo"): + bg.require_sha(sha) + self.next_id += 1 + raw = {"id": self.next_id, "context": context, "state": state, "description": description[:140], + "target_url": target_url, "created_at": bg.fmt_time(self.clock), "creator": {"login": creator}} + self.data.setdefault(sha, []).append(raw) + self._save() + self.clock += dt.timedelta(seconds=1) + return bg.Status.from_api(raw) + + def statuses(self, sha): + if self.on_statuses: + self.on_statuses(sha) + return [bg.Status.from_api(r) for r in self.data.get(sha, [])] + + def add_pr(self, number, branch, base, labels=("nightly",), draft=False, head_repo=REPO): + self.prs[number] = {"number": number, "branch": branch, "base": base, "labels": list(labels), + "draft": draft, "head_repo": head_repo, "state": "open"} + + def _render(self, p): + sha = git(self.origin, "rev-parse", f"refs/heads/{p['branch']}") + return {"number": p["number"], "state": p["state"], "draft": p["draft"], "title": f"PR {p['number']}", + "html_url": f"https://github.com/{REPO}/pull/{p['number']}", + "labels": [{"name": n} for n in p["labels"]], "base": {"ref": p["base"]}, + "head": {"sha": sha, "ref": p["branch"], "repo": {"full_name": p["head_repo"]}}} + + def open_prs(self): + return [self._render(p) for p in self.prs.values() if p["state"] == "open"] + + def pr(self, number): + return self._render(self.prs[number]) + + def dispatch(self, workflow, ref, inputs): + self.dispatched.append((workflow, ref, inputs)) + + +class FakeCI: + """Validates by tree content: a file RED, or both semantic-a and semantic-b, is a failure.""" + + def __init__(self, gh: FakeGitHub, origin: Path): + self.gh, self.origin, self.runs = gh, origin, [] + self.before_post = None + + def verdict(self, sha): + names = set(git(self.origin, "ls-tree", "-r", "--name-only", sha).splitlines()) + return "failure" if "RED" in names or {"semantic-a", "semantic-b"} <= names else "success" + + def start(self, sha, base=""): + self.runs.append(sha) + if self.before_post: + self.before_post(sha) + state = self.verdict(sha) + for ctx in GATES[:-1]: + self.gh.post_status(sha, "failure" if (state == "failure" and ctx == "gev-ci/unit") else "success", + ctx, "fake gate", creator="github-actions[bot]") + self.gh.post_status(sha, state, "gev-ci/full", "fake full", creator="github-actions[bot]") + + +class Fixture(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="gev-gates-test-")) + self.origin = self.tmp / "origin.git" + self.store = self.tmp / "statuses.json" + git(self.tmp, "init", "-q", "--bare", str(self.origin)) + git(self.origin, "config", "receive.denyNonFastForwards", "true") + git(self.origin, "config", "receive.denyDeletes", "true") + self.gh = FakeGitHub(self.origin, self.store) + hook = self.origin / "hooks" / "pre-receive" + hook.write_text(HOOK % str(self.store)) + hook.chmod(0o755) + self.work = self.tmp / "work" + git(self.tmp, "init", "-q", "-b", "nightly", str(self.work)) + for k, v in (("user.name", "t"), ("user.email", "t@example.com"), ("commit.gpgsign", "false")): + git(self.work, "config", k, v) + git(self.work, "remote", "add", "origin", str(self.origin)) + self.ci = FakeCI(self.gh, self.origin) + root = self.commit("README", "root\n") + git(self.work, "push", "-q", "origin", "nightly:refs/heads/seed") # unprotected ref first + self.ci.start(root) # nightly/staging start validated, like 53f0caa + git(self.work, "push", "-q", "origin", "nightly", "nightly:staging") + self.root = root + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def commit(self, path, text, msg=None): + (self.work / path).write_text(text) + git(self.work, "add", path) + git(self.work, "commit", "-q", "-m", msg or f"add {path}") + return git(self.work, "rev-parse", "HEAD") + + def branch(self, name, base, files, green=True, push=True): + git(self.work, "fetch", "-q", "origin") + git(self.work, "checkout", "-q", "-B", name, base) + sha = "" + for path, text in files: + sha = self.commit(path, text) + if push: + git(self.work, "push", "-q", "origin", f"{name}:refs/heads/{name}") + if green: + self.ci.start(sha) + return sha + + def remote(self, branch): + return git(self.origin, "rev-parse", f"refs/heads/{branch}") + + def repo(self): + return bg.GitRepo(str(self.origin), workdir=str(self.tmp / f"scratch-{len(os.listdir(self.tmp))}"), + use_gh_credentials=False) + + def integrate(self, dry_run=False, validator=None, policy=None): + return ni.integrate(self.gh, self.repo(), policy or POLICY, validator or self.ci, bg.Summary(path=str(self.tmp / "summary.md")), + dry_run=dry_run, poll_seconds=0, sleep=lambda s: None, stamp="20261120T000000Z") + + def observe(self, only=None): + return so.observe(self.gh, self.repo(), POLICY, bg.Summary(path=""), only) + + def promote(self, sha, dry_run=False): + return ps.promote(self.gh, self.repo(), POLICY, sha, bg.Summary(path=str(self.tmp / "promo.md")), + dry_run=dry_run) + + def soak_hourly(self, hours, start_after=1.0): + self.gh.advance(start_after) + for _ in range(int(hours)): + self.observe() + self.gh.advance(1) + + +class TestHarness(Fixture): + def test_origin_enforces_like_github(self): + """The harness itself refuses unvalidated and non-ff updates (so tests prove real refusals).""" + sha = self.branch("unvalidated", self.root, [("u.txt", "u\n")], green=False) + r = subprocess.run(["git", "-C", str(self.work), "push", "origin", f"{sha}:refs/heads/nightly"], + capture_output=True, text=True) + self.assertNotEqual(r.returncode, 0) + self.assertIn("required status gev-ci/full", r.stderr) + self.assertEqual(self.remote("nightly"), self.root) + + +class TestIntegration(Fixture): + def make_prs(self): + a = self.branch("feat/a", self.root, [("a.txt", "a\n")]) + b = self.branch("feat/b", self.root, [("b.txt", "b\n")]) + s = self.branch("feat/on-staging", self.root, [("s.txt", "s\n")]) + self.branch("feat/unlabeled", self.root, [("x1.txt", "x\n")]) + self.branch("feat/draft", self.root, [("x2.txt", "x\n")]) + self.branch("feat/fork", self.root, [("x3.txt", "x\n")]) + self.branch("feat/stacked", self.root, [("x4.txt", "x\n")]) + self.branch("feat/red-head", self.root, [("RED", "x\n")]) + self.branch("feat/no-ci", self.root, [("x5.txt", "x\n")], green=False) + untrusted = self.branch("feat/untrusted", self.root, [("x6.txt", "x\n")], green=False) + for ctx in GATES: + self.gh.post_status(untrusted, "success", ctx, "self-reported", creator="drive-by") + flaky = self.branch("feat/flaky", self.root, [("x7.txt", "x\n")]) + self.gh.post_status(flaky, "failure", "gev-ci/unit", "rerun went red", creator="kvnloo") + self.branch("feat/c1", self.root, [("conflict.txt", "one\n")]) + self.branch("feat/c2", self.root, [("conflict.txt", "two\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + self.gh.add_pr(2, "feat/b", "nightly") + self.gh.add_pr(3, "feat/on-staging", "staging") + self.gh.add_pr(4, "feat/unlabeled", "nightly", labels=()) + self.gh.add_pr(5, "feat/draft", "nightly", draft=True) + self.gh.add_pr(6, "feat/fork", "nightly", head_repo="someone/gods-eye-view") + self.gh.add_pr(7, "feat/stacked", "feat/a") + self.gh.add_pr(8, "feat/red-head", "nightly") + self.gh.add_pr(9, "feat/no-ci", "nightly") + self.gh.add_pr(10, "feat/untrusted", "nightly") + self.gh.add_pr(11, "feat/flaky", "nightly") + self.gh.add_pr(12, "feat/c1", "nightly") + self.gh.add_pr(13, "feat/c2", "nightly") + return a, b, s + + def test_accepts_only_green_eligible_prs_and_validates_the_exact_integration_sha(self): + a, b, s = self.make_prs() + res = self.integrate() + self.assertEqual(res.exit_code, 0, res.reason) + out = {c.number: c.outcome for c in res.candidates} + self.assertNotIn(4, out) # unlabeled PRs are never listed + self.assertEqual(out[1], "integrated") + self.assertEqual(out[2], "integrated") + self.assertTrue(out[3].startswith("integrated (base staging"), out[3]) + self.assertEqual(out[12], "integrated") + self.assertIn("draft", out[5]) + self.assertIn("not `kvnloo/gods-eye-view`", out[6]) + self.assertIn("base `feat/a` is not integrated", out[7]) + self.assertIn("head not green (red", out[8]) + self.assertIn("missing", out[9]) + self.assertIn("untrusted", out[10]) + self.assertIn("gev-ci/unit=failure", out[11]) + self.assertIn("conflicts", out[13]) + tip = self.remote("nightly") + self.assertEqual(res.published, tip) + self.assertEqual(self.ci.runs[-1], tip) # CI ran on the exact published SHA + self.assertTrue(bg.evaluate_exact_ci(self.gh.statuses(tip), POLICY).green) + # first-parent chain is root -> merges, so nightly only ever fast-forwards + chain = git(self.origin, "rev-list", "--first-parent", f"{self.root}..{tip}").splitlines() + self.assertEqual(len(chain), 4) + for head in (a, b, s): + self.assertEqual(subprocess.run(["git", "-C", str(self.origin), "merge-base", "--is-ancestor", head, tip]).returncode, 0) + self.assertEqual(self.remote("staging"), self.root) # integration never touches staging + summary = (self.tmp / "summary.md").read_text() + for needle in (tip, a, "gev-ci verdict (exact SHA)", "#13"): + self.assertIn(needle, summary) + + def test_red_batch_falls_back_to_one_pr_at_a_time(self): + self.branch("feat/sa", self.root, [("semantic-a", "a\n")]) + self.branch("feat/sb", self.root, [("semantic-b", "b\n")]) + self.gh.add_pr(21, "feat/sa", "nightly") + self.gh.add_pr(22, "feat/sb", "nightly") + res = self.integrate() + self.assertEqual(res.exit_code, 0, res.reason) + out = {c.number: c.outcome for c in res.candidates} + self.assertEqual(out[21], "integrated") + self.assertIn("rejected: red on top of nightly", out[22]) + self.assertEqual(len(res.attempts), 3) # batch (red), #21 (green), #21+#22 (red) + self.assertIn("red", res.attempts[0].verdict) + tip = self.remote("nightly") + self.assertEqual(tip, res.attempts[1].sha) + names = git(self.origin, "ls-tree", "-r", "--name-only", tip).split() + self.assertIn("semantic-a", names) + self.assertNotIn("semantic-b", names) + + def test_single_red_integration_publishes_nothing(self): + self.branch("feat/sa", self.root, [("semantic-a", "a\n")]) + base_with_b = self.branch("feat/sb", self.root, [("semantic-b", "b\n")]) + # land semantic-b on nightly first through the integrator itself + self.gh.add_pr(31, "feat/sb", "nightly") + self.assertEqual(self.integrate().exit_code, 0) + self.gh.prs[31]["state"] = "closed" + before = self.remote("nightly") + self.gh.add_pr(32, "feat/sa", "nightly") + res = self.integrate() + self.assertEqual(res.exit_code, 1) + self.assertIn("no candidate produced a green integration SHA", res.reason) + self.assertEqual(self.remote("nightly"), before) + self.assertTrue(base_with_b) + + def test_refuses_when_nightly_moves_during_validation(self): + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + other = self.branch("hotfix", self.root, [("h.txt", "h\n")]) + + def race(sha): + if sha != other and self.remote("nightly") == self.root: + git(self.work, "push", "-q", "origin", f"{other}:refs/heads/nightly") + self.ci.before_post = race + res = self.integrate() + self.assertEqual(res.exit_code, 1) + self.assertIn("moved during the run", res.reason) + self.assertEqual(self.remote("nightly"), other) + + def test_refuses_when_a_pr_head_moves_after_its_check(self): + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + + def push_new_head(sha): + if git(self.origin, "rev-parse", "refs/heads/feat/a") != self.remote("nightly"): + git(self.work, "checkout", "-q", "feat/a") + self.commit("a2.txt", "late\n") + git(self.work, "push", "-q", "origin", "feat/a") + self.ci.before_post = None + self.ci.before_post = push_new_head + res = self.integrate() + self.assertEqual(res.exit_code, 1) + self.assertIn("PR #1 changed during the run", res.reason) + self.assertEqual(self.remote("nightly"), self.root) + + def test_red_status_after_validation_blocks_publish(self): + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + orig_pr = self.gh.pr + + def pr_then_flip(number): + # a re-run goes red after the CI wait saw green, before the publish re-read + tip = self.ci.runs[-1] + if not any(s["state"] == "failure" for s in self.gh.data.get(tip, [])): + self.gh.post_status(tip, "failure", "gev-ci/perf-smoke", "late rerun red") + return orig_pr(number) + self.gh.pr = pr_then_flip + res = self.integrate() + self.assertEqual(res.exit_code, 1) + self.assertIn("no longer green", res.reason) + self.assertEqual(self.remote("nightly"), self.root) + + def test_stale_green_on_pr_head_does_not_authorize_the_merge_commit(self): + a = self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + # nobody validates the merge commit; a zero wait budget times out at once + res = self.integrate(validator=ni.ExternalValidator(), policy=dict(POLICY, ci_wait_minutes=0)) + self.assertEqual(res.exit_code, 1) + self.assertIn("timeout", res.attempts[0].verdict) + self.assertEqual(self.remote("nightly"), self.root) + self.assertTrue(bg.evaluate_exact_ci(self.gh.statuses(a), POLICY).green) + + def test_nothing_to_do_and_dry_run_never_push(self): + res = self.integrate() + self.assertEqual((res.exit_code, res.reason), (0, "nothing to integrate")) + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + res = self.integrate(dry_run=True) + self.assertEqual(res.exit_code, 0) + self.assertEqual(res.candidates[0].outcome, "would integrate") + self.assertEqual(self.remote("nightly"), self.root) + self.assertEqual(git(self.origin, "for-each-ref", "refs/heads/factory/"), "") + + def test_already_integrated_pr_is_skipped(self): + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + self.assertEqual(self.integrate().exit_code, 0) + res = self.integrate() + self.assertEqual(res.candidates[0].outcome, "skipped: already in nightly") + self.assertEqual(res.reason, "nothing to integrate") + + def test_broken_invariant_refuses(self): + # staging gets a commit nightly lacks (validated so the hook admits it) + side = self.branch("side", self.root, [("side.txt", "s\n")]) + git(self.work, "push", "-q", "origin", f"{side}:refs/heads/staging") + res = self.integrate() + self.assertEqual(res.exit_code, 1) + self.assertIn("is not an ancestor", res.reason) + + +class TestSoakMath(unittest.TestCase): + def st(self, i, ctx, state, hours, creator="kvnloo"): + return bg.Status(i, ctx, state, T0 + dt.timedelta(hours=hours), creator) + + def obs(self, hours_list, start_id=100, creator="kvnloo"): + return [self.st(start_id + n, "gev-soak/nightly", "success", h, creator) for n, h in enumerate(hours_list)] + + def green(self, at=0.0): + return [self.st(i, c, "success", at, "github-actions[bot]") for i, c in enumerate(GATES, 1)] + + def test_exactly_24h_passes_and_23h_fails(self): + base = self.green() + ok = bg.compute_soak(base + self.obs([h for h in range(1, 26)]), POLICY, T0 + dt.timedelta(hours=25)) + self.assertTrue(ok.ok, ok.reason) + self.assertEqual(ok.hours, 24.0) + short = bg.compute_soak(base + self.obs(range(1, 24)), POLICY, T0 + dt.timedelta(hours=23)) + self.assertFalse(short.ok) + self.assertIn("22.00 h of the required 24 h", short.reason) + + def test_red_resets_start(self): + statuses = self.green() + self.obs(range(1, 40)) + statuses.append(self.st(90, "gev-ci/unit", "failure", 10.5)) + statuses += [self.st(91, "gev-ci/unit", "success", 11, "github-actions[bot]"), + self.st(92, "gev-ci/full", "success", 11, "github-actions[bot]")] + rep = bg.compute_soak(statuses, POLICY, T0 + dt.timedelta(hours=39)) + self.assertTrue(rep.ok, rep.reason) + self.assertEqual(bg.fmt_time(rep.start), bg.fmt_time(T0 + dt.timedelta(hours=11))) + self.assertEqual(rep.last_reset.context, "gev-ci/unit") + # as seen at hour 34: only 23 h since the reset, so not yet + cut = [s for s in statuses if s.created_at <= T0 + dt.timedelta(hours=34)] + early = bg.compute_soak(cut, POLICY, T0 + dt.timedelta(hours=34)) + self.assertFalse(early.ok) + self.assertIn("23.00 h", early.reason) + + def test_red_soak_observation_resets_and_untrusted_greens_are_ignored(self): + statuses = self.green() + self.obs(range(1, 30)) + statuses.append(self.st(95, "gev-soak/nightly", "failure", 5.5)) + rep = bg.compute_soak(statuses, POLICY, T0 + dt.timedelta(hours=29)) + self.assertFalse(rep.ok) + self.assertIn("no trusted gev-ci/full success since the last red", rep.reason) + fake = self.green() + self.obs(range(1, 30), creator="drive-by") + rep = bg.compute_soak(fake, POLICY, T0 + dt.timedelta(hours=29)) + self.assertFalse(rep.ok) + self.assertEqual(rep.ignored_untrusted, 29) + + def test_gaps_break_the_streak(self): + statuses = self.green() + self.obs([1, 2, 3, 12, 13, 18, 24, 26]) + rep = bg.compute_soak(statuses, POLICY, T0 + dt.timedelta(hours=26)) + self.assertFalse(rep.ok) + self.assertEqual(len(rep.gaps), 1) + stale = bg.compute_soak(self.green() + self.obs(range(1, 30)), POLICY, T0 + dt.timedelta(hours=40)) + self.assertFalse(stale.ok) + self.assertIn("old (limit 6 h)", stale.reason) + + def test_observations_before_ci_went_green_do_not_count(self): + statuses = self.obs(range(0, 30)) + self.green(at=20) + rep = bg.compute_soak(statuses, POLICY, T0 + dt.timedelta(hours=29)) + self.assertFalse(rep.ok) + self.assertEqual(rep.observations, 10) + + def test_policy_cannot_lower_the_floor(self): + p = Path(tempfile.mkdtemp()) / "p.json" + p.write_text(json.dumps(dict(POLICY, min_soak_hours=1))) + with self.assertRaises(bg.Refusal): + bg.load_policy(p) + + +class TestPromotion(Fixture): + def nightly_tip(self): + self.branch("feat/a", self.root, [("a.txt", "a\n")]) + self.gh.add_pr(1, "feat/a", "nightly") + res = self.integrate() + self.assertEqual(res.exit_code, 0, res.reason) + return res.published + + def test_accepts_after_24h_green_soak_and_fast_forwards(self): + tip = self.nightly_tip() + self.soak_hourly(25) + p = self.promote(tip) + self.assertEqual(p.exit_code, 0, p.reason) + self.assertEqual(self.remote("staging"), tip) + self.assertGreaterEqual(p.soak["soak_hours"], 24) + self.assertEqual(bg.latest_by_context(self.gh.statuses(tip))["gev-promote/staging"].state, "success") + again = self.promote(tip) + self.assertEqual(again.exit_code, 0) + self.assertIn("already at", again.reason) + + def test_an_older_nightly_sha_soaks_while_nightly_moves_on(self): + first = self.nightly_tip() + self.soak_hourly(12) + self.branch("feat/b", self.root, [("b.txt", "b\n")]) + self.gh.add_pr(2, "feat/b", "nightly") + self.gh.prs[1]["state"] = "closed" + second = self.integrate().published + self.assertNotEqual(second, first) + self.soak_hourly(13, start_after=0) + self.assertEqual(self.promote(first).exit_code, 0) + self.assertEqual(self.remote("staging"), first) + refused = self.promote(second) # only ~13 h of its own soak + self.assertEqual(refused.exit_code, 1) + self.assertIn("soaked", refused.reason) + self.assertEqual(self.remote("staging"), first) + + def test_refuses_insufficient_soak(self): + tip = self.nightly_tip() + self.soak_hourly(23) + p = self.promote(tip) + self.assertEqual(p.exit_code, 1) + self.assertIn("of the required 24 h", p.reason) + self.assertEqual(self.remote("staging"), self.root) + + def test_refuses_when_red_inside_the_window(self): + tip = self.nightly_tip() + self.soak_hourly(10) + self.gh.post_status(tip, "error", "gev-ci/globe-smoke", "rerun could not draw", creator="github-actions[bot]") + self.ci.start(tip) # rerun green again + self.soak_hourly(20, start_after=0) + p = self.promote(tip) + self.assertEqual(p.exit_code, 1) + self.assertIn("soaked", p.reason) + self.assertEqual(p.soak["last_reset"]["context"], "gev-ci/globe-smoke") + self.soak_hourly(5, start_after=0) + self.assertEqual(self.promote(tip).exit_code, 0) + + def test_refuses_when_the_nightly_tip_goes_red(self): + tip = self.nightly_tip() + self.soak_hourly(12) + self.gh.post_status(tip, "failure", "gev-ci/full", "rerun red", creator="github-actions[bot]") + self.soak_hourly(14, start_after=0) + p = self.promote(tip) + self.assertEqual(p.exit_code, 1) + self.assertIn("gev-ci", p.reason) + + def test_refuses_with_missing_evidence(self): + tip = self.nightly_tip() + p = self.promote(tip) # CI green, zero soak observations before this run + self.assertEqual(p.exit_code, 1) + self.assertEqual(self.remote("staging"), self.root) + self.assertIn("soaked 0.00 h of the required 24 h", p.reason) + # a SHA in nightly history whose statuses are gone from the store: the merged PR head + pr_head = git(self.origin, "rev-parse", "refs/heads/feat/a") + self.gh.data.pop(pr_head, None) + self.gh._save() + p = self.promote(pr_head) + self.assertEqual(p.exit_code, 1) + self.assertIn("gev-ci on", p.reason) + self.assertIn("missing", p.reason) + + def test_refuses_sha_outside_nightly_history(self): + tip = self.nightly_tip() + self.soak_hourly(25) + outside = self.branch("feat/outside", tip, [("o.txt", "o\n")]) + for _ in range(30): + self.gh.post_status(outside, "success", "gev-soak/nightly", "forged observation") + self.gh.advance(1) + p = self.promote(outside) + self.assertEqual(p.exit_code, 1) + self.assertIn("not in `nightly` history", p.reason) + + def test_refuses_divergence(self): + tip = self.nightly_tip() + self.soak_hourly(25) + side = self.branch("side", self.root, [("side.txt", "s\n")]) + git(self.work, "push", "-q", "origin", f"{side}:refs/heads/staging") + p = self.promote(tip) + self.assertEqual(p.exit_code, 1) + self.assertIn("not an ancestor", p.reason) + self.assertEqual(self.remote("staging"), side) + + def test_refuses_when_refs_change_mid_promotion(self): + tip = self.nightly_tip() + self.soak_hourly(25) + self.branch("feat/b", self.root, [("b.txt", "b\n")]) + self.gh.add_pr(2, "feat/b", "nightly") + self.gh.prs[1]["state"] = "closed" + newer = {} + before = len(self.gh.data[tip]) + + def move_nightly(sha): + # fires on the first read after promotion posted its fresh observation + if sha == tip and not newer and len(self.gh.data[tip]) > before: + self.gh.on_statuses = None + newer["sha"] = self.integrate().published + self.gh.on_statuses = move_nightly + p = self.promote(tip) + self.assertTrue(newer.get("sha")) + self.assertEqual(p.exit_code, 1) + self.assertIn("refs changed during promotion", p.reason) + self.assertEqual(self.remote("staging"), self.root) + + def test_refuses_bad_sha_and_dry_run_does_not_push(self): + tip = self.nightly_tip() + self.assertEqual(self.promote(tip[:12]).exit_code, 2) + self.assertEqual(self.promote("main").exit_code, 2) + self.soak_hourly(25) + p = self.promote(tip, dry_run=True) + self.assertEqual(p.exit_code, 0, p.reason) + self.assertIn("dry run", p.reason) + self.assertEqual(self.remote("staging"), self.root) + + +if __name__ == "__main__": + unittest.main() From ab10df42afa6c7e4239d2265473d8764c41ebbf0 Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 19:37:30 -0600 Subject: [PATCH 17/18] docs(factory): nightly integration, soak ledger and promotion runbook --- docs/factory/NIGHTLY-PROMOTION.md | 287 ++++++++++++++++++++++++++++++ 1 file changed, 287 insertions(+) create mode 100644 docs/factory/NIGHTLY-PROMOTION.md diff --git a/docs/factory/NIGHTLY-PROMOTION.md b/docs/factory/NIGHTLY-PROMOTION.md new file mode 100644 index 00000000000..89085377b1f --- /dev/null +++ b/docs/factory/NIGHTLY-PROMOTION.md @@ -0,0 +1,287 @@ +# Nightly integration and staging promotion + +Owner card: t_cf66fac4. CI contract consumed: [`docs/factory-ci.md`](../factory-ci.md) +(exact-SHA `gev-ci/*` commit statuses; `gev-ci/full` is the required check). + +| Piece | File | +|---|---| +| Policy (values below) | `ci/factory/branch-policy.json` | +| Shared logic | `scripts/factory/branch_gates.py` | +| Nightly integration | `scripts/factory/nightly_integrate.py`, `.github/workflows/factory-nightly-integrate.yml` | +| Soak observation | `scripts/factory/soak_observe.py`, `.github/workflows/factory-soak-observe.yml` | +| Staging promotion | `scripts/factory/promote_staging.py`, `.github/workflows/factory-promote-staging.yml` | +| Tests | `scripts/factory/tests/test_branch_gates.py` | +| Server-side guards | rulesets 28125550 and 28125551 (below) | + +## The invariant + +`staging ⊑ nightly`: staging is always an ancestor of nightly, and both branches +only move forward. Every SHA that either branch points to carries a green +`gev-ci/full` on that exact SHA. Integration and promotion refuse to run when the +invariant is already broken, and never repair it by rewriting history. + +## Nightly integration + +Runs on a schedule (08:41 UTC) or on demand. In order: + +1. **Read refs.** Read `nightly` (call it B) and `staging`. If staging is not an + ancestor of B, refuse. +2. **Select.** Take open PRs labeled `nightly`, oldest number first. A PR is + eligible only if all of these hold: + + | Condition | Otherwise | + |---|---| + | Not a draft | `skipped: draft` | + | Base is `nightly` or `staging` | `skipped: base X is not integrated`. Stacked PRs wait for their parent. | + | Head is on `kvnloo/gods-eye-view` | `skipped: head is on ` | + | Every `gev-ci/*` context is green on the exact head SHA. The latest status per context counts: a trusted success passes. A failure or error from anyone fails. Missing, pending or untrusted is not green. | `skipped: head not green (…)` | + | Head is not already in B | `skipped: already in nightly` | + | Merges cleanly onto the tip built so far | `skipped: conflicts with nightly after …` | + +3. **PRs based on `staging`.** There are 19, retargeted from `main` during the + migration. They are integrated the same way: their head is merged into + nightly. The PR stays open against `staging`. GitHub should mark it merged + once a promotion makes staging contain its head. That is GitHub's documented + behaviour for a pushed base, but it is not yet observed on this repo, so + check it on the first such promotion. Nothing is ever pushed to staging from + a PR. The summary labels these rows. On 2026-11-25, 18 of the 19 are + drafts and #111 has no gev-ci results, so none would qualify yet (see the + eligibility preview in the card report). +4. **Build.** Build one merge commit per PR with `git merge-tree` and + `commit-tree`. No working tree is used. Each merge's first parent is the + previous tip, so `git log --first-parent nightly` lists the published tips. + The message records the PR, its exact head SHA and its base. +5. **Validate the exact integration SHA.** Push it to a new branch named + `factory/nightly-candidate/-`. Validation needs a ref on + GitHub, and the name is new every time, so no push is ever forced. Then run + full CI on that SHA, with B as `base-sha`: in Actions, + `factory-ci-sha.yml` (dispatch); on a host, `scripts/factory-ci-boat.sh`. The + verdict is read back from the commit statuses on that SHA, never from a job + exit code. The wait only accepts a `gev-ci/full` newer than the run's start, + by status id, so an older verdict cannot satisfy it. +6. **Red batch.** If the batch is red, rebuild one PR at a time on top of the + last green tip and validate each one. The number of CI runs per integration + is capped at `max_ci_runs_per_integration` (8). The last green SHA is the only + one that can be published. +7. **Publish, failing closed.** Right before the push, all of these are checked + again: + - `nightly` still equals B; + - every included PR is open with the same head SHA; + - the statuses on the SHA to publish are still green. + + Then a plain `git push :refs/heads/nightly` (no force flag), and a read + of the remote ref, which must equal the SHA. +8. **Report.** The workflow summary has a table with one row per labeled PR + (base, full head SHA, outcome) and a table with one row per validated + integration SHA (PRs, candidate ref, per-context verdict). It also records + nightly before and after. `--report` writes the same data as JSON; the + workflow uploads it as an artifact. + +Exit codes: 0 means published or nothing to do. 1 means refused or red. 2 is a +usage error. 75 means another run holds the host lock. + +## Serialization and race safety + +These layers are independent. Any one of them stops a wrong SHA from being +published. + +| Layer | Stops | +|---|---| +| Actions `concurrency: factory-branch-mutation`, shared by integration and promotion. A host flock on `~/.cache/gev-factory/branch-mutation.lock`. | two mutators from the same runner type | +| Re-read `nightly`/`staging` before the push; refuse if either moved | a concurrent update between validation and publish | +| Re-read the statuses on the exact SHA before the push | a red re-run, or a stale green | +| Re-read every included PR head | a PR force-updated after its check | +| Plain push: git and GitHub refuse a non-fast-forward | lost commits. If the ref moved to an ancestor of the validated SHA in the last instant, the push still publishes exactly the validated SHA. | +| Ruleset **28125551** `nightly+staging: exact-SHA gev-ci/full`: `required_status_checks: [gev-ci/full]`, no bypass | GitHub itself refuses any push to nightly or staging whose new SHA lacks a passing `gev-ci/full`. This covers other agents, manual pushes and stale scripts. | +| Ruleset **28125550** `nightly+staging: no rewrite`: `deletion` and `non_fast_forward`, no bypass | force pushes and deletion, by anyone, admin included | +| Post-push read-back | an update that did not land as the validated SHA | + +A live probe on 2026-11-26 showed the status ruleset refusing a push. It used the +same rule shape on the throwaway namespace `factory/ruleset-probe/**` (ruleset +28125518, disabled after the probe) with a probe-only context: + +- Creating a branch at a commit with no status: `GH013 … Required status check + "factory-probe/required" is expected`, refused. +- A fast-forward to a commit with a `failure`: `… is failing`, refused. +- The same pushes after a `success` was posted: accepted. + +Caveat: for a merge through the PR UI, GitHub evaluates required checks on the +PR head, not on the merge commit it creates. Only the integrator validates the +merge commit itself. Prefer the `nightly` label to the merge button. + +## Soak: what is persisted and how it is audited + +**Ledger.** The ledger is the commit-status history of each SHA on GitHub. +GitHub sets the `created_at` timestamp and the `creator` login on each status, +and the REST API has no delete for statuses. So the history is append-only, is +timestamped by the server, and cannot be backdated by any script, this one +included. No code path accepts a caller-supplied time or a soak start. + +**Observation.** `soak_observe.py` runs hourly (`53 * * * *`). It posts one +`gev-soak/nightly` status on every tracked SHA. Tracked SHAs are the +first-parent commits in `staging..nightly` that carry a `gev-ci/full` status, +which are the tips that integration published. The posted state is one of: + +- `success`: the SHA is in nightly history, its own `gev-ci/*` statuses are + green, and the current nightly tip is green. +- `failure` (a reset): the SHA left nightly history, its own `gev-ci/*` statuses + went red, or the nightly tip is red. +- `pending`: the result is inconclusive, for example the tip is not validated. + Pending neither extends nor resets soak, but a long pending stretch breaks + soak through the gap rule. + +An older tip keeps soaking after nightly moves past it, so you can always +promote a slightly older SHA that has finished its 24 h. + +**Computing soak** (`compute_soak`, pure, unit-tested): + +1. **Reset.** The reset point is the newest `failure` or `error`, from any + creator, in any `gev-ci/*` context or in `gev-soak/nightly`. +2. **Start.** After the reset, find the first trusted `gev-ci/full` success. + Trusted creators are listed in `trusted_status_creators`: `kvnloo` for Boat + runs and `github-actions[bot]`. Observations count from that success onward. + Observations from any other creator are counted in the report, then ignored. +3. **Gaps.** Split the trusted `success` observations wherever two are more than + `max_observation_gap_hours` (6) apart. Only the final unbroken run counts. The + last observation must also be within 6 h of now. +4. **Pass.** That run must span at least `min_soak_hours` (24) and hold at least + `min_soak_observations` (4) observations. `load_policy` refuses any policy + value below 24 h. + +**Audit any SHA:** + +```sh +gh api --paginate "repos/kvnloo/gods-eye-view/commits//statuses?per_page=100" \ + --jq '.[] | [.created_at, .context, .state, .creator.login, .description] | @tsv' | sort +``` + +Each promotion also posts `gev-promote/staging` on the promoted SHA. The +workflow summary embeds the computed soak report: start, end, hours, +observation count, the last reset with its status id, and any gaps. The +`promotion.json` artifact is kept for 400 days. + +**Limits.** GitHub keeps at most 1,000 statuses per SHA and context. At one +observation an hour that is about 41 days for a SHA that never gets promoted. +A commit status proves who posted it, not which code ran. A trusted principal +could post green observations by hand. They still could not backdate them, and +the creator and `target_url` show who posted each one. A dedicated GitHub App +identity for the observer would narrow this further. That App is pending, see +Credentials. + +## Staging promotion + +Run it with an explicitly chosen SHA: + +```sh +# Actions (once on staging): Actions → Factory staging promotion → Run workflow → sha=<40 hex> +# Host (from a trusted checkout of staging): +python3 scripts/factory/promote_staging.py --sha <40-hex> --dry-run # every check, no push +python3 scripts/factory/promote_staging.py --sha <40-hex> +``` + +It refuses on the first failing check below. The workflow also validates the +SHA's format before checking anything out. + +| Check | Refusal | +|---|---| +| Full 40-hex SHA. Branch names and short SHAs are not accepted. | exit 2 | +| Commit exists. The SHA is in `nightly` history (an ancestor of, or equal to, the tip). | not in nightly history | +| `staging` is an ancestor of the SHA | divergence; the move would not be a fast-forward | +| Every `gev-ci/*` context on that exact SHA is a trusted success | failed or missing evidence | +| A fresh `gev-soak/nightly` observation is green, then `compute_soak` passes | insufficient soak, a red during the window, a gap, or a stale observation | +| `staging` and `nightly` still equal the values first read. The statuses are still green. | refs changed, or the state changed | +| Plain push, then read the ref back | push refused, or the result is not visible | + +If staging already equals the SHA, the result is a no-op with exit 0. + +## Nightly stays compatible with ff-only promotion + +- Nightly only gains commits. Integration adds merge commits whose first parent + is the old tip, and ruleset 28125550 forbids rewinding or deleting the branch. + Any SHA that was ever on nightly therefore stays in nightly history. +- Staging only moves to a SHA that is already in nightly history and descends + from the current staging. So `staging ⊑ nightly` holds after every promotion, + and the next promotion is again a fast-forward. +- To undo a change, merge a revert PR into nightly. Never reset nightly. A bad + change that already reached staging is fixed by promoting a later nightly SHA + that contains the revert, after its own soak. +- `main` (the upstream mirror, card t_4f3cfa1b) reaches nightly as an ordinary + PR (head `main`) that is merged, not rebased. Fork-only work never goes to + main. +- Staging-based PRs reach staging only through nightly, as described above. A + direct merge into staging would need a green `gev-ci/full` on the PR head + (ruleset 28125551), and `ci.yml`'s fork branch policy refuses PRs into staging. + +## Bootstrap order (schedules fire only from `staging`) + +1. Merge into nightly: #343 (factory CI: `factory-ci-sha.yml`, the Boat runner), + #341 (main sync), #342 (modularity) and this card's PR. Use the label and the + host runner below, or the PR UI with a green `gev-ci/full` on the head. +2. Run `soak_observe.py` hourly from a host: GitHub Actions is paused on this + fork, so the hourly observation workflow cannot run yet. +3. After at least 24 h of green soak, promote that nightly SHA. Its tree then + contains all four PRs. That puts `factory-main-sync.yml` (#341, as t_4f3cfa1b + asked), `factory-ci-sha.yml` and these three workflows on the default branch. + From then on `schedule` and dispatch work, once Actions is re-enabled. + +Host runner, until Actions runs. Use a clean, trusted checkout of `staging`, with +Kevin's `gh` login (it has the `repo` and `workflow` scopes) and `boat` signed in: + +```sh +python3 scripts/factory/soak_observe.py # hourly +python3 scripts/factory/nightly_integrate.py --validator boat --dry-run # preview +python3 scripts/factory/nightly_integrate.py --validator boat # nightly +``` + +No host timer is installed. Installing one is an owner decision. + +## Credentials + +- **API calls** (PRs, statuses, workflow dispatch): `GITHUB_TOKEN` in Actions, + and `gh` on a host. +- **Pushes** to nightly, staging and candidate refs: in Actions, an installation + token of a GitHub App, because `GITHUB_TOKEN` cannot push commits that touch + `.github/workflows/`. Configure environment `factory-branches` with the + variable `FACTORY_APP_CLIENT_ID` and the secret `FACTORY_APP_PRIVATE_KEY`. + The App needs `contents: write` and `workflows: write` on this repository + only. Restrict the environment to the `staging` branch. Creating the App + needs the owner in a browser, so it is not done yet. +- **No new deploy key.** The `main: sync bot only` ruleset bypass covers every + write deploy key (t_4f3cfa1b). `verify-main-protection.sh` fails if a second + one exists. + +## Candidate refs + +`factory/nightly-candidate/*` branches keep the exact SHA that was validated, +including red and rejected ones, for audit. Nothing deletes them automatically. +An operator may prune those older than 30 days that are already in nightly, or +that were rejected and are no longer needed. + +## Tests + +```sh +python3 -m unittest discover -s scripts/factory/tests -p 'test_branch_gates.py' -v +``` + +The suite (27 tests) uses real git: a local bare origin that refuses a +non-fast-forward or a deletion. Its pre-receive hook enforces a trusted +`gev-ci/full` on nightly and staging, as ruleset 28125551 does. Alongside it +runs a fake GitHub that owns its clock, the way GitHub owns `created_at`. Tests +make time pass by advancing that server clock. Production code has no flag +that injects time, statuses or a remote. + +- **Acceptance:** only green and eligible PRs are integrated, including one + based on staging. CI runs on the exact published SHA. The first-parent chain + is linear. A red batch falls back to one PR at a time. A promotion succeeds + after 24 h of soak, and an older nightly SHA is promoted while nightly keeps + moving. +- **Refusals:** + - integration: draft, fork, stacked, red, missing, untrusted or flaky head; + conflict; red integration; nightly moved; PR head moved; red status after + validation; stale green on the PR head only; broken invariant. + - promotion: soak of 23 h; red inside the window, then recovery; red tip; + missing evidence; SHA outside nightly despite forged soak statuses; + divergence; refs changed mid-promotion; short SHA or branch name; dry run. + - soak math: exactly 24 h passes and 23 h fails; resets; gaps; staleness; + observations made before CI went green; untrusted observations; the policy + floor. From 1e471af8df8b936b62b3149d191489f071736383 Mon Sep 17 00:00:00 2001 From: kvnloo Date: Wed, 25 Nov 2026 20:16:49 -0600 Subject: [PATCH 18/18] test(factory): an older verdict on the same SHA cannot satisfy the CI wait Closes the one surviving mutant (status-id freshness guard in wait_for_full). --- docs/factory/NIGHTLY-PROMOTION.md | 4 ++-- scripts/factory/tests/test_branch_gates.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/factory/NIGHTLY-PROMOTION.md b/docs/factory/NIGHTLY-PROMOTION.md index 89085377b1f..75c6f3b149b 100644 --- a/docs/factory/NIGHTLY-PROMOTION.md +++ b/docs/factory/NIGHTLY-PROMOTION.md @@ -263,7 +263,7 @@ that were rejected and are no longer needed. python3 -m unittest discover -s scripts/factory/tests -p 'test_branch_gates.py' -v ``` -The suite (27 tests) uses real git: a local bare origin that refuses a +The suite (28 tests) uses real git: a local bare origin that refuses a non-fast-forward or a deletion. Its pre-receive hook enforces a trusted `gev-ci/full` on nightly and staging, as ruleset 28125551 does. Alongside it runs a fake GitHub that owns its clock, the way GitHub owns `created_at`. Tests @@ -284,4 +284,4 @@ that injects time, statuses or a remote. divergence; refs changed mid-promotion; short SHA or branch name; dry run. - soak math: exactly 24 h passes and 23 h fails; resets; gaps; staleness; observations made before CI went green; untrusted observations; the policy - floor. + floor; an older `gev-ci/full` on the same SHA does not satisfy the CI wait. diff --git a/scripts/factory/tests/test_branch_gates.py b/scripts/factory/tests/test_branch_gates.py index b75b74c9ad2..512cb70b6c7 100644 --- a/scripts/factory/tests/test_branch_gates.py +++ b/scripts/factory/tests/test_branch_gates.py @@ -467,6 +467,18 @@ def test_policy_cannot_lower_the_floor(self): bg.load_policy(p) +class TestCiWait(Fixture): + def test_an_older_verdict_on_the_same_sha_does_not_satisfy_the_wait(self): + sha = self.root # already carries a green gev-ci/full from setUp + before = bg.max_status_id(self.gh, sha) + stale = bg.wait_for_full(self.gh, sha, POLICY, 0, 0, lambda s: None, min_id=before) + self.assertEqual(stale.state, "pending") + self.assertIn("timeout", stale.summary()) + self.ci.start(sha) # a fresh run posts a newer verdict + fresh = bg.wait_for_full(self.gh, sha, POLICY, 0, 0, lambda s: None, min_id=before) + self.assertTrue(fresh.green) + + class TestPromotion(Fixture): def nightly_tip(self): self.branch("feat/a", self.root, [("a.txt", "a\n")])