From 3a23bbd1951920f585366039aedfbcc39dfdb4a7 Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 23 Nov 2026 10:01:24 +1100 Subject: [PATCH 1/4] ci: gate file size, function complexity and import cycles The 300-line file limit was only written down, and 239 source files are over it. The ratchet now fails when a file crosses 300 lines or a file already over it grows. oxlint warns on long or complex functions, deep nesting, long parameter lists, nested ternaries and import cycles, with each package's warning limit set to today's count so it cannot rise. The lint job writes a summary of file sizes and warnings by rule to the run page so the totals are visible while they are worked down. --- .github/workflows/main.yml | 8 + agent_docs/code_style.md | 2 +- oxlint/base.jsonc | 23 +- packages/api/package.json | 2 +- packages/app/package.json | 2 +- packages/cli/package.json | 2 +- packages/common-utils/package.json | 2 +- packages/hdx-eval/package.json | 2 +- scripts/ci/__tests__/quality-report.test.mjs | 22 ++ scripts/ci/__tests__/ratchet.test.mjs | 58 ++++- scripts/ci/file-size-baseline.json | 241 +++++++++++++++++++ scripts/ci/oxlint-warnings.mjs | 2 +- scripts/ci/quality-report.mjs | 96 ++++++++ scripts/ci/ratchet.mjs | 144 +++++++++-- 14 files changed, 583 insertions(+), 23 deletions(-) create mode 100644 scripts/ci/__tests__/quality-report.test.mjs create mode 100644 scripts/ci/file-size-baseline.json create mode 100644 scripts/ci/quality-report.mjs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2761e4259..56016c825 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -59,6 +59,7 @@ jobs: run: node --test scripts/ci/__tests__/ratchet.test.mjs scripts/ci/__tests__/oxlint-warnings.test.mjs + scripts/ci/__tests__/quality-report.test.mjs # Also unconditional, and against the PR's own tree. claude-code-review.yml # runs this file too, but from a base-branch checkout, so a PR that breaks # what it pins (the AGENTS.md heading every review footer links to) passes @@ -69,6 +70,13 @@ jobs: .github/scripts/code-review/__tests__/review-comments.test.mjs - name: Escape-hatch ratchet run: node scripts/ci/ratchet.mjs + # Advisory: the gates are the ratchet above and each package's + # --max-warnings. This only makes the totals visible on the run page. + - name: Code quality report + if: always() + continue-on-error: true + timeout-minutes: 2 + run: node scripts/ci/quality-report.mjs >> "$GITHUB_STEP_SUMMARY" # Also unconditional: the api's own `ci:lint` regenerates the spec but # never asserts on it, and nx can skip or cache-replay that task. - name: Check openapi.json is in sync with its sources diff --git a/agent_docs/code_style.md b/agent_docs/code_style.md index 3f24037b2..ff913beef 100644 --- a/agent_docs/code_style.md +++ b/agent_docs/code_style.md @@ -14,7 +14,7 @@ ## Code Organization - **Single Responsibility**: One clear purpose per component/function -- **File Size**: Max 300 lines - refactor when approaching limit +- **File Size**: Max 300 lines - refactor when approaching limit. `yarn ratchet` fails when a file crosses it or an already-larger file grows - **DRY**: Grep for an existing implementation before adding a type, schema, helper, or component - see "Before you add a type, schema, or helper" below (REQUIRED) diff --git a/oxlint/base.jsonc b/oxlint/base.jsonc index 4973a7d15..1038234af 100644 --- a/oxlint/base.jsonc +++ b/oxlint/base.jsonc @@ -11,7 +11,7 @@ // the top-level config, which is this file (via extends) when run from a // package and the root one when run from the repo root. "options": { "typeAware": true, "reportUnusedDisableDirectives": "warn" }, - "plugins": ["eslint", "typescript"], + "plugins": ["eslint", "typescript", "import"], "categories": { "correctness": "off", "suspicious": "off", @@ -97,6 +97,17 @@ "reportVarsOnlyUsedAsTypes": true, }, ], + // Size and structure. Warnings, so each package's --max-warnings stops + // the count rising without blocking on what is already there. + "max-lines-per-function": [ + "warn", + { "max": 150, "skipBlankLines": true, "skipComments": true }, + ], + "complexity": ["warn", 20], + "max-depth": ["warn", 4], + "max-params": ["warn", 4], + "no-nested-ternary": "warn", + "import/no-cycle": "warn", "no-restricted-imports": [ "error", { @@ -110,6 +121,16 @@ ], }, "overrides": [ + { + // A describe() callback is one function holding the whole suite. + "files": [ + "**/__tests__/**", + "**/*.{test,spec}.{ts,tsx}", + "**/tests/**", + "**/*.stories.tsx", + ], + "rules": { "max-lines-per-function": "off" }, + }, { // typescript-eslint's `eslint-recommended` turns these off for TS files // because tsc reports them, and turns no-var/prefer-* on. Plain JS files diff --git a/packages/api/package.json b/packages/api/package.json index a46ff850d..5457d143e 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -106,7 +106,7 @@ "dev-task": "DOTENV_CONFIG_PATH=.env.development nodemon --exec 'ts-node' --transpile-only -r tsconfig-paths/register -r dotenv-expand/config -r ./src/telemetry.ts ./src/tasks/index.ts", "build": "rimraf ./build && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && cp -r ./src/opamp/proto ./build/opamp/", "build:vercel": "rimraf ./build && tsc -p tsconfig.vercel.json && tsc-alias -p tsconfig.vercel.json && cp -r ./src/opamp/proto ./build/opamp/", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 302 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 437 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt 'src/**/*.ts' 'scripts/**/*.ts'", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:openapi", "ci:unit": "jest --ci --coverage", diff --git a/packages/app/package.json b/packages/app/package.json index 043a65673..708fab016 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -14,7 +14,7 @@ "build:clickhouse": "NEXT_PUBLIC_IS_LOCAL_MODE=true NEXT_PUBLIC_CLICKHOUSE_BUILD=true next build --webpack && node scripts/prepare-clickhouse-build-export.js", "run:clickhouse": "test -d out && npx rimraf tmp && mkdir tmp && cp -r out tmp/clickstack && echo 'visit http://localhost:3000/clickstack to start' && npx serve tmp -l 3000 || echo 'run build:clickhouse first'", "start": "next start", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 569 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 1161 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt '**/*.{ts,tsx,css,scss}'", "lint:styles": "stylelint **/*/*.{css,scss}", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:styles --quiet", diff --git a/packages/cli/package.json b/packages/cli/package.json index f922b75f7..f6d1247e0 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -33,7 +33,7 @@ "compile:linux": "bun build src/cli.tsx --compile --target=bun-linux-x64 --outfile dist/hdx-linux-x64", "compile:macos": "bun build src/cli.tsx --compile --target=bun-darwin-arm64 --outfile dist/hdx-darwin-arm64", "compile:macos-x64": "bun build src/cli.tsx --compile --target=bun-darwin-x64 --outfile dist/hdx-darwin-x64", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 0 && yarn run -T oxfmt --check 'src/**/*.{ts,tsx}'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 74 && yarn run -T oxfmt --check 'src/**/*.{ts,tsx}'", "ci:build": "tsup", "ci:lint": "yarn lint && yarn tsc --noEmit", "ci:unit": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand --ci --passWithNoTests", diff --git a/packages/common-utils/package.json b/packages/common-utils/package.json index acf485e4a..cd390665d 100644 --- a/packages/common-utils/package.json +++ b/packages/common-utils/package.json @@ -51,7 +51,7 @@ "build": "tsup && yarn build:types", "build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json", "ci:build": "yarn build", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 80 && yarn run -T oxfmt --check 'src/**/*.ts'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 233 && yarn run -T oxfmt --check 'src/**/*.ts'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt 'src/**/*.ts'", "ci:lint": "yarn lint && yarn tsc --noEmit", "ci:unit": "jest --ci --coverage", diff --git a/packages/hdx-eval/package.json b/packages/hdx-eval/package.json index b5c363216..0e2bb6e7d 100644 --- a/packages/hdx-eval/package.json +++ b/packages/hdx-eval/package.json @@ -36,7 +36,7 @@ "scripts": { "build": "rimraf ./dist && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json", "dev": "NODE_OPTIONS=--max-old-space-size=8192 ./scripts/env.sh tsx src/cli.ts", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 0 && yarn run -T oxfmt --check 'src/**/*.ts'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 44 && yarn run -T oxfmt --check 'src/**/*.ts'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt 'src/**/*.ts'", "ci:lint": "yarn lint && yarn tsc --noEmit", "ci:unit": "jest --ci --coverage --forceExit", diff --git a/scripts/ci/__tests__/quality-report.test.mjs b/scripts/ci/__tests__/quality-report.test.mjs new file mode 100644 index 000000000..0cb6a08e9 --- /dev/null +++ b/scripts/ci/__tests__/quality-report.test.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { lintSection, sizeSection } from '../quality-report.mjs'; + +test('file size section lists the largest files first', () => { + const out = sizeSection({ 'a.ts': 400, 'b.ts': 900 }); + assert.match(out, /2 source files over 300 lines, 700 lines over/); + assert.ok(out.indexOf('b.ts') < out.indexOf('a.ts')); +}); + +test('lint section totals each rule across packages, most common first', () => { + const out = lintSection({ + api: { limit: 5, rules: { complexity: 2, 'max-depth': 3 } }, + app: { limit: 9, rules: { complexity: 4 } }, + }); + assert.match(out, /\| `complexity` \| 2 \| 4 \| 6 \|/); + assert.match(out, /\| `max-depth` \| 3 \| 0 \| 3 \|/); + assert.ok(out.indexOf('complexity') < out.indexOf('max-depth')); + assert.match(out, /\| \*\*Total\*\* \| 5 \| 4 \|/); + assert.match(out, /\| \*\*Limit\*\* \| 5 \| 9 \|/); +}); diff --git a/scripts/ci/__tests__/ratchet.test.mjs b/scripts/ci/__tests__/ratchet.test.mjs index c60436142..a92dbee4c 100644 --- a/scripts/ci/__tests__/ratchet.test.mjs +++ b/scripts/ci/__tests__/ratchet.test.mjs @@ -10,7 +10,14 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import test from 'node:test'; -import { collectCounts, compare, discoverPackages } from '../ratchet.mjs'; +import { + collectCounts, + collectLargeFiles, + compare, + compareSizes, + discoverPackages, + nextSizeBaseline, +} from '../ratchet.mjs'; /** Builds a throwaway workspace: { pkgName: { 'src/a.ts': 'source' } }. */ function fixture(packages, workspaces = ['packages/*']) { @@ -172,3 +179,52 @@ test('the committed baseline is not already breached by the real repo', () => { // Only asserts not-above-baseline: below-baseline is a deliberate warn. assert.equal(compare(collectCounts(repoRoot), baseline).failed, false); }); + +test('collects only non-test source files over the line limit', () => { + const long = 'x;\n'.repeat(301); + const root = fixture({ + app: { + 'src/big.ts': long, + 'src/ok.ts': 'x;\n'.repeat(300), + 'src/__tests__/big.test.ts': long, + }, + }); + assert.deepEqual(collectLargeFiles(root), { 'packages/app/src/big.ts': 301 }); +}); + +test('a new large file or a grown one fails; a shrunk one only warns', () => { + const baseline = { 'a.ts': 500, 'b.ts': 500 }; + assert.equal( + compareSizes({ ...baseline, 'new.ts': 301 }, baseline).failed, + true, + ); + assert.equal( + compareSizes({ 'a.ts': 501, 'b.ts': 500 }, baseline).failed, + true, + ); + const shrunk = compareSizes({ 'a.ts': 400 }, baseline); + assert.equal(shrunk.failed, false); + assert.equal(shrunk.messages.length, 2); +}); + +test('a moved file points at ratchet:update instead of asking for a split', () => { + const { failed, messages } = compareSizes( + { 'new/a.ts': 500 }, + { 'a.ts': 500 }, + ); + assert.equal(failed, true); + assert.match(messages[0], /moved or split from a\.ts/); +}); + +test('update records shrinkage and moves but refuses growth unless allowed', () => { + const baseline = { 'a.ts': 500, 'b.ts': 500, 'old.ts': 900 }; + const current = { 'a.ts': 400, 'b.ts': 600, 'moved.ts': 900, 'new.ts': 950 }; + assert.deepEqual(nextSizeBaseline(current, baseline), { + next: { 'a.ts': 400, 'b.ts': 500, 'moved.ts': 900 }, + refused: ['b.ts', 'new.ts'], + }); + assert.deepEqual(nextSizeBaseline(current, baseline, true), { + next: current, + refused: [], + }); +}); diff --git a/scripts/ci/file-size-baseline.json b/scripts/ci/file-size-baseline.json new file mode 100644 index 000000000..d8295c107 --- /dev/null +++ b/scripts/ci/file-size-baseline.json @@ -0,0 +1,241 @@ +{ + "packages/api/scripts/seed-alerts.ts": 478, + "packages/api/src/controllers/ai.ts": 353, + "packages/api/src/controllers/alertHistory.ts": 592, + "packages/api/src/controllers/alerts.ts": 614, + "packages/api/src/controllers/promql.ts": 863, + "packages/api/src/controllers/timeseriesEngine.ts": 491, + "packages/api/src/fixtures.ts": 1010, + "packages/api/src/mcp/prompts/dashboards/content.ts": 1685, + "packages/api/src/mcp/tools/alerts/schemas.ts": 364, + "packages/api/src/mcp/tools/dashboards/patchDashboard.ts": 311, + "packages/api/src/mcp/tools/dashboards/queryTiles.ts": 363, + "packages/api/src/mcp/tools/dashboards/saveDashboard.ts": 478, + "packages/api/src/mcp/tools/dashboards/schemas.ts": 2292, + "packages/api/src/mcp/tools/dashboards/validation.ts": 419, + "packages/api/src/mcp/tools/dashboards/variables.ts": 378, + "packages/api/src/mcp/tools/query/emergingSignals.ts": 377, + "packages/api/src/mcp/tools/query/eventDeltas.ts": 492, + "packages/api/src/mcp/tools/query/helpers.ts": 1134, + "packages/api/src/mcp/tools/query/runEventPatterns.ts": 611, + "packages/api/src/mcp/tools/query/schemas.ts": 452, + "packages/api/src/mcp/tools/query/serviceHealth/report.ts": 302, + "packages/api/src/mcp/tools/query/table.ts": 368, + "packages/api/src/mcp/tools/sources/describeMetric.ts": 767, + "packages/api/src/mcp/tools/sources/describeSource.ts": 659, + "packages/api/src/mcp/tools/sources/describeTable.ts": 380, + "packages/api/src/mcp/tools/sources/describeTableQueries.ts": 341, + "packages/api/src/mcp/tools/sources/listSources.ts": 378, + "packages/api/src/mcp/tools/sources/schemas.ts": 599, + "packages/api/src/mcp/tools/trace/waterfall.ts": 795, + "packages/api/src/models/alert.ts": 309, + "packages/api/src/models/source.ts": 326, + "packages/api/src/opamp/controllers/opampController.ts": 671, + "packages/api/src/routers/api/alerts.ts": 489, + "packages/api/src/routers/api/clickhouseProxy.ts": 333, + "packages/api/src/routers/api/dashboards.ts": 420, + "packages/api/src/routers/api/prometheus.ts": 945, + "packages/api/src/routers/api/team.ts": 347, + "packages/api/src/routers/api/webhooks.ts": 546, + "packages/api/src/routers/external-api/v2/alerts.ts": 1183, + "packages/api/src/routers/external-api/v2/charts.ts": 709, + "packages/api/src/routers/external-api/v2/connections.ts": 623, + "packages/api/src/routers/external-api/v2/dashboards.ts": 4123, + "packages/api/src/routers/external-api/v2/savedSearches.ts": 724, + "packages/api/src/routers/external-api/v2/search.ts": 457, + "packages/api/src/routers/external-api/v2/sources.ts": 1316, + "packages/api/src/routers/external-api/v2/team.ts": 321, + "packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts": 410, + "packages/api/src/routers/external-api/v2/utils/dashboards.ts": 2053, + "packages/api/src/routers/external-api/v2/webhooks.ts": 878, + "packages/api/src/tasks/checkAlerts/index.ts": 2473, + "packages/api/src/tasks/checkAlerts/providers/default.ts": 852, + "packages/api/src/tasks/checkAlerts/template.ts": 1027, + "packages/api/src/tasks/checkAlerts/transports/generic.ts": 303, + "packages/api/src/utils/externalApi.ts": 557, + "packages/api/src/utils/instrumentation.ts": 353, + "packages/api/src/utils/trimToolResponse.ts": 355, + "packages/api/src/utils/zod.ts": 1494, + "packages/app/src/api.ts": 1041, + "packages/app/src/BenchmarkPage.tsx": 440, + "packages/app/src/ChartUtils.tsx": 1612, + "packages/app/src/ClickhousePage.tsx": 883, + "packages/app/src/components/ActiveFilterPills.tsx": 353, + "packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx": 305, + "packages/app/src/components/AdhocDashboardFilter/useAdhocFilterOptions.ts": 412, + "packages/app/src/components/alerts/AlertDetailChart.tsx": 452, + "packages/app/src/components/alerts/AlertHistoryCards.tsx": 302, + "packages/app/src/components/alerts/EditAlertModal.tsx": 500, + "packages/app/src/components/AppNav/AppNav.components.tsx": 429, + "packages/app/src/components/AppNav/AppNav.tsx": 614, + "packages/app/src/components/ChartDisplaySettingsDrawer.tsx": 585, + "packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx": 326, + "packages/app/src/components/ChartEditor/utils.ts": 825, + "packages/app/src/components/charts/chartAnnotations.tsx": 330, + "packages/app/src/components/charts/ChartSeriesTooltip.tsx": 465, + "packages/app/src/components/ColorRulesEditor.tsx": 387, + "packages/app/src/components/ConnectionForm.tsx": 535, + "packages/app/src/components/ContextFilterPills.tsx": 359, + "packages/app/src/components/ContextSidePanel.tsx": 328, + "packages/app/src/components/DashboardContainer.tsx": 432, + "packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx": 397, + "packages/app/src/components/DashboardFiltersModal/SqlQueryFilterEditForm.tsx": 418, + "packages/app/src/components/Dashboards/DashboardsListPage.tsx": 432, + "packages/app/src/components/DBDeltaChart.tsx": 678, + "packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx": 596, + "packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx": 575, + "packages/app/src/components/DBEditTimeChartForm/ChartSeriesEditor.tsx": 563, + "packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx": 1603, + "packages/app/src/components/DBEditTimeChartForm/OnClickForm/OnClickDrawer.tsx": 376, + "packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx": 322, + "packages/app/src/components/DBEditTimeChartForm/utils.ts": 636, + "packages/app/src/components/DBHeatmapChart/HeatmapPlot.tsx": 395, + "packages/app/src/components/DBHeatmapChart/heatmapQueries.ts": 340, + "packages/app/src/components/DBHistogramChart.tsx": 313, + "packages/app/src/components/DBInfraPanel.tsx": 372, + "packages/app/src/components/DBNumberChart.tsx": 414, + "packages/app/src/components/DBRowDataPanel.tsx": 499, + "packages/app/src/components/DBRowJsonViewer.tsx": 885, + "packages/app/src/components/DBRowOverviewPanel.tsx": 536, + "packages/app/src/components/DBRowSidePanel.tsx": 1499, + "packages/app/src/components/DBRowTable.tsx": 2051, + "packages/app/src/components/DBSearchPageFilters.tsx": 2049, + "packages/app/src/components/DBSearchPageFilters/hooks.ts": 456, + "packages/app/src/components/DBSearchPageFilters/NestedFilterGroup.tsx": 335, + "packages/app/src/components/DBSearchPageFilters/utils.ts": 357, + "packages/app/src/components/DBTable/TableSearchInput.tsx": 364, + "packages/app/src/components/DBTableChart.tsx": 390, + "packages/app/src/components/DBTimeChart.tsx": 1213, + "packages/app/src/components/DBTracePanel.tsx": 513, + "packages/app/src/components/DBTraceWaterfallChart.tsx": 1732, + "packages/app/src/components/ExceptionSubpanel.tsx": 764, + "packages/app/src/components/HyperJson.tsx": 492, + "packages/app/src/components/KubeComponents.tsx": 335, + "packages/app/src/components/KubernetesFilters.tsx": 353, + "packages/app/src/components/linkedSpans.tsx": 419, + "packages/app/src/components/MetricAttributeHelperPanel.tsx": 516, + "packages/app/src/components/NumberFormat.tsx": 368, + "packages/app/src/components/OnboardingModal.tsx": 1003, + "packages/app/src/components/PropertyComparisonChart.tsx": 335, + "packages/app/src/components/RevealSnippet/RevealSnippet.tsx": 359, + "packages/app/src/components/SavedSearches/SavedSearchesListPage.tsx": 325, + "packages/app/src/components/SearchInput/AutocompleteInput.tsx": 411, + "packages/app/src/components/SearchInput/SyntaxReferenceModal.tsx": 360, + "packages/app/src/components/ServiceMap/ServiceMap.tsx": 451, + "packages/app/src/components/ServiceMap/utils.ts": 380, + "packages/app/src/components/Sources/SourceForm/LogTableModelForm.tsx": 339, + "packages/app/src/components/Sources/SourceForm/MaterializedViews.tsx": 584, + "packages/app/src/components/Sources/SourceForm/MetricTableModelForm.tsx": 328, + "packages/app/src/components/Sources/SourceForm/SourceForm.tsx": 859, + "packages/app/src/components/Sources/SourceForm/TraceTableModelForm.tsx": 447, + "packages/app/src/components/sourceSelectUtils.tsx": 322, + "packages/app/src/components/SQLEditor/constants.ts": 1241, + "packages/app/src/components/SQLEditor/SQLInlineEditor.tsx": 448, + "packages/app/src/components/SQLEditor/variableCompletions.tsx": 350, + "packages/app/src/components/TeamSettings/IacMigrationSection.tsx": 325, + "packages/app/src/components/TeamSettings/TeamMembersSection.tsx": 453, + "packages/app/src/components/TeamSettings/TeamQueryConfigSection.tsx": 356, + "packages/app/src/components/TeamSettings/WebhookForm.tsx": 510, + "packages/app/src/components/TimelineChart/TimelineChart.tsx": 515, + "packages/app/src/components/TimelineChart/TimelineMinimap.tsx": 370, + "packages/app/src/components/TimePicker/TimePicker.tsx": 581, + "packages/app/src/dashboard.ts": 370, + "packages/app/src/DashboardFilters.tsx": 370, + "packages/app/src/DBChartPage.tsx": 367, + "packages/app/src/DBDashboardImportPage.tsx": 1648, + "packages/app/src/DBDashboardPage.tsx": 3742, + "packages/app/src/DBSearchPage.tsx": 3299, + "packages/app/src/DBSearchPageAlertModal.tsx": 733, + "packages/app/src/DBServiceMapPage.tsx": 471, + "packages/app/src/DOMPlayer.tsx": 637, + "packages/app/src/HDXMultiSeriesTableChart.tsx": 633, + "packages/app/src/HDXMultiSeriesTimeChart.tsx": 2335, + "packages/app/src/hooks/useAutoCompleteOptions.tsx": 325, + "packages/app/src/hooks/useChartConfig.tsx": 616, + "packages/app/src/hooks/useDashboardFilters.tsx": 571, + "packages/app/src/hooks/useMetadata.tsx": 873, + "packages/app/src/hooks/useOffsetPaginatedQuery.tsx": 593, + "packages/app/src/hooks/usePatterns.tsx": 345, + "packages/app/src/hooks/useQueriedDashboardFilterValues.tsx": 451, + "packages/app/src/hooks/useReleaseAnnotations.tsx": 532, + "packages/app/src/hooks/useServiceMap.tsx": 468, + "packages/app/src/KubernetesDashboardPage.tsx": 1738, + "packages/app/src/llm/dashboard/LLMDashboardPage.tsx": 380, + "packages/app/src/llm/dashboard/LLMSessionPanel.tsx": 322, + "packages/app/src/llm/lib/expressions.ts": 570, + "packages/app/src/NamespaceDetailsSidePanel.tsx": 439, + "packages/app/src/NodeDetailsSidePanel.tsx": 452, + "packages/app/src/PodDetailsSidePanel.tsx": 481, + "packages/app/src/searchFilters.tsx": 754, + "packages/app/src/ServicesDashboardPage/DatabaseTab.tsx": 517, + "packages/app/src/ServicesDashboardPage/HttpTab.tsx": 699, + "packages/app/src/ServicesDashboardPage/ServicesDashboardPage.tsx": 487, + "packages/app/src/SessionEventList.tsx": 310, + "packages/app/src/sessions.ts": 905, + "packages/app/src/SessionSidePanel.tsx": 329, + "packages/app/src/SessionsPage.tsx": 609, + "packages/app/src/SessionSubpanel.tsx": 646, + "packages/app/src/source.ts": 979, + "packages/app/src/TeamPage.tsx": 402, + "packages/app/src/theme/mantineTheme.ts": 441, + "packages/app/src/timeQuery.ts": 581, + "packages/app/src/useUserPreferences.tsx": 353, + "packages/app/src/utils.ts": 1492, + "packages/app/src/utils/alerts.ts": 380, + "packages/app/src/utils/materializedViews.ts": 467, + "packages/app/src/utils/sentryStackParser.ts": 330, + "packages/cli/src/api/client.ts": 634, + "packages/cli/src/api/eventQuery.ts": 381, + "packages/cli/src/cli.tsx": 2490, + "packages/cli/src/components/AlertsPage.tsx": 515, + "packages/cli/src/components/DashboardPage.tsx": 350, + "packages/cli/src/components/EventViewer/EventViewer.tsx": 430, + "packages/cli/src/components/EventViewer/SubComponents.tsx": 301, + "packages/cli/src/components/EventViewer/useEventData.ts": 339, + "packages/cli/src/components/EventViewer/useKeybindings.ts": 675, + "packages/cli/src/components/TraceWaterfall/TraceWaterfall.tsx": 388, + "packages/cli/src/mcp/install.ts": 403, + "packages/cli/src/shared/chartData.ts": 543, + "packages/cli/src/shared/formatNumber.ts": 610, + "packages/cli/src/shared/tileConfig.ts": 405, + "packages/common-utils/src/clickhouse/index.ts": 1270, + "packages/common-utils/src/core/eventDeltas.ts": 409, + "packages/common-utils/src/core/formula.ts": 558, + "packages/common-utils/src/core/histogram.ts": 661, + "packages/common-utils/src/core/linkUrlBuilder.ts": 366, + "packages/common-utils/src/core/materializedViews.ts": 1014, + "packages/common-utils/src/core/metadata.ts": 3800, + "packages/common-utils/src/core/promqlChart.ts": 432, + "packages/common-utils/src/core/renderChartConfig.ts": 3580, + "packages/common-utils/src/core/utils.ts": 2047, + "packages/common-utils/src/dashboardFilterValues.ts": 334, + "packages/common-utils/src/dashboardValidation.ts": 601, + "packages/common-utils/src/drain/drain.ts": 375, + "packages/common-utils/src/filters.ts": 1691, + "packages/common-utils/src/iac.ts": 456, + "packages/common-utils/src/macros.ts": 613, + "packages/common-utils/src/queryParser.ts": 2364, + "packages/common-utils/src/referenceVariables.ts": 385, + "packages/common-utils/src/types.ts": 3661, + "packages/common-utils/src/variables.ts": 1429, + "packages/hdx-eval/src/cli.ts": 1220, + "packages/hdx-eval/src/clickhouse/schema.ts": 435, + "packages/hdx-eval/src/generators/metrics.ts": 317, + "packages/hdx-eval/src/generators/templates.ts": 1152, + "packages/hdx-eval/src/grading/dashboardInspection.ts": 616, + "packages/hdx-eval/src/grading/grade.ts": 396, + "packages/hdx-eval/src/grading/judge.ts": 413, + "packages/hdx-eval/src/hyperdx/api.ts": 463, + "packages/hdx-eval/src/hyperdx/setup.ts": 435, + "packages/hdx-eval/src/reports/aggregate.ts": 373, + "packages/hdx-eval/src/reports/markdown.ts": 324, + "packages/hdx-eval/src/runs/instrument.ts": 309, + "packages/hdx-eval/src/scenarios/dashboard-build/generate.ts": 567, + "packages/hdx-eval/src/scenarios/deploy-regression/generate.ts": 1055, + "packages/hdx-eval/src/scenarios/error-root-cause/generate.ts": 736, + "packages/hdx-eval/src/scenarios/latency-spike/generate.ts": 554, + "packages/hdx-eval/src/scenarios/metric-saturation/generate.ts": 1070, + "packages/hdx-eval/src/scenarios/noisy-signals/generate.ts": 420, + "packages/hdx-eval/src/scenarios/quiet-saturation/generate.ts": 976, + "packages/hdx-eval/src/scenarios/service-health-check/generate.ts": 428 +} diff --git a/scripts/ci/oxlint-warnings.mjs b/scripts/ci/oxlint-warnings.mjs index 93fccc908..4751aa3b5 100644 --- a/scripts/ci/oxlint-warnings.mjs +++ b/scripts/ci/oxlint-warnings.mjs @@ -219,7 +219,7 @@ function annotate(warnings, root) { } } -function runOxlint(cwd, oxlintArgs) { +export function runOxlint(cwd, oxlintArgs) { const require = createRequire(path.join(cwd, 'noop.js')); const pkgJson = require.resolve('oxlint/package.json'); const bin = path.join(path.dirname(pkgJson), 'bin/oxlint'); diff --git a/scripts/ci/quality-report.mjs b/scripts/ci/quality-report.mjs new file mode 100644 index 000000000..244c34a28 --- /dev/null +++ b/scripts/ci/quality-report.mjs @@ -0,0 +1,96 @@ +#!/usr/bin/env node +// Markdown summary of file sizes and oxlint warnings, for the CI job summary. +// Advisory: the ratchet and each package's --max-warnings do the gating. +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { collectWarnings, runOxlint } from './oxlint-warnings.mjs'; +import { + collectLargeFiles, + discoverPackages, + MAX_FILE_LINES, +} from './ratchet.mjs'; + +const TOP = 15; + +function table(header, rows) { + return [header, header.map(() => '---'), ...rows] + .map(cells => `| ${cells.join(' | ')} |`) + .join('\n'); +} + +export function sizeSection(large) { + const files = Object.entries(large).sort(([, a], [, b]) => b - a); + const excess = files.reduce((sum, [, n]) => sum + n - MAX_FILE_LINES, 0); + return [ + '### File size', + `${files.length} source files over ${MAX_FILE_LINES} lines, ${excess} lines over the limit in total. Largest ${Math.min(TOP, files.length)}:`, + table( + ['File', 'Lines'], + files.slice(0, TOP).map(([file, n]) => [`\`${file}\``, n]), + ), + ].join('\n\n'); +} + +/** @param {Record}>} byPackage */ +export function lintSection(byPackage) { + const packages = Object.keys(byPackage); + const count = (pkg, rule) => byPackage[pkg].rules[rule] ?? 0; + const total = pkg => + Object.values(byPackage[pkg].rules).reduce((a, b) => a + b, 0); + const rules = [ + ...new Set(packages.flatMap(p => Object.keys(byPackage[p].rules))), + ] + .map(rule => [rule, packages.reduce((sum, p) => sum + count(p, rule), 0)]) + .sort(([, a], [, b]) => b - a); + return [ + '### oxlint warnings', + table( + ['Rule', ...packages, 'Total'], + [ + ...rules.map(([rule, sum]) => [ + `\`${rule}\``, + ...packages.map(p => count(p, rule)), + sum, + ]), + ['**Total**', ...packages.map(total), ''], + ['**Limit**', ...packages.map(p => byPackage[p].limit ?? ''), ''], + ], + ), + ].join('\n\n'); +} + +function lintPackage(dir) { + const { scripts = {} } = JSON.parse( + readFileSync(path.join(dir, 'package.json'), 'utf8'), + ); + const limit = scripts.lint?.match(/--max-warnings (\d+)/)?.[1]; + const rules = {}; + for (const w of collectWarnings(runOxlint(dir, []).results)) { + rules[w.ruleId] = (rules[w.ruleId] ?? 0) + 1; + } + return { limit: limit && Number(limit), rules }; +} + +function main() { + const root = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../..', + ); + const byPackage = {}; + for (const [name, dir] of discoverPackages(root)) { + if (existsSync(path.join(dir, '.oxlintrc.json'))) { + byPackage[name] = lintPackage(dir); + } + } + console.log( + [ + '## Code quality report', + sizeSection(collectLargeFiles(root)), + lintSection(byPackage), + ].join('\n\n'), + ); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) main(); diff --git a/scripts/ci/ratchet.mjs b/scripts/ci/ratchet.mjs index cf877ff5d..d96705d2f 100644 --- a/scripts/ci/ratchet.mjs +++ b/scripts/ci/ratchet.mjs @@ -7,6 +7,7 @@ * e.g. when two count-lowering PRs merge close together and `main`'s * committed baseline briefly sits above the real count. * Advisory patterns (see ADVISORY) are counted and reported but never fail. + * File sizes get the same treatment per file: see compareSizes. */ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; @@ -94,24 +95,117 @@ export function discoverPackages(root) { return found; } -function countDir(dir) { - const counts = Object.fromEntries(Object.keys(PATTERNS).map(n => [n, 0])); +function* sourceFiles(dir) { for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory()) { - if (isSkippedDir(entry.name)) continue; - const sub = countDir(full); - for (const name of Object.keys(counts)) counts[name] += sub[name]; + if (!isSkippedDir(entry.name)) yield* sourceFiles(full); } else if (entry.isFile() && EXTS.has(path.extname(entry.name))) { - const src = readFileSync(full, 'utf8'); - for (const [name, re] of Object.entries(PATTERNS)) { - counts[name] += src.match(re)?.length ?? 0; - } + yield full; + } + } +} + +function countDir(dir) { + const counts = Object.fromEntries(Object.keys(PATTERNS).map(n => [n, 0])); + for (const file of sourceFiles(dir)) { + const src = readFileSync(file, 'utf8'); + for (const [name, re] of Object.entries(PATTERNS)) { + counts[name] += src.match(re)?.length ?? 0; } } return counts; } +export const MAX_FILE_LINES = 300; + +// Tests, stories and type declarations are long for reasons that splitting +// does not fix. +const SIZE_EXEMPT = + /(^|\/)(__tests__|__mocks__|__fixtures__|tests|migrations)\/|\.(test|spec|stories)\.tsx?$|\.d\.ts$/; + +/** Line counts of source files over MAX_FILE_LINES, keyed by repo-relative path. */ +export function collectLargeFiles(root) { + const large = {}; + for (const dir of discoverPackages(root).values()) { + for (const file of sourceFiles(dir)) { + const rel = path.relative(root, file).split(path.sep).join('/'); + if (SIZE_EXEMPT.test(rel)) continue; + const lines = readFileSync(file, 'utf8').trimEnd().split('\n').length; + if (lines > MAX_FILE_LINES) large[rel] = lines; + } + } + return Object.fromEntries( + Object.entries(large).sort(([a], [b]) => a.localeCompare(b)), + ); +} + +/** A baselined file that is gone, or now under the limit, and was at least this long. */ +function movedFrom(lines, current, baseline) { + return Object.keys(baseline).find( + old => !(old in current) && baseline[old] >= lines, + ); +} + +/** + * A file already over the limit may not grow, and no other file may cross it. + * @returns {{failed: boolean, messages: string[]}} + */ +export function compareSizes(current, baseline) { + const messages = []; + let failed = false; + for (const [file, lines] of Object.entries(current)) { + const max = baseline[file]; + const source = max === undefined && movedFrom(lines, current, baseline); + if (source) { + failed = true; + messages.push( + `x ${file}: ${lines} lines, moved or split from ${source} — run \`yarn ratchet:update\``, + ); + } else if (max === undefined) { + failed = true; + messages.push( + `x ${file}: ${lines} lines > ${MAX_FILE_LINES} — split it into smaller files`, + ); + } else if (lines > max) { + failed = true; + messages.push( + `x ${file}: ${lines} lines > baseline ${max} — already over ${MAX_FILE_LINES}, so put the new code in another file`, + ); + } + } + for (const [file, max] of Object.entries(baseline)) { + if ((current[file] ?? 0) < max) { + messages.push( + `! ${file}: ${current[file] ?? `under ${MAX_FILE_LINES + 1}`} lines < baseline ${max} — run \`yarn ratchet:update\` to lock the improvement in`, + ); + } + } + return { failed, messages }; +} + +/** + * The baseline `--update` writes. Without `allowGrowth` it only records + * shrinkage and moves, so the command the warnings recommend cannot also + * accept a file that grew. + * @returns {{next: Record, refused: string[]}} + */ +export function nextSizeBaseline(current, baseline, allowGrowth = false) { + const next = {}; + const refused = []; + for (const [file, lines] of Object.entries(current)) { + const max = + baseline[file] ?? baseline[movedFrom(lines, current, baseline) ?? '']; + if (allowGrowth || lines <= max) { + next[file] = lines; + } else { + refused.push(file); + if (file in baseline) next[file] = baseline[file]; + } + } + return { next, refused }; +} + /** Escape-hatch counts for every workspace package, keyed by package dir name. */ export function collectCounts(root) { const current = {}; @@ -174,18 +268,40 @@ function main() { '../..', ); const baselinePath = path.join(root, 'scripts/ci/ratchet-baseline.json'); + const sizePath = path.join(root, 'scripts/ci/file-size-baseline.json'); const current = collectCounts(root); + const sizes = collectLargeFiles(root); + + const sizeBaseline = existsSync(sizePath) + ? JSON.parse(readFileSync(sizePath, 'utf8')) + : {}; if (process.argv.includes('--update')) { + const { next, refused } = nextSizeBaseline( + sizes, + sizeBaseline, + process.argv.includes('--allow-growth'), + ); writeFileSync(baselinePath, JSON.stringify(current, null, 2) + '\n'); + writeFileSync(sizePath, JSON.stringify(next, null, 2) + '\n'); console.log( - `ratchet baseline written to ${path.relative(root, baselinePath)}`, + `ratchet baselines written to ${path.relative(root, path.dirname(baselinePath))}`, ); - return 0; + for (const file of refused) { + console.error( + `x ${file}: ${sizes[file]} lines not recorded — \`--update\` only lowers file sizes; split the file, or pass \`--allow-growth\` and say why in the PR`, + ); + } + return refused.length ? 1 : 0; } - const baseline = JSON.parse(readFileSync(baselinePath, 'utf8')); - const { failed, messages } = compare(current, baseline); + const counts = compare( + current, + JSON.parse(readFileSync(baselinePath, 'utf8')), + ); + const size = compareSizes(sizes, sizeBaseline); + const failed = counts.failed || size.failed; + const messages = [...counts.messages, ...size.messages]; for (const message of messages) { (message.startsWith('x ') ? console.error : console.warn)(message); } @@ -193,7 +309,7 @@ function main() { console.log( messages.length ? 'ratchet ok: nothing above a gated baseline (see notes above)' - : 'ratchet ok: all escape-hatch counts at baseline', + : 'ratchet ok: all counts and file sizes at baseline', ); return 0; } From 76135aaf5a2f253cf41681a6c840f0f8762bb04a Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 23 Nov 2026 16:46:08 +1100 Subject: [PATCH 2/4] ci: post the code quality report as a PR comment The report was only on the run summary page, which nobody opens. The lint job now posts it as one comment per PR, updated on each push, with the tables collapsed. --- .github/workflows/main.yml | 19 ++++++++++++++++++- scripts/ci/__tests__/quality-report.test.mjs | 1 + scripts/ci/quality-report.mjs | 13 ++++++++++--- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 56016c825..032f3660d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -11,6 +11,9 @@ jobs: lint: timeout-minutes: 8 runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: write steps: - name: Checkout uses: actions/checkout@v6 @@ -73,10 +76,24 @@ jobs: # Advisory: the gates are the ratchet above and each package's # --max-warnings. This only makes the totals visible on the run page. - name: Code quality report + id: quality if: always() continue-on-error: true timeout-minutes: 2 - run: node scripts/ci/quality-report.mjs >> "$GITHUB_STEP_SUMMARY" + run: | + node scripts/ci/quality-report.mjs > "$RUNNER_TEMP/quality-report.md" + cat "$RUNNER_TEMP/quality-report.md" >> "$GITHUB_STEP_SUMMARY" + - name: Comment PR with code quality report + # Skip fork and Dependabot PRs: their GITHUB_TOKEN is read-only + if: + always() && steps.quality.outcome == 'success' && github.event_name == + 'pull_request' && github.event.pull_request.head.repo.fork != true && + github.actor != 'dependabot[bot]' + continue-on-error: true + uses: mshick/add-pr-comment@ec328af66588ab8f77cdeb2c264f14aba45bbf59 # v3.12.0 + with: + message-path: ${{ runner.temp }}/quality-report.md + message-id: code-quality-report # Also unconditional: the api's own `ci:lint` regenerates the spec but # never asserts on it, and nx can skip or cache-replay that task. - name: Check openapi.json is in sync with its sources diff --git a/scripts/ci/__tests__/quality-report.test.mjs b/scripts/ci/__tests__/quality-report.test.mjs index 0cb6a08e9..20735ea99 100644 --- a/scripts/ci/__tests__/quality-report.test.mjs +++ b/scripts/ci/__tests__/quality-report.test.mjs @@ -17,6 +17,7 @@ test('lint section totals each rule across packages, most common first', () => { assert.match(out, /\| `complexity` \| 2 \| 4 \| 6 \|/); assert.match(out, /\| `max-depth` \| 3 \| 0 \| 3 \|/); assert.ok(out.indexOf('complexity') < out.indexOf('max-depth')); + assert.match(out, /api 5\/5, app 4\/9 \(count\/limit\)/); assert.match(out, /\| \*\*Total\*\* \| 5 \| 4 \|/); assert.match(out, /\| \*\*Limit\*\* \| 5 \| 9 \|/); }); diff --git a/scripts/ci/quality-report.mjs b/scripts/ci/quality-report.mjs index 244c34a28..5392d09ca 100644 --- a/scripts/ci/quality-report.mjs +++ b/scripts/ci/quality-report.mjs @@ -14,10 +14,12 @@ import { const TOP = 15; -function table(header, rows) { - return [header, header.map(() => '---'), ...rows] +// Collapsed so the PR comment stays a few lines long. +function table(summary, header, rows) { + const body = [header, header.map(() => '---'), ...rows] .map(cells => `| ${cells.join(' | ')} |`) .join('\n'); + return `
\n${summary}\n\n${body}\n\n
`; } export function sizeSection(large) { @@ -25,8 +27,9 @@ export function sizeSection(large) { const excess = files.reduce((sum, [, n]) => sum + n - MAX_FILE_LINES, 0); return [ '### File size', - `${files.length} source files over ${MAX_FILE_LINES} lines, ${excess} lines over the limit in total. Largest ${Math.min(TOP, files.length)}:`, + `${files.length} source files over ${MAX_FILE_LINES} lines, ${excess} lines over the limit in total.`, table( + `Largest ${Math.min(TOP, files.length)}`, ['File', 'Lines'], files.slice(0, TOP).map(([file, n]) => [`\`${file}\``, n]), ), @@ -46,7 +49,11 @@ export function lintSection(byPackage) { .sort(([, a], [, b]) => b - a); return [ '### oxlint warnings', + packages + .map(p => `${p} ${total(p)}/${byPackage[p].limit ?? '?'}`) + .join(', ') + ' (count/limit).', table( + 'By rule', ['Rule', ...packages, 'Total'], [ ...rules.map(([rule, sum]) => [ From ec16ec21b56b24be85cafac4952ab7443bd0e22c Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 23 Nov 2026 16:46:48 +1100 Subject: [PATCH 3/4] ci: keep the PR comment to totals and link the full report --- .github/workflows/main.yml | 8 ++--- scripts/ci/__tests__/quality-report.test.mjs | 20 ++++++++++- scripts/ci/quality-report.mjs | 38 ++++++++++++++++---- 3 files changed, 55 insertions(+), 11 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 032f3660d..5378b2917 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -80,9 +80,9 @@ jobs: if: always() continue-on-error: true timeout-minutes: 2 - run: | - node scripts/ci/quality-report.mjs > "$RUNNER_TEMP/quality-report.md" - cat "$RUNNER_TEMP/quality-report.md" >> "$GITHUB_STEP_SUMMARY" + run: + node scripts/ci/quality-report.mjs --comment + "$RUNNER_TEMP/quality-comment.md" >> "$GITHUB_STEP_SUMMARY" - name: Comment PR with code quality report # Skip fork and Dependabot PRs: their GITHUB_TOKEN is read-only if: @@ -92,7 +92,7 @@ jobs: continue-on-error: true uses: mshick/add-pr-comment@ec328af66588ab8f77cdeb2c264f14aba45bbf59 # v3.12.0 with: - message-path: ${{ runner.temp }}/quality-report.md + message-path: ${{ runner.temp }}/quality-comment.md message-id: code-quality-report # Also unconditional: the api's own `ci:lint` regenerates the spec but # never asserts on it, and nx can skip or cache-replay that task. diff --git a/scripts/ci/__tests__/quality-report.test.mjs b/scripts/ci/__tests__/quality-report.test.mjs index 20735ea99..ed8d1385a 100644 --- a/scripts/ci/__tests__/quality-report.test.mjs +++ b/scripts/ci/__tests__/quality-report.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { lintSection, sizeSection } from '../quality-report.mjs'; +import { commentBody, lintSection, sizeSection } from '../quality-report.mjs'; test('file size section lists the largest files first', () => { const out = sizeSection({ 'a.ts': 400, 'b.ts': 900 }); @@ -21,3 +21,21 @@ test('lint section totals each rule across packages, most common first', () => { assert.match(out, /\| \*\*Total\*\* \| 5 \| 4 \|/); assert.match(out, /\| \*\*Limit\*\* \| 5 \| 9 \|/); }); + +test('the PR comment is the totals and a link to the full report', () => { + const out = commentBody( + { 'a.ts': 400, 'b.ts': 900 }, + { api: { limit: 5, rules: { complexity: 2, 'max-depth': 3 } } }, + 'https://example.test/runs/1', + ); + assert.equal( + out, + [ + '## Code quality report', + '- 2 source files over 300 lines, 700 lines over the limit in total', + '- oxlint warnings (count/limit): api 5/5', + '', + '[Full report](https://example.test/runs/1)', + ].join('\n'), + ); +}); diff --git a/scripts/ci/quality-report.mjs b/scripts/ci/quality-report.mjs index 5392d09ca..46e555325 100644 --- a/scripts/ci/quality-report.mjs +++ b/scripts/ci/quality-report.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node // Markdown summary of file sizes and oxlint warnings, for the CI job summary. // Advisory: the ratchet and each package's --max-warnings do the gating. -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -68,6 +68,24 @@ export function lintSection(byPackage) { ].join('\n\n'); } +/** The short version posted on the PR; the full report is on the run page. */ +export function commentBody(large, byPackage, runUrl) { + const sizes = Object.values(large); + const excess = sizes.reduce((sum, n) => sum + n - MAX_FILE_LINES, 0); + const lint = Object.entries(byPackage) + .map(([pkg, { limit, rules }]) => { + const total = Object.values(rules).reduce((a, b) => a + b, 0); + return `${pkg} ${total}/${limit ?? '?'}`; + }) + .join(', '); + return [ + '## Code quality report', + `- ${sizes.length} source files over ${MAX_FILE_LINES} lines, ${excess} lines over the limit in total`, + `- oxlint warnings (count/limit): ${lint}`, + ...(runUrl ? ['', `[Full report](${runUrl})`] : []), + ].join('\n'); +} + function lintPackage(dir) { const { scripts = {} } = JSON.parse( readFileSync(path.join(dir, 'package.json'), 'utf8'), @@ -91,13 +109,21 @@ function main() { byPackage[name] = lintPackage(dir); } } + const large = collectLargeFiles(root); console.log( - [ - '## Code quality report', - sizeSection(collectLargeFiles(root)), - lintSection(byPackage), - ].join('\n\n'), + ['## Code quality report', sizeSection(large), lintSection(byPackage)].join( + '\n\n', + ), ); + + const commentPath = process.argv[process.argv.indexOf('--comment') + 1]; + if (process.argv.includes('--comment') && commentPath) { + const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env; + const runUrl = + GITHUB_RUN_ID && + `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`; + writeFileSync(commentPath, commentBody(large, byPackage, runUrl) + '\n'); + } } if (process.argv[1] === fileURLToPath(import.meta.url)) main(); From d34294306605e2837a77ea67d1cc4f026e17c189 Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Mon, 23 Nov 2026 16:53:29 +1100 Subject: [PATCH 4/4] ci: only treat a deleted file as a move source in the size ratchet A baselined file that shrank under 300 lines, or any unrelated deleted file, let a new oversized file through plain ratchet:update. A source now has to be gone from disk and covers new files only up to its own line count. Also builds common-utils before the quality report so its type-aware counts match what ci:lint gates on. --- .github/workflows/main.yml | 10 ++-- scripts/ci/__tests__/ratchet.test.mjs | 45 ++++++++++++++++- scripts/ci/ratchet.mjs | 69 +++++++++++++++++++-------- 3 files changed, 98 insertions(+), 26 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5378b2917..fd7ab5601 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -79,10 +79,12 @@ jobs: id: quality if: always() continue-on-error: true - timeout-minutes: 2 - run: - node scripts/ci/quality-report.mjs --comment - "$RUNNER_TEMP/quality-comment.md" >> "$GITHUB_STEP_SUMMARY" + timeout-minutes: 3 + # `nx affected` above builds dist only for what the PR touches, and + # type-aware lint counts change when common-utils is unbuilt. + run: | + npx nx run @hyperdx/common-utils:ci:build + node scripts/ci/quality-report.mjs --comment "$RUNNER_TEMP/quality-comment.md" >> "$GITHUB_STEP_SUMMARY" - name: Comment PR with code quality report # Skip fork and Dependabot PRs: their GITHUB_TOKEN is read-only if: diff --git a/scripts/ci/__tests__/ratchet.test.mjs b/scripts/ci/__tests__/ratchet.test.mjs index a92dbee4c..726729f1f 100644 --- a/scripts/ci/__tests__/ratchet.test.mjs +++ b/scripts/ci/__tests__/ratchet.test.mjs @@ -16,6 +16,7 @@ import { compare, compareSizes, discoverPackages, + main, nextSizeBaseline, } from '../ratchet.mjs'; @@ -216,6 +217,29 @@ test('a moved file points at ratchet:update instead of asking for a split', () = assert.match(messages[0], /moved or split from a\.ts/); }); +test('a file that shrank but still exists does not license a new large file', () => { + const baseline = { 'shrunk.ts': 1600 }; + const current = { 'new.ts': 1500 }; + const exists = file => file === 'shrunk.ts'; + assert.match( + compareSizes(current, baseline, exists).messages[0], + /new\.ts: 1500 lines > 300/, + ); + assert.deepEqual(nextSizeBaseline(current, baseline, { exists }), { + next: {}, + refused: ['new.ts'], + }); +}); + +test('a deleted file covers new files only up to its own line count', () => { + const baseline = { 'old.ts': 1000 }; + const current = { 'part1.ts': 600, 'part2.ts': 400, 'extra.ts': 400 }; + assert.deepEqual(nextSizeBaseline(current, baseline), { + next: { 'part1.ts': 600, 'part2.ts': 400 }, + refused: ['extra.ts'], + }); +}); + test('update records shrinkage and moves but refuses growth unless allowed', () => { const baseline = { 'a.ts': 500, 'b.ts': 500, 'old.ts': 900 }; const current = { 'a.ts': 400, 'b.ts': 600, 'moved.ts': 900, 'new.ts': 950 }; @@ -223,8 +247,27 @@ test('update records shrinkage and moves but refuses growth unless allowed', () next: { 'a.ts': 400, 'b.ts': 500, 'moved.ts': 900 }, refused: ['b.ts', 'new.ts'], }); - assert.deepEqual(nextSizeBaseline(current, baseline, true), { + assert.deepEqual(nextSizeBaseline(current, baseline, { allowGrowth: true }), { next: current, refused: [], }); }); + +test('--update exits 1 and leaves a grown file out unless --allow-growth', () => { + const root = fixture({ app: { 'src/big.ts': 'x;\n'.repeat(400) } }); + mkdirSync(path.join(root, 'scripts/ci'), { recursive: true }); + const sizePath = path.join(root, 'scripts/ci/file-size-baseline.json'); + const read = file => JSON.parse(readFileSync(file, 'utf8')); + + assert.equal(main(root, ['--update']), 1); + assert.deepEqual(read(sizePath), {}); + assert.deepEqual( + read(path.join(root, 'scripts/ci/ratchet-baseline.json')), + collectCounts(root), + ); + assert.equal(main(root, []), 1); + + assert.equal(main(root, ['--update', '--allow-growth']), 0); + assert.deepEqual(read(sizePath), { 'packages/app/src/big.ts': 400 }); + assert.equal(main(root, []), 0); +}); diff --git a/scripts/ci/ratchet.mjs b/scripts/ci/ratchet.mjs index d96705d2f..05ab4d34d 100644 --- a/scripts/ci/ratchet.mjs +++ b/scripts/ci/ratchet.mjs @@ -140,23 +140,45 @@ export function collectLargeFiles(root) { ); } -/** A baselined file that is gone, or now under the limit, and was at least this long. */ -function movedFrom(lines, current, baseline) { - return Object.keys(baseline).find( - old => !(old in current) && baseline[old] >= lines, +/** + * Pairs new oversized files with baselined files deleted from disk. A source + * covers at most its own line count, so a move or a split passes but new code + * cannot hide behind an unrelated deletion. A file that only shrank is not a + * source: its lines are still in the tree. + * @returns {Map} new path -> baselined path it came from + */ +function findMoves(current, baseline, exists) { + const left = new Map( + Object.entries(baseline).filter( + ([file]) => !(file in current) && !exists(file), + ), ); + const moves = new Map(); + for (const [file, lines] of Object.entries(current)) { + if (file in baseline) continue; + const sameName = old => path.basename(old) === path.basename(file); + const source = [...left.keys()] + .sort((x, y) => sameName(y) - sameName(x)) + .find(old => left.get(old) >= lines); + if (source) { + moves.set(file, source); + left.set(source, left.get(source) - lines); + } + } + return moves; } /** * A file already over the limit may not grow, and no other file may cross it. * @returns {{failed: boolean, messages: string[]}} */ -export function compareSizes(current, baseline) { +export function compareSizes(current, baseline, exists = () => false) { const messages = []; let failed = false; + const moves = findMoves(current, baseline, exists); for (const [file, lines] of Object.entries(current)) { const max = baseline[file]; - const source = max === undefined && movedFrom(lines, current, baseline); + const source = moves.get(file); if (source) { failed = true; messages.push( @@ -190,12 +212,16 @@ export function compareSizes(current, baseline) { * accept a file that grew. * @returns {{next: Record, refused: string[]}} */ -export function nextSizeBaseline(current, baseline, allowGrowth = false) { +export function nextSizeBaseline( + current, + baseline, + { allowGrowth = false, exists = () => false } = {}, +) { const next = {}; const refused = []; + const moves = findMoves(current, baseline, exists); for (const [file, lines] of Object.entries(current)) { - const max = - baseline[file] ?? baseline[movedFrom(lines, current, baseline) ?? '']; + const max = baseline[file] ?? (moves.has(file) ? lines : undefined); if (allowGrowth || lines <= max) { next[file] = lines; } else { @@ -262,11 +288,13 @@ export function compare(current, baseline) { return { failed, improved, messages }; } -function main() { - const root = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../..', - ); +const REPO_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../..', +); + +export function main(root = REPO_ROOT, argv = process.argv) { + const exists = file => existsSync(path.join(root, file)); const baselinePath = path.join(root, 'scripts/ci/ratchet-baseline.json'); const sizePath = path.join(root, 'scripts/ci/file-size-baseline.json'); const current = collectCounts(root); @@ -276,12 +304,11 @@ function main() { ? JSON.parse(readFileSync(sizePath, 'utf8')) : {}; - if (process.argv.includes('--update')) { - const { next, refused } = nextSizeBaseline( - sizes, - sizeBaseline, - process.argv.includes('--allow-growth'), - ); + if (argv.includes('--update')) { + const { next, refused } = nextSizeBaseline(sizes, sizeBaseline, { + allowGrowth: argv.includes('--allow-growth'), + exists, + }); writeFileSync(baselinePath, JSON.stringify(current, null, 2) + '\n'); writeFileSync(sizePath, JSON.stringify(next, null, 2) + '\n'); console.log( @@ -299,7 +326,7 @@ function main() { current, JSON.parse(readFileSync(baselinePath, 'utf8')), ); - const size = compareSizes(sizes, sizeBaseline); + const size = compareSizes(sizes, sizeBaseline, exists); const failed = counts.failed || size.failed; const messages = [...counts.messages, ...size.messages]; for (const message of messages) {