:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): pin which CI jobs run per PR, push, and schedule scenario (#97423)
Georges-Antoine Assi967191be5fcc
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex be83705ed72f..c8e83e7ca397 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -31,6 +31,23 @@ Run `bin/hogli lint:workflows` and `actionlint` before pushing — they gate CI,Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, secrets a reusable workflow reads being declared and passed by its callers, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).Third-party action digests are bumped by Renovate.+## Check what a condition does before you push it++The linters check the shape of an `if:`; `tools/workflow-plan` checks what it does.+It evaluates every job and step condition with GitHub's own expression evaluator against a synthetic draft PR, ready PR, fork PR, merge-queue run, master push, hourly schedule, and manual dispatch, and prints which jobs run:++```bash+hogli ci:plan .github/workflows/ci-backend.yml # one row per job, one column per scenario+hogli ci:plan .github/workflows/ci-backend.yml --steps changes+hogli test:workflows # the pinned expectations, run in ci-lint-workflows+```++`tools/workflow-plan/tests/workflows.test.ts` pins the rules in this file as `runs` / `skipped` rows per scenario: drafts skip the product matrix, the queue takes the full one, forks skip telemetry, a `no-ci` draft still reports its gate, the hourly run takes the matrices and skips the PR-only checks, and a superseded run records the gate as `cancelled`.+Every job in those two workflows that carries an `if:` must be named by at least one row, which a coverage test enforces: add a conditional job and the suite fails until a row says what it should do.+When you change a condition in `ci-backend.yml` or `ci-frontend.yml`, run the suite and update the row that describes the behavior you changed; when you add a lever to another heavy suite, add rows for it.+The planner stubs the paths filter as "everything changed" and knows nothing a `run:` body produces, so a scenario stubs selector outputs by step id.+It does not model trigger `paths:`, concurrency, or matrix expansion beyond a cell count; see [the README](../../../tools/workflow-plan/README.md).+## The dispatch budget (500 runs / 10s / repo)GitHub caps _workflow-run dispatch_ at 500 runs per 10s per repo; overflow fails as `startup_failure` and takes unrelated runs in the same window down with it (a stack restack pushing many branches is the usual trigger).diff --git a/.github/workflows/ci-lint-workflows.yml b/.github/workflows/ci-lint-workflows.ymlindex bf515357dcf5..8656b439c441 100644--- a/.github/workflows/ci-lint-workflows.yml+++ b/.github/workflows/ci-lint-workflows.yml@@ -7,6 +7,7 @@ on:- .github/actions/**- services/**- tools/hogli-commands/hogli_commands/workflow_lint/**+ - tools/workflow-plan/**- hogli.yamlconcurrency:@@ -36,3 +37,28 @@ jobs:- name: Lint workflowsrun: ./bin/hogli lint:workflows++ workflow-run-plans:+ name: Workflow run plans+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false+ sparse-checkout: |+ .github+ tools/workflow-plan+ patches+ .nvmrc+ package.json+ pnpm-lock.yaml+ pnpm-workspace.yaml+ sparse-checkout-cone-mode: false++ - uses: ./.github/actions/pnpm-install+ with:+ install-command: pnpm install --frozen-lockfile --filter @posthog/workflow-plan++ - name: Check job and step conditions against the pinned run plans+ run: pnpm --filter @posthog/workflow-plan testdiff --git a/hogli.yaml b/hogli.yamlindex 687455f6477e..74570cc85bcf 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -792,6 +792,9 @@ tests:test:e2e:bin_script: e2e-test-runnerdescription: Set up test databases and run Playwright E2E tests+ test:workflows:+ cmd: pnpm --filter @posthog/workflow-plan test+ description: Check which jobs of .github/workflows run per PR/push/schedule scenario against the pinned expectationstest:quarantine:click: hogli_commands.quarantine.cli:quarantinedescription: Manage .test_quarantine.json — quarantine flaky tests so they stop blocking CI@@ -1057,6 +1060,9 @@ tools:ci:preflight:click: hogli_commands.ci_preflight:ci_preflightdescription: Catch deterministic CI failures reachable from your diff before you push (advisory; --fix, --strict)+ ci:plan:+ cmd: pnpm --filter @posthog/workflow-plan --silent plan+ description: Show which jobs (or --steps <job>) of a workflow file run on a draft, ready, or fork PR, the merge queue, a master push, schedule, and dispatchdesktop:desktop:dev:cmd: pnpm --dir products/desktop devdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0ccb6a4e8d43..32bde9e8eb9b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -519,7 +519,7 @@ importers:version: 5.3.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))mockdate:specifier: ^3.0.5version: 3.0.5@@ -1979,7 +1979,7 @@ importers:version: 3.6.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))storybook:specifier: 'catalog:'version: 10.4.6(@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -2408,7 +2408,7 @@ importers:version: 8.57.0jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])@@ -3608,7 +3608,7 @@ importers:version: 2.1.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])@@ -4926,7 +4926,7 @@ importers:version: 1.2.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])@@ -5493,12 +5493,38 @@ importers:specifier: ^4.1.0version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ tools/workflow-plan:+ dependencies:+ '@actions/expressions':+ specifier: 0.3.61+ version: 0.3.61+ js-yaml:+ specifier: ^4.1.0+ version: 4.1.1+ devDependencies:+ '@types/js-yaml':+ specifier: ^4.0.9+ version: 4.0.9+ '@types/node':+ specifier: ^24.0.0+ version: 24.13.3+ typescript:+ specifier: 6.0.3+ version: 6.0.3+ vitest:+ specifier: ^4.1.0+ version: 4.1.8(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages:'@aashutoshrathi/[email protected]':resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==}engines: {node: '>=0.10.0'}+ '@actions/[email protected]':+ resolution: {integrity: sha512-Ig+tXELvTjlqxQAWBQnLNn2dPpNraLMdSnT+vDzDPmJtbNUhIAH/Z9kVT8pZ8UtJi9vUGs8hwHE8JFJmbOnLEA==}+ engines: {node: '>= 20'}+'@adobe/[email protected]':resolution: {integrity: sha512-+u76oB43nOHrF4DDWRLWDCtci7f3QJoEBigemIdIeTi1ODqjx6Tad9NCVnPRwewWlKkVab5PlK8DCtPTyX7S8g==}@@ -13200,6 +13226,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-XTYugzhuwqWjws0CVz8QpM36+T+Dz5mTEBKhNs/esGLnCIlGdRy+Dq78NRjd7ls7r8BC8ZRMOrKlkO1hU0JOwA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==}+'@types/[email protected]':resolution: {integrity: sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==}@@ -13314,6 +13343,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-pAZSHMiagDR7cARo/cch1f3rXy0AEXwsVsVH09FcyeJVAzCnGgmYis7P3JidtTUjyadhTeSo8TgRPswstghDaw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}+'@types/[email protected]':resolution: {integrity: sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ==}@@ -22761,6 +22793,9 @@ packages:resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}+ resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}+resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}@@ -23643,6 +23678,8 @@ snapshots:'@aashutoshrathi/[email protected]': {}+ '@actions/[email protected]': {}+'@adobe/[email protected]': {}'@adobe/[email protected]': {}@@ -27081,6 +27118,14 @@ snapshots:optionalDependencies:'@types/node': 22.18.8+ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/core': 11.2.1(@types/[email protected])+ '@inquirer/type': 4.0.7(@types/[email protected])+ optionalDependencies:+ '@types/node': 24.13.3+ optional: true+'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/core': 11.2.1(@types/[email protected])@@ -27100,6 +27145,19 @@ snapshots:optionalDependencies:'@types/node': 22.18.8+ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/ansi': 2.0.7+ '@inquirer/figures': 2.0.7+ '@inquirer/type': 4.0.7(@types/[email protected])+ cli-width: 4.1.0+ fast-wrap-ansi: 0.2.2+ mute-stream: 3.0.0+ signal-exit: 4.1.0+ optionalDependencies:+ '@types/node': 24.13.3+ optional: true+'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/ansi': 2.0.7@@ -27118,6 +27176,11 @@ snapshots:optionalDependencies:'@types/node': 22.18.8+ '@inquirer/[email protected](@types/[email protected])':+ optionalDependencies:+ '@types/node': 24.13.3+ optional: true+'@inquirer/[email protected](@types/[email protected])':optionalDependencies:'@types/node': 25.8.0@@ -27281,7 +27344,7 @@ snapshots:- supports-color- ts-node+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27296,7 +27359,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -27317,7 +27380,7 @@ snapshots:- supports-color- ts-node- '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -27332,7 +27395,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -33144,6 +33207,8 @@ snapshots:expect: 30.0.5pretty-format: 30.0.5+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/node': 22.18.8@@ -33266,6 +33331,10 @@ snapshots:dependencies:undici-types: 6.21.0+ '@types/[email protected]':+ dependencies:+ undici-types: 7.18.2+'@types/[email protected]':dependencies:undici-types: 7.24.6@@ -33837,6 +33906,15 @@ snapshots:msw: 2.14.6(@types/[email protected])([email protected])vite: 8.1.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 4.1.8+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+ msw: 2.14.6(@types/[email protected])([email protected])+ vite: 8.1.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+'@vitest/[email protected]([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 4.1.8@@ -36582,7 +36660,7 @@ snapshots:imurmurhash: 0.1.4is-glob: 4.0.3is-path-inside: 3.0.3- js-yaml: 4.1.0+ js-yaml: 4.1.1json-stable-stringify-without-jsonify: 1.0.1levn: 0.4.1lodash.merge: 4.6.2@@ -38457,15 +38535,15 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38476,15 +38554,15 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5([email protected]([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38622,7 +38700,7 @@ snapshots:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38651,11 +38729,12 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38684,7 +38763,7 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -38722,7 +38801,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38750,12 +38829,13 @@ snapshots:strip-json-comments: 3.1.1optionalDependencies:'@types/node': 25.8.0+ esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38782,7 +38862,8 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- esbuild-register: 3.6.0([email protected])+ '@types/node': 25.8.0transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -39677,12 +39758,12 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -39690,12 +39771,12 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5([email protected]([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -41162,6 +41243,32 @@ snapshots:transitivePeerDependencies:- '@types/node'+ dependencies:+ '@inquirer/confirm': 6.1.1(@types/[email protected])+ '@mswjs/interceptors': 0.41.3+ '@open-draft/deferred-promise': 3.0.0+ '@types/statuses': 2.0.6+ cookie: 1.1.1+ graphql: 16.13.2+ headers-polyfill: 5.0.1+ is-node-process: 1.2.0+ outvariant: 1.4.3+ path-to-regexp: 6.3.0+ picocolors: 1.1.1+ rettime: 0.11.11+ statuses: 2.0.2+ strict-event-emitter: 0.5.1+ tough-cookie: 6.0.1+ type-fest: 5.5.0+ until-async: 3.0.2+ yargs: 17.7.2+ optionalDependencies:+ typescript: 6.0.3+ transitivePeerDependencies:+ - '@types/node'+ optional: true+dependencies:'@inquirer/confirm': 6.1.1(@types/[email protected])@@ -45570,6 +45677,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -45975,6 +46084,24 @@ snapshots:tsx: 4.20.5yaml: 2.9.0+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ lightningcss: 1.32.0+ picomatch: 4.0.4+ postcss: 8.5.16+ rolldown: 1.1.4+ tinyglobby: 0.2.17+ optionalDependencies:+ '@types/node': 24.13.3+ esbuild: 0.28.1+ fsevents: 2.3.3+ jiti: 2.6.1+ less: 4.2.2+ sass-embedded: 1.70.0+ terser: 5.46.0+ tsx: 4.20.5+ yaml: 2.9.0+[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0@@ -46085,6 +46212,36 @@ snapshots:transitivePeerDependencies:- msw+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ dependencies:+ '@vitest/expect': 4.1.8+ '@vitest/mocker': 4.1.8([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 4.1.8+ '@vitest/runner': 4.1.8+ '@vitest/snapshot': 4.1.8+ '@vitest/spy': 4.1.8+ '@vitest/utils': 4.1.8+ es-module-lexer: 2.0.0+ expect-type: 1.3.0+ magic-string: 0.30.21+ obug: 2.1.2+ pathe: 2.0.3+ picomatch: 4.0.4+ std-env: 4.1.0+ tinybench: 2.9.0+ tinyexec: 1.1.2+ tinyglobby: 0.2.16+ tinyrainbow: 3.1.0+ vite: 8.1.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@opentelemetry/api': 1.9.0+ '@types/node': 24.13.3+ happy-dom: 20.9.0+ jsdom: 20.0.3+ transitivePeerDependencies:+ - msw+[email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.8diff --git a/tools/workflow-plan/README.md b/tools/workflow-plan/README.mdnew file mode 100644index 000000000000..40e1846b28fd--- /dev/null+++ b/tools/workflow-plan/README.md@@ -0,0 +1,57 @@+# workflow-plan++Evaluates the `if:` conditions in `.github/workflows/*.yml` the way GitHub does, against synthetic PR, push, schedule, and cancellation scenarios, and reports which jobs and steps run.+The evaluator is GitHub's own [`@actions/expressions`](https://www.npmjs.com/package/@actions/expressions), so operator precedence, coercion, `contains`, `fromJSON`, and the `labels.*.name` filter syntax behave as they do in Actions.++## See a workflow's run plan++```bash+hogli ci:plan .github/workflows/ci-backend.yml+hogli ci:plan .github/workflows/ci-backend.yml --steps changes+```++The table has one row per job and one column per built-in scenario: `draft`, `ready`, and `fork` pull requests, a `queued` merge-queue run, a `merged` push to master, a `scheduled` run, and a `dispatched` run.+A cell reads `▶` for a job that runs, `✗` for one that fails, `⊘` for one that is cancelled, and `.` for a skipped job; a trailing `0` marks a matrix that expands to no cells. A job with `continue-on-error: true` that fails shows `✗`, while its dependents read `needs.<job>.result` as `success`, as on GitHub. A legend under the table repeats this.+In a terminal the header row is bold and every second row has a shaded background; set `NO_COLOR` to turn that off.+Every paths filter is stubbed as if all of its filters matched.+Outputs that scripts produce at runtime are empty, so a job gated on `needs.x.outputs.matrix != ''` shows as skipped and a matrix built from such an output has no cell count.+Where a workflow cannot be planned without such a value, `SCRIPT_STUBS` in `src/scenarios.ts` supplies it per workflow path: the release plan output, and the Depot shadow's sampling variable and dice roll so `.depot/workflows/ci-backend.yml` plans as sampled in.++## Pin the intended behavior in a test++```bash+hogli test:workflows+```++`tests/workflows.test.ts` holds one row per workflow and scenario, naming the jobs that must run and the jobs that must skip.+The rows encode the rules in [the authoring skill](../../.agents/skills/authoring-ci-workflows/SKILL.md): drafts skip the product matrix, the merge queue takes the full one, forks skip telemetry, a `no-ci` draft still reports its gate, the hourly schedule runs the matrices and skips the PR-only checks, and a superseded run records its gate as `cancelled` rather than `failure`.+A coverage test keeps those rows exhaustive: every job in `ci-backend.yml` and `ci-frontend.yml` that carries an `if:` must be named by at least one row, so a new conditional job fails the suite until someone states what it should do.+A smoke test also feeds every workflow through the built-in scenarios and fails on any condition the evaluator rejects.++Add a row when you add or change a condition.+A row needs three things:++```ts+backend(+ { name: 'draft PR', github: pullRequest({ draft: true }) },+ {+ runs: ['changes', 'django', 'django_tests'],+ skipped: ['turbo-tests'],+ }+)+```++- `github`: the event, from `pullRequest()`, `mergeQueue()`, `push()`, `schedule()`, or `workflowDispatch()` in `src/scenarios.ts`.+- `steps`: stubbed step outputs by job id and step id (or step name), for the paths filter and selector scripts. `allFiltersChanged(workflow)` stubs every filter as matched; `pathsFilter({ backend: false })` narrows one.+- `runs`, `skipped`, `results`: the jobs to assert on. `results` takes the exact outcome, which is how a gate is checked for `cancelled` on a superseded run.++A cancelled run is modeled as cancelled before any job starts, except the jobs listed in `completedBeforeCancel`, which plan as if the run were live.+That is how the self-cancel in `ci-backend.yml` is tested: `repo-checks` completes with a failing step, the run cancels, and the gate still runs because its OR-ed `deterministic_failure` disjunct is true.++## What it does not model++- Trigger-level `on.<event>.paths`, `branches`, and `types` filters. A scenario assumes the workflow was dispatched.+- Concurrency groups and `cancel-in-progress`.+- Matrix expansion beyond a cell count, which the CLI prints as `0` when a job's matrix resolves to no cells.+- Anything a `run:` body does. Step outputs come only from stubs.+- Reusable-workflow calls are planned as one job. Stub their outputs with `jobOutputs`.diff --git a/tools/workflow-plan/package.json b/tools/workflow-plan/package.jsonnew file mode 100644index 000000000000..1178e071c22e--- /dev/null+++ b/tools/workflow-plan/package.json@@ -0,0 +1,23 @@+{+ "name": "@posthog/workflow-plan",+ "version": "0.0.0",+ "private": true,+ "description": "Evaluates GitHub Actions job and step conditions against PR, push, and schedule scenarios",+ "license": "MIT",+ "type": "module",+ "scripts": {+ "plan": "node src/cli.ts",+ "test": "vitest run",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@actions/expressions": "0.3.61",+ "js-yaml": "^4.1.0"+ },+ "devDependencies": {+ "@types/js-yaml": "^4.0.9",+ "@types/node": "^24.0.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.0"+ }+}diff --git a/tools/workflow-plan/src/cli.ts b/tools/workflow-plan/src/cli.tsnew file mode 100644index 000000000000..7fd5d0c4881a--- /dev/null+++ b/tools/workflow-plan/src/cli.ts@@ -0,0 +1,96 @@+import { existsSync } from 'node:fs'+import path from 'node:path'+import { parseArgs } from 'node:util'++import { loadWorkflow, planWorkflow } from './plan.ts'+import { type TableStyle, renderPlanTable, renderSteps } from './render.ts'+import { REPO_ROOT, defaultScenarios } from './scenarios.ts'++const USAGE = `Usage: hogli ci:plan <workflow.yml | workflow name> [--steps <job-id>]++Prints which jobs of the workflow run under each built-in scenario. --steps lists the+steps of one job instead. Every paths filter is stubbed as if all of its filters matched;+outputs that scripts produce are empty unless src/scenarios.ts stubs them for the workflow, so an+unstubbed matrix cannot be sized and a gate on one reads as skipped.`++const WORKFLOWS_DIR = path.join(REPO_ROOT, '.github/workflows')+const WORKFLOW_SUFFIXES = ['.yml', '.yaml']++// pnpm --filter runs this from the package directory; INIT_CWD is where the person typed the command.+function resolveWorkflowPath(argument: string): string | undefined {+ const fromInvocation = path.resolve(process.env['INIT_CWD'] ?? process.cwd(), argument)+ if (existsSync(fromInvocation)) {+ return fromInvocation+ }+ const hasSuffix = WORKFLOW_SUFFIXES.some((suffix) => argument.endsWith(suffix))+ const names = hasSuffix ? [argument] : WORKFLOW_SUFFIXES.map((suffix) => `${argument}${suffix}`)+ return names.map((name) => path.join(WORKFLOWS_DIR, name)).find(existsSync)+}++// COLORFGBG is "<fg>;<bg>"; ANSI background 7 or 15 means the terminal is light.+const LIGHT_TERMINAL = /;(7|15)$/++// Same shade phrocs uses for a selected row: ANSI black or white follows the terminal theme. Cursor and+// Zed map those to the default background, which would paint nothing, so they get an explicit RGB gray.+function selectionBackground(): string {+ const light = LIGHT_TERMINAL.test(process.env['COLORFGBG'] ?? '')+ const editorTerminal =+ !!process.env['CURSOR_TRACE_ID'] || process.env['TERM_PROGRAM'] === 'zed' || process.env['ZED_TERM'] === 'true'+ if (editorTerminal) {+ return light ? '\x1b[48;2;212;212;212m' : '\x1b[48;2;58;58;58m'+ }+ return light ? '\x1b[47m' : '\x1b[40m'+}++function tableStyle(): TableStyle | undefined {+ if (!process.stdout.isTTY || process.env['NO_COLOR']) {+ return undefined+ }+ const background = selectionBackground()+ return {+ header: (line) => `\x1b[1m${line}\x1b[0m`,+ stripe: (line) => `${background}${line}\x1b[0m`,+ }+}++function print(text: string): void {+ process.stdout.write(`${text}\n`)+}++function fail(message: string): number {+ process.stderr.write(`${message}\n`)+ return 2+}++function main(argv: string[]): number {+ const { values, positionals } = parseArgs({+ args: argv,+ options: { steps: { type: 'string' }, help: { type: 'boolean' } },+ allowPositionals: true,+ })+ const workflowArgument = positionals[0]+ if (values.help || !workflowArgument) {+ print(USAGE)+ return values.help ? 0 : 2+ }+ const workflowPath = resolveWorkflowPath(workflowArgument)+ if (workflowPath === undefined) {+ return fail(+ `no workflow ${workflowArgument} at that path or in ${path.relative(REPO_ROOT, WORKFLOWS_DIR)}\n\n${USAGE}`+ )+ }+ const workflow = loadWorkflow(workflowPath)+ const scenarioPlans = defaultScenarios(workflow, workflowPath).map((scenario) => ({+ scenario,+ plan: planWorkflow(workflow, scenario),+ }))+ const style = tableStyle()+ print(`\n${values.steps ? renderSteps(scenarioPlans, values.steps, style) : renderPlanTable(scenarioPlans, style)}`)+ return scenarioPlans.some(({ plan }) => plan.errors.length > 0) ? 1 : 0+}++try {+ process.exitCode = main(process.argv.slice(2))+} catch (error) {+ process.exitCode = fail(error instanceof Error ? error.message : String(error))+}diff --git a/tools/workflow-plan/src/expressions.ts b/tools/workflow-plan/src/expressions.tsnew file mode 100644index 000000000000..86416317f0b2--- /dev/null+++ b/tools/workflow-plan/src/expressions.ts@@ -0,0 +1,127 @@+import { Evaluator, Lexer, Parser, data, wellKnownFunctions } from '@actions/expressions'+import type { FunctionDefinition } from '@actions/expressions/funcs/info'+import { TokenType } from '@actions/expressions/lexer'+import { truthy } from '@actions/expressions/result'++export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }+export type Context = Record<string, JsonValue>+export type FunctionMap = Map<string, FunctionDefinition>++export interface StatusState {+ dependenciesSucceeded: boolean+ dependenciesFailed: boolean+ cancelled: boolean+}++export const CONTEXT_NAMES = [+ 'github',+ 'needs',+ 'vars',+ 'env',+ 'inputs',+ 'steps',+ 'secrets',+ 'runner',+ 'job',+ 'matrix',+ 'strategy',+]++// GitHub applies success() implicitly when an `if:` names no status function.+const STATUS_FUNCTIONS = new Set(['success', 'failure', 'cancelled', 'always'])+const WHOLE_EXPRESSION = /^\$\{\{([\s\S]*)\}\}$/+const EMBEDDED_EXPRESSION = /\$\{\{([\s\S]*?)\}\}/g++export const HASH_FILES_STUB = 'workflow-plan-stub-hash'++function booleanFunction(name: string, value: () => boolean): [string, FunctionDefinition] {+ return [name, { name, minArgs: 0, maxArgs: 0, call: () => new data.BooleanData(value()) }]+}++// An empty string is an output no script produced at plan time, so it resolves to null instead of failing.+const FROM_JSON_OR_NULL: FunctionDefinition = {+ name: 'fromJSON',+ minArgs: 1,+ maxArgs: 1,+ call: (...args) =>+ args[0]!.coerceString().trim() === '' ? new data.Null() : wellKnownFunctions['fromjson']!.call(...args),+}++export function planFunctions(state: StatusState): FunctionMap {+ return new Map<string, FunctionDefinition>([+ booleanFunction('success', () => state.dependenciesSucceeded && !state.cancelled),+ booleanFunction('failure', () => state.dependenciesFailed),+ booleanFunction('cancelled', () => state.cancelled),+ booleanFunction('always', () => true),+ [+ 'hashfiles',+ { name: 'hashFiles', minArgs: 1, maxArgs: 255, call: () => new data.StringData(HASH_FILES_STUB) },+ ],+ ['fromjson', FROM_JSON_OR_NULL],+ ])+}++export function evaluateExpression(expression: string, context: Context, functions: FunctionMap): data.ExpressionData {+ const tokens = new Lexer(expression).lex().tokens+ const ast = new Parser(tokens, CONTEXT_NAMES, [...functions.values()]).parse()+ const contextData = JSON.parse(JSON.stringify(context), data.reviver) as data.Dictionary+ return new Evaluator(ast, contextData, functions).evaluate()+}++function unwrapExpression(raw: string): string | undefined {+ return WHOLE_EXPRESSION.exec(raw.trim())?.[1]?.trim()+}++/** Evaluates a YAML value that may be one whole expression, a template, or a plain literal, keeping structure. */+export function evaluateValue(raw: unknown, context: Context, functions: FunctionMap): unknown {+ if (typeof raw !== 'string') {+ return raw+ }+ const expression = unwrapExpression(raw)+ if (expression !== undefined) {+ return JSON.parse(JSON.stringify(evaluateExpression(expression, context, functions), data.replacer))+ }+ if (!raw.includes('${{')) {+ return raw+ }+ const evaluated = evaluateTemplate(raw, context, functions)+ try {+ return JSON.parse(evaluated)+ } catch {+ return evaluated+ }+}++function namesStatusFunction(expression: string): boolean {+ const tokens = new Lexer(expression).lex().tokens+ return tokens.some(+ (token, index) =>+ token.type === TokenType.IDENTIFIER &&+ STATUS_FUNCTIONS.has(token.lexeme.toLowerCase()) &&+ tokens[index + 1]?.type === TokenType.LEFT_PAREN+ )+}++export function evaluateCondition(raw: unknown, context: Context, functions: FunctionMap): boolean {+ if (raw === undefined || raw === null) {+ return truthy(functions.get('success')!.call())+ }+ let expression = unwrapExpression(String(raw)) ?? String(raw).trim()+ if (!namesStatusFunction(expression)) {+ expression = `success() && (${expression})`+ }+ return truthy(evaluateExpression(expression, context, functions))+}++export function evaluateTemplate(raw: unknown, context: Context, functions: FunctionMap): string {+ if (typeof raw !== 'string') {+ return raw === undefined || raw === null ? '' : String(raw)+ }+ return raw.replace(EMBEDDED_EXPRESSION, (_, expression: string) =>+ evaluateExpression(expression.trim(), context, functions).coerceString()+ )+}++export function containsExpression(raw: unknown): boolean {+ return typeof raw === 'string' && raw.includes('${{')+}diff --git a/tools/workflow-plan/src/plan.ts b/tools/workflow-plan/src/plan.tsnew file mode 100644index 000000000000..89363a36f698--- /dev/null+++ b/tools/workflow-plan/src/plan.ts@@ -0,0 +1,361 @@+import { load } from 'js-yaml'+import { readFileSync } from 'node:fs'++import {+ type Context,+ type FunctionMap,+ type JsonValue,+ evaluateCondition,+ evaluateTemplate,+ evaluateValue,+ planFunctions,+} from './expressions.ts'++export type Outcome = 'success' | 'failure' | 'cancelled' | 'skipped'++export const WORKFLOW_SITE = '<workflow>'++export interface StepStub {+ outputs?: Record<string, string>+ outcome?: Outcome+}++export interface Scenario {+ name: string+ github: Context+ vars?: Record<string, string>+ /** Stubbed step results by job id, then step id (or name). Steps the plan skips lose their stubbed outputs. */+ steps?: Record<string, Record<string, StepStub>>+ /** Overrides a job's evaluated outputs, for reusable-workflow calls and script-driven outputs. */+ jobOutputs?: Record<string, Record<string, string>>+ /** The run was cancelled before any job started, except those in `completedBeforeCancel`. */+ cancelled?: boolean+ completedBeforeCancel?: readonly string[]+}++export interface RawStep {+ id?: string+ name?: string+ if?: unknown+ uses?: string+ run?: string+ env?: Record<string, unknown>+ with?: Record<string, unknown>+ 'continue-on-error'?: unknown+ parallel?: RawStep[]+}++export interface RawJob {+ name?: string+ if?: unknown+ needs?: string | string[]+ uses?: string+ env?: Record<string, unknown>+ outputs?: Record<string, unknown>+ steps?: RawStep[]+ strategy?: { matrix?: unknown }+ 'continue-on-error'?: unknown+}++export interface Workflow {+ name?: string+ on?: unknown+ env?: Record<string, unknown>+ jobs: Record<string, RawJob>+}++export interface StepPlan {+ index: number+ id: string | undefined+ name: string | undefined+ uses: string | undefined+ runs: boolean+}++export interface JobPlan {+ id: string+ outcome: Outcome+ result: Outcome+ outputs: Record<string, string>+ steps: StepPlan[]+ /** Number of matrix cells the job expands to; undefined when there is no matrix or it could not be evaluated. */+ matrixCells: number | undefined+}++export interface PlanError {+ job: string+ step?: string+ where: 'if' | 'env' | 'outputs' | 'matrix' | 'continue-on-error'+ message: string+}++export interface WorkflowPlan {+ jobs: Record<string, JobPlan>+ errors: PlanError[]+}++interface StepContext {+ outputs: Record<string, string>+ outcome: Outcome+ conclusion: Outcome+}++export function parseWorkflow(source: string): Workflow {+ const parsed = load(source)+ if (typeof parsed !== 'object' || parsed === null || typeof (parsed as Workflow).jobs !== 'object') {+ throw new Error('workflow has no jobs')+ }+ return parsed as Workflow+}++export function loadWorkflow(path: string): Workflow {+ return parseWorkflow(readFileSync(path, 'utf8'))+}++export function flattenSteps(steps: RawStep[] | undefined): RawStep[] {+ return (steps ?? []).flatMap((step) => (Array.isArray(step.parallel) ? flattenSteps(step.parallel) : [step]))+}++function needIds(job: RawJob): string[] {+ if (job.needs === undefined) {+ return []+ }+ return Array.isArray(job.needs) ? job.needs : [job.needs]+}++function jobOrder(jobs: Record<string, RawJob>): string[] {+ const order: string[] = []+ const seen = new Set<string>()+ const visit = (id: string): void => {+ if (seen.has(id) || !(id in jobs)) {+ return+ }+ seen.add(id)+ for (const need of needIds(jobs[id]!)) {+ visit(need)+ }+ order.push(id)+ }+ Object.keys(jobs).forEach(visit)+ return order+}++function evaluateEnv(+ raw: Record<string, unknown> | undefined,+ context: Context,+ functions: FunctionMap+): Record<string, string> {+ const env: Record<string, string> = {}+ for (const [key, value] of Object.entries(raw ?? {})) {+ env[key] = evaluateTemplate(value, context, functions)+ }+ return env+}++export function countMatrixCells(rawMatrix: unknown, context: Context, functions: FunctionMap): number | undefined {+ if (rawMatrix === undefined || rawMatrix === null) {+ return undefined+ }+ const matrix = evaluateValue(rawMatrix, context, functions)+ if (Array.isArray(matrix)) {+ return matrix.length+ }+ if (typeof matrix !== 'object' || matrix === null) {+ return undefined+ }+ const entries = matrix as Record<string, unknown>+ const include = evaluateValue(entries['include'], context, functions)+ if (include === null) {+ return undefined+ }+ const includeCount = Array.isArray(include) ? include.length : 0+ const axes = Object.entries(entries)+ .filter(([key]) => key !== 'include' && key !== 'exclude')+ .map(([, value]) => evaluateValue(value, context, functions))+ if (axes.some((value) => value === null)) {+ return undefined+ }+ const axisSizes = axes.map((value) => (Array.isArray(value) ? value.length : 1))+ if (axisSizes.length === 0) {+ return includeCount+ }+ return axisSizes.reduce((product, size) => product * size, 1) + includeCount+}++function toStepPlan(step: RawStep, index: number, runs: boolean): StepPlan {+ return { index, id: step.id, name: step.name, uses: step.uses, runs }+}++function planSteps(+ jobId: string,+ steps: RawStep[],+ context: Context,+ env: Record<string, string>,+ stubs: Record<string, StepStub>,+ cancelled: boolean,+ errors: PlanError[]+): { steps: StepPlan[]; stepContexts: Record<string, StepContext>; failed: boolean } {+ const stepContexts: Record<string, StepContext> = {}+ const plans: StepPlan[] = []+ let failed = false+ steps.forEach((step, index) => {+ const stepStatus = planFunctions({+ dependenciesSucceeded: !failed,+ dependenciesFailed: failed,+ cancelled,+ })+ const stepContext: Context = { ...context, steps: stepContexts as unknown as JsonValue }+ let contextWithStepEnv: Context = { ...stepContext, env }+ let runs = false+ try {+ contextWithStepEnv = { ...stepContext, env: { ...env, ...evaluateEnv(step.env, stepContext, stepStatus) } }+ runs = evaluateCondition(step.if, contextWithStepEnv, stepStatus)+ } catch (error) {+ errors.push({ job: jobId, step: step.id ?? `#${index}`, where: 'if', message: String(error) })+ }+ const stub = stubs[step.id ?? ''] ?? stubs[step.name ?? '']+ const outcome: Outcome = runs ? (stub?.outcome ?? 'success') : 'skipped'+ let continueOnError = false+ try {+ continueOnError = evaluateTemplate(step['continue-on-error'], contextWithStepEnv, stepStatus) === 'true'+ } catch (error) {+ errors.push({+ job: jobId,+ step: step.id ?? `#${index}`,+ where: 'continue-on-error',+ message: String(error),+ })+ }+ const conclusion: Outcome = outcome === 'failure' && continueOnError ? 'success' : outcome+ if (outcome === 'failure' && !continueOnError) {+ failed = true+ }+ if (step.id) {+ stepContexts[step.id] = { outputs: runs ? (stub?.outputs ?? {}) : {}, outcome, conclusion }+ }+ plans.push(toStepPlan(step, index, runs))+ })+ return { steps: plans, stepContexts, failed }+}++export function planWorkflow(workflow: Workflow, scenario: Scenario): WorkflowPlan {+ const errors: PlanError[] = []+ const jobs: Record<string, JobPlan> = {}+ const completed = new Set(scenario.completedBeforeCancel ?? [])+ const baseContext: Context = {+ github: scenario.github,+ vars: scenario.vars ?? {},+ inputs: {},+ secrets: { GITHUB_TOKEN: 'stub-token' },+ matrix: {},+ runner: { os: 'Linux', arch: 'X64', name: 'workflow-plan' },+ strategy: {},+ }+ let workflowEnv: Record<string, string> = {}+ try {+ workflowEnv = evaluateEnv(+ workflow.env,+ baseContext,+ planFunctions({ dependenciesSucceeded: true, dependenciesFailed: false, cancelled: false })+ )+ } catch (error) {+ errors.push({ job: WORKFLOW_SITE, where: 'env', message: String(error) })+ }++ for (const jobId of jobOrder(workflow.jobs)) {+ const job = workflow.jobs[jobId]!+ const cancelled = !!scenario.cancelled && !completed.has(jobId)+ const needs = needIds(job)+ const needsContext = Object.fromEntries(+ needs.map((need) => [need, { result: jobs[need]?.result ?? 'success', outputs: jobs[need]?.outputs ?? {} }])+ )+ const needResults = Object.values(needsContext).map((need) => need.result)+ const status = planFunctions({+ dependenciesSucceeded: needResults.every((result) => result === 'success'),+ dependenciesFailed: needResults.some((result) => result === 'failure'),+ cancelled,+ })+ const contextWithoutEnv: Context = {+ ...baseContext,+ needs: needsContext,+ job: { status: 'success' },+ }+ let env: Record<string, string> = { ...workflowEnv }+ try {+ env = { ...env, ...evaluateEnv(job.env, contextWithoutEnv, status) }+ } catch (error) {+ errors.push({ job: jobId, where: 'env', message: String(error) })+ }+ const context: Context = { ...contextWithoutEnv, env }++ let runs = false+ try {+ runs = evaluateCondition(job.if, context, status)+ } catch (error) {+ errors.push({ job: jobId, where: 'if', message: String(error) })+ }++ const allSteps = flattenSteps(job.steps)+ if (!runs) {+ const outcome: Outcome = cancelled ? 'cancelled' : 'skipped'+ jobs[jobId] = {+ id: jobId,+ outcome,+ result: outcome,+ outputs: {},+ steps: allSteps.map((step, index) => toStepPlan(step, index, false)),+ matrixCells: undefined,+ }+ continue+ }++ let matrixCells: number | undefined+ try {+ matrixCells = countMatrixCells(job.strategy?.matrix, context, status)+ } catch (error) {+ errors.push({ job: jobId, where: 'matrix', message: String(error) })+ }++ const stepPlan = planSteps(jobId, allSteps, context, env, scenario.steps?.[jobId] ?? {}, cancelled, errors)+ let outputs: Record<string, string> = {}+ try {+ outputs = evaluateEnv(+ job.outputs,+ { ...context, steps: stepPlan.stepContexts as unknown as JsonValue },+ status+ )+ } catch (error) {+ errors.push({ job: jobId, where: 'outputs', message: String(error) })+ }+ for (const [key, value] of Object.entries(outputs)) {+ outputs[key] = value.trim()+ }+ const outcome: Outcome = stepPlan.failed ? 'failure' : 'success'+ let continueOnError = false+ try {+ continueOnError = evaluateTemplate(job['continue-on-error'], context, status) === 'true'+ } catch (error) {+ errors.push({ job: jobId, where: 'continue-on-error', message: String(error) })+ }+ jobs[jobId] = {+ id: jobId,+ outcome,+ result: outcome === 'failure' && continueOnError ? 'success' : outcome,+ outputs: { ...outputs, ...scenario.jobOutputs?.[jobId] },+ steps: stepPlan.steps,+ matrixCells,+ }+ }+ return { jobs, errors }+}++export function formatPlanError(scenarioName: string, error: PlanError): string {+ const site = error.step ? `${error.job}/${error.step}` : error.job+ return `${scenarioName}: ${site} ${error.where}: ${error.message}`+}++export function runningJobs(plan: WorkflowPlan): string[] {+ return Object.values(plan.jobs)+ .filter((job) => job.result === 'success' || job.result === 'failure')+ .map((job) => job.id)+}diff --git a/tools/workflow-plan/src/render.ts b/tools/workflow-plan/src/render.tsnew file mode 100644index 000000000000..2ebf68c49b6d--- /dev/null+++ b/tools/workflow-plan/src/render.ts@@ -0,0 +1,105 @@+import { type Outcome, type Scenario, type WorkflowPlan, formatPlanError } from './plan.ts'++export interface ScenarioPlan {+ scenario: Scenario+ plan: WorkflowPlan+}++interface Column {+ name: string+ cells: string[]+}++/** Terminal-only decoration of the header row and every second data row. */+export interface TableStyle {+ header: (line: string) => string+ stripe: (line: string) => string+}++const MARKS: Record<Outcome, string> = {+ success: '▶',+ failure: '✗',+ cancelled: '⊘',+ skipped: '.',+}++const EMPTY_MATRIX_SUFFIX = '0'++const LEGEND = [+ [MARKS.success, 'runs'],+ [MARKS.failure, 'fails'],+ [MARKS.cancelled, 'cancelled'],+ [MARKS.skipped, 'skipped'],+ [EMPTY_MATRIX_SUFFIX, 'no matrix expansion'],+]+ .map(([mark, meaning]) => `${mark} = ${meaning}`)+ .join(' ')++function center(text: string, width: number): string {+ const left = Math.floor((width - text.length) / 2)+ return text.padStart(text.length + left).padEnd(width)+}++function renderGrid(cornerLabel: string, rowLabels: string[], columns: Column[], style?: TableStyle): string[] {+ const labelWidth = Math.max(cornerLabel.length, ...rowLabels.map((label) => label.length))+ const widths = columns.map(({ name, cells }) => Math.max(name.length, ...cells.map((cell) => cell.length)))+ const row = (label: string, cells: string[]): string =>+ `${label.padEnd(labelWidth)} ${cells.map((cell, index) => center(cell, widths[index]!)).join(' ')}`+ const decorate = (line: string, rowIndex: number): string =>+ style && rowIndex % 2 === 1 ? style.stripe(line) : line.trimEnd()+ const header = row(+ cornerLabel,+ columns.map(({ name }) => name)+ ).trimEnd()+ return [+ style ? style.header(header) : header,+ ...rowLabels.map((label, rowIndex) =>+ decorate(+ row(+ label,+ columns.map(({ cells }) => cells[rowIndex]!)+ ),+ rowIndex+ )+ ),+ ]+}++export function renderPlanTable(scenarioPlans: ScenarioPlan[], style?: TableStyle): string {+ const first = scenarioPlans[0]+ if (!first) {+ return ''+ }+ const jobIds = Object.keys(first.plan.jobs)+ const columns = scenarioPlans.map(({ scenario, plan }) => ({+ name: scenario.name,+ cells: jobIds.map((jobId) => {+ const job = plan.jobs[jobId]!+ return job.matrixCells === 0 ? `${MARKS[job.outcome]}${EMPTY_MATRIX_SUFFIX}` : MARKS[job.outcome]+ }),+ }))+ const lines = [...renderGrid('job', jobIds, columns, style), '', LEGEND]+ const errors = scenarioPlans.flatMap(({ scenario, plan }) =>+ plan.errors.map((error) => formatPlanError(scenario.name, error))+ )+ if (errors.length > 0) {+ lines.push('', 'Errors:', ...errors)+ }+ return lines.join('\n')+}++export function renderSteps(scenarioPlans: ScenarioPlan[], jobId: string, style?: TableStyle): string {+ const first = scenarioPlans[0]+ const job = first?.plan.jobs[jobId]+ if (!first || !job) {+ return `no job named ${jobId}`+ }+ const labels = job.steps.map((step) => step.id ?? step.name ?? step.uses ?? `#${step.index}`)+ const columns = scenarioPlans.map(({ scenario, plan }) => ({+ name: scenario.name,+ cells: job.steps.map((_, stepIndex) =>+ plan.jobs[jobId]!.steps[stepIndex]!.runs ? MARKS.success : MARKS.skipped+ ),+ }))+ return [...renderGrid('step', labels, columns, style), '', LEGEND].join('\n')+}diff --git a/tools/workflow-plan/src/scenarios.ts b/tools/workflow-plan/src/scenarios.tsnew file mode 100644index 000000000000..b74aaee935b4--- /dev/null+++ b/tools/workflow-plan/src/scenarios.ts@@ -0,0 +1,224 @@+import { load } from 'js-yaml'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import type { Context, JsonValue } from './expressions.ts'+import { type RawStep, type Scenario, type StepStub, type Workflow, flattenSteps } from './plan.ts'++export const REPOSITORY = 'PostHog/posthog'+export const FORK_REPOSITORY = 'octocat/posthog'+export const DEFAULT_BRANCH = 'master'++const FAKE_HEAD_SHA = 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678'+const FAKE_BASE_SHA = 'f9e8d7c6b5a4938271605f4e3d2c1b0a98765432'++export type PullRequestAction =+ | 'opened'+ | 'synchronize'+ | 'reopened'+ | 'ready_for_review'+ | 'labeled'+ | 'unlabeled'+ | 'closed'++export interface PullRequestOptions {+ draft?: boolean+ labels?: readonly string[]+ fork?: boolean+ headRef?: string+ action?: PullRequestAction+ /** The label the `labeled` / `unlabeled` event carries. */+ label?: string+}++function repositoryPayload(fullName: string): JsonValue {+ const [owner, name] = fullName.split('/')+ return {+ full_name: fullName,+ name: name ?? fullName,+ owner: { login: owner ?? '' },+ default_branch: DEFAULT_BRANCH,+ }+}++function baseContext(eventName: string, actor: string): Context {+ return {+ event_name: eventName,+ repository: REPOSITORY,+ repository_owner: 'PostHog',+ actor,+ triggering_actor: actor,+ run_id: '1000',+ run_number: '1',+ run_attempt: '1',+ workflow: 'workflow',+ job: 'job',+ server_url: 'https://github.com',+ api_url: 'https://api.github.com',+ token: 'stub-token',+ sha: FAKE_HEAD_SHA,+ }+}++export function pullRequest(options: PullRequestOptions = {}): Context {+ const {+ draft = false,+ labels = [],+ fork = false,+ headRef = 'feat/example',+ action = 'synchronize',+ label,+ } = options+ const actor = 'octocat'+ const number = 1+ const headRepository = fork ? FORK_REPOSITORY : REPOSITORY+ const event: Record<string, JsonValue> = {+ action,+ number,+ repository: repositoryPayload(REPOSITORY),+ pull_request: {+ number,+ draft,+ state: action === 'closed' ? 'closed' : 'open',+ title: 'Example change',+ labels: labels.map((name) => ({ name })),+ user: { login: actor },+ head: {+ ref: headRef,+ sha: FAKE_HEAD_SHA,+ repo: { ...(repositoryPayload(headRepository) as object), fork },+ },+ base: { ref: DEFAULT_BRANCH, sha: FAKE_BASE_SHA, repo: repositoryPayload(REPOSITORY) },+ },+ }+ if (label !== undefined) {+ event['label'] = { name: label }+ }+ return {+ ...baseContext('pull_request', actor),+ ref: `refs/pull/${number}/merge`,+ ref_name: `${number}/merge`,+ head_ref: headRef,+ base_ref: DEFAULT_BRANCH,+ event,+ }+}++/** The Trunk merge queue tests a `trunk-merge/**` branch through a draft pull request. */+export function mergeQueue(options: Omit<PullRequestOptions, 'headRef' | 'draft'> = {}): Context {+ return pullRequest({ ...options, draft: true, headRef: 'trunk-merge/abc123' })+}++function branchContext(eventName: string, actor: string): Context {+ return {+ ...baseContext(eventName, actor),+ ref: `refs/heads/${DEFAULT_BRANCH}`,+ ref_name: DEFAULT_BRANCH,+ head_ref: '',+ base_ref: '',+ }+}++export function push(): Context {+ return {+ ...branchContext('push', 'octocat'),+ event: {+ ref: `refs/heads/${DEFAULT_BRANCH}`,+ before: FAKE_BASE_SHA,+ after: FAKE_HEAD_SHA,+ repository: repositoryPayload(REPOSITORY),+ head_commit: { id: FAKE_HEAD_SHA, message: 'feat: example', timestamp: '2026-01-01T00:00:00Z' },+ },+ }+}++export function schedule(): Context {+ return {+ ...branchContext('schedule', 'github-actions[bot]'),+ event: { schedule: '0 * * * *', repository: repositoryPayload(REPOSITORY) },+ }+}++export function workflowDispatch(): Context {+ return {+ ...branchContext('workflow_dispatch', 'octocat'),+ event: { inputs: {}, ref: `refs/heads/${DEFAULT_BRANCH}`, repository: repositoryPayload(REPOSITORY) },+ }+}++/** What the vendored paths-filter action emits for a run where the given filters matched or not. */+export function pathsFilter(changed: Record<string, boolean>): StepStub {+ const outputs: Record<string, string> = {+ changes: JSON.stringify(Object.keys(changed).filter((name) => changed[name])),+ }+ for (const [name, matched] of Object.entries(changed)) {+ outputs[name] = matched ? 'true' : 'false'+ outputs[`${name}_files`] = matched ? `example/${name}.txt` : ''+ }+ return { outputs }+}++function filterNames(step: RawStep): string[] {+ const filters = step.with?.['filters']+ if (typeof filters === 'string') {+ const parsed = load(filters)+ return typeof parsed === 'object' && parsed !== null ? Object.keys(parsed) : []+ }+ if (typeof filters === 'object' && filters !== null) {+ return Object.keys(filters)+ }+ return []+}++function isPathsFilterStep(step: RawStep): step is RawStep & { id: string } {+ return typeof step.id === 'string' && typeof step.uses === 'string' && step.uses.includes('paths-filter')+}++/** Stubs every paths-filter step in the workflow as if every one of its filters matched. */+export function allFiltersChanged(workflow: Workflow): Record<string, Record<string, StepStub>> {+ const stubs: Record<string, Record<string, StepStub>> = {}+ for (const [jobId, job] of Object.entries(workflow.jobs)) {+ for (const step of flattenSteps(job.steps)) {+ if (!isPathsFilterStep(step)) {+ continue+ }+ const changed = Object.fromEntries(filterNames(step).map((name) => [name, true]))+ stubs[jobId] = { ...stubs[jobId], [step.id]: pathsFilter(changed) }+ }+ }+ return stubs+}++export const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url))++type ScriptStubs = Pick<Scenario, 'vars' | 'jobOutputs'>++// Values only a script produces at runtime, without which a workflow's gates cannot be planned.+const SCRIPT_STUBS: Record<string, ScriptStubs> = {+ '.github/workflows/release.yml': {+ jobOutputs: {+ plan: {+ val: JSON.stringify({ ci: { github: { artifacts_matrix: { include: null }, pr_run_mode: 'upload' } } }),+ },+ },+ },+ // The Depot shadow gates its whole graph on a sampling variable and a dice roll; plan it as sampled in.+ '.depot/workflows/ci-backend.yml': {+ vars: { CI_DEPOT_SHADOW_PERCENT: '100' },+ jobOutputs: { sample: { sampled: 'true' } },+ },+}++export function defaultScenarios(workflow: Workflow, workflowPath: string): Scenario[] {+ const steps = allFiltersChanged(workflow)+ const common = { steps, ...SCRIPT_STUBS[path.relative(REPO_ROOT, workflowPath).split(path.sep).join('/')] }+ return [+ { name: 'draft', github: pullRequest({ draft: true }), ...common },+ { name: 'ready', github: pullRequest(), ...common },+ { name: 'fork', github: pullRequest({ fork: true }), ...common },+ { name: 'queued', github: mergeQueue(), ...common },+ { name: 'merged', github: push(), ...common },+ { name: 'scheduled', github: schedule(), ...common },+ { name: 'dispatched', github: workflowDispatch(), ...common },+ ]+}diff --git a/tools/workflow-plan/tests/plan.test.ts b/tools/workflow-plan/tests/plan.test.tsnew file mode 100644index 000000000000..b916927203d5--- /dev/null+++ b/tools/workflow-plan/tests/plan.test.ts@@ -0,0 +1,314 @@+import { describe, expect, it } from 'vitest'++import type { Context } from '../src/expressions.ts'+import { type Outcome, type Scenario, WORKFLOW_SITE, parseWorkflow, planWorkflow } from '../src/plan.ts'+import { allFiltersChanged, pullRequest, push } from '../src/scenarios.ts'++const scenario = (overrides: Partial<Scenario> = {}, github: Context = pullRequest()): Scenario => ({+ name: 'test',+ github,+ ...overrides,+})++// Workflows write `!cancelled()` in a block scalar because a bare `!` starts a YAML tag.+const block = (condition: string): string => `>-\n ${condition.split('\n').join('\n ')}`++const twoJobs = (condition: string | undefined, upstreamRuns = true, upstreamTolerated = false): string => `+on: push+jobs:+ a:+ if: ${upstreamRuns}+ continue-on-error: ${upstreamTolerated}+ runs-on: ubuntu-latest+ steps: [{ id: s, run: echo }]+ b:+ needs: a+ ${condition === undefined ? '' : `if: ${block(condition)}`}+ runs-on: ubuntu-latest+ steps: [{ run: echo }]+`++describe('planWorkflow', () => {+ it.each<{ condition: string | undefined; upstream: Outcome; tolerated?: boolean; expected: Outcome }>([+ { condition: "github.event_name == 'push'", upstream: 'failure', expected: 'skipped' },+ { condition: "github.event_name == 'push'", upstream: 'failure', tolerated: true, expected: 'success' },+ { condition: 'failure()', upstream: 'failure', tolerated: true, expected: 'skipped' },+ { condition: "!cancelled() && github.event_name == 'push'", upstream: 'failure', expected: 'success' },+ { condition: 'always()', upstream: 'failure', expected: 'success' },+ { condition: 'failure()', upstream: 'failure', expected: 'success' },+ { condition: 'failure()', upstream: 'success', expected: 'skipped' },+ { condition: "contains('always()', 'always')", upstream: 'failure', expected: 'skipped' },+ { condition: undefined, upstream: 'skipped', expected: 'skipped' },+ { condition: '!cancelled()', upstream: 'skipped', expected: 'success' },+ ])(+ 'applies success() implicitly: if=$condition after upstream=$upstream tolerated=$tolerated gives $expected',+ ({ condition, upstream, tolerated = false, expected }) => {+ const upstreamSteps = upstream === 'failure' ? { a: { s: { outcome: 'failure' as const } } } : {}+ const plan = planWorkflow(+ parseWorkflow(twoJobs(condition, upstream !== 'skipped', tolerated)),+ scenario({ steps: upstreamSteps }, push())+ )+ expect(plan.jobs['a']).toMatchObject({+ outcome: upstream,+ result: upstream === 'failure' && tolerated ? 'success' : upstream,+ })+ expect(plan.jobs['b']?.result).toBe(expected)+ }+ )++ it.each<{ condition: string; flag: string; expected: Outcome }>([+ { condition: '${{ !cancelled() }}', flag: 'false', expected: 'cancelled' },+ { condition: 'always()', flag: 'false', expected: 'success' },+ { condition: "!cancelled() || needs.a.outputs.flag == 'true'", flag: 'true', expected: 'success' },+ { condition: "!cancelled() || needs.a.outputs.flag == 'true'", flag: 'false', expected: 'cancelled' },+ ])(+ 'records a gate on a cancelled run: if=$condition with flag=$flag gives $expected',+ ({ condition, flag, expected }) => {+ const source = `+on: push+jobs:+ a:+ runs-on: ubuntu-latest+ outputs:+ flag: \${{ steps.verdict.outputs.flag }}+ steps: [{ id: verdict, run: echo }]+ b:+ needs: a+ if: ${block(condition)}+ runs-on: ubuntu-latest+ steps: [{ run: echo }]+`+ const plan = planWorkflow(+ parseWorkflow(source),+ scenario({+ cancelled: true,+ completedBeforeCancel: ['a'],+ steps: { a: { verdict: { outputs: { flag } } } },+ })+ )+ expect(plan.jobs['b']?.result).toBe(expected)+ }+ )++ it('reads empty outputs from a skipped job and drops outputs of a skipped step', () => {+ const source = `+on: push+jobs:+ changes:+ if: github.event_name != 'push'+ runs-on: ubuntu-latest+ outputs:+ backend: \${{ steps.filter.outputs.backend || 'true' }}+ steps:+ - id: filter+ if: github.event_name != 'schedule'+ run: echo+ consumer:+ needs: changes+ if: '!cancelled()'+ runs-on: ubuntu-latest+ outputs:+ backend: \${{ needs.changes.outputs.backend || 'default' }}+ steps: [{ run: echo }]+`+ const workflow = parseWorkflow(source)+ const stubs = { changes: { filter: { outputs: { backend: 'false' } } } }++ const onPr = planWorkflow(workflow, scenario({ steps: stubs }))+ expect(onPr.jobs['changes']?.outputs).toEqual({ backend: 'false' })++ const onPush = planWorkflow(workflow, scenario({ steps: stubs }, push()))+ expect(onPush.jobs['changes']?.outputs).toEqual({})+ expect(onPush.jobs['consumer']?.outputs).toEqual({ backend: 'default' })++ const filterSkipped = planWorkflow(+ workflow,+ scenario({ steps: stubs }, { ...pullRequest(), event_name: 'schedule' })+ )+ expect(filterSkipped.jobs['changes']?.outputs).toEqual({ backend: 'true' })+ })++ it('skips steps after a failure unless a status function or continue-on-error says otherwise', () => {+ const source = `+on: push+jobs:+ a:+ runs-on: ubuntu-latest+ env:+ ALLOW_FAILURE: 'false'+ steps:+ - id: flaky+ continue-on-error: true+ run: echo+ - id: after-tolerated+ if: steps.flaky.outcome == 'failure' && steps.flaky.conclusion == 'success'+ run: echo+ - id: tolerated-by-step-env+ env:+ ALLOW_FAILURE: 'true'+ continue-on-error: \${{ env.ALLOW_FAILURE }}+ run: echo+ - id: after-step-env-tolerated+ run: echo+ - id: broken+ run: echo+ - id: plain+ run: echo+ - id: on-failure+ if: failure()+ run: echo+ - id: cleanup+ if: always()+ run: echo+`+ const plan = planWorkflow(+ parseWorkflow(source),+ scenario({+ steps: {+ a: {+ flaky: { outcome: 'failure' },+ 'tolerated-by-step-env': { outcome: 'failure' },+ broken: { outcome: 'failure' },+ },+ },+ })+ )+ const runs = Object.fromEntries(plan.jobs['a']!.steps.map((step) => [step.id, step.runs]))+ expect(runs).toEqual({+ flaky: true,+ 'after-tolerated': true,+ 'tolerated-by-step-env': true,+ 'after-step-env-tolerated': true,+ broken: true,+ plain: false,+ 'on-failure': true,+ cleanup: true,+ })+ expect(plan.jobs['a']?.result).toBe('failure')+ })++ it.each<{ condition: string; expected: Outcome }>([+ { condition: '${{ github.event.pull_request.draft != true }}', expected: 'success' },+ { condition: "contains(github.event.pull_request.labels.*.name, 'no-ci')", expected: 'success' },+ { condition: "contains(github.event.pull_request.labels.*.name, 'run-ci-backend')", expected: 'skipped' },+ {+ condition: "github.event_name != 'pull_request'\n|| startsWith(github.head_ref, 'feat/')",+ expected: 'success',+ },+ { condition: 'false', expected: 'skipped' },+ { condition: "env.INTERNAL == 'true'", expected: 'success' },+ ])('evaluates the condition forms workflows use: $condition', ({ condition, expected }) => {+ const source = `+on: pull_request+jobs:+ a:+ if: ${block(condition)}+ runs-on: ubuntu-latest+ env:+ INTERNAL: \${{ github.event.pull_request.head.repo.full_name == github.repository }}+ steps: [{ run: echo }]+`+ const plan = planWorkflow(parseWorkflow(source), scenario({}, pullRequest({ labels: ['no-ci'] })))+ expect(plan.errors).toEqual([])+ expect(plan.jobs['a']?.result).toBe(expected)+ })++ it.each<{ matrix: string; output: string; expected: number | undefined }>([+ { matrix: '${{ fromJSON(needs.a.outputs.m) }}', output: '', expected: undefined },+ { matrix: '\n include: ${{ fromJSON(needs.a.outputs.m) }}', output: '', expected: undefined },+ { matrix: '${{ fromJSON(needs.a.outputs.m) }}', output: '{"include":[]}', expected: 0 },+ { matrix: '${{ fromJSON(needs.a.outputs.m) }}', output: '{"include":[{"g":1},{"g":2}]}', expected: 2 },+ { matrix: '\n include: ${{ fromJSON(needs.a.outputs.m) }}', output: '[{"g":1}]', expected: 1 },+ { matrix: '\n os: [a, b]\n node: [1, 2]', output: '', expected: 4 },+ { matrix: '\n shard: [1, 2]\n image: ubuntu-${{ github.ref_name }}', output: '', expected: 2 },+ {+ matrix: "${{ needs.a.outputs.m != '' && fromJSON(needs.a.outputs.m) || fromJSON('{\"shard\":[1]}') }}",+ output: '',+ expected: 1,+ },+ ])('counts matrix cells for $matrix with output $output', ({ matrix, output, expected }) => {+ const source = `+on: push+jobs:+ a:+ runs-on: ubuntu-latest+ outputs:+ m: \${{ steps.s.outputs.m }}+ steps: [{ id: s, run: echo }]+ b:+ needs: a+ runs-on: ubuntu-latest+ strategy:+ matrix: ${matrix}+ steps: [{ run: echo }]+`+ const plan = planWorkflow(parseWorkflow(source), scenario({ steps: { a: { s: { outputs: { m: output } } } } }))+ expect(plan.errors).toEqual([])+ expect(plan.jobs['b']?.matrixCells).toBe(expected)+ })++ it('records an evaluation error without abandoning the rest of the plan', () => {+ const source = `+on: push+env:+ BROKEN: \${{ unknownFunction() }}+jobs:+ a:+ if: unknownFunction()+ runs-on: ubuntu-latest+ steps: [{ run: echo }]+ b:+ runs-on: ubuntu-latest+ steps: [{ run: echo }]+ c:+ continue-on-error: \${{ unknownFunction() }}+ runs-on: ubuntu-latest+ steps:+ - id: s+ continue-on-error: \${{ unknownFunction() }}+ run: echo+`+ const plan = planWorkflow(parseWorkflow(source), scenario())+ expect(plan.errors.map((error) => [error.job, error.step, error.where])).toEqual([+ [WORKFLOW_SITE, undefined, 'env'],+ ['a', undefined, 'if'],+ ['c', 's', 'continue-on-error'],+ ['c', undefined, 'continue-on-error'],+ ])+ expect(plan.jobs['b']?.result).toBe('success')+ expect(plan.jobs['c']?.result).toBe('success')+ })++ it('stubs every filter of a paths-filter step as changed, from block-string or mapping filters', () => {+ const source = `+on: push+jobs:+ changes:+ runs-on: ubuntu-latest+ steps:+ - uses: ./.github/actions/paths-filter+ id: filter+ with:+ filters: |+ backend:+ - 'posthog/**'+ docs:+ - 'docs/**'+ other:+ runs-on: ubuntu-latest+ steps:+ - uses: dorny/paths-filter@abc+ id: changed+ with:+ filters:+ rust: ['rust/**']+`+ const stubs = allFiltersChanged(parseWorkflow(source))+ expect(stubs['changes']?.['filter']?.outputs).toMatchObject({+ backend: 'true',+ docs: 'true',+ backend_files: expect.any(String),+ })+ expect(stubs['other']?.['changed']?.outputs).toMatchObject({ rust: 'true', changes: '["rust"]' })+ })+})diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.tsnew file mode 100644index 000000000000..9cad16960a0c--- /dev/null+++ b/tools/workflow-plan/tests/workflows.test.ts@@ -0,0 +1,364 @@+// These tests check the workflows under .github/workflows, not the planner. A failure here means a+// job condition in a workflow file changed what runs; the planner itself is covered by plan.test.ts.+import { readdirSync } from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'++import {+ type Outcome,+ type Scenario,+ type StepStub,+ type Workflow,+ formatPlanError,+ loadWorkflow,+ planWorkflow,+ runningJobs,+} from '../src/plan.ts'+import {+ REPO_ROOT,+ allFiltersChanged,+ defaultScenarios,+ mergeQueue,+ pathsFilter,+ pullRequest,+ push,+ schedule,+} from '../src/scenarios.ts'++const WORKFLOWS_DIR = path.join(REPO_ROOT, '.github/workflows')+const workflowFiles = readdirSync(WORKFLOWS_DIR).filter((file) => file.endsWith('.yml') || file.endsWith('.yaml'))+const cache = new Map<string, Workflow>()+const workflow = (file: string): Workflow => {+ const cached = cache.get(file)+ if (cached) {+ return cached+ }+ const loaded = loadWorkflow(path.join(WORKFLOWS_DIR, file))+ cache.set(file, loaded)+ return loaded+}++type Stubs = Record<string, Record<string, StepStub>>++// What the selector scripts emit on a run where every filter matched and one product group was selected.+const backendSelectors: Stubs = {+ 'detect-snapshot-mode': { detect: { outputs: { mode: 'normal' } } },+ 'turbo-discover': { discover: { outputs: { run_legacy: 'true', matrix: '[{"group":"a"}]', mode: 'full' } } },+ 'build-product-test-matrix': { build: { outputs: { include: '[{"group":"a"}]' } } },+ build_django_matrix: { build: { outputs: { include: '[{"group":"a"}]' } } },+}+const frontendSelectors: Stubs = {+ 'select-jest-tests': {+ classify: { outputs: { mode: 'full', should_run: 'true', matrix: '[{"shard":1}]', shard_count: '1' } },+ },+}++interface Expectation {+ file: string+ scenario: Scenario+ runs?: string[]+ skipped?: string[]+ results?: Record<string, Outcome>+}++type ExpectationBuilder = (+ overrides: Partial<Scenario> & { name: string },+ rest: Omit<Expectation, 'file' | 'scenario'>+) => Expectation++const suite = (file: string, selectors: Stubs): ExpectationBuilder => {+ const filters = allFiltersChanged(workflow(file))+ return (overrides, rest) => ({+ file,+ scenario: { github: pullRequest(), ...overrides, steps: { ...filters, ...selectors, ...overrides.steps } },+ ...rest,+ })+}+const backend = suite('ci-backend.yml', backendSelectors)+const frontend = suite('ci-frontend.yml', frontendSelectors)+const PINNED_WORKFLOWS = ['ci-backend.yml', 'ci-frontend.yml']++const frontendOnlyFilters: Stubs = {+ changes: {+ filter: pathsFilter({+ backend: false,+ migrations: false,+ migrations_any: false,+ migration_replay: false,+ persons_sql: false,+ tasks_temporal: false,+ openapi_types: false,+ product_yamls: false,+ }),+ },+}++const EXPECTATIONS: Expectation[] = [+ backend(+ { name: 'draft PR', github: pullRequest({ draft: true }) },+ {+ runs: [+ 'changes',+ 'turbo-discover',+ 'django',+ 'repo-checks',+ 'check-migrations',+ 'check-openapi-types',+ 'django_tests',+ ],+ skipped: ['turbo-tests', 'backend-coverage-report'],+ }+ ),+ backend(+ {+ name: 'draft PR labeled run-ci-backend',+ github: pullRequest({ draft: true, labels: ['run-ci-backend'] }),+ },+ {+ runs: ['turbo-tests', 'django'],+ }+ ),+ backend(+ { name: 'ready PR' },+ {+ runs: [+ 'turbo-tests',+ 'django',+ 'backend-coverage-report',+ 'django_tests',+ 'get_clickhouse_versions',+ 'build-product-test-matrix',+ 'build_django_matrix',+ 'test-selection-verdict',+ 'capture-test-selection',+ ],+ skipped: ['handle-snapshots', 'cancel-backend-on-openapi-check-failure'],+ }+ ),+ backend(+ { name: 'merge queue', github: mergeQueue() },+ {+ runs: ['turbo-tests', 'django', 'django_tests'],+ skipped: ['backend-coverage-report'],+ }+ ),+ backend(+ { name: 'draft PR labeled no-ci', github: pullRequest({ draft: true, labels: ['no-ci'] }) },+ {+ runs: ['django_tests'],+ skipped: ['changes', 'django', 'turbo-tests', 'repo-checks', 'check-migrations'],+ }+ ),+ backend(+ { name: 'fork PR', github: pullRequest({ fork: true }) },+ {+ runs: ['changes', 'django', 'django_tests'],+ skipped: [+ 'validate-product-yamls',+ 'calculate-running-time',+ 'report-test-timings',+ 'capture-test-selection',+ 'handle-snapshots',+ ],+ }+ ),+ backend(+ { name: 'frontend-only PR', steps: frontendOnlyFilters },+ {+ runs: ['changes', 'django_tests'],+ skipped: [+ 'detect-snapshot-mode',+ 'turbo-tests',+ 'django',+ 'get_clickhouse_versions',+ 'build_django_matrix',+ ],+ }+ ),+ backend(+ { name: 'master push', github: push() },+ {+ runs: ['changes', 'repo-checks', 'check-migrations', 'mirror-schema-cache', 'django_tests'],+ skipped: [+ 'detect-snapshot-mode',+ 'turbo-tests',+ 'django',+ 'get_clickhouse_versions',+ 'build-product-test-matrix',+ 'build_django_matrix',+ 'test-selection-verdict',+ ],+ }+ ),+ backend(+ { name: 'hourly schedule', github: schedule() },+ {+ runs: ['changes', 'turbo-tests', 'django', 'django_tests'],+ skipped: ['repo-checks', 'check-migrations', 'check-openapi-types', 'mirror-schema-cache'],+ }+ ),+ backend(+ { name: 'ready PR, superseded and cancelled', cancelled: true },+ {+ results: { django_tests: 'cancelled' },+ }+ ),+ backend(+ {+ name: 'ready PR, self-cancelled after a deterministic repo-checks failure',+ cancelled: true,+ completedBeforeCancel: ['changes', 'repo-checks'],+ steps: {+ 'repo-checks': {+ 'Run repo invariants (whole-repo pytest guards)': { outcome: 'failure' },+ 'deterministic-failure': { outputs: { deterministic_failure: 'true' } },+ },+ },+ },+ {+ runs: ['django_tests', 'cancel-backend-on-repo-check-failure'],+ results: { 'repo-checks': 'failure' },+ }+ ),+ backend(+ {+ name: 'ready PR, cancelled after repo-checks failed during setup',+ cancelled: true,+ completedBeforeCancel: ['changes', 'repo-checks'],+ steps: {+ 'repo-checks': {+ 'Set up Python': { outcome: 'failure' },+ 'deterministic-failure': { outputs: { deterministic_failure: 'true' } },+ },+ },+ },+ { results: { 'repo-checks': 'failure', django_tests: 'cancelled' } }+ ),+ frontend(+ { name: 'draft PR', github: pullRequest({ draft: true }) },+ {+ runs: ['changes', 'select-jest-tests', 'jest', 'frontend-typescript-checks', 'frontend_tests'],+ }+ ),+ frontend(+ { name: 'merge queue', github: mergeQueue() },+ {+ runs: ['jest', 'frontend_tests'],+ skipped: ['select-jest-tests'],+ }+ ),+ frontend(+ { name: 'ready PR labeled run-ci-frontend', github: pullRequest({ labels: ['run-ci-frontend'] }) },+ {+ runs: ['jest'],+ skipped: ['select-jest-tests'],+ }+ ),+ frontend(+ { name: 'draft PR labeled no-ci', github: pullRequest({ draft: true, labels: ['no-ci'] }) },+ {+ runs: ['frontend_tests'],+ skipped: ['changes', 'jest', 'frontend-format', 'frontend-typescript-checks'],+ }+ ),+ frontend(+ { name: 'fork PR', github: pullRequest({ fork: true }) },+ {+ runs: ['jest', 'frontend_tests'],+ skipped: ['capture-jest-selection', 'report-test-signals', 'calculate-running-time'],+ }+ ),+ frontend(+ { name: 'master push', github: push() },+ {+ runs: ['frontend-format', 'frontend-typescript-checks', 'frontend_tests'],+ skipped: ['jest', 'select-jest-tests'],+ }+ ),+ frontend(+ { name: 'hourly schedule', github: schedule() },+ {+ runs: ['jest', 'jest-replay-shared', 'frontend_tests'],+ skipped: ['frontend-format', 'frontend-bundle-size', 'frontend-typescript-checks'],+ }+ ),+ frontend(+ { name: 'ready PR, superseded and cancelled', cancelled: true },+ {+ results: { frontend_tests: 'cancelled' },+ }+ ),+]++interface StepExpectation {+ file: string+ job: string+ step: string+ scenario: Scenario+ runs: boolean+}++const STEP_EXPECTATIONS: StepExpectation[] = PINNED_WORKFLOWS.flatMap((file) => [+ { file, job: 'changes', step: 'filter', scenario: { name: 'ready PR', github: pullRequest() }, runs: true },+ { file, job: 'changes', step: 'filter', scenario: { name: 'master push', github: push() }, runs: false },+ { file, job: 'changes', step: 'filter', scenario: { name: 'hourly schedule', github: schedule() }, runs: false },+ { file, job: 'changes', step: 'app-token', scenario: { name: 'ready PR', github: pullRequest() }, runs: true },+ {+ file,+ job: 'changes',+ step: 'app-token',+ scenario: { name: 'fork PR', github: pullRequest({ fork: true }) },+ runs: false,+ },+])++const namedJobs = (file: string): Set<string> =>+ new Set(+ EXPECTATIONS.filter((expectation) => expectation.file === file).flatMap((expectation) => [+ ...(expectation.runs ?? []),+ ...(expectation.skipped ?? []),+ ...Object.keys(expectation.results ?? {}),+ ])+ )++describe('.github/workflows run plans', () => {+ it.each(PINNED_WORKFLOWS)('%s names every conditional job in an expectation row', (file) => {+ const unnamed = Object.entries(workflow(file).jobs)+ .filter(([id, job]) => job.if !== undefined && !namedJobs(file).has(id))+ .map(([id]) => id)+ expect(unnamed).toEqual([])+ })++ it.each(workflowFiles)('%s evaluates every job and step condition under the built-in scenarios', (file) => {+ const wf = workflow(file)+ const errors = defaultScenarios(wf, path.join(WORKFLOWS_DIR, file)).flatMap((scenario) =>+ planWorkflow(wf, scenario).errors.map((error) => formatPlanError(scenario.name, error))+ )+ expect(errors).toEqual([])+ })++ it.each(EXPECTATIONS)(+ '$file on $scenario.name runs the intended jobs',+ ({ file, scenario, runs, skipped, results }) => {+ const plan = planWorkflow(workflow(file), scenario)+ expect(plan.errors).toEqual([])+ const running = new Set(runningJobs(plan))+ const named = [...(runs ?? []), ...(skipped ?? []), ...Object.keys(results ?? {})]+ expect({+ unknownJobs: named.filter((id) => !(id in plan.jobs)),+ didNotRun: (runs ?? []).filter((id) => !running.has(id)),+ didNotSkip: (skipped ?? []).filter((id) => plan.jobs[id]?.result !== 'skipped'),+ results: Object.fromEntries(Object.keys(results ?? {}).map((id) => [id, plan.jobs[id]?.result])),+ }).toEqual({ unknownJobs: [], didNotRun: [], didNotSkip: [], results: results ?? {} })+ }+ )++ it.each(STEP_EXPECTATIONS)(+ '$file $job/$step on $scenario.name runs=$runs',+ ({ file, job, step, scenario, runs }) => {+ const plan = planWorkflow(workflow(file), scenario)+ const planned = plan.jobs[job]?.steps.find((candidate) => candidate.id === step)+ expect({ id: planned?.id, runs: planned?.runs }).toEqual({ id: step, runs })+ }+ )+})diff --git a/tools/workflow-plan/tsconfig.json b/tools/workflow-plan/tsconfig.jsonnew file mode 100644index 000000000000..a19c0df70dd1--- /dev/null+++ b/tools/workflow-plan/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "es2022",+ "module": "nodenext",+ "moduleResolution": "nodenext",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "erasableSyntaxOnly": true,+ "noEmit": true,+ "strict": true,+ "noImplicitReturns": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "skipLibCheck": true,+ "types": ["node"]+ },+ "include": ["src/**/*.ts", "tests/**/*.ts", "vitest.config.mts"]+}diff --git a/tools/workflow-plan/vitest.config.mts b/tools/workflow-plan/vitest.config.mtsnew file mode 100644index 000000000000..ca048bbe5eb8--- /dev/null+++ b/tools/workflow-plan/vitest.config.mts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ environment: 'node',+ include: ['tests/**/*.test.ts'],+ },+})