@ai-ecoverse/slicc-shared-web 2.12.3 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Configuration shared by SLICC's web repos ([slicc-bios](https://github.com/ai-ec
10
10
  | `tsconfig.json` | TypeScript base for Node's type stripping | `tsconfig.json`: `{ "extends": "@ai-ecoverse/slicc-shared-web/tsconfig.json", "include": ["src/**/*.ts"] }` |
11
11
  | `lefthook.yml` | Pre-commit hooks: Biome, typecheck, no comments, no unit tests in git, AGENTS.md, and diff coverage over [only the unit tests the change reaches](#which-unit-tests-a-commit-runs) | `lefthook.yml`: the [fail-closed snippet below](#hooks-that-fail-closed), and `prepare`: `slicc-install-hooks` plus the committed `.githooks/` it writes ([one hooks directory per worktree](#one-hooks-directory-per-worktree)) |
12
12
  | `mcr.config.mjs` | Unit-test coverage for JS and TS sources (`.js`, `.mjs`, `.cjs`, `.ts`, `.mts`, `.cts`) in `src/` or the `slicc.unitSources` directories (TS types are stripped first; TS that strip-only mode rejects, such as enums and parameter properties, is transformed with [amaro](https://github.com/nodejs/amaro) under the tests too, through an `--import` loader the config adds to `NODE_OPTIONS`, and its coverage is mapped back to the `.ts` lines; the same loader resolves a relative `./x.js`, `.mjs` or `.cjs` that isn't on disk to its `.ts`, `.mts` or `.cts` sibling, and imports a `.json` module, such as a package whose `main` is JSON, without `with { type: 'json' }`), written to `coverage/unit/lcov.info`. Every source file is in it, tested or not, and paths are matched relative to the repo root, so a checkout under a dot-directory such as `~/.bb/` still reports untested files to diff coverage. With `SLICC_UNIT_TESTS` set, `node --test` runs only those files ([below](#which-unit-tests-a-commit-runs)) | `test:unit`: `mcr -c node_modules/@ai-ecoverse/slicc-shared-web/mcr.config.mjs node --test 'test/unit/**/*.test.mjs'` |
13
- | `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. Every step prints its own `<step>: PASS …` line, and slicc-lint checks for it: a step that exits 0 without one fails the run with exit 70 (`slicc-lint: FAIL <step> (no PASS line from it)`), so a check that silently stops early can't pass. The last line, `slicc-lint: PASS`, comes only after every step has printed its PASS, and a gate can require it. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md and [`# renovate:` annotations](#versions-pinned-in-workflow-files) in workflow and action files. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set, and `slicc-unit-cover` is the diff-coverage hook. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps). `slicc-memory-peak` prints the job's [memory peak](#memory-peak). `slicc-install-hooks` installs the hooks into [this worktree's own directory](#one-hooks-directory-per-worktree), and on Windows does nothing and exits 0, so `npm ci` works there | `lint`: `slicc-lint`, and the hooks above |
13
+ | `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. Every step prints its own `<step>: PASS …` line, and slicc-lint checks for it: a step that exits 0 without one fails the run with exit 70 (`slicc-lint: FAIL <step> (no PASS line from it)`), so a check that silently stops early can't pass. The last line, `slicc-lint: PASS`, comes only after every step has printed its PASS, and a gate can require it. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md and [`# renovate:` annotations](#versions-pinned-in-workflow-files) in workflow and action files. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set, and `slicc-unit-cover` is the diff-coverage hook. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps). `slicc-memory-peak` prints the job's [memory peak](#memory-peak). `slicc-flaky retry|verdict|report` is the pipeline's [flaky-test](#pipeline) rerun, gate and reporter. `slicc-install-hooks` installs the hooks into [this worktree's own directory](#one-hooks-directory-per-worktree), and on Windows does nothing and exits 0, so `npm ci` works there | `lint`: `slicc-lint`, and the hooks above |
14
14
  | `pnpmfile.mjs` | pnpm's counterpart to the Renovate preset: an `updateConfig` hook that adds `@ai-ecoverse/*` to `minimumReleaseAgeExclude`, so pnpm 12 doesn't hold back our own fresh releases (`ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`) while third-party packages keep its age check | in a repo with a pnpm lockfile, as a [config dependency](https://pnpm.io/config-dependencies) in `pnpm-workspace.yaml`: `configDependencies: { '@ai-ecoverse/slicc-shared-web': X.Y.Z }` plus `pnpmfile: node_modules/.pnpm-config/@ai-ecoverse/slicc-shared-web/pnpmfile.mjs` |
15
15
  | `harness/` | The CDP integration-test harness, described [below](#integration-test-harness) | `import { launch } from '@ai-ecoverse/slicc-shared-web/harness'`, and `--test-global-setup=node_modules/@ai-ecoverse/slicc-shared-web/harness/global.mjs` |
16
16
  | `testing/` | Git fixtures that pass the AI git wrapper: `initFixtureRepo(dir, { hooks })` inits a throwaway repo with its own identity, no signing and no template hooks (`hooks: false` sets `core.hooksPath` to `/dev/null`), `commit(dir, message)` commits what is staged without `--no-verify`, and `commitAll(dir, message)` stages with `git add -A -- :/` first, all ignoring global and system git config, so a global `core.hooksPath` never runs in the fixture. Use them instead of `git add -A`, `git add .` or `--no-verify` in a test, which the wrapper refuses when an AI tool runs the suite | `import { commitAll, initFixtureRepo } from '@ai-ecoverse/slicc-shared-web/testing'` |
@@ -63,6 +63,7 @@ The caller cancels superseded runs on pull requests only, so a push to `main` ne
63
63
  | `deploy`: `deploy` in the `staging` environment, only when the input is set | ✓ | ✓ | |
64
64
  | `test` (one per shard) and `integration`, a check to require | ✓ | ✓ | |
65
65
  | `windows`: `windows-test` on `windows-latest`, only when the input is set | ✓ | ✓ | |
66
+ | `flaky`: files and closes `flaky-test` issues, never a check, only with `flaky-retry` above 0 | ✓ | ✓ | |
66
67
  | `context`, `reviewer` (Claude and Codex) and `post`, when the pull request [gets a review](#which-pull-requests-get-a-review) | ✓ | | |
67
68
  | `review`, the other check to require | ✓ | always green | |
68
69
  | `release`: `semantic-release` | | | ✓ |
@@ -81,6 +82,8 @@ The caller cancels superseded runs on pull requests only, so a push to `main` ne
81
82
  windows-test: npm run test:windows
82
83
  ```
83
84
 
85
+ **Flaky tests.** With `flaky-retry` above 0 (this repo's own CI sets 3; the default, 0, runs the tests once, as before), a shard whose tests failed reruns its failing files once, right away, on the same runner and commit, through `slicc-flaky retry`, which the test, `integration` and `flaky` jobs take from the pipeline's own commit. A test that fails, then passes is a flip; one that fails twice is a failure. A test is its file and its top-level name, and its key is the first 16 hex digits of `sha256(file \0 name)`. There is no rerun, and the shard fails as before, without a JUnit report or a failing test in it, with more than `flaky-retry` failing files, or when less than the rerun's limit, min(15 min, a quarter of `timeout-minutes`), is left of `timeout-minutes`. The rerun gets `SLICC_TEST_RETRY=1` and only those files, writes `junit/<shard>.retry.xml` (and no second `.files` list), keeps the first run's `artifacts/` and `coverage/` (its own artifacts go to `artifacts/retry/`), and is killed at the limit. `junit/<shard>.flaky.json` records each retried test's first and retry outcome, its first error and the runner. A flip passes the shard only if an open `flaky-test` issue has its key and has seen it on another commit (it has no `new` label, or its commit isn't this one), the test file doesn't match `strict-tests` and the pull request doesn't change it; every other flip stays red, and so does a test that is skipped, cancelled or missing on the rerun, a rerun that ran no test, wrote no JUnit report or timed out, and a test that passed first and failed on the rerun. Only the rerun's results count for those tests; its exit status doesn't, so a check after `node --test` in `test` (such as this repo's `verify.mjs`) doesn't fail a rerun of one file. `lint` reads the open `flaky-test` issues once (with `issues: read`) and the pull request's changed files, and hands them to the shards and `integration`; when it can't, no flake is known and every flip stays red. `integration` judges each shard's flips again from its JUnit reports and that list, counts only the failures it doesn't excuse, keeps every other check on the first run, and names the flakes: `integration: PASS … , 2 known flakes passed on retry (#916, #844)`. Each shard also uploads the tests that finally failed as `failed-<shard>-<attempt>`, and a test that failed on an earlier attempt of the run and passes now counts as a flip in the report, though not for the gate. The `flaky` job (`issues: write`, `actions: read`, `continue-on-error`) writes a table of the run's flips and failures to its step summary and files one issue per test: title `flaky: <file name> › <test name>`, label `flaky-test`, `new` until a second commit, `guard` for a strict row, whose issue and comments name only the test, the run and the commit, and ``Key: `<key>` `` in the body. It finds the issue among the open ones, then among those closed in the last 30 days, which it reopens, and otherwise opens one; it comments at most once per issue per run with the run and attempt, the event, the pull request, the shard, the runner, the commit and the first error (at most 3,000 characters). It posts nothing that holds the job token or a token-shaped string (the same scan the cert review's `post` had), nothing on a branch matching `flaky-quiet-branches`, nothing on a pull request whose run also has a failure or a shard that wasn't rerun, nothing for a test the pull request changes, and nothing at all when a run would open more than 5 issues (`flaky: <n> flips in one run, not filing (infrastructure?)`). In the merge queue, each open issue whose test passed first time gets `<!-- clean: <n> since <date> -->` in its body, which a flip clears; at `flaky-close-after` it is closed with `no flip in <n> clean merge-group runs since <date>; a new flip reopens it`. It needs `node --test` through the shared harness: `$TEST` must honour `SLICC_TEST_FILES` and write node's JUnit report with `file=`.
86
+
84
87
  **Reviewer** runs twice, once with [claude-code-action](https://github.com/anthropics/claude-code-action) and once with [codex-action](https://github.com/openai/codex-action), on the same prompt, whether the tests passed or not. Both run on Amazon Bedrock with the org secret `AWS_BEARER_TOKEN_BEDROCK`, in the region of the org variable `CERT_AWS_REGION` (`us-west-2` without it). Claude uses the model in `CERT_BEDROCK_MODEL` (`global.anthropic.claude-opus-5-5` without it), as the cert reviews do. Codex uses its built-in `amazon-bedrock-runtime` provider (codex-action waits for its OpenAI proxy's `<run id>.json` in `codex-home` whenever it has a prompt, so the job writes a placeholder one) and the model in `CODEX_BEDROCK_MODEL` (`global.openai.gpt-6.1-sol` without it). Models that Bedrock serves only through inference profiles, as Sol 6.1 is, need the runtime provider and the profile's `global.` id; the `amazon-bedrock` provider's endpoint doesn't list them. The job token can only read. Each reviewer gets:
85
88
 
86
89
  - the pull request's head, with full history, as the working directory, and its base in `$RUNNER_TEMP/base`, each after `npm ci` (claude-code-action needs the working directory to be a checkout, and a base nested inside it would break the head's Biome config). Everything else the reviewers get or write (the prompt, context, integration artifacts, `browsers.json`, findings and screenshots) is in `$RUNNER_TEMP/review`, outside the checkout, so a reviewer's `npm run lint` sees only the repository;
@@ -149,6 +152,10 @@ The commands in `lint`, `test`, `deploy`, `review-browser` and `after-release` r
149
152
  | `review-renovate` | none | globs of Renovate group slugs whose pull requests get a review |
150
153
  | `node-options` | none | node flags added to the test step's `NODE_OPTIONS`, such as `--max-old-space-size=8192` |
151
154
  | `require-tests` | `true` | `integration` fails when no test ran |
155
+ | `flaky-retry` | `0` | the most failing files a shard reruns once, [flaky tests](#pipeline); `0` reruns and reports nothing |
156
+ | `strict-tests` | `**/*guard*.test.*` and `**/*security*.test.*` | newline-separated globs of test files whose flips stay red; a repo lists its own guard rows too |
157
+ | `flaky-quiet-branches` | `probe/**` | newline-separated globs of branches whose flips are never filed or commented |
158
+ | `flaky-close-after` | `20` | clean merge-queue runs before a `flaky-test` issue closes |
152
159
  | `release-environment` | none | the GitHub environment the release job runs in |
153
160
  | `after-release` | none | a command run after semantic-release, with `RELEASE_VERSION` |
154
161
  | `release-secrets` | none | newline- or space-separated secret names (any case) that semantic-release and `after-release` get |
@@ -285,7 +292,7 @@ SLICC_UNIT_ALL=1 git commit
285
292
 
286
293
  ## Integration-test harness
287
294
 
288
- `harness/` drives Chromium over raw CDP on `--remote-debugging-pipe`, as its only client, from `node --test`. On CI (`CI` set, as GitHub Actions does) Chrome runs headed, since headless Chrome behaves slightly differently; the pipeline starts Xvfb when the runner has no display. On a developer machine (no `CI`) it runs headless, so a test run doesn't open windows. `SLICC_HEADLESS=1` or `0`, or `launch({ headless })`, overrides either way. On Linux, a headed Chrome on CI (or with no `DISPLAY`) gets an Xvfb display of its own, started with `-displayfd` so it picks a free number and stopped with the browser: browsers launched side by side, as `node --test` runs files with `--test-concurrency`, never share a screen, so none takes another's window focus (four on one display broke `:focus-visible` checks in slicc-spectrum#572). This needs `Xvfb` on `PATH`; without it, Chrome uses `DISPLAY`, and on a Linux desktop without `CI` it always does. A repo that launches its own Chrome, for example on a TCP debugging port that `launch()` doesn't offer, matches this with the same exports: `headlessByDefault(env)` says whether to run headless, `modeFlags(headless)` gives the flags for that mode, and `screenFor(headed, env)` starts the private Xvfb when one is needed and returns `{ env, child, close }`, whose `env` the Chrome process gets. A headed Chrome gets `--enable-unsafe-swiftshader`, so WebGL falls back to software on a display without a GPU, as headless Chrome's does (slicc-bios#901's splash scene saw no WebGL2 otherwise). Every page, service worker, shared worker and dedicated worker, nested ones included, starts paused, gets coverage (and the CPU profiler, when profiling is on) switched on in the same tick, and only then runs. With nothing to collect (`coverage: []` and profiling off) pages and shared workers start paused, and service workers are left out of the auto-attach and attached once they exist, so they never wait for the harness. A held start that Chrome repeats when it stops and restarts a service worker during an update left the updated worker installed and the next navigation unanswered whenever the harness was slow to run it (slicc-bios#844, #836, #789). Shared workers stay in the held auto-attach: attaching one after the fact races its teardown, and Chrome's browser process then crashes on a failed `worker_host_` check in `shared_worker_devtools_agent_host.cc` (slicc-bios#901). Each test gets its own browser context and leaves `artifacts/<suite>/<test>/` behind: a screenshot per tab and a `console.log` of every target. Lines logged before the first test, such as an extension service worker's at startup, go into the first test's `console.log`. The global teardown merges the raw coverage into `coverage/` (console table, lcov, V8 HTML) and writes `artifacts/hotspots.md`.
295
+ `harness/` drives Chromium over raw CDP on `--remote-debugging-pipe`, as its only client, from `node --test`. On CI (`CI` set, as GitHub Actions does) Chrome runs headed, since headless Chrome behaves slightly differently; the pipeline starts Xvfb when the runner has no display. On a developer machine (no `CI`) it runs headless, so a test run doesn't open windows. `SLICC_HEADLESS=1` or `0`, or `launch({ headless })`, overrides either way. On Linux, a headed Chrome on CI (or with no `DISPLAY`) gets an Xvfb display of its own, started with `-displayfd` so it picks a free number and stopped with the browser: browsers launched side by side, as `node --test` runs files with `--test-concurrency`, never share a screen, so none takes another's window focus (four on one display broke `:focus-visible` checks in slicc-spectrum#572). This needs `Xvfb` on `PATH`; without it, Chrome uses `DISPLAY`, and on a Linux desktop without `CI` it always does. A repo that launches its own Chrome, for example on a TCP debugging port that `launch()` doesn't offer, matches this with the same exports: `headlessByDefault(env)` says whether to run headless, `modeFlags(headless)` gives the flags for that mode, and `screenFor(headed, env)` starts the private Xvfb when one is needed and returns `{ env, child, close }`, whose `env` the Chrome process gets. A headed Chrome gets `--enable-unsafe-swiftshader`, so WebGL falls back to software on a display without a GPU, as headless Chrome's does (slicc-bios#901's splash scene saw no WebGL2 otherwise). Every page, service worker, shared worker and dedicated worker, nested ones included, starts paused, gets coverage (and the CPU profiler, when profiling is on) switched on in the same tick, and only then runs. With nothing to collect (`coverage: []` and profiling off) pages and shared workers start paused, and service workers are left out of the auto-attach and attached once they exist, so they never wait for the harness. A held start that Chrome repeats when it stops and restarts a service worker during an update left the updated worker installed and the next navigation unanswered whenever the harness was slow to run it (slicc-bios#844, #836, #789). Shared workers stay in the held auto-attach: attaching one after the fact races its teardown, and Chrome's browser process then crashes on a failed `worker_host_` check in `shared_worker_devtools_agent_host.cc` (slicc-bios#901). Each test gets its own browser context and leaves `artifacts/<suite>/<test>/` behind: a screenshot per tab and a `console.log` of every target. `targets.log` is a timestamped JSON-lines timeline of target discovery, attachment (including parent sessions and held starts), navigation, load events and failed loads. It also records when the harness sends `Runtime.runIfWaitingForDebugger`, whether Chrome answers or the call fails, and any failed attachment-setup commands; each test starts with a snapshot of existing sessions and their last resume state. Lines logged before the first test, such as an extension service worker's at startup, go into the first test's `console.log`. The global teardown merges the raw coverage into `coverage/` (console table, lcov, V8 HTML) and writes `artifacts/hotspots.md`.
289
296
 
290
297
  CPU profiling is off by default. V8's sampler interrupts each page and worker thread every 100 µs with a signal, and the renderer SIGSEGVs in slicc-bios#114 all fault inside a signal handler walking the interrupted thread's frames, which points at it. Turn it on with `profile: true` or `SLICC_PROFILE=1` to get one CPU profile per target and snapshot in the test's artifact directory, and the 15 frames with the most self time in the repo's own scripts in `hotspots.md`. Without it, `hotspots.md` says that profiling is off.
291
298
 
@@ -0,0 +1,928 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import {
5
+ appendFileSync,
6
+ cpSync,
7
+ existsSync,
8
+ globSync,
9
+ mkdirSync,
10
+ readdirSync,
11
+ readFileSync,
12
+ realpathSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from 'node:fs';
16
+ import { basename, dirname, isAbsolute, join, matchesGlob, relative, sep } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { inflateRawSync } from 'node:zlib';
19
+
20
+ export const LABEL = 'flaky-test';
21
+ const LABELS = [
22
+ [LABEL, 'fbca04', 'A test that failed, then passed on a retry'],
23
+ ['new', 'c2e0c6', 'A flaky test seen on one commit so far'],
24
+ ['guard', 'b60205', 'A strict (guard or security) test that flipped'],
25
+ ];
26
+ const CAP = 5;
27
+ const ERROR = 3000;
28
+ const DAY = 86400000;
29
+ const NONE = /\/slicc-shared-web\/unit\/none\.mjs$/;
30
+ const ENTITIES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
31
+ const TAG = /<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"]|"[^"]*")*)>/g;
32
+ const SECRET_SHAPES = [
33
+ /gh[pousr]_[A-Za-z0-9]{20,}/,
34
+ /github_pat_[A-Za-z0-9_]{20,}/,
35
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,
36
+ /ABSK[A-Za-z0-9+/=]{16,}/,
37
+ /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,
38
+ /-----BEGIN [A-Z0-9 ]*-----/,
39
+ ];
40
+
41
+ export function key({ file, name }) {
42
+ return createHash('sha256').update(`${file}\u0000${name}`).digest('hex').slice(0, 16);
43
+ }
44
+
45
+ export function title({ file, name }) {
46
+ const text = `flaky: ${basename(file)} › ${name}`;
47
+ return text.length > 240 ? `${text.slice(0, 239)}…` : text;
48
+ }
49
+
50
+ function fence(log) {
51
+ const text = (log || 'no error message').slice(0, ERROR);
52
+ return `~~~~\n${text.replaceAll('~~~~', '~ ~ ~ ~')}\n~~~~`;
53
+ }
54
+
55
+ export function carriesSecret(text, secrets = []) {
56
+ const raw = String(text);
57
+ const lower = raw.toLowerCase();
58
+ for (const value of secrets.filter(
59
+ (secret) => typeof secret === 'string' && secret.length >= 8
60
+ )) {
61
+ const bytes = Buffer.from(value);
62
+ const forms = [
63
+ value,
64
+ JSON.stringify(value).slice(1, -1),
65
+ bytes.toString('base64'),
66
+ bytes.toString('base64').replace(/=+$/, ''),
67
+ bytes.toString('base64url'),
68
+ bytes.toString('hex'),
69
+ encodeURIComponent(value),
70
+ value.split('').reverse().join(''),
71
+ ];
72
+ if (forms.some((form) => raw.includes(form) || lower.includes(form.toLowerCase()))) {
73
+ return 'a secret value this run holds';
74
+ }
75
+ }
76
+ const shape = SECRET_SHAPES.find((pattern) => pattern.test(raw));
77
+ return shape ? `a token-shaped string (${shape.source.slice(0, 16)}…)` : '';
78
+ }
79
+
80
+ export function decode(text) {
81
+ return text.replace(/&(?:#x([0-9a-f]+)|#(\d+)|([a-z]+));/gi, (all, hex, dec, named) => {
82
+ if (hex) return String.fromCodePoint(Number.parseInt(hex, 16));
83
+ if (dec) return String.fromCodePoint(Number(dec));
84
+ return ENTITIES[named] ?? all;
85
+ });
86
+ }
87
+
88
+ function attribute(attrs, name) {
89
+ const found = new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(attrs);
90
+ return found ? decode(found[1]) : undefined;
91
+ }
92
+
93
+ export function local(file, root) {
94
+ if (!root || !isAbsolute(file)) return file;
95
+ return relative(root, file).split(sep).join('/');
96
+ }
97
+
98
+ export function statusOf(test) {
99
+ const all = [...test.leaves.values()];
100
+ if (all.includes('fail')) return 'fail';
101
+ return all.includes('pass') ? 'pass' : 'skip';
102
+ }
103
+
104
+ function settle(tests, leaf, root) {
105
+ if (NONE.test(leaf.file)) return;
106
+ const status = leaf.skipped ? 'skip' : leaf.failed ? 'fail' : 'pass';
107
+ const [name] = leaf.path;
108
+ const file = local(leaf.top, root);
109
+ const id = `${file}\u0000${name}`;
110
+ const test = tests.get(id) ?? { file, name, leaves: new Map(), error: '', failed: 0 };
111
+ const path = leaf.path.join(' › ');
112
+ if (test.leaves.get(path) !== 'fail') test.leaves.set(path, status);
113
+ if (status === 'fail') {
114
+ test.failed += 1;
115
+ test.error ||= leaf.error.slice(0, ERROR);
116
+ }
117
+ tests.set(id, test);
118
+ }
119
+
120
+ function suite(state, { close, attrs, single }) {
121
+ if (close) state.stack.pop();
122
+ else if (!single) {
123
+ if (state.stack.length === 0) state.top = undefined;
124
+ state.stack.push(attribute(attrs, 'name') ?? '');
125
+ }
126
+ }
127
+
128
+ function testcase(state, { close, attrs, single }) {
129
+ if (!close) {
130
+ const file = attribute(attrs, 'file') ?? '';
131
+ if (state.stack.length === 0 || state.top === undefined) state.top = file;
132
+ state.leaf = {
133
+ path: [...state.stack, attribute(attrs, 'name') ?? ''],
134
+ file,
135
+ top: state.top,
136
+ error: '',
137
+ };
138
+ }
139
+ if (close || single) {
140
+ if (state.leaf) settle(state.tests, state.leaf, state.root);
141
+ state.leaf = undefined;
142
+ }
143
+ }
144
+
145
+ export function parse(xml, root, tests = new Map()) {
146
+ const state = { stack: [], leaf: undefined, text: undefined, top: undefined, tests, root };
147
+ for (const match of xml.matchAll(TAG)) {
148
+ const [whole, close, tag, rest] = match;
149
+ const single = rest.endsWith('/');
150
+ const part = {
151
+ whole,
152
+ close,
153
+ tag,
154
+ attrs: single ? rest.slice(0, -1) : rest,
155
+ single,
156
+ at: match.index,
157
+ };
158
+ if (tag === 'testsuite') suite(state, part);
159
+ else if (tag === 'testcase') testcase(state, part);
160
+ else if (state.leaf) inside(state, xml, part);
161
+ }
162
+ return tests;
163
+ }
164
+
165
+ function inside(state, xml, { whole, close, tag, attrs, single, at }) {
166
+ if (tag === 'skipped') {
167
+ if (!close) state.leaf.skipped = true;
168
+ return;
169
+ }
170
+ if (!close) {
171
+ state.leaf.failed = true;
172
+ const message = attribute(attrs, 'message') ?? '';
173
+ if (single) state.leaf.error ||= message;
174
+ else state.text = { from: at + whole.length, message };
175
+ return;
176
+ }
177
+ if (state.text) {
178
+ state.leaf.error ||= decode(xml.slice(state.text.from, at)).trim() || state.text.message;
179
+ state.text = undefined;
180
+ }
181
+ }
182
+
183
+ export function load(files, root) {
184
+ const tests = new Map();
185
+ for (const file of files) parse(readFileSync(file, 'utf8'), root, tests);
186
+ return tests;
187
+ }
188
+
189
+ export function firstReports(dir, shard) {
190
+ const own = new RegExp(`^${shard.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(-\\d+)?\\.xml$`);
191
+ return (existsSync(dir) ? readdirSync(dir) : [])
192
+ .filter((name) => own.test(name))
193
+ .sort()
194
+ .map((name) => join(dir, name));
195
+ }
196
+
197
+ export function globs(text) {
198
+ return (text ?? '')
199
+ .split('\n')
200
+ .map((line) => line.trim())
201
+ .filter(Boolean);
202
+ }
203
+
204
+ export function lint(text) {
205
+ try {
206
+ const parsed = JSON.parse(text || 'null');
207
+ return { known: parsed?.known ?? {}, changed: parsed?.changed ?? [] };
208
+ } catch {
209
+ return { known: {}, changed: [] };
210
+ }
211
+ }
212
+
213
+ export function isKnown(entry, sha) {
214
+ return (
215
+ Boolean(entry) && (entry.commit === null || (Boolean(entry.commit) && entry.commit !== sha))
216
+ );
217
+ }
218
+
219
+ function category(test, { known, strict, changed, sha }) {
220
+ if (strict.some((glob) => matchesGlob(test.file, glob))) return 'strict';
221
+ if (changed.includes(test.file)) return 'changed';
222
+ return isKnown(known[key(test)], sha) ? 'known' : 'new';
223
+ }
224
+
225
+ export function problem(rerun, retry) {
226
+ if (!rerun) return 'not rerun';
227
+ if (rerun.timedOut) return 'the rerun timed out';
228
+ if (!retry) return 'the rerun wrote no JUnit report';
229
+ const ran = [...retry.values()].some(
230
+ (test) => statusOf(test) === 'fail' || (statusOf(test) === 'pass' && test.name !== test.file)
231
+ );
232
+ return ran ? '' : 'the rerun ran no test';
233
+ }
234
+
235
+ function recovered(before, after) {
236
+ if (!after || statusOf(after) === 'fail') return false;
237
+ return [...before.leaves].every(
238
+ ([path, status]) => status !== 'fail' || after.leaves.get(path) === 'pass'
239
+ );
240
+ }
241
+
242
+ function row(before, after, broken, rules) {
243
+ const test = before ?? after;
244
+ const base = {
245
+ file: test.file,
246
+ name: test.name,
247
+ key: key(test),
248
+ first: before ? statusOf(before) : 'missing',
249
+ retry: after ? statusOf(after) : 'missing',
250
+ error: (before?.error || after?.error || '').slice(0, ERROR),
251
+ back: false,
252
+ excused: false,
253
+ };
254
+ if (base.first === 'fail') {
255
+ if (broken || !recovered(before, after)) return { ...base, kind: 'failure' };
256
+ const kind = category(test, rules);
257
+ return { ...base, kind, excused: kind === 'known', issue: rules.known[base.key]?.issue };
258
+ }
259
+ if (base.retry !== 'fail') return { ...base, kind: 'pass' };
260
+ if (base.first !== 'pass') return { ...base, kind: 'failure' };
261
+ return { ...base, kind: category(test, rules), back: true };
262
+ }
263
+
264
+ export function judge({ first, retry, rerun, ...rules }) {
265
+ const broken = problem(rerun, retry);
266
+ const files = new Set(rerun?.files ?? []);
267
+ const ids = new Set([...first.keys(), ...(retry?.keys() ?? [])]);
268
+ const rows = [];
269
+ for (const id of ids) {
270
+ const before = first.get(id);
271
+ const failedFirst = before && statusOf(before) === 'fail';
272
+ const after = failedFirst || !broken ? retry?.get(id) : undefined;
273
+ const test = before ?? after;
274
+ if (!test || (!failedFirst && !files.has(test.file))) continue;
275
+ rows.push(row(before, after, broken, rules));
276
+ }
277
+ const failing = rows.filter((entry) => entry.first === 'fail');
278
+ const ok =
279
+ !broken && failing.length > 0 && rows.every((entry) => entry.kind === 'pass' || entry.excused);
280
+ return { rows, ok, broken };
281
+ }
282
+
283
+ function describe(entry, reason) {
284
+ if (entry.kind === 'failure') return reason ? `failed, not rerun: ${reason}` : 'failed twice';
285
+ if (entry.manual) {
286
+ const note =
287
+ { strict: ' (a strict row)', changed: ' (the PR changes this test)' }[entry.kind] ?? '';
288
+ return `failed on attempt ${entry.from}, then passed on attempt ${entry.attempt}${note}`;
289
+ }
290
+ if (entry.back) return 'passed, then failed on retry';
291
+ if (entry.kind === 'known')
292
+ return `known flake${entry.issue ? ` #${entry.issue}` : ''}, passed on retry`;
293
+ if (entry.kind === 'strict')
294
+ return 'strict row flipped: failed, then passed on retry, so it stays red';
295
+ if (entry.kind === 'changed')
296
+ return "this PR's test is nondeterministic: it flipped, and the PR changes its file";
297
+ return 'first flip: failed, then passed on retry, so it stays red until it flips on another commit too';
298
+ }
299
+
300
+ function bounded(command, env, ms) {
301
+ return new Promise((resolve) => {
302
+ const child = spawn('bash', ['-eo', 'pipefail', '-c', command], {
303
+ env,
304
+ stdio: 'inherit',
305
+ detached: true,
306
+ });
307
+ const kill = (signal) => {
308
+ try {
309
+ process.kill(-child.pid, signal);
310
+ } catch {}
311
+ };
312
+ let late = false;
313
+ const timer = setTimeout(() => {
314
+ late = true;
315
+ kill('SIGKILL');
316
+ }, ms);
317
+ child.on('close', (status) => {
318
+ clearTimeout(timer);
319
+ kill('SIGKILL');
320
+ resolve({ status: status ?? 1, late });
321
+ });
322
+ });
323
+ }
324
+
325
+ function move(from, to) {
326
+ if (!existsSync(from)) return;
327
+ cpSync(from, to, { recursive: true });
328
+ rmSync(from, { recursive: true, force: true });
329
+ }
330
+
331
+ async function rerunFiles(files, ms, env, shard) {
332
+ const scratch = join(env.RUNNER_TEMP, 'slicc-flaky', 'retry');
333
+ rmSync(scratch, { recursive: true, force: true });
334
+ mkdirSync(scratch, { recursive: true });
335
+ const junit = join(scratch, `${shard}.xml`);
336
+ const options = (env.NODE_OPTIONS ?? '').replace(
337
+ `--test-reporter-destination=${env.SLICC_TEST_JUNIT}`,
338
+ `--test-reporter-destination=${junit}`
339
+ );
340
+ const stash = join(scratch, 'first');
341
+ move('artifacts', join(stash, 'artifacts'));
342
+ move('coverage', join(stash, 'coverage'));
343
+ const started = Date.now();
344
+ const { status, late } = await bounded(
345
+ env.TEST,
346
+ {
347
+ ...env,
348
+ NODE_OPTIONS: options,
349
+ SLICC_TEST_FILES: files.join('\n'),
350
+ SLICC_TEST_SHARD: 'retry',
351
+ SLICC_TEST_JUNIT: junit,
352
+ SLICC_TEST_RETRY: '1',
353
+ },
354
+ ms
355
+ );
356
+ const took = Date.now() - started;
357
+ move('artifacts', join(stash, 'artifacts', 'retry'));
358
+ rmSync('coverage', { recursive: true, force: true });
359
+ move(join(stash, 'artifacts'), 'artifacts');
360
+ move(join(stash, 'coverage'), 'coverage');
361
+ const reports = readdirSync(scratch).filter((name) => name.endsWith('.xml'));
362
+ const inner = reports.map((name) =>
363
+ readFileSync(join(scratch, name), 'utf8')
364
+ .replace(/<\?xml[^>]*\?>/, '')
365
+ .replace(/<\/?testsuites>/g, '')
366
+ .trim()
367
+ );
368
+ if (reports.length > 0) {
369
+ writeFileSync(
370
+ join('junit', `${shard}.retry.xml`),
371
+ `<?xml version="1.0" encoding="utf-8"?>\n<testsuites>\n${inner.join('\n')}\n</testsuites>\n`
372
+ );
373
+ }
374
+ return { files, ms: took, exit: status, timedOut: late };
375
+ }
376
+
377
+ function context(env) {
378
+ return {
379
+ shard: env.SHARD,
380
+ attempt: Number(env.GITHUB_RUN_ATTEMPT || 1),
381
+ sha: env.SHA || env.GITHUB_SHA || '',
382
+ runner: env.RUNNER_NAME || '',
383
+ root: process.cwd(),
384
+ };
385
+ }
386
+
387
+ function rules(env) {
388
+ const { known, changed } = lint(env.FLAKY);
389
+ return { known, changed, strict: globs(env.STRICT), sha: env.SHA || env.GITHUB_SHA || '' };
390
+ }
391
+
392
+ function skipReason({ reports, failing, files, most, elapsed, limit, budget, options }) {
393
+ if (reports.length === 0) return 'no JUnit report';
394
+ if (failing.length === 0) return 'no failing test in the JUnit report';
395
+ if (files.length > most) return `${files.length} files failed, more than flaky-retry (${most})`;
396
+ if (elapsed + limit > budget) return 'past the time budget';
397
+ if (!options) return 'NODE_OPTIONS names no JUnit destination';
398
+ return '';
399
+ }
400
+
401
+ function announce(entries, reason) {
402
+ for (const entry of entries) {
403
+ const line = `${entry.file} › ${entry.name}: ${describe(entry, reason)}`;
404
+ if (entry.kind === 'pass') continue;
405
+ if (entry.excused) console.log(`::notice title=Flaky::${line}`);
406
+ else console.log(`::error title=Flaky::${line}`);
407
+ }
408
+ }
409
+
410
+ export async function retry(env = process.env) {
411
+ const started = Date.now();
412
+ const first = spawnSync('bash', ['-eo', 'pipefail', '-c', env.TEST], { env, stdio: 'inherit' });
413
+ const status = first.status ?? 1;
414
+ const record = { ...context(env), rerun: null, skipped: null, ok: status === 0, rows: [] };
415
+ const shard = record.shard;
416
+ mkdirSync('junit', { recursive: true });
417
+ const save = () =>
418
+ writeFileSync(join('junit', `${shard}.flaky.json`), `${JSON.stringify(record, null, 2)}\n`);
419
+ if (status === 0) {
420
+ save();
421
+ return 0;
422
+ }
423
+ const reports = firstReports('junit', shard);
424
+ const tests = load(reports, record.root);
425
+ const failing = [...tests.values()].filter((test) => statusOf(test) === 'fail');
426
+ const files = [...new Set(failing.map((test) => test.file))];
427
+ const budget = Number(env.TIMEOUT_MINUTES) * 60000;
428
+ const limit = Math.min(15 * 60000, budget / 4);
429
+ const options =
430
+ Boolean(env.SLICC_TEST_JUNIT) &&
431
+ (env.NODE_OPTIONS ?? '').includes(`--test-reporter-destination=${env.SLICC_TEST_JUNIT}`);
432
+ const most = Number(env.FLAKY_RETRY);
433
+ const skipped = skipReason({
434
+ reports,
435
+ failing,
436
+ files,
437
+ most,
438
+ elapsed: Date.now() - started,
439
+ limit,
440
+ budget,
441
+ options,
442
+ });
443
+ const given = rules(env);
444
+ if (skipped) {
445
+ record.skipped = skipped;
446
+ record.rows = judge({ first: tests, retry: undefined, rerun: null, ...given }).rows;
447
+ console.log(`flaky: shard ${shard}: not rerun: ${skipped}`);
448
+ } else {
449
+ console.log(
450
+ `flaky: shard ${shard}: rerunning ${files.join(' ')} (at most ${Math.round(limit / 1000)} s)`
451
+ );
452
+ record.rerun = await rerunFiles(files, limit, env, shard);
453
+ const retried = join('junit', `${shard}.retry.xml`);
454
+ const after = existsSync(retried) ? load([retried], record.root) : undefined;
455
+ const verdict = judge({ first: tests, retry: after, rerun: record.rerun, ...given });
456
+ record.rows = verdict.rows;
457
+ record.ok = verdict.ok;
458
+ if (verdict.broken) console.log(`flaky: shard ${shard}: ${verdict.broken}`);
459
+ }
460
+ announce(record.rows, skipped);
461
+ save();
462
+ const failures = record.rows.filter((entry) => entry.kind === 'failure');
463
+ if (failures.length > 0) {
464
+ const dir = join(env.RUNNER_TEMP, 'slicc-flaky', 'failed');
465
+ mkdirSync(dir, { recursive: true });
466
+ const { rows, rerun, ok, ...rest } = record;
467
+ const failed = failures.map(({ file, name, key: id, error }) => ({
468
+ file,
469
+ name,
470
+ key: id,
471
+ error,
472
+ }));
473
+ writeFileSync(
474
+ join(dir, `failed-${shard}-${record.attempt}.json`),
475
+ `${JSON.stringify({ ...rest, failed }, null, 2)}\n`
476
+ );
477
+ }
478
+ const passed = record.rows.filter((entry) => entry.excused);
479
+ if (record.ok) {
480
+ const issues = passed.map((entry) => (entry.issue ? `#${entry.issue}` : entry.key)).join(', ');
481
+ console.log(
482
+ `flaky: shard ${shard}: PASS, ${passed.length} known flake${passed.length === 1 ? '' : 's'} passed on retry (${issues})`
483
+ );
484
+ return 0;
485
+ }
486
+ console.log(`flaky: shard ${shard}: FAIL`);
487
+ return skipped ? status : 1;
488
+ }
489
+
490
+ export function verdict(env = process.env, dir = 'junit') {
491
+ const given = rules(env);
492
+ const covered = new Set();
493
+ const passed = [];
494
+ let failed = 0;
495
+ for (const json of globSync(`${dir}/**/*.flaky.json`).sort()) {
496
+ const record = JSON.parse(readFileSync(json, 'utf8'));
497
+ const shard = basename(json, '.flaky.json');
498
+ const here = dirname(json);
499
+ const reports = firstReports(here, shard);
500
+ for (const report of reports) covered.add(report);
501
+ const first = load(reports, record.root);
502
+ const retried = join(here, `${shard}.retry.xml`);
503
+ const after = existsSync(retried) ? load([retried], record.root) : undefined;
504
+ const result = judge({ first, retry: after, rerun: record.rerun, ...given });
505
+ const excused = new Set(
506
+ result.ok ? result.rows.filter((entry) => entry.excused).map((entry) => entry.key) : []
507
+ );
508
+ for (const test of first.values()) if (!excused.has(key(test))) failed += test.failed;
509
+ passed.push(...result.rows.filter((entry) => excused.has(entry.key)));
510
+ }
511
+ for (const report of globSync(`${dir}/**/*.xml`).sort()) {
512
+ if (covered.has(report) || report.endsWith('.retry.xml')) continue;
513
+ for (const test of load([report]).values()) failed += test.failed;
514
+ }
515
+ const known = passed.map((entry) => (entry.issue ? `#${entry.issue}` : entry.key));
516
+ const out = join(env.RUNNER_TEMP, 'slicc-flaky');
517
+ mkdirSync(out, { recursive: true });
518
+ writeFileSync(join(out, 'verdict.json'), `${JSON.stringify({ failed, known })}\n`);
519
+ console.log(
520
+ `flaky: verdict: ${failed} failing tests left, ${known.length} known flakes passed on retry${known.length ? ` (${known.join(', ')})` : ''}`
521
+ );
522
+ return 0;
523
+ }
524
+
525
+ function runUrl(ctx, attempt) {
526
+ return `${ctx.server}/${ctx.repo}/actions/runs/${ctx.run}/attempts/${attempt}`;
527
+ }
528
+
529
+ function lead(flip) {
530
+ if (flip.manual) return `Attempt ${flip.from} failed with:`;
531
+ return flip.back ? 'The retry failed with:' : 'The first run failed with:';
532
+ }
533
+
534
+ export function occurrence(flip, ctx) {
535
+ return [
536
+ `- Run: ${runUrl(ctx, flip.attempt)}`,
537
+ `- Event: ${ctx.event}${ctx.pr ? `, PR #${ctx.pr}` : ''}, shard ${flip.shard}`,
538
+ `- Runner: ${flip.runner || 'unknown'}`,
539
+ `- Commit: ${flip.sha || 'unknown'}`,
540
+ '',
541
+ lead(flip),
542
+ '',
543
+ fence(flip.error),
544
+ ].join('\n');
545
+ }
546
+
547
+ function sentence(flip) {
548
+ const test = `\`${flip.file}\` › ${flip.name}`;
549
+ if (flip.manual) {
550
+ return `${test} failed on attempt ${flip.from} of a run, then passed on attempt ${flip.attempt} of it, on the same commit.`;
551
+ }
552
+ if (flip.back)
553
+ return `${test} passed, then failed when its shard ran the file again on the same commit.`;
554
+ return `${test} failed, then passed when its shard ran the file again on the same commit.`;
555
+ }
556
+
557
+ export function body(flip, ctx) {
558
+ const marker = `Every later flip of this test adds a comment here. Key: \`${key(flip)}\``;
559
+ if (flip.strict) {
560
+ return [
561
+ `\`${flip.file}\` › ${flip.name} flipped. It is a strict row, so the details stay in the run.`,
562
+ '',
563
+ `- Run: ${runUrl(ctx, flip.attempt)}`,
564
+ `- Commit: ${flip.sha || 'unknown'}`,
565
+ '',
566
+ marker,
567
+ ].join('\n');
568
+ }
569
+ return [sentence(flip), '', occurrence(flip, ctx), '', marker].join('\n');
570
+ }
571
+
572
+ export function comment(flip, ctx) {
573
+ if (flip.strict)
574
+ return `\`${flip.file}\` › ${flip.name} flipped again: ${runUrl(ctx, flip.attempt)}`;
575
+ return occurrence(flip, ctx);
576
+ }
577
+
578
+ export function clean(text) {
579
+ const found = /<!-- clean: (\d+) since (\S+) -->/.exec(text ?? '');
580
+ return found ? { count: Number(found[1]), since: found[2] } : { count: 0, since: undefined };
581
+ }
582
+
583
+ export function withClean(text, count, since) {
584
+ const stripped = (text ?? '').replace(/\n*<!-- clean: \d+ since \S+ -->/, '');
585
+ return count > 0 ? `${stripped}\n\n<!-- clean: ${count} since ${since} -->` : stripped;
586
+ }
587
+
588
+ export function unzip(zip) {
589
+ const entries = [];
590
+ const end = zip.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
591
+ for (let at = zip.readUInt32LE(end + 16), left = zip.readUInt16LE(end + 10); left > 0; left--) {
592
+ const size = zip.readUInt32LE(at + 20);
593
+ const named = zip.readUInt16LE(at + 28);
594
+ const name = zip.toString('utf8', at + 46, at + 46 + named);
595
+ const start = zip.readUInt32LE(at + 42);
596
+ const from = start + 30 + zip.readUInt16LE(start + 26) + zip.readUInt16LE(start + 28);
597
+ const data = zip.subarray(from, from + size);
598
+ entries.push([name, String(zip.readUInt16LE(at + 10) === 8 ? inflateRawSync(data) : data)]);
599
+ at += 46 + named + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32);
600
+ }
601
+ return entries;
602
+ }
603
+
604
+ function client(ctx) {
605
+ return async (method, path, payload) => {
606
+ const response = await fetch(`${ctx.api}/${path}`, {
607
+ method,
608
+ headers: {
609
+ authorization: `Bearer ${ctx.token}`,
610
+ accept: 'application/vnd.github+json',
611
+ 'x-github-api-version': '2022-11-28',
612
+ ...(payload ? { 'content-type': 'application/json' } : {}),
613
+ },
614
+ body: payload ? JSON.stringify(payload) : undefined,
615
+ signal: AbortSignal.timeout(60000),
616
+ });
617
+ if (!response.ok) {
618
+ const error = new Error(
619
+ `${method} ${path}: ${response.status} ${(await response.text()).slice(0, 200)}`
620
+ );
621
+ error.status = response.status;
622
+ throw error;
623
+ }
624
+ if (response.status === 204) return null;
625
+ return path.endsWith('/zip') ? Buffer.from(await response.arrayBuffer()) : response.json();
626
+ };
627
+ }
628
+
629
+ async function pages(call, path) {
630
+ const found = [];
631
+ for (let page = 1; page <= 10; page++) {
632
+ const batch = await call(
633
+ 'GET',
634
+ `${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`
635
+ );
636
+ const items = Array.isArray(batch) ? batch : (batch.artifacts ?? []);
637
+ found.push(...items);
638
+ if (items.length < 100) break;
639
+ }
640
+ return found;
641
+ }
642
+
643
+ function shards(dir) {
644
+ return globSync(`${dir}/**/*.flaky.json`)
645
+ .sort()
646
+ .map((json) => {
647
+ const record = JSON.parse(readFileSync(json, 'utf8'));
648
+ const first = load(firstReports(dirname(json), basename(json, '.flaky.json')), record.root);
649
+ return { record, first };
650
+ });
651
+ }
652
+
653
+ async function failedBefore(call, ctx) {
654
+ const artifacts = await pages(call, `repos/${ctx.repo}/actions/runs/${ctx.run}/artifacts`);
655
+ const failed = new Map();
656
+ for (const artifact of artifacts) {
657
+ const attempt = Number(/^failed-.+-(\d+)$/.exec(artifact.name)?.[1]);
658
+ if (artifact.expired || !(attempt < ctx.attempt)) continue;
659
+ const zip = await call('GET', `repos/${ctx.repo}/actions/artifacts/${artifact.id}/zip`);
660
+ for (const [, text] of unzip(zip)) {
661
+ const list = JSON.parse(text);
662
+ for (const test of list.failed) {
663
+ if ((failed.get(test.key)?.from ?? 0) < list.attempt)
664
+ failed.set(test.key, { ...test, from: list.attempt });
665
+ }
666
+ }
667
+ }
668
+ return failed;
669
+ }
670
+
671
+ async function earlier(call, ctx, found, given) {
672
+ if (ctx.attempt <= 1) return [];
673
+ const failed = await failedBefore(call, ctx);
674
+ const flips = [];
675
+ for (const { record, first } of found) {
676
+ for (const test of first.values()) {
677
+ const before = failed.get(key(test));
678
+ if (!before || statusOf(test) !== 'pass' || record.attempt <= before.from) continue;
679
+ const kind = category(test, given);
680
+ flips.push({
681
+ ...before,
682
+ kind: kind === 'strict' || kind === 'changed' ? kind : 'manual',
683
+ manual: true,
684
+ attempt: record.attempt,
685
+ shard: record.shard,
686
+ runner: record.runner,
687
+ sha: record.sha,
688
+ });
689
+ }
690
+ }
691
+ return flips;
692
+ }
693
+
694
+ function quietReason(ctx, found) {
695
+ const glob = ctx.quiet.find((pattern) => matchesGlob(ctx.branch, pattern));
696
+ if (glob) return `quiet branch (${glob})`;
697
+ const broken = found.some(
698
+ ({ record }) => record.skipped || record.rows.some((entry) => entry.kind === 'failure')
699
+ );
700
+ if (ctx.event === 'pull_request' && broken) return 'the run also has real failures';
701
+ return '';
702
+ }
703
+
704
+ async function labels(call, ctx) {
705
+ for (const [name, color, description] of LABELS) {
706
+ await call('POST', `repos/${ctx.repo}/labels`, { name, color, description }).catch((error) => {
707
+ if (error.status !== 422) throw error;
708
+ });
709
+ }
710
+ }
711
+
712
+ function keyOf(issue) {
713
+ return /Key: `([0-9a-f]{16})`/.exec(issue.body ?? '')?.[1];
714
+ }
715
+
716
+ async function recur(call, ctx, flip, issue, closed) {
717
+ const text = comment(flip, ctx);
718
+ const secret = carriesSecret(text, [ctx.token]);
719
+ if (secret) return `not posted: it carries ${secret}`;
720
+ const path = `repos/${ctx.repo}/issues/${issue.number}`;
721
+ const names = issue.labels.map((label) => (typeof label === 'string' ? label : label.name));
722
+ const reset = withClean(issue.body, 0);
723
+ if (closed || reset !== (issue.body ?? '')) {
724
+ await call('PATCH', path, { ...(closed ? { state: 'open' } : {}), body: reset });
725
+ }
726
+ await call('POST', `${path}/comments`, { body: text });
727
+ const commit = /^- Commit: (\S+)/m.exec(issue.body ?? '')?.[1];
728
+ if (names.includes('new') && commit && commit !== flip.sha) {
729
+ await call('DELETE', `${path}/labels/new`).catch((error) => {
730
+ if (error.status !== 404) throw error;
731
+ });
732
+ }
733
+ if (flip.strict && !names.includes('guard'))
734
+ await call('POST', `${path}/labels`, { labels: ['guard'] });
735
+ return `#${issue.number}${closed ? ' (reopened)' : ''}`;
736
+ }
737
+
738
+ async function create(call, ctx, flip) {
739
+ const name = title(flip);
740
+ const text = body(flip, ctx);
741
+ const secret = carriesSecret(`${name}\n${text}`, [ctx.token]);
742
+ if (secret) return `not posted: it carries ${secret}`;
743
+ const created = await call('POST', `repos/${ctx.repo}/issues`, {
744
+ title: name,
745
+ body: text,
746
+ labels: [LABEL, 'new', ...(flip.strict ? ['guard'] : [])],
747
+ });
748
+ return `#${created.number} (new)`;
749
+ }
750
+
751
+ async function sweep(call, ctx, open, touched, passing) {
752
+ const today = new Date(ctx.now).toISOString().slice(0, 10);
753
+ for (const issue of open) {
754
+ const id = keyOf(issue);
755
+ if (!id || touched.has(issue.number) || !passing.has(id)) continue;
756
+ const { count, since = today } = clean(issue.body);
757
+ const next = withClean(issue.body, count + 1, since);
758
+ const path = `repos/${ctx.repo}/issues/${issue.number}`;
759
+ if (count + 1 < ctx.closeAfter) {
760
+ await call('PATCH', path, { body: next });
761
+ continue;
762
+ }
763
+ await call('POST', `${path}/comments`, {
764
+ body: `no flip in ${ctx.closeAfter} clean merge-group runs since ${since}; a new flip reopens it`,
765
+ });
766
+ await call('PATCH', path, { body: next, state: 'closed', state_reason: 'completed' });
767
+ console.log(`flaky: closed #${issue.number} after ${ctx.closeAfter} clean merge-group runs`);
768
+ }
769
+ }
770
+
771
+ async function file(call, ctx, flips, passing) {
772
+ const notes = new Map();
773
+ const listed = (state) =>
774
+ pages(
775
+ call,
776
+ `repos/${ctx.repo}/issues?labels=${LABEL}&state=${state}${state === 'closed' ? `&since=${new Date(ctx.now - 30 * DAY).toISOString()}` : ''}`
777
+ );
778
+ const open = (await listed('open')).filter((issue) => !issue.pull_request);
779
+ const cutoff = ctx.now - 30 * DAY;
780
+ const closed = (await listed('closed')).filter(
781
+ (issue) => !issue.pull_request && Date.parse(issue.closed_at) >= cutoff
782
+ );
783
+ const find = (list, id) => list.find((issue) => keyOf(issue) === id);
784
+ const plan = flips.map((flip) => ({
785
+ flip,
786
+ open: find(open, flip.key),
787
+ closed: find(closed, flip.key),
788
+ }));
789
+ const fresh = plan.filter((entry) => !entry.open && !entry.closed).length;
790
+ if (fresh > CAP) {
791
+ const line = `flaky: ${flips.length} flips in one run, not filing (infrastructure?)`;
792
+ console.log(line);
793
+ for (const flip of flips) notes.set(flip.key, 'not filed: too many flips in one run');
794
+ return { notes, line };
795
+ }
796
+ if (fresh > 0) await labels(call, ctx);
797
+ const touched = new Set();
798
+ for (const entry of plan) {
799
+ const issue = entry.open ?? entry.closed;
800
+ if (issue) touched.add(issue.number);
801
+ const note = issue
802
+ ? await recur(call, ctx, entry.flip, issue, !entry.open)
803
+ : await create(call, ctx, entry.flip);
804
+ notes.set(entry.flip.key, note);
805
+ console.log(`flaky: ${title(entry.flip)}: ${note}`);
806
+ }
807
+ if (ctx.event === 'merge_group') await sweep(call, ctx, open, touched, passing);
808
+ return { notes, line: '' };
809
+ }
810
+
811
+ function cell(text) {
812
+ return String(text)
813
+ .replace(/\|/g, '\\|')
814
+ .replace(/\s*\n\s*/g, ' ');
815
+ }
816
+
817
+ export function table(entries, notes, lines) {
818
+ const head = ['### Flaky tests', '', ...lines.filter(Boolean).flatMap((line) => [line, ''])];
819
+ if (entries.length === 0) return [...head, 'No flips or failures.', ''].join('\n');
820
+ return [
821
+ ...head,
822
+ '| Test | Shard | Outcome | Issue |',
823
+ '|---|---|---|---|',
824
+ ...entries.map(
825
+ (entry) =>
826
+ `| ${cell(`\`${entry.file}\` › ${entry.name}`)} | ${cell(entry.shard)} | ${cell(describe(entry, entry.reason))} | ${cell(notes.get(entry.key) ?? '')} |`
827
+ ),
828
+ '',
829
+ ].join('\n');
830
+ }
831
+
832
+ function reportContext(env) {
833
+ const ref = env.GITHUB_REF_NAME ?? '';
834
+ return {
835
+ api: env.GITHUB_API_URL || 'https://api.github.com',
836
+ server: env.GITHUB_SERVER_URL || 'https://github.com',
837
+ repo: env.GITHUB_REPOSITORY,
838
+ run: env.GITHUB_RUN_ID,
839
+ attempt: Number(env.GITHUB_RUN_ATTEMPT || 1),
840
+ event: env.GITHUB_EVENT_NAME,
841
+ branch: env.GITHUB_HEAD_REF || ref,
842
+ pr: env.PR || /\/pr-(\d+)-/.exec(ref)?.[1] || '',
843
+ token: env.GH_TOKEN ?? '',
844
+ quiet: globs(env.QUIET),
845
+ closeAfter: Number(env.CLOSE_AFTER || 20),
846
+ now: Date.now(),
847
+ };
848
+ }
849
+
850
+ function collect(found, ctx) {
851
+ const entries = [];
852
+ const passing = new Set();
853
+ for (const { record, first } of found) {
854
+ for (const test of first.values()) if (statusOf(test) === 'pass') passing.add(key(test));
855
+ if (record.attempt !== ctx.attempt) continue;
856
+ for (const entry of record.rows) {
857
+ if (entry.kind === 'pass') continue;
858
+ entries.push({
859
+ ...entry,
860
+ shard: record.shard,
861
+ attempt: record.attempt,
862
+ runner: record.runner,
863
+ sha: record.sha,
864
+ reason: record.skipped,
865
+ strict: entry.kind === 'strict',
866
+ });
867
+ }
868
+ }
869
+ for (const entry of entries) if (entry.kind !== 'failure') passing.delete(entry.key);
870
+ return { entries, passing };
871
+ }
872
+
873
+ export async function report(env = process.env, dir = 'junit') {
874
+ const ctx = reportContext(env);
875
+ const given = rules(env);
876
+ const found = shards(dir);
877
+ const { entries, passing } = collect(found, ctx);
878
+ const call = client(ctx);
879
+ const lines = [];
880
+ let notes = new Map();
881
+ try {
882
+ const seen = new Set(entries.map((entry) => entry.key));
883
+ for (const flip of ctx.token ? await earlier(call, ctx, found, given) : []) {
884
+ if (seen.has(flip.key)) continue;
885
+ seen.add(flip.key);
886
+ entries.push({ ...flip, strict: flip.kind === 'strict' });
887
+ passing.delete(flip.key);
888
+ }
889
+ const flips = entries.filter((entry) => entry.kind !== 'failure');
890
+ const reportable = flips.filter((entry) => entry.kind !== 'changed');
891
+ for (const entry of flips)
892
+ if (entry.kind === 'changed') notes.set(entry.key, 'not filed: the PR changes this test');
893
+ const quiet = quietReason(ctx, found);
894
+ if (!ctx.token) lines.push('flaky: no token, nothing filed');
895
+ else if (quiet) {
896
+ lines.push(`flaky: not filing: ${quiet}`);
897
+ for (const flip of reportable) notes.set(flip.key, `not filed: ${quiet}`);
898
+ } else if (reportable.length > 0 || ctx.event === 'merge_group') {
899
+ const filed = await file(call, ctx, reportable, passing);
900
+ notes = new Map([...notes, ...filed.notes]);
901
+ lines.push(filed.line);
902
+ }
903
+ } catch (error) {
904
+ const line =
905
+ error.status === 403
906
+ ? 'flaky: no issues: write, so nothing more was filed'
907
+ : `flaky: GitHub API failed, so nothing more was filed (${error.message.split('\n')[0]})`;
908
+ lines.push(line);
909
+ console.log(`::warning title=Flaky::${line}`);
910
+ }
911
+ const text = table(entries, notes, lines);
912
+ console.log(text);
913
+ if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, text);
914
+ return 0;
915
+ }
916
+
917
+ export async function main(argv = process.argv.slice(2), env = process.env) {
918
+ const [mode] = argv;
919
+ if (mode === 'retry') return retry(env);
920
+ if (mode === 'verdict') return verdict(env);
921
+ if (mode === 'report') return report(env);
922
+ console.error('usage: slicc-flaky retry|verdict|report');
923
+ return 2;
924
+ }
925
+
926
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
927
+ process.exitCode = await main();
928
+ }
@@ -4,6 +4,7 @@ import { cwd } from 'node:process';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import * as mcrUtil from 'monocart-coverage-reports/util';
6
6
  import { CRASHED } from './cdp.mjs';
7
+ import { targetLog } from './targets.mjs';
7
8
  import { trace } from './trace.mjs';
8
9
  import { bounded, ignore, raw, samples, sleep, TIMED_OUT } from './util.mjs';
9
10
 
@@ -243,6 +244,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
243
244
  const parents = new Map();
244
245
  const tabs = new Map();
245
246
  const early = [];
247
+ const targets = targetLog(cdp);
246
248
  const own = ownership(parents);
247
249
  const ours = covered(server, coverage);
248
250
  let run = null;
@@ -285,16 +287,12 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
285
287
  const list = commands(targetInfo, { coverage, exits, profiling });
286
288
  if (waitingForDebugger) list.push(['Runtime.runIfWaitingForDebugger']);
287
289
  const ready = Promise.all(
288
- list.map(([method, params]) => cdp.send(method, params, sessionId).catch(ignore))
290
+ list.map(([method, params]) => targets.send(method, params, sessionId))
289
291
  );
290
292
  if (targetInfo.type === 'page') tab(targetInfo.targetId).resolve(ready.then(() => sessionId));
291
293
  return ready;
292
294
  }
293
295
 
294
- function resume(sessionId) {
295
- return cdp.send('Runtime.runIfWaitingForDebugger', {}, sessionId).catch(ignore);
296
- }
297
-
298
296
  function log(sessionId, line) {
299
297
  const target = sessions.get(sessionId);
300
298
  const into = destination(run, target, early);
@@ -333,7 +331,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
333
331
  async function lifecycle({ method, params, sessionId }) {
334
332
  if (method === 'Target.attachedToTarget') {
335
333
  if (own.adopt(params, sessionId)) await attach(params);
336
- else if (own.ours(params.sessionId)) await resume(params.sessionId);
334
+ else if (own.ours(params.sessionId)) await targets.resume(params.sessionId);
337
335
  }
338
336
  if (method === 'Target.detachedFromTarget') {
339
337
  sessions.delete(params.sessionId);
@@ -341,7 +339,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
341
339
  own.drop(params.sessionId);
342
340
  }
343
341
  const restarted = method === 'Inspector.targetReloadedAfterCrash';
344
- if (restarted && own.ours(sessionId)) await resume(sessionId);
342
+ if (restarted && own.ours(sessionId)) await targets.resume(sessionId);
345
343
  }
346
344
 
347
345
  cdp.on(async ({ method, params, sessionId }) => {
@@ -378,6 +376,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
378
376
  }
379
377
 
380
378
  function begin(context, dir, name) {
379
+ targets.begin();
381
380
  run = {
382
381
  context,
383
382
  dir,
@@ -401,6 +400,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
401
400
  await mkdir(raw, { recursive: true });
402
401
  await mkdir(samples, { recursive: true });
403
402
  await Promise.all([
403
+ writeFile(new URL('targets.log', current.dir), targets.text()),
404
404
  writeFile(new URL(`${current.name}.json`, raw), JSON.stringify(entries.filter(Boolean))),
405
405
  writeFile(new URL(`${current.name}.json`, samples), JSON.stringify(found)),
406
406
  writeFile(
@@ -0,0 +1,59 @@
1
+ const events = new Set([
2
+ 'Target.targetCreated',
3
+ 'Target.targetInfoChanged',
4
+ 'Target.targetDestroyed',
5
+ 'Target.attachedToTarget',
6
+ 'Target.detachedFromTarget',
7
+ 'Page.windowOpen',
8
+ 'Page.frameNavigated',
9
+ 'Page.loadEventFired',
10
+ 'Network.loadingFailed',
11
+ ]);
12
+
13
+ export function targetLog(cdp) {
14
+ const sessions = new Map();
15
+ let lines = [];
16
+ const log = (event) => lines.push(JSON.stringify({ at: new Date().toISOString(), ...event }));
17
+ const resume = (sessionId, state, error) => {
18
+ const result = { at: new Date().toISOString(), state, error: error?.message };
19
+ const attached = sessions.get(sessionId);
20
+ if (attached) attached.resume = result;
21
+ log({ method: 'Runtime.runIfWaitingForDebugger', sessionId, ...result });
22
+ };
23
+ cdp.on(({ method, params, sessionId }) => {
24
+ if (method === 'Target.attachedToTarget') {
25
+ sessions.set(params.sessionId, { ...params, parent: sessionId });
26
+ }
27
+ if (method === 'Target.detachedFromTarget') sessions.delete(params.sessionId);
28
+ if (method === 'Target.targetInfoChanged') {
29
+ for (const attached of sessions.values()) {
30
+ if (attached.targetInfo.targetId === params.targetInfo.targetId) {
31
+ attached.targetInfo = params.targetInfo;
32
+ }
33
+ }
34
+ }
35
+ if (events.has(method)) log({ method, sessionId, params });
36
+ });
37
+ async function send(method, params, sessionId) {
38
+ const waiting = method === 'Runtime.runIfWaitingForDebugger';
39
+ if (waiting) resume(sessionId, 'sent');
40
+ try {
41
+ const result = await cdp.send(method, params, sessionId);
42
+ if (waiting) resume(sessionId, 'answered');
43
+ return result;
44
+ } catch (error) {
45
+ if (waiting) resume(sessionId, 'failed', error);
46
+ else log({ method, sessionId, state: 'failed', error: error.message });
47
+ return null;
48
+ }
49
+ }
50
+ return {
51
+ send,
52
+ resume: (sessionId) => send('Runtime.runIfWaitingForDebugger', {}, sessionId),
53
+ begin() {
54
+ lines = [];
55
+ for (const params of sessions.values()) log({ method: 'Harness.existingSession', params });
56
+ },
57
+ text: () => lines.map((line) => `${line}\n`).join(''),
58
+ };
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "2.12.3",
3
+ "version": "2.13.0",
4
4
  "description": "Shared Renovate, Biome, TypeScript, lefthook and GitHub Actions configuration, plus the CDP integration-test harness, for SLICC's web repos",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -35,6 +35,7 @@
35
35
  "bin": {
36
36
  "slicc-agents-md": "bin/slicc-agents-md.sh",
37
37
  "slicc-diff-cover": "bin/slicc-diff-cover.sh",
38
+ "slicc-flaky": "bin/slicc-flaky.mjs",
38
39
  "slicc-install-hooks": "bin/slicc-install-hooks.mjs",
39
40
  "slicc-lint": "bin/slicc-lint.sh",
40
41
  "slicc-lint-comments": "bin/slicc-lint-comments.sh",
@@ -66,8 +67,8 @@
66
67
  "release": "semantic-release"
67
68
  },
68
69
  "devDependencies": {
69
- "@ai-ecoverse/slicc-browsers": "1.18.14",
70
- "@ai-ecoverse/slicc-cdp": "1.41.12",
70
+ "@ai-ecoverse/slicc-browsers": "1.18.15",
71
+ "@ai-ecoverse/slicc-cdp": "1.41.21",
71
72
  "@biomejs/biome": "2.5.15",
72
73
  "lefthook": "2.2.2",
73
74
  "monocart-coverage-reports": "2.13.2",