diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8fb5f48fb8c..99ed71a5201 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -732,10 +732,12 @@ jobs: # - `content/docs/ui/pages.mdx`, where the per-element data # binding section of the old data-source guide landed. Two Test # UI pins read its fences and its block table (objectstack#27145). - # And, a class of its own outside that count: each root - # `docs/adr/` file a ui test reads, named verbatim (objectstack#37935, - # the row at the end of this list). `check:ci-filter-parity` derives - # those rows from the ui tests and holds them to them both ways. + # And, a class of its own outside that count: each file outside ui/ + # that a ui test reads, named verbatim (objectstack#37935, #38133; + # the group at the end of this list). `check:ci-filter-parity` + # derives those rows from the ui tests and holds them to them both + # ways, and pins this whole step's input and every ui job's `if:` + # (objectstack#38132). ui: - 'ui/**' - 'pnpm-lock.yaml' @@ -773,18 +775,49 @@ jobs: # confined to a pnpm bump matched no list here, so the ui jobs # skipped on the PR and in the queue alike. - 'package.json' - # The ADR files under the root `docs/adr/` that a ui test reads - # (#37935), each named verbatim. Today one: Test UI's + # The root path walker, which ui/scripts/select-affected-tests.mjs + # imports at run time (`loadPathWalker`) to place every ui test: + # select-affected-tests.test.ts asserts on it. A read inside an + # imported ui module, which the gate's ui-test scan does not see, + # so it is named here rather than in the group below. + - 'scripts/check-cross-package-test-inputs.mjs' + # ── UI TEST READS OUTSIDE ui/ ─────────────────────────────── + # Each file outside ui/ that a ui test reads, named verbatim + # (#37935, #38133). A diff confined to one could break the test + # that reads it while starting no ui job, on the PR or in the + # queue (this list reads the queue diff too). Named files rather + # than a subtree: a subtree row would start the whole ui battery + # on every edit beside the one file a test reads, and `ui_consumers` + # already covers the seven packages it names. + # `check:ci-filter-parity` derives the readers from the ui tests + # and holds every row below this heading to them, both ways. A + # read deliberately left unscheduled is a `ui-read trade-off:` + # line naming the file and why, never a missing row. + # # studioMenuPlacement.test.ts holds ADR-0084's type-to-group - # table equal to the Studio menu code, so an edit confined to - # that ADR could break the pin while starting no ui job, on the - # PR or in the queue (this list reads the queue diff too). Named - # files rather than `docs/adr/**`: no other ui test reads under - # the root `docs/adr/` (the ui tree's own ADRs are `ui/**`), and - # a subtree row would start the whole ui battery on every ADR - # edit. `check:ci-filter-parity` derives the readers from the ui - # tests themselves and holds this group to them, both ways. + # table equal to the Studio menu code. - 'docs/adr/0084-application-builder-information-architecture.md' + # quick-reference-commands-4149.test.ts holds the root + # CONTRIBUTING.md's UI Workspace commands to the ui scripts. + - 'CONTRIBUTING.md' + # identityImportFields.endpointColumns-34536.test.ts holds the + # identity import dialog's columns to what the endpoint reads. + - 'packages/plugins/plugin-auth/src/admin-import-users.ts' + # The ui shard planner and selector tests import the shard + # count from the root roster reader, which imports invoked-as. + - 'scripts/ci-shard-matrix.mjs' + - 'scripts/invoked-as.mjs' + # metadata-form-option-names.test.ts loads the platform zh-CN + # forms pack through `new URL(literal, import.meta.url)` and holds + # the Console's option maps equal to it. + - 'packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts' + # ui-read trade-off: packages/mcp/src/skill-md.ts -- the + # Console's objectstack-skill.test.ts imports it to pin the + # "Download skill" mirror; the server half of that drift pin + # runs in Test Core on every packages/mcp change, and a + # mirror-only diff starts it through the `crosspkg` row (#31017). + # The modules it loads at runtime (ask-skill.generated.ts, + # mcp-http-tools.ts and theirs) inherit this trade-off. # The seven packages objectui installs from this tree (the set its # `.objectstack-pin` used to pack). A change here compiles, builds # and tests the Console in the same PR — the check the retired Spec diff --git a/scripts/check-ci-filter-parity.mjs b/scripts/check-ci-filter-parity.mjs index 777db637c47..1ec57047cde 100644 --- a/scripts/check-ci-filter-parity.mjs +++ b/scripts/check-ci-filter-parity.mjs @@ -232,37 +232,121 @@ * JSON, no `tasks` map, and no generic `test` task. The self-test pins the task * pair against the real job's command. * - * ## The fifth subject: Test UI and the root ADR files ui tests read (#37935) + * ## The fifth subject: Test UI and the files outside ui/ that ui tests read (#37935, #38133) * * `studioMenuPlacement.test.ts` (Test UI) holds ADR-0084's type-to-group table * equal to the Studio menu code, and it reads the ADR from the ROOT * `docs/adr/`, outside `ui/`. The `ui:` list named no such file, so a diff * confined to the ADR started no ui job on the PR, nor in the merge queue, * where the `ui` output reads the queue diff through the same list: the pin - * first ran on the next ui PR, red on a change that PR did not make. + * first ran on the next ui PR, red on a change that PR did not make. The same + * holds for every file outside `ui/` a ui test reads -- a root document, a + * server source whose shape a ui test pins, a root script a ui test imports -- + * so the population is all of them, not the one root that showed it first. * * `uiRootReadsOf` DERIVES the population from the ui tests themselves: every * tracked `ui/**` test file is read by `scanPathExpressions`, the walker - * `check:cross-package-test-inputs` and the ui test selector already use, so - * this is not a recognizer of its own and holds no list. Each read under - * UI_READ_ROOTS must be covered, by the same pure-string rule, by a list the - * `test-ui` job's `if:` ORs (read back out of it; `ui` must be among them), - * and a `ui` row under those roots that no ui test reads is a leftover, since - * it starts every ui job for an edit nothing there reads. The remedy is the - * file VERBATIM, never `docs/adr/**`, which would start the ui battery on every - * ADR edit for the one file a ui test reads. + * `check:cross-package-test-inputs` and the ui test selector already use, and + * an import is resolved by that gate's own `resolveImportTarget`, so this is + * not a recognizer of its own and holds no list. One spelling the walker does + * not read is read here too: a one-piece relative literal that climbs out of + * `ui/` from the test's own directory and names a file on disk, the + * `await import(new URL('../…', import.meta.url).href)` form + * (`metadata-form-option-names.test.ts` loads the platform zh-CN forms pack + * that way). A module a test loads, by import or by that literal, runs its own + * first-party imports, so each one is a read of that test too: + * `moduleReadClosure`, attributed `TEST (via MODULE)`; an import in it that + * resolves to nothing is a refusal. That is how `scripts/invoked-as.mjs`, which + * `scripts/ci-shard-matrix.mjs` imports, is in the population. The closure + * reads TypeScript modules as TypeScript resolves them (S5): a `.js` specifier + * names its `.ts` source when no `.js` file exists, an extensionless one gains + * the TS extensions or `/index.ts`, and a type-only `import type` / `export + * type` statement, which loads nothing, is not followed. Only a module the + * test LOADS is walked: an import, or a `new URL` literal in a test that calls + * `import(`. A file a test reads as TEXT (`readFileSync`) is a read, and what + * it imports is not. A module reached only through a declared trade-off + * inherits it, reported as a trade-off `via` that module: the mcp + * `skill-md.ts` trade-off covers `ask-skill.generated.ts` and the + * `mcp-http-tools.ts` closure it loads. One that a test also loads directly + * needs its own row. Each read must be covered, by + * the same pure-string rule, by a list the `test-ui` job's `if:` ORs (read + * back out of it; `ui` must be among them), or be DECLARED a trade-off. * - * Known bounds: the population is the root `docs/adr/` alone, as ruled. Other - * reads outside `ui/` that the walker sees and no ui list covers (measured on - * the commit this subject landed on: a root markdown file, two server sources - * and a root script) are a family of their own, each a scheduling trade-off - * rather than a missing row, and are not judged here. A ui test whose read the - * walker cannot resolve (an unread argument, a manifest-name `findUp`, which is - * judged with no package name) is not in the population, exactly as the - * walker's other callers do not see it. The walker reads each test file's own - * text, so a read made inside a module the test IMPORTS is not seen either: a - * `ui` row whose only reader is such a helper is reported as reader-less, and - * the leftover direction therefore says check, then delete, never delete. + * Both answers live in one place in ci.yml, the reads group at the end of the + * `ui:` list: every row below its UI_READS_GROUP_MARKER heading is a file a ui + * test reads, named verbatim, and a `# ui-read trade-off: PATH -- REASON` line + * there is a read left unscheduled on purpose, with the reason that names what + * runs it instead. The remedy is the file verbatim, never a subtree, which + * would start the ui battery on every edit beside the one file a test reads. + * The other direction is judged in the group alone: a row below the heading no + * ui test reads is a leftover, and a trade-off for a read no test makes, or + * for one a row now covers, is stale. Rows above the heading are the ui jobs' + * own build and gate inputs, which no test read accounts for, and the sixth + * subject pins them instead. The group is read from the `filters:` TEXT + * because YAML drops the comments that carry it; a missing or doubled heading + * and an unreadable trade-off line are refusals. + * + * Known bounds: a ui test whose read the walker cannot resolve (an unread + * argument, a manifest-name `findUp`, which is judged with no package name) is + * not in the population, exactly as the walker's other callers do not see it. + * The walker reads each test file's own text; for a module the test loads, + * only its static relative IMPORTS are followed, never the files it reads from + * disk or its dynamic imports, and an import a source spells across lines + * with no line-start `import`/`export` or `} from` is not read (the + * statement-shaped rule of `first-party-closure.mjs`). A `new URL` literal in + * a test that calls `import(` is walked even when the test only reads that + * file, the conservative direction. So a `readFileSync` inside an imported helper + * is not seen, nor is a module loaded by a computed `import()` (the ui + * selector loads `scripts/check-cross-package-test-inputs.mjs` that way): a + * reads-group row whose only reader is such a helper is reported as + * reader-less, and the leftover direction therefore says check, then delete, + * never delete. The walker module itself is a row ABOVE the heading for that + * reason, held by the sixth subject. Imports inside `ui/` are not followed + * here, since a change under `ui/**` starts the job anyway; a module there + * that reads outside `ui/` is the bound above. + * + * ## The sixth subject: the ui scheduling pin (#38132) + * + * The fifth subject holds the reads group to the reads, and nothing else in + * this gate read the rest of what decides whether a ui job starts: the other + * inputs of the paths-filter step (`predicate-quantifier`, `base`, `ref` and + * the rest each change which diff is read or how a row matches it), the + * `filter` job's output expressions the ui jobs read, the rows above the + * reads group, and every ui job's own `if:`. An edit to any of them could make + * a ui job skip on a diff where it ran before, and the gate stayed green. + * + * `judgeUiScheduling` holds the real ci.yml to UI_PIN_FILE, the least it may + * schedule the ui jobs. The step's `with:` keys and the pinned outputs are + * held EXACTLY, since neither has a direction this gate can read. The rows of + * each pinned filter are held EXACTLY too, as a ratchet (the `ui` list's rows + * below its reads-group heading are the fifth subject's and are left out): a + * pinned row gone reds as missing, and a row added reds as unpinned until the + * pin names it, so that its later removal is caught. Every job whose + * definition reads a ui output (UI_OUTPUT_NAMES) must carry a pinned + * condition, held the same way: the job's `if:` is read as clauses of a + * conjunction, each the set of its disjuncts (`conditionClauses`). GitHub + * wraps an `if:` that names no status function in an implicit `success()`, so + * such a condition carries that clause (IMPLICIT_SUCCESS) and an absent `if:` + * is that clause alone: dropping `!cancelled()` or `always()` ADDS it, and is + * the narrowing it is. A condition must be implied clause by clause by its pin + * (`conditionAtLeast`): adding a clause, dropping a disjunct or rewriting an + * atom reds as narrowed, naming the clause; one that is implied but not equal + * in CNF (a clause dropped, a disjunct added) reds as wider than the pin. The + * comparison is syntactic, so a rewrite that is in fact equivalent or wider + * reds too, which is the safe direction. A deliberate change updates the pin in + * the same PR, so the change to what runs is read where it is made. The pin is a JSON record beside this script, not a + * table in it, so no path literal here is read as this gate's population. + * + * Known bounds: the rows of `core`, which only `live-e2e-ui` ORs in, are not + * pinned here (the first, third and fourth subjects hold them); the workflow's + * own `on:` triggers, their `paths:` / `paths-ignore:` and `branches:` filters, + * which decide whether ci.yml runs at all and so gate every ui job before any + * `if:` is read, are not judged; a narrowing + * through another job's output a ui `if:` reads (`borrowed-verdict`, + * `queue-verdict`, `test-ui-plan`), through `needs:`, or through a step-level + * `if:` inside a ui job is not judged; and the `ui-tree` step's own script is + * not read. Refusals: the pin file absent, not JSON, or missing any of its + * four parts or a ui output, and every refusal of the filter reader. * * ## Wiring * @@ -276,7 +360,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; +import { dirname, join, posix, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import process from 'node:process'; @@ -284,9 +368,9 @@ import { requireDependency } from './import-prerequisite.mjs'; const { parse } = await requireDependency('yaml', () => import('yaml'), import.meta.url); import { collectInvocations } from './check-self-test-wired.mjs'; -import { scanPathExpressions } from './check-cross-package-test-inputs.mjs'; +import { resolveImportTarget, scanPathExpressions } from './check-cross-package-test-inputs.mjs'; import { CROSS_PACKAGE_TEST_INPUTS } from './cross-package-test-inputs.mjs'; -import { firstPartyModuleClosure } from './first-party-closure.mjs'; +import { firstPartyImportEdges, firstPartyModuleClosure } from './first-party-closure.mjs'; import { isEntrypoint } from './invoked-as.mjs'; // ── The self-test's own battery roster and floor (#13489) ────────────────── @@ -318,12 +402,13 @@ const SELF_TEST_BATTERIES = Object.freeze({ '(9) Build Core and the build inputs turbo.json declares': 42, '(10) Build Core and the scripts its own steps run': 30, '(11) Test Core and the generic test tasks\' root inputs': 18, - '(12) Test UI and the root ADR files ui tests read': 16, + '(12) Test UI and the files outside ui/ that ui tests read': 48, + '(13) the ui scheduling pin: the paths-filter input, the ui outputs, the ui rows and every ui job condition': 43, }); // DELETING an entry silences that battery's floor exactly as effectively as // zeroing it, so the roster's own size is pinned too. -const SELF_TEST_BATTERY_FLOOR = 11; +const SELF_TEST_BATTERY_FLOOR = 12; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -474,7 +559,7 @@ function readFilterLists(source) { return { refusal: `${CI_WORKFLOW}'s \`${name}:\` filter is not a list of path strings.` }; } } - return { jobs, filters }; + return { jobs, filters, raw, step: pathsFilterSteps[0] }; } /** @@ -905,38 +990,43 @@ function reportTestInputs(verdict) { return 0; } -// ── The fifth subject: Test UI and the root ADR files ui tests read (#37935) ── +// ── The fifth subject: Test UI and the files outside ui/ that ui tests read (#37935, #38133) ── /** The job that runs the ui tree's vitest suites, by id. */ export const UI_TEST_JOB = 'test-ui'; /** The filter outputs its `if:` may OR; `ui` must be among the ones it names. */ export const UI_SCHEDULING_FILTERS = Object.freeze(['ui', 'ui_consumers']); -/** Where an uncovered read belongs, and the list whose rows under the roots are judged for leftovers. */ +/** Where an uncovered read belongs, and the list whose reads group is judged for leftovers. */ export const UI_REMEDY_FILTER = 'ui'; -/** The tree whose tests are read. */ +/** The tree whose tests are read; every read outside it is this subject's population. */ export const UI_TREE = 'ui'; /** - * The repo-root roots this subject judges. The ruled population is the root - * `docs/adr/` (see the header for why it is not every read outside `ui/`). + * The heading comment that opens the reads group at the end of the `ui:` list. + * Every row below it must have a reader; rows above it are the ui jobs' own + * build and gate inputs, which no test read accounts for. */ -export const UI_READ_ROOTS = Object.freeze(['docs/adr']); +export const UI_READS_GROUP_MARKER = 'UI TEST READS OUTSIDE ui/'; +/** A comment line in the reads group declaring a read left unscheduled on purpose: ` -- `. */ +export const UI_TRADE_OFF_MARKER = 'ui-read trade-off:'; const UI_TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/; -const underRoots = (path) => UI_READ_ROOTS.some((r) => path === r || path.startsWith(`${r}/`)); +const insideUiTree = (path) => path === UI_TREE || path.startsWith(`${UI_TREE}/`); /** - * Every path under UI_READ_ROOTS that a tracked ui test file reads, each with - * its readers, or `{ refusal }`. The reads come from `scanPathExpressions`, the + * Every path outside `ui/` that a tracked ui test file reads, each with its + * readers, or `{ refusal }`. The reads come from `scanPathExpressions`, the * walker `check:cross-package-test-inputs` and the ui test selector already use * -- not a recognizer of this gate's own. `files` (a bound name) and relative * `imports` are file candidates, `dirs` (a listing) directory candidates, and * each counts only as what it really is on disk, the filter * `check:cross-package-test-inputs` applies to the same walker's answer: the * walker puts every BOUND name in `files`, so a directory bound to a name and - * then listed sits in both sets, and only the disk says it is a directory. A - * candidate naming nothing on disk is a synthetic fixture path, not a read. A - * directory read is covered only by its subtree. + * then listed sits in both sets, and only the disk says it is a directory. An + * import is resolved by that gate's own `resolveImportTarget` (an + * extensionless or `.js` specifier names the `.ts` source). A candidate naming + * nothing on disk is a synthetic fixture path, not a read. A directory read is + * covered only by its subtree. * * @param {string} root the repository root * @param {string[] | null} [listed] repo-relative tracked files (git's answer when absent) @@ -962,19 +1052,103 @@ export function uiRootReadsOf(root, listed = null) { } const segs = rel.split('/'); const scan = scanPathExpressions(source, segs.length - 1, segs, null); - const candidates = [...[...scan.files, ...scan.imports].map((p) => [p, 'file']), ...[...scan.dirs].map((p) => [p, 'dir'])]; + const imports = [...scan.imports].map((p) => resolveImportTarget(p, root) ?? p); + // The second candidate source (#38133): a one-piece relative literal that + // resolves outside ui/ from the test's own directory, whatever call it is + // handed to -- `new URL(literal, import.meta.url)` for a dynamic import is + // the spelling the walker does not read. A file on disk only: a literal + // naming a directory (`'../../..'`) is a root, not a read. + const escaping = [...source.matchAll(ESCAPING_LITERAL)] + .map((m) => posix.normalize(posix.join(posix.dirname(rel), m[2]))) + .filter((p) => !insideUiTree(p) && realKindOf(root, p) === 'file'); + const candidates = [...[...scan.files, ...imports, ...escaping].map((p) => [p, 'file']), ...[...scan.dirs].map((p) => [p, 'dir'])]; + // The modules the test LOADS, whose own imports run with it: its imports, + // and a `new URL(literal, import.meta.url)` in a source that calls + // `import(` (S5). A file read as text (`readFileSync`) is not loaded, and + // what it imports is no read of the test. + const loaded = new Set(imports); + if (DYNAMIC_IMPORT.test(source)) { + for (const m of source.matchAll(URL_LITERAL)) loaded.add(posix.normalize(posix.join(posix.dirname(rel), m[2]))); + } for (const name of new Set(candidates.map(([p]) => p))) { - if (!underRoots(name)) continue; + if (!name || insideUiTree(name) || name.startsWith('..') || name.startsWith('/') || name.split('/').includes('node_modules')) continue; const kind = realKindOf(root, name); if (!kind || !candidates.some(([p, k]) => p === name && k === kind)) continue; - const row = byPath.get(name) ?? { path: name, kind, from: [] }; - if (!row.from.includes(rel)) row.from.push(rel); - byPath.set(name, row); + // A module the test loads runs its own first-party imports too, so each + // one is a read of this test (S4), TypeScript modules included (S5): `moduleReadClosure`. + let reached = [name]; + if (kind === 'file' && loaded.has(name) && MODULE_FILE.test(name)) { + try { + reached = moduleReadClosure(name, root); + } catch (err) { + return { refusal: `the module ${name}, which the ui test ${rel} loads, has an import that resolves to nothing: ${err?.message ?? err}` }; + } + } + for (const path of reached) { + if (insideUiTree(path)) continue; + const row = byPath.get(path) ?? { path, kind: path === name ? kind : 'file', from: [] }; + const via = path === name ? rel : `${rel} (via ${name})`; + if (!row.from.includes(via)) row.from.push(via); + byPath.set(path, row); + } } } return { tests: tests.length, rows: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)) }; } +/** + * Every first-party module reachable from `entryRel` by static relative + * imports, INCLUDING it, read the way TypeScript resolves them (S5): a `.js` + * specifier names its `.ts`/`.tsx` source when no `.js` file exists, and an + * extensionless one gains `.ts`/`.tsx`/`.mts` or `/index.ts` -- the same + * `resolveImportTarget` that resolves the tests' own imports. The edges are + * `firstPartyImportEdges`, the statement-shaped reader that the third + * subject's `firstPartyModuleClosure` walks. That walker follows only + * `.js`/`.mjs`, because it stages runnable copies, and is left as it is. A + * module under `ui/` is not walked (a change there starts the job anyway), nor + * is a `.json` or other non-module file. A specifier that resolves to nothing + * throws, never a short closure. + */ +export function moduleReadClosure(entryRel, root) { + const seen = []; + const walk = (rel) => { + if (seen.includes(rel)) return; + seen.push(rel); + if (insideUiTree(rel) || !MODULE_FILE.test(rel)) return; + for (const spec of runtimeImportEdges(readFileSync(join(root, rel), 'utf8'))) { + const target = posix.normalize(posix.join(posix.dirname(rel), spec)); + const found = resolveImportTarget(target, root) ?? resolveImportTarget(`${target}/index.ts`, root); + if (!found) throw new Error(`${rel} imports ${JSON.stringify(spec)}, which resolves to no file under the repo root`); + walk(found); + } + }; + walk(entryRel); + return seen; +} + +/** + * `firstPartyImportEdges` less the type-only statements (`import type`, + * `export type`), which TypeScript erases: they load nothing when the test + * runs. A multi-line statement is judged by its opening keyword line. + */ +export function runtimeImportEdges(source) { + const text = String(source ?? ''); + const typeOnly = new Set(); + for (const m of text.matchAll(/^[ \t]*(?:import|export)[ \t]+type\b[^;]*?from[ \t]*['"](\.[^'"\n]+)['"]/gms)) typeOnly.add(m[1]); + const runtime = new Set(); + for (const m of text.matchAll(/^[ \t]*(?:import|export)(?![ \t]+type\b)[^;'"]*?from[ \t]*['"](\.[^'"\n]+)['"]/gms)) runtime.add(m[1]); + return firstPartyImportEdges(text).filter((spec) => runtime.has(spec) || !typeOnly.has(spec)); +} + +/** A one-piece relative literal that climbs: `'../x'`, `"../../y/z.ts"`. */ +const ESCAPING_LITERAL = /(['"`])(\.\.\/[A-Za-z0-9._@/-]+)\1/g; +/** A `new URL('../…', import.meta.url)` literal, the dynamic-import spelling. */ +const URL_LITERAL = /\bnew\s+URL\(\s*(['"`])(\.\.\/[^'"`\n$]+)\1\s*,\s*import\.meta\.url/g; +/** A dynamic `import(` call. */ +const DYNAMIC_IMPORT = /\bimport\s*\(/; +/** A file whose first-party imports run when it is loaded. */ +const MODULE_FILE = /\.[cm]?[jt]sx?$/; + /** `'file'`, `'dir'`, or null when `rel` names nothing on disk under `root`. */ function realKindOf(root, rel) { try { @@ -990,9 +1164,94 @@ const uiCoverage = (row, entries) => row.kind === 'dir' ? coverageVerdict(`${row.path}/x`, entries) : coverageVerdict(row.path, entries); /** - * The verdict on Test UI's scheduling against the root ADR files ui tests read. - * Takes ci.yml's SOURCE STRING and the reads (`uiRootReadsOf`'s answer); - * `{ refusal }` for every state in which the subject was not read. + * The reads group of the `ui:` list, read out of the `filters:` input's TEXT, + * because YAML drops the comments that carry its heading and its trade-offs. + * Returns `{ rows, tradeOffs }` -- the list items below the heading and a Map + * of declared trade-off path to reason -- or `{ refusal }`. + */ +export function uiReadsGroupOf(raw) { + const lines = String(raw ?? '').split('\n'); + const indentOf = (l) => l.match(/^\s*/)[0].length; + const keyAt = lines.findIndex((l) => new RegExp(`^\\s*${UI_REMEDY_FILTER}:\\s*$`).test(l)); + if (keyAt < 0) return { refusal: `${CI_WORKFLOW}'s \`filters:\` input has no \`${UI_REMEDY_FILTER}:\` list to read the reads group from.` }; + const keyIndent = indentOf(lines[keyAt]); + let end = lines.length; + for (let i = keyAt + 1; i < lines.length; i++) { + const t = lines[i].trim(); + if (t && indentOf(lines[i]) <= keyIndent && !t.startsWith('#') && !t.startsWith('-')) { + end = i; + break; + } + } + // Only lines indented under the key belong to it: a comment at the key's own + // column introduces the NEXT list. + const body = lines.slice(keyAt + 1, end).filter((l) => !l.trim() || indentOf(l) > keyIndent); + const headings = body.map((l, i) => [l, i]).filter(([l]) => l.trim().startsWith('#') && l.includes(UI_READS_GROUP_MARKER)); + if (headings.length !== 1) { + return { + refusal: + `${CI_WORKFLOW}'s \`${UI_REMEDY_FILTER}:\` list carries ${headings.length} \`${UI_READS_GROUP_MARKER}\` heading(s); this gate reads ` + + `exactly one, above the rows that schedule the ui tests' reads outside ${UI_TREE}/.`, + }; + } + const rows = []; + const tradeOffs = new Map(); + const malformed = []; + // The reason runs on over the comment lines that follow the marker line, up + // to the next row, the next marker line, a bare `#` or a blank line. + let open = null; + for (const line of body.slice(headings[0][1] + 1)) { + const t = line.trim(); + const item = /^-\s*(['"]?)(.*)\1\s*$/.exec(t); + if (item) { + open = null; + rows.push(item[2]); + continue; + } + const comment = /^#\s*(.*)$/.exec(t)?.[1]; + if (comment === undefined || comment.trim() === '') { + open = null; + continue; + } + // A trade-off line STARTS with the marker; prose that mentions it does not declare one. + if (!comment.startsWith(UI_TRADE_OFF_MARKER)) { + if (open) tradeOffs.set(open, `${tradeOffs.get(open)} ${comment.trim()}`); + continue; + } + const m = /^(\S+)\s+--\s+(\S.*)$/.exec(comment.slice(UI_TRADE_OFF_MARKER.length).trim()); + if (m) { + tradeOffs.set(m[1], m[2].trim()); + open = m[1]; + } else { + open = null; + malformed.push(t); + } + } + if (malformed.length > 0) { + return { + refusal: + `${CI_WORKFLOW}'s reads group carries a \`${UI_TRADE_OFF_MARKER}\` line this gate cannot read; spell it ` + + `\`# ${UI_TRADE_OFF_MARKER} PATH -- REASON\`:\n` + malformed.map((l) => ` ${l}`).join('\n'), + }; + } + return { rows, tradeOffs }; +} + +/** + * The declared trade-off a read inherits, or null: a module reached ONLY + * through a traded-off module (every reader is `TEST (via MODULE)` with MODULE + * traded off) runs under the same reason, since it is what that module loads. + */ +function inheritedTradeOff(row, tradeOffs) { + const parents = row.from.map((f) => /\(via (.+)\)$/.exec(f)?.[1] ?? null); + if (parents.length === 0 || parents.some((p) => !p || !tradeOffs.has(p))) return null; + return [...new Set(parents)].sort().join(', '); +} + +/** + * The verdict on Test UI's scheduling against the files outside `ui/` that ui + * tests read. Takes ci.yml's SOURCE STRING and the reads (`uiRootReadsOf`'s + * answer); `{ refusal }` for every state in which the subject was not read. */ export function judgeUiReads(source, reads) { const read = readFilterLists(source); @@ -1013,58 +1272,327 @@ export function judgeUiReads(source, reads) { for (const name of named) { if (!(name in read.filters)) return { refusal: `${CI_WORKFLOW}'s \`filters:\` input declares no \`${name}:\` filter.` }; } + const group = uiReadsGroupOf(read.raw); + if (group.refusal) return group; const entries = named.flatMap((n) => read.filters[n]); const covered = []; + const tradedOff = []; const uncovered = []; for (const row of reads.rows) { const verdict = uiCoverage(row, entries); - (verdict.covered ? covered : uncovered).push({ ...row, ...verdict }); - } - // The other direction: a `ui` row under the judged roots that no ui test - // reads any more starts the whole ui battery for nothing. - const stale = read.filters[UI_REMEDY_FILTER].filter( - (entry) => underRoots(entry.replace(/\/\*\*$/, '')) && !reads.rows.some((row) => uiCoverage(row, [entry]).covered), - ); - return { condition, named, tests: reads.tests, rows: reads.rows, covered, uncovered, stale }; + if (verdict.covered) covered.push({ ...row, ...verdict }); + else if (group.tradeOffs.has(row.path)) tradedOff.push({ ...row, reason: group.tradeOffs.get(row.path) }); + else if (inheritedTradeOff(row, group.tradeOffs)) tradedOff.push({ ...row, reason: `imported by the declared trade-off ${inheritedTradeOff(row, group.tradeOffs)}`, via: inheritedTradeOff(row, group.tradeOffs) }); + else uncovered.push({ ...row, ...verdict }); + } + // The other direction: a reads-group row that no ui test reads any more + // starts the whole ui battery for nothing, and a trade-off for a read that is + // gone, or that a row now schedules, declares a gap that is not there. + const stale = group.rows.filter((entry) => !reads.rows.some((row) => uiCoverage(row, [entry]).covered)); + const staleTradeOffs = [...group.tradeOffs.keys()].filter( + (path) => !reads.rows.some((row) => row.path === path) || covered.some((row) => row.path === path), + ); + return { condition, named, tests: reads.tests, rows: reads.rows, covered, tradedOff, uncovered, stale, staleTradeOffs }; } function reportUiReads(verdict) { if (verdict.refusal) { - console.error(`FAIL: check-ci-filter-parity could not judge Test UI's reads under ${UI_READ_ROOTS.join(', ')}.\n\n - ${verdict.refusal}\n`); + console.error(`FAIL: check-ci-filter-parity could not judge Test UI's reads outside ${UI_TREE}/.\n\n - ${verdict.refusal}\n`); return 1; } const problems = []; if (verdict.uncovered.length > 0) { problems.push( - `${verdict.uncovered.length} path(s) under ${UI_READ_ROOTS.map((r) => `\`${r}/\``).join(', ')} that a ui test reads are covered by ` + - `none of ${verdict.named.map((n) => `\`${n}\``).join(', ')} in ${CI_WORKFLOW}. A diff confined to one starts no\n` + - ` \`${UI_TEST_JOB}\` job, on the PR or in the merge queue, so the test that reads it first runs on the next ui PR:\n` + + `${verdict.uncovered.length} path(s) outside ${UI_TREE}/ that a ui test reads are covered by none of ` + + `${verdict.named.map((n) => `\`${n}\``).join(', ')} in ${CI_WORKFLOW} and declared as no trade-off. A diff confined to one\n` + + ` starts no \`${UI_TEST_JOB}\` job, on the PR or in the merge queue, so the test that reads it first runs on the next ui PR:\n` + verdict.uncovered.map((r) => ` ${r.path}${r.kind === 'dir' ? '/**' : ''} (read by ${r.from.join(', ')})`).join('\n') + - `\n Add each one VERBATIM to the \`${UI_REMEDY_FILTER}:\` filter in ${CI_WORKFLOW} (a directory read as \`/**\`).`, + `\n Add each one VERBATIM below the \`${UI_READS_GROUP_MARKER}\` heading of the \`${UI_REMEDY_FILTER}:\` filter in ${CI_WORKFLOW}\n` + + ` (a directory read as \`/**\`), or change the test so it does not read the file. A read left unscheduled on\n` + + ` purpose is a \`# ${UI_TRADE_OFF_MARKER} PATH -- REASON\` line in that group, naming what runs it instead.`, ); } if (verdict.stale.length > 0) { problems.push( - `${CI_WORKFLOW}'s \`${UI_REMEDY_FILTER}:\` filter carries entr(ies) under ${UI_READ_ROOTS.join(', ')} that no ui test reads any more:\n` + + `${CI_WORKFLOW}'s \`${UI_REMEDY_FILTER}:\` reads group carries row(s) that no ui test reads any more:\n` + verdict.stale.map((e) => ` ${e}`).join('\n') + `\n Check each, then delete it: it starts every ui job for an edit no ui test file reads. This gate sees only\n` + ` the reads a ui test file spells itself, not one made inside a module the test imports, so first confirm\n` + - ` no imported helper reads it.`, + ` no imported helper reads it; a row such a helper needs belongs above the heading, with its reason.`, + ); + } + if (verdict.staleTradeOffs.length > 0) { + problems.push( + `${CI_WORKFLOW}'s reads group declares trade-off(s) for a read no ui test makes, or one a row already schedules:\n` + + verdict.staleTradeOffs.map((e) => ` ${e}`).join('\n') + + `\n Delete the \`${UI_TRADE_OFF_MARKER}\` line: it declares a scheduling gap that is not there.`, + ); + } + if (problems.length > 0) { + console.error(`FAIL: ci.yml's \`${UI_REMEDY_FILTER}\` filter is out of step with the files outside ${UI_TREE}/ the ui tests read.\n`); + for (const p of problems) console.error(` - ${p}\n`); + return 1; + } + console.log( + `OK: all ${verdict.rows.length} path(s) outside ${UI_TREE}/ read by the ${verdict.tests} tracked ui test file(s) are ` + + `covered by ${verdict.named.map((n) => `\`${n}\``).join(' or ')}, which the \`${UI_TEST_JOB}\` job's \`if:\` reads` + + (verdict.tradedOff.length > 0 ? `, or declared as a trade-off (${verdict.tradedOff.map((r) => r.path).join(', ')})` : '') + + `, and every row and trade-off of the reads group still has a reader.`, + ); + return 0; +} + +// ── The sixth subject: the ui scheduling pin (#38132) ── + +/** The pin record: the least ci.yml may schedule the ui jobs. Read, never copied here. */ +export const UI_PIN_FILE = 'scripts/ci-filter-parity.ui-pin.json'; +/** The `filter` job outputs the ui jobs are scheduled by; a job reading any of them is a ui job. */ +export const UI_OUTPUT_NAMES = Object.freeze(['ui', 'ui_consumers', 'ui_tree']); +const UI_OUTPUT_READ = new RegExp(`needs\\.filter\\.outputs\\.(?:${UI_OUTPUT_NAMES.join('|')})(?![\\w])`); + +/** An expression without its `${{ }}` wrapper, whitespace collapsed. */ +export const normalizeExpression = (expr) => + String(expr ?? '') + .trim() + .replace(/^\$\{\{\s*([\s\S]*?)\s*\}\}$/, '$1') + .replace(/\s+/g, ' ') + .trim(); + +/** Split `s` on `op` at paren depth 0, outside quoted strings. */ +function splitTopLevel(s, op) { + const parts = []; + let depth = 0; + let quote = null; + let start = 0; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (quote) { + if (c === quote) quote = null; + continue; + } + if (c === "'" || c === '"') quote = c; + else if (c === '(') depth += 1; + else if (c === ')') depth -= 1; + else if (depth === 0 && s.startsWith(op, i)) { + parts.push(s.slice(start, i)); + start = i + op.length; + i += op.length - 1; + } + } + parts.push(s.slice(start)); + return parts.map((p) => p.trim()); +} + +/** `( x )` → `x`, only when the outer parens enclose the whole expression. */ +function stripOuterParens(s) { + let t = s.trim(); + while (t.startsWith('(') && t.endsWith(')')) { + let depth = 0; + let wraps = true; + for (let i = 0; i < t.length; i++) { + if (t[i] === '(') depth += 1; + else if (t[i] === ')') depth -= 1; + if (depth === 0 && i < t.length - 1) { + wraps = false; + break; + } + } + if (!wraps) break; + t = t.slice(1, -1).trim(); + } + return t; +} + +/** + * A job condition as clauses of a conjunction, each clause the set of its + * disjuncts: `a && (b || c)` → `[[a], [b, c]]`. An atom is compared as its + * normalised text, so the comparison is syntactic. A condition naming no + * status function carries GitHub's implicit `success()` as one more clause + * (IMPLICIT_SUCCESS), and an absent `if:` is that clause alone. + */ +export function conditionClauses(expr) { + const text = normalizeExpression(expr); + const clauses = text + ? splitTopLevel(text, '&&').map((conjunct) => [...new Set(splitTopLevel(stripOuterParens(conjunct), '||'))].sort()) + : []; + // GitHub wraps an `if:` that names no status function in an implicit + // `success()`, so that clause is real and is spelled out: dropping + // `!cancelled()` or `always()` ADDS it, and reads as the narrowing it is. + if (!clauses.some((c) => c.some((atom) => STATUS_FUNCTION.test(atom)))) clauses.push([IMPLICIT_SUCCESS]); + return clauses; +} + +/** A status-function call inside an atom: `success()`, `always()`, `cancelled()`, `failure()`, negated or not. */ +const STATUS_FUNCTION = /\b(?:success|always|cancelled|failure)\(\s*\)/; +/** The clause GitHub adds to an `if:` that names no status function. */ +export const IMPLICIT_SUCCESS = 'success() (implicit)'; + +/** + * Does `actual` run at least whenever `pinned` does? Sound and syntactic: + * every clause of `actual` must contain all the disjuncts of some clause of + * `pinned`, so each actual clause is implied by a pinned one. Dropping a + * clause or adding a disjunct passes; adding a clause, dropping a disjunct or + * changing an atom does not -- the conservative answer on a rewrite that is in + * fact wider is a red naming the clause, never a silent pass. + */ +export function conditionAtLeast(actual, pinned) { + const p = conditionClauses(pinned); + const narrower = conditionClauses(actual).filter((clause) => !p.some((pc) => pc.every((atom) => clause.includes(atom)))); + return { holds: narrower.length === 0, narrower: narrower.map((c) => c.join(' || ')) }; +} + +/** The pin record's own shape, or the reason it cannot be read. */ +function pinRefusal(pin) { + if (!pin || typeof pin !== 'object' || Array.isArray(pin)) return `${UI_PIN_FILE} is missing or is not a JSON object.`; + const isStrings = (xs) => Array.isArray(xs) && xs.length > 0 && xs.every((x) => typeof x === 'string'); + const isMap = (m) => m && typeof m === 'object' && !Array.isArray(m) && Object.keys(m).length > 0; + if (!isStrings(pin.inputs)) return `${UI_PIN_FILE} carries no \`inputs\` list of the paths-filter step's \`with:\` keys.`; + if (!isMap(pin.outputs) || !Object.values(pin.outputs).every((v) => typeof v === 'string')) return `${UI_PIN_FILE} carries no \`outputs\` map of filter output expressions.`; + if (!isMap(pin.rows) || !Object.values(pin.rows).every(isStrings)) return `${UI_PIN_FILE} carries no \`rows\` map of filter name to its pinned rows.`; + if (!isMap(pin.conditions) || !Object.values(pin.conditions).every((v) => typeof v === 'string')) return `${UI_PIN_FILE} carries no \`conditions\` map of ui job to its pinned \`if:\`.`; + for (const name of UI_OUTPUT_NAMES) if (!(name in pin.outputs)) return `${UI_PIN_FILE} pins no \`${name}\` output.`; + return null; +} + +/** + * The verdict on ci.yml against the ui scheduling pin: the paths-filter step's + * whole `with:` input (its keys exactly, and a floor of rows for each filter + * the pin names), the `filter` job's output expressions the ui jobs read + * (exactly), and the `if:` of every job that reads a ui output (at least as + * wide as its pin, and every such job pinned). `{ refusal }` when either side + * could not be read. + */ +export function judgeUiScheduling(source, pin) { + const refusal = pinRefusal(pin); + if (refusal) return { refusal }; + const read = readFilterLists(source); + if (read.refusal) return read; + const { jobs, filters, step } = read; + + const withKeys = Object.keys(step.with ?? {}); + const extraInputs = withKeys.filter((k) => !pin.inputs.includes(k)); + const missingInputs = pin.inputs.filter((k) => !withKeys.includes(k)); + + const outputs = jobs.filter?.outputs ?? {}; + const changedOutputs = Object.entries(pin.outputs) + .filter(([name, expr]) => normalizeExpression(outputs[name]) !== normalizeExpression(expr)) + .map(([name, expr]) => ({ name, pinned: normalizeExpression(expr), actual: name in outputs ? normalizeExpression(outputs[name]) : '(absent)' })); + + // The rows are held EXACTLY (a ratchet): a row gone narrows, and a row added + // is unpinned until the pin names it, so its later removal is caught. The + // `ui` list's reads group is the fifth subject's and is left out here. + const group = uiReadsGroupOf(read.raw); + if (group.refusal) return group; + const pinnedListOf = (name) => (filters[name] ?? []).filter((row) => name !== UI_REMEDY_FILTER || !group.rows.includes(row)); + const missingRows = Object.entries(pin.rows).flatMap(([name, rows]) => + rows.filter((row) => !pinnedListOf(name).includes(row)).map((row) => ({ name, row })), + ); + const unpinnedRows = Object.entries(pin.rows).flatMap(([name, rows]) => + pinnedListOf(name).filter((row) => !rows.includes(row)).map((row) => ({ name, row })), + ); + + const uiJobs = Object.entries(jobs) + .filter(([id, job]) => id !== 'filter' && UI_OUTPUT_READ.test(JSON.stringify(job ?? {}))) + .map(([id]) => id); + const unpinnedJobs = uiJobs.filter((id) => !(id in pin.conditions)); + const vanishedJobs = Object.keys(pin.conditions).filter((id) => !(id in jobs)); + const narrowedJobs = []; + const widenedJobs = []; + for (const [id, pinned] of Object.entries(pin.conditions)) { + if (!(id in jobs)) continue; + const actual = jobs[id]?.if; + const verdict = conditionAtLeast(actual, pinned); + if (!verdict.holds) narrowedJobs.push({ id, pinned: normalizeExpression(pinned), actual: normalizeExpression(actual) || '(absent)', clauses: verdict.narrower }); + else if (JSON.stringify(conditionClauses(actual).sort()) !== JSON.stringify(conditionClauses(pinned).sort())) { + widenedJobs.push({ id, pinned: normalizeExpression(pinned), actual: normalizeExpression(actual) || '(absent)' }); + } + } + return { uiJobs, pinnedInputs: pin.inputs, extraInputs, missingInputs, changedOutputs, missingRows, unpinnedRows, unpinnedJobs, vanishedJobs, narrowedJobs, widenedJobs }; +} + +function reportUiScheduling(verdict) { + if (verdict.refusal) { + console.error(`FAIL: check-ci-filter-parity could not judge the ui scheduling against ${UI_PIN_FILE}.\n\n - ${verdict.refusal}\n`); + return 1; + } + const problems = []; + if (verdict.extraInputs.length > 0 || verdict.missingInputs.length > 0) { + problems.push( + `the \`dorny/paths-filter\` step's \`with:\` input is pinned to exactly the keys ${JSON.stringify(verdict.pinnedInputs)}` + + (verdict.extraInputs.length ? `; added: ${verdict.extraInputs.join(', ')}` : '') + + (verdict.missingInputs.length ? `; removed: ${verdict.missingInputs.join(', ')}` : '') + + `.\n Every input of that action decides which diff is read or how a row matches it, so each one is pinned.`, + ); + } + for (const o of verdict.changedOutputs) { + problems.push( + `the \`filter\` job's \`${o.name}\` output is pinned exactly, and it changed:\n pinned: ${o.pinned}\n actual: ${o.actual}`, + ); + } + if (verdict.missingRows.length > 0) { + problems.push( + `pinned row(s) are gone from the filters the ui jobs read, so a diff they matched no longer starts those jobs:\n` + + verdict.missingRows.map((r) => ` ${r.name}: ${r.row}`).join('\n'), + ); + } + if (verdict.unpinnedRows.length > 0) { + problems.push( + `row(s) the ui jobs read are not in the pin, so removing one later would go unseen. If each widening is meant,\n` + + ` add it to \`rows\` in ${UI_PIN_FILE} in this PR:\n` + + verdict.unpinnedRows.map((r) => ` ${r.name}: ${r.row}`).join('\n'), + ); + } + for (const j of verdict.widenedJobs) { + problems.push( + `the \`${j.id}\` job's \`if:\` is wider than its pin, so narrowing it back later would go unseen. If the widening is\n` + + ` meant, set its condition in ${UI_PIN_FILE} to the new one in this PR:\n pinned: ${j.pinned}\n actual: ${j.actual}`, + ); + } + for (const j of verdict.narrowedJobs) { + problems.push( + `the \`${j.id}\` job's \`if:\` is not provably at least as wide as its pin; these clauses are new or narrower:\n` + + j.clauses.map((c) => ` ${c}`).join('\n') + + `\n pinned: ${j.pinned}\n actual: ${j.actual}`, ); } + if (verdict.unpinnedJobs.length > 0) { + problems.push(`job(s) that read a ui output carry no pinned condition: ${verdict.unpinnedJobs.join(', ')}.`); + } + if (verdict.vanishedJobs.length > 0) { + problems.push(`pinned ui job(s) are gone from ${CI_WORKFLOW}: ${verdict.vanishedJobs.join(', ')}.`); + } if (problems.length > 0) { - console.error(`FAIL: ci.yml's \`${UI_REMEDY_FILTER}\` filter is out of step with the root files the ui tests read.\n`); + console.error(`FAIL: ${CI_WORKFLOW} schedules the ui jobs differently from ${UI_PIN_FILE}.\n`); for (const p of problems) console.error(` - ${p}\n`); + console.error( + `What is pinned: the paths-filter step's \`with:\` keys and the \`filter\` outputs ${UI_OUTPUT_NAMES.join(', ')} (and any other\n` + + `output a ui job reads) exactly; the rows of each pinned filter exactly (the \`ui\` reads group is the fifth\n` + + `subject's); and every job reading a ui output, with its \`if:\` exactly in CNF. An edit that schedules the ui jobs\n` + + `LESS is the failure this subject exists to catch; one that schedules them MORE is held too, so that undoing it\n` + + `later is caught. An edit that is deliberate -- a row, a new ui job, a renamed one, a condition, an output or\n` + + `input rewritten -- updates\n` + + `${UI_PIN_FILE} in the same PR, so the change to what runs is read where it is made.\n`, + ); return 1; } console.log( - `OK: all ${verdict.rows.length} path(s) under ${UI_READ_ROOTS.join(', ')} read by the ${verdict.tests} tracked ui test file(s) are ` + - `covered by ${verdict.named.map((n) => `\`${n}\``).join(' or ')}, which the \`${UI_TEST_JOB}\` job's \`if:\` reads, and every ` + - `\`${UI_REMEDY_FILTER}\` row under those roots still has a reader.`, + `OK: ${CI_WORKFLOW} schedules the ${verdict.uiJobs.length} ui job(s) exactly as ${UI_PIN_FILE} pins: the paths-filter input, ` + + `the ui outputs, the pinned rows and every ui job's \`if:\`.`, ); return 0; } +/** The pin record under `root`, parsed, or null when it cannot be read -- the judge refuses on null by name. */ +function readPin(root) { + const text = readOrNull(root, UI_PIN_FILE); + if (text === null) return null; + try { + return JSON.parse(text); + } catch { + return null; + } +} + function report(verdict) { if (verdict.refusal) { console.error(`FAIL: check-ci-filter-parity could not judge the scheduling filters.\n\n - ${verdict.refusal}\n`); @@ -1119,7 +1647,7 @@ function report(verdict) { return 0; } -export function main(root = REPO_ROOT, table = CROSS_PACKAGE_TEST_INPUTS, uiReads = null) { +export function main(root = REPO_ROOT, table = CROSS_PACKAGE_TEST_INPUTS, uiReads = null, uiPin = undefined) { let source; try { source = readFileSync(join(root, CI_WORKFLOW), 'utf8'); @@ -1136,7 +1664,9 @@ export function main(root = REPO_ROOT, table = CROSS_PACKAGE_TEST_INPUTS, uiRead // `uiReads` is injectable only so the self-test can judge a scratch ci.yml // against the real tree's reads; a real run always reads `root`'s ui tests. const uiCode = reportUiReads(judgeUiReads(source, uiReads ?? uiRootReadsOf(root))); - return crosspkg === 0 && buildCode === 0 && testCode === 0 && uiCode === 0 ? 0 : 1; + // `uiPin` likewise: injectable for the self-test, read from `root` otherwise. + const pinCode = reportUiScheduling(judgeUiScheduling(source, uiPin === undefined ? readPin(root) : uiPin)); + return crosspkg === 0 && buildCode === 0 && testCode === 0 && uiCode === 0 && pinCode === 0 ? 0 : 1; } /** A root file's text, or null when it cannot be read -- the judge refuses on null by name. */ @@ -1199,18 +1729,31 @@ function list(root = REPO_ROOT, table = CROSS_PACKAGE_TEST_INPUTS) { console.error(`FAIL: ${ui.refusal}`); return 1; } - console.log(`\nreads under ${UI_READ_ROOTS.join(', ')} by the ${ui.tests} ui test file(s), against ${ui.named.join(' + ')} (${UI_TEST_JOB}):`); - for (const row of [...ui.covered, ...ui.uncovered].sort((a, b) => a.path.localeCompare(b.path))) { - console.log(`${row.covered ? 'ok ' : 'FAIL'} ${row.path}${row.covered ? ` via ${row.kind === 'dir' ? 'subtree' : row.kind} ${row.via}` : ''} (${row.from.join(', ')})`); + console.log(`\nreads outside ${UI_TREE}/ by the ${ui.tests} ui test file(s), against ${ui.named.join(' + ')} (${UI_TEST_JOB}):`); + for (const row of [...ui.covered, ...ui.tradedOff, ...ui.uncovered].sort((a, b) => a.path.localeCompare(b.path))) { + const how = row.covered ? ` via ${row.kind === 'dir' ? 'subtree' : row.kind} ${row.via}` : row.reason ? ' trade-off' : ''; + console.log(`${row.covered || row.reason ? 'ok ' : 'FAIL'} ${row.path}${how} (${row.from.join(', ')})`); } for (const entry of ui.stale) console.log(`FAIL ${entry} stale: no ui test reads it`); + for (const entry of ui.staleTradeOffs) console.log(`FAIL ${entry} stale trade-off: no ui test reads it, or a row covers it`); + const pin = judgeUiScheduling(readFileSync(join(root, CI_WORKFLOW), 'utf8'), readPin(root)); + if (pin.refusal) { + console.error(`FAIL: ${pin.refusal}`); + return 1; + } + console.log(`\nui jobs against ${UI_PIN_FILE}: ${pin.uiJobs.join(', ')}`); + const pinRed = pin.extraInputs.length + pin.missingInputs.length + pin.changedOutputs.length + pin.missingRows.length + + pin.unpinnedRows.length + pin.unpinnedJobs.length + pin.vanishedJobs.length + pin.narrowedJobs.length + pin.widenedJobs.length; + console.log(pinRed === 0 ? 'ok the paths-filter input, the ui outputs, the pinned rows and every ui job condition hold' : `FAIL ${pinRed} pin finding(s); run without --list for each`); return verdict.uncovered.length > 0 || build.uncovered.length > 0 || build.guardsUncovered.length > 0 || build.stale.length > 0 || test.uncovered.length > 0 || ui.uncovered.length > 0 || - ui.stale.length > 0 + ui.stale.length > 0 || + ui.staleTradeOffs.length > 0 || + pinRed > 0 ? 1 : 0; } @@ -1641,7 +2184,7 @@ export async function selfTest() { try { mkdirSync(join(scratch, '.github', 'workflows'), { recursive: true }); writeFileSync(join(scratch, CI_WORKFLOW), ciSource); - for (const rel of [TURBO_CONFIG, ROOT_MANIFEST, ...realGuardPaths]) { + for (const rel of [TURBO_CONFIG, ROOT_MANIFEST, UI_PIN_FILE, ...realGuardPaths]) { mkdirSync(dirname(join(scratch, rel)), { recursive: true }); writeFileSync(join(scratch, rel), readFileSync(join(REPO_ROOT, rel), 'utf8')); } @@ -2078,11 +2621,13 @@ export async function selfTest() { `bound: every whole-package test \`turbo run\` the real \`${SCHEDULED_JOB}\` job makes names exactly ${TEST_TASKS.join(' ')} -- got ${JSON.stringify(turboTaskLists)}`, ); - // ── (12) Test UI and the root ADR files ui tests read (#37935) ────────── - battery('(12) Test UI and the root ADR files ui tests read'); + // ── (12) Test UI and the files outside ui/ that ui tests read (#37935) ────────── + battery('(12) Test UI and the files outside ui/ that ui tests read'); const UI_IF = "${{ !cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false') }}"; - const uiWorkflow = ({ ui = ['ui/**'], consumers = ['packages/spec/**'], condition = UI_IF, job = 'test-ui' } = {}) => { + // The `ui` list's first row is the tree; every later row sits under the + // reads-group heading, followed by the trade-off lines, as in the real file. + const uiWorkflow = ({ ui = ['ui/**'], consumers = ['packages/spec/**'], condition = UI_IF, job = 'test-ui', tradeOffs = [], heading = true } = {}) => { const list = (xs) => xs.map((e) => ` - '${e}'`).join('\n'); return [ 'name: CI', @@ -2094,7 +2639,10 @@ export async function selfTest() { ' with:', ' filters: |', ' ui:', - list(ui), + list(ui.slice(0, 1)), + ...(heading ? [` # ── ${UI_READS_GROUP_MARKER} ──`, ` # prose naming \`${UI_TRADE_OFF_MARKER}\` declares nothing`] : []), + ...(ui.length > 1 ? [list(ui.slice(1))] : []), + ...tradeOffs.map((t) => ` # ${UI_TRADE_OFF_MARKER} ${t}`), ' ui_consumers:', list(consumers), ` ${job}:`, @@ -2205,6 +2753,264 @@ export async function selfTest() { ); assert(inScratchTree(uiRowDropped, (root) => quietly(() => main(root, undefined, realUiReads))) === 1, '-- and main() returns 1 over it: the report path, not only `judgeUiReads`'); + // #38133: the population is every read outside ui/, not the root docs/adr. + // A root document and an extensionless import of a server source, each + // found by the walker and resolved on disk. + const ROOT_DOC = ['CONTRIBUTING', 'md'].join('.'); + const SERVER_SRC = ['packages', 'srv', 'src', 'endpoint.ts'].join('/'); + const wideReader = + `${UI_SEED}import { columns } from '../../../../packages/srv/src/endpoint';\n` + + `readFileSync(resolve(HERE, '../../../../${ROOT_DOC}'), 'utf8');\n`; + const uiWide = uiScratch( + { [ROOT_DOC]: '# contributing\n', [SERVER_SRC]: 'export const columns = [];\n', 'ui/packages/p/src/w.test.ts': wideReader }, + (r) => r, + ); + assert( + uiPaths(uiWide.rows).join(',') === [ROOT_DOC, SERVER_SRC].join(','), + `the collector finds a root document and an extensionless import of a server source, both outside ui/ -- got ${JSON.stringify(uiWide.rows)}`, + ); + const wideHole = judgeUiReads(uiWorkflow(), uiWide); + assert(uiPaths(wideHole.uncovered).join(',') === [ROOT_DOC, SERVER_SRC].join(','), `-- and both are reported uncovered with no row -- got ${uiPaths(wideHole.uncovered).join(', ')}`); + const wideRows = judgeUiReads(uiWorkflow({ ui: ['ui/**', ROOT_DOC, SERVER_SRC] }), uiWide); + assert(wideRows.uncovered?.length === 0 && wideRows.stale?.length === 0, `positive control: each named verbatim in the reads group is covered -- ${wideRows.refusal ?? uiPaths(wideRows.uncovered).join(', ')}`); + assert(judgeUiReads(uiWorkflow({ consumers: ['packages/srv/**'], ui: ['ui/**', ROOT_DOC] }), uiWide).uncovered?.length === 0, '-- and a server source under a `ui_consumers` subtree is covered by it'); + + // A declared trade-off: the read stays unscheduled and the gate stays green. + const traded = judgeUiReads(uiWorkflow({ ui: ['ui/**', ROOT_DOC], tradeOffs: [`${SERVER_SRC} -- its server twin runs in Test Core`] }), uiWide); + assert( + traded.uncovered?.length === 0 && uiPaths(traded.tradedOff).join(',') === SERVER_SRC && traded.staleTradeOffs?.length === 0 && quietly(() => reportUiReads(traded)) === 0, + `a read declared as a trade-off is neither uncovered nor stale, and the report path returns 0 -- got ${traded.refusal ?? JSON.stringify(traded.uncovered)}`, + ); + const tradeGone = judgeUiReads(uiWorkflow({ ui: ['ui/**', ROOT_DOC, SERVER_SRC], tradeOffs: [`${SERVER_SRC} -- covered now`, 'packages/none/x.ts -- nobody reads it'] }), uiWide); + assert( + (tradeGone.staleTradeOffs ?? []).join(',') === [SERVER_SRC, 'packages/none/x.ts'].join(',') && quietly(() => reportUiReads(tradeGone)) === 1, + `a trade-off a row covers, and one for a read no test makes, are both stale and red -- got ${(tradeGone.staleTradeOffs ?? []).join(', ')}`, + ); + assert(uiRefusal(judgeUiReads(uiWorkflow({ ui: ['ui/**', ROOT_DOC], tradeOffs: [SERVER_SRC] }), uiWide)), 'refuses a trade-off line with no `-- REASON`'); + assert(uiRefusal(judgeUiReads(uiWorkflow({ heading: false, ui: ['ui/**', ROOT_DOC] }), uiWide)), 'refuses when the `ui` list carries no reads-group heading'); + // A row ABOVE the heading is a job input, not a read, and is never a leftover. + const aboveHeading = judgeUiReads(uiWorkflow({ ui: ['pnpm-lock.yaml', ROOT_DOC, SERVER_SRC] }), uiWide); + assert(aboveHeading.stale?.length === 0, `a reader-less row above the heading is not judged as a leftover -- got ${(aboveHeading.stale ?? []).join(', ')}`); + + // The real tree: each #38133 row and the declared trade-off, rolled back. + for (const [row, path] of [ + [" - 'CONTRIBUTING.md'\n", 'CONTRIBUTING.md'], + [" - 'packages/plugins/plugin-auth/src/admin-import-users.ts'\n", 'packages/plugins/plugin-auth/src/admin-import-users.ts'], + [" - 'scripts/ci-shard-matrix.mjs'\n", 'scripts/ci-shard-matrix.mjs'], + [" - 'scripts/invoked-as.mjs'\n", 'scripts/invoked-as.mjs'], + [ + " - 'packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts'\n", + 'packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts', + ], + ]) { + // Dropped from INSIDE the reads group: a row may also sit in another list (`core`). + const at = realSource.indexOf(row, realSource.indexOf(UI_READS_GROUP_MARKER)); + const dropped = at < 0 ? realSource : realSource.slice(0, at) + realSource.slice(at + row.length); + assert( + at >= 0 && uiPaths(judgeUiReads(dropped, realUiReads).uncovered).join(',') === path, + `the checked-in ci.yml with the #38133 row for ${path} dropped reports exactly that path`, + ); + } + const TRADE_LINE = ` # ${UI_TRADE_OFF_MARKER} packages/mcp/src/skill-md.ts -- the\n`; + const tradeDropped = realSource.replace(TRADE_LINE, ''); + assert( + realSource.includes(TRADE_LINE) && + uiPaths(judgeUiReads(tradeDropped, realUiReads).uncovered).join(',') === + uiPaths(judgeUiReads(realSource, realUiReads).tradedOff).join(',') && + uiPaths(judgeUiReads(tradeDropped, realUiReads).uncovered).includes('packages/mcp/src/skill-md.ts'), + 'the checked-in ci.yml with its declared trade-off line dropped reports packages/mcp/src/skill-md.ts uncovered, and every module it loads with it', + ); + const realReason = uiReadsGroupOf(readFilterLists(realSource).raw).tradeOffs?.get('packages/mcp/src/skill-md.ts') ?? ''; + assert( + realReason.startsWith('the Console\'s objectstack-skill.test.ts imports it') && realReason.includes('through the `crosspkg` row (#31017).') && realReason.endsWith('inherit this trade-off.'), + `a trade-off's reason runs over its continuation comment lines, not just the marker line -- got ${JSON.stringify(realReason)}`, + ); + + // The `new URL(literal, import.meta.url)` spelling (the rework's M1): a + // dynamic import of a module outside ui/, which the shared walker does not + // read. The collector reads the escaping literal, and then the module's own + // first-party imports (S4), each attributed through the module that loads it. + const PACK = 'packages/q/src/pack.mjs'; + const PACK_HELPER = 'packages/q/src/helper.mjs'; + const urlReader = "const mod = await import(new URL('../../../../packages/q/src/pack.mjs', import.meta.url).href);\nconst root = new URL('../../..', import.meta.url);\n"; + const packOnDisk = { [PACK]: "import { h } from './helper.mjs';\nexport const pack = h;\n", [PACK_HELPER]: 'export const h = 1;\n' }; + const uiUrl = uiScratch({ ...packOnDisk, 'ui/packages/p/src/u.test.ts': urlReader }, (r) => r); + assert( + !uiUrl.refusal && uiPaths(uiUrl.rows).join(',') === `${PACK_HELPER},${PACK}`, + `a \`new URL(literal, import.meta.url)\` import outside ui/ is a read, and so is the module's own import; a literal naming a directory is not -- got ${uiUrl.refusal ?? JSON.stringify(uiUrl.rows)}`, + ); + assert( + (uiUrl.rows ?? []).find((r) => r.path === PACK_HELPER)?.from.join(',') === `ui/packages/p/src/u.test.ts (via ${PACK})`, + '-- the closure member is attributed through the module that loads it', + ); + assert( + uiPaths(judgeUiReads(uiWorkflow({ ui: ['ui/**', PACK] }), uiUrl).uncovered).join(',') === PACK_HELPER && + judgeUiReads(uiWorkflow({ ui: ['ui/**', 'packages/q/**'] }), uiUrl).uncovered?.length === 0, + '-- and a row for the module alone leaves its import uncovered by path', + ); + const uiUrlBroken = uiScratch({ [PACK]: "import { h } from './gone.mjs';\n", 'ui/packages/p/src/u.test.ts': urlReader }, (r) => r); + assert(typeof uiUrlBroken.refusal === 'string', `a loaded module whose import resolves to nothing refuses, never a clean zero -- got ${JSON.stringify(uiUrlBroken)}`); + const uiUrlAbsent = uiScratch({ 'ui/packages/p/src/u.test.ts': urlReader }, (r) => r); + assert(!uiUrlAbsent.refusal && (uiUrlAbsent.rows ?? []).length === 0, '-- and an escaping literal that names nothing on disk is a synthetic path, not a read'); + // S5: a TypeScript module's imports, resolved as TypeScript resolves them. + const TS_MOD = 'packages/t/src/mod.ts'; + const TS_DEP = 'packages/t/src/dep.ts'; + const TS_TYPES = 'packages/t/src/types.ts'; + const tsOnDisk = { + [TS_MOD]: "import type { T } from './types.js';\nimport {\n dep,\n} from './dep.js';\nexport const m: T = dep;\n", + [TS_DEP]: 'export const dep = 1;\n', + [TS_TYPES]: 'export type T = number;\n', + }; + const tsImporter = "import { m } from '../../../../packages/t/src/mod';\n"; + const uiTs = uiScratch({ ...tsOnDisk, 'ui/packages/p/src/t.test.ts': tsImporter }, (r) => r); + assert( + !uiTs.refusal && uiPaths(uiTs.rows).join(',') === `${TS_DEP},${TS_MOD}`, + `a .ts module's \`./dep.js\` import is walked to its .ts source, and a type-only import is not -- got ${uiTs.refusal ?? JSON.stringify(uiTs.rows)}`, + ); + const tsTextReader = `${UI_SEED}readFileSync(resolve(HERE, '../../../../packages/t/src/mod.ts'), 'utf8');\n`; + const uiTsText = uiScratch({ ...tsOnDisk, 'ui/packages/p/src/t.test.ts': tsTextReader }, (r) => r); + assert(uiPaths(uiTsText.rows).join(',') === TS_MOD, `a module read as TEXT is a read, and its imports are not -- got ${JSON.stringify(uiTsText.rows)}`); + const inherit = judgeUiReads(uiWorkflow({ tradeOffs: [`${TS_MOD} -- runs elsewhere`] }), uiTs); + assert( + inherit.uncovered?.length === 0 && uiPaths(inherit.tradedOff).join(',') === `${TS_DEP},${TS_MOD}` && + inherit.tradedOff.find((r) => r.path === TS_DEP)?.via === TS_MOD && inherit.staleTradeOffs?.length === 0, + `a module reached only through a traded-off module inherits its trade-off -- got ${JSON.stringify(inherit.tradedOff ?? inherit)}`, + ); + const uiTsBoth = uiScratch( + { ...tsOnDisk, 'ui/packages/p/src/t.test.ts': tsImporter, 'ui/packages/p/src/d.test.ts': "import { dep } from '../../../../packages/t/src/dep';\n" }, + (r) => r, + ); + assert( + uiPaths(judgeUiReads(uiWorkflow({ tradeOffs: [`${TS_MOD} -- runs elsewhere`] }), uiTsBoth).uncovered).join(',') === TS_DEP, + '-- but not one a test also loads directly, which needs its own row', + ); + const realMcp = judgeUiReads(realSource, realUiReads); + assert( + (realMcp.tradedOff ?? []).find((r) => r.path === 'packages/mcp/src/ask-skill.generated.ts')?.via === 'packages/mcp/src/skill-md.ts', + 'on the real tree, skill-md.ts\'s `./ask-skill.generated.js` import is read as its .ts source and inherits the mcp trade-off', + ); + + // On the real tree: the reads the rework names are collected. + const realUiPaths = uiPaths(realUiReads.rows); + for (const need of ['packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts', 'scripts/invoked-as.mjs']) { + assert(realUiPaths.includes(need), `on the real tree the collector reads ${need} -- got ${realUiPaths.join(', ')}`); + } + + // ── (13) the ui scheduling pin (#38132) ───────────────────────────────── + battery('(13) the ui scheduling pin: the paths-filter input, the ui outputs, the ui rows and every ui job condition'); + const realPin = readPin(REPO_ROOT); + const pinOf = (source, pin = realPin) => judgeUiScheduling(source, pin); + const pinRed = (v) => + !v.refusal && + v.extraInputs.length + v.missingInputs.length + v.changedOutputs.length + v.missingRows.length + v.unpinnedRows.length + + v.unpinnedJobs.length + v.vanishedJobs.length + v.narrowedJobs.length + v.widenedJobs.length > 0; + const realPinVerdict = pinOf(realSource); + assert( + !realPinVerdict.refusal && !pinRed(realPinVerdict) && realPinVerdict.uiJobs.length === Object.keys(realPin.conditions).length && realPinVerdict.uiJobs.includes(UI_TEST_JOB), + `positive control: the checked-in ci.yml holds its pin, and every job reading a ui output is pinned -- ${realPinVerdict.refusal ?? JSON.stringify(realPinVerdict)}`, + ); + assert(quietly(() => reportUiScheduling(realPinVerdict)) === 0, '-- and the report path returns 0 over it'); + + // The CNF reading of a condition, and the at-least-as-wide relation. + assert( + JSON.stringify(conditionClauses("${{ !cancelled() && (a != 'false' || b != 'false') && c }}")) === JSON.stringify([['!cancelled()'], ["a != 'false'", "b != 'false'"], ['c']]), + 'a condition reads as clauses of a conjunction, each the set of its disjuncts, the `${{ }}` wrapper dropped', + ); + assert(conditionAtLeast("x && (a || b || c)", "x && (a || b) && y").holds, 'dropping a clause or adding a disjunct is at least as wide'); + assert(!conditionAtLeast("x && (a || b) && z", "x && (a || b)").holds, 'adding a clause is narrower'); + assert(!conditionAtLeast("x && a", "x && (a || b)").holds, 'dropping a disjunct is narrower'); + assert(!conditionAtLeast("x && a == 'false'", "x && a != 'false'").holds, 'changing an atom is narrower (syntactic: never a silent pass)'); + assert(conditionAtLeast("(x) && ( a || b )", "x && (b || a)").holds, 'whitespace, order and redundant parentheses do not matter'); + + // Each pinned part ablated on the REAL ci.yml. + const FILTERS_LINE = ' with:\n filters: |\n'; + assert(realSource.split(FILTERS_LINE).length === 2, 'the real paths-filter step carries one `with:` block that opens with `filters:`'); + const inputAdded = realSource.replace(FILTERS_LINE, " with:\n predicate-quantifier: 'every'\n filters: |\n"); + const inputVerdict = pinOf(inputAdded); + assert((inputVerdict.extraInputs ?? []).join(',') === 'predicate-quantifier', `a \`with:\` input added to the paths-filter step reds by name -- got ${JSON.stringify(inputVerdict.extraInputs)}`); + assert(inScratchTree(inputAdded, (root) => quietly(() => main(root, undefined, realUiReads))) === 1, '-- and main() returns 1 over it, the pin read from the scratch tree'); + + const UI_OUTPUT_LINE = " ui: ${{ steps.changes.outputs.ui || 'true' }}\n"; + assert(realSource.includes(UI_OUTPUT_LINE), 'the real `filter` job carries the pinned `ui` output line'); + const outputNarrowed = pinOf(realSource.replace(UI_OUTPUT_LINE, " ui: ${{ steps.changes.outputs.ui || 'false' }}\n")); + assert((outputNarrowed.changedOutputs ?? []).map((o) => o.name).join(',') === 'ui', `the \`ui\` output rewritten reds by name -- got ${JSON.stringify(outputNarrowed.changedOutputs)}`); + + const UI_TREE_ROW = " - 'ui/**'\n"; + const SPEC_ROW = " - 'packages/spec/**'\n"; + assert(realSource.split(UI_TREE_ROW).length === 2 && realSource.split(SPEC_ROW).length === 2, 'the real ci.yml carries the `ui/**` and `packages/spec/**` rows once each'); + const rowsDropped = pinOf(realSource.replace(UI_TREE_ROW, '').replace(SPEC_ROW, '')); + assert( + (rowsDropped.missingRows ?? []).map((r) => `${r.name}:${r.row}`).join(',') === 'ui:ui/**,ui_consumers:packages/spec/**', + `a pinned \`ui\` row and a pinned \`ui_consumers\` row dropped red by list and row -- got ${JSON.stringify(rowsDropped.missingRows)}`, + ); + const rowAdded = pinOf(realSource.replace(UI_TREE_ROW, `${UI_TREE_ROW} - 'extra/**'\n`)); + assert( + (rowAdded.unpinnedRows ?? []).map((r) => `${r.name}:${r.row}`).join(',') === 'ui:extra/**' && (rowAdded.missingRows ?? []).length === 0, + `ratchet: a row ADDED to \`ui\` above the reads group reds as unpinned, by list and row -- got ${JSON.stringify(rowAdded.unpinnedRows)}`, + ); + const withExtra = realSource.replace(UI_TREE_ROW, `${UI_TREE_ROW} - 'extra/**'\n`); + const pinWithExtra = { ...realPin, rows: { ...realPin.rows, ui: [...realPin.rows.ui, 'extra/**'] } }; + assert(!pinRed(pinOf(withExtra, pinWithExtra)), '-- and goes green once the pin names it'); + assert((pinOf(realSource, pinWithExtra).missingRows ?? []).map((r) => r.row).join(',') === 'extra/**', '-- after which removing that row reds as missing'); + const WALKER_ROW = " - 'scripts/check-cross-package-test-inputs.mjs'\n"; + assert(realSource.split(WALKER_ROW).length === 2, 'the real `ui` list carries the walker-module row once'); + assert( + (pinOf(realSource.replace(WALKER_ROW, '')).missingRows ?? []).map((r) => r.row).join(',') === 'scripts/check-cross-package-test-inputs.mjs', + 'the row added in the rework round (the walker module) is pinned: dropping it reds', + ); + const groupRows = uiReadsGroupOf(readFilterLists(realSource).raw).rows ?? []; + assert(groupRows.length > 0 && groupRows.every((r) => !realPin.rows.ui.includes(r)), 'the reads group rows are the fifth subject\'s and are not in the pin'); + + const TEST_UI_IF = ` if: \${{ ${realPin.conditions[UI_TEST_JOB]} }}\n`; + assert(realSource.includes(TEST_UI_IF), 'the real `test-ui` job carries its pinned `if:` verbatim'); + const ifTo = (replacement) => pinOf(realSource.replace(TEST_UI_IF, ` if: \${{ ${replacement} }}\n`)); + const narrowedIds = (v) => (v.narrowedJobs ?? []).map((j) => j.id).join(','); + const pinnedTestUi = realPin.conditions[UI_TEST_JOB]; + assert(narrowedIds(ifTo(`${pinnedTestUi} && github.event_name != 'pull_request'`)) === UI_TEST_JOB, 'a conjunct added to `test-ui` reds it by job'); + assert(narrowedIds(ifTo(pinnedTestUi.replace(" || needs.filter.outputs.ui_consumers != 'false'", ''))) === UI_TEST_JOB, '-- and so does dropping its `ui_consumers` disjunct'); + assert(narrowedIds(ifTo(pinnedTestUi.replace("needs.filter.outputs.ui != 'false'", "needs.filter.outputs.ui == 'true'"))) === UI_TEST_JOB, '-- and so does rewriting its `ui` atom'); + const ifWidened = ifTo(pinnedTestUi.replace(" && needs.test-ui-plan.outputs.shards != '[]'", '')); + assert( + narrowedIds(ifWidened) === '' && (ifWidened.widenedJobs ?? []).map((j) => j.id).join(',') === UI_TEST_JOB && pinRed(ifWidened), + 'ratchet: a conjunct DROPPED is not a narrowing, but reds as wider than the pin', + ); + assert(quietly(() => reportUiScheduling(ifWidened)) === 1, '-- and the report path returns 1 over it'); + + // GitHub's implicit success(): dropping a status function is a narrowing. + assert( + JSON.stringify(conditionClauses("a != 'false'")) === JSON.stringify([["a != 'false'"], [IMPLICIT_SUCCESS]]) && + JSON.stringify(conditionClauses(undefined)) === JSON.stringify([[IMPLICIT_SUCCESS]]), + 'a condition naming no status function carries the implicit success() clause, and an absent `if:` is that clause alone', + ); + assert(!conditionAtLeast("a != 'false'", "!cancelled() && a != 'false'").holds, 'dropping `!cancelled()` is a narrowing (implicit success())'); + assert(!conditionAtLeast("a != 'false'", "always() && a != 'false'").holds, 'dropping `always()` is a narrowing (implicit success())'); + assert(!conditionAtLeast(undefined, '!cancelled()').holds, 'removing an `if: !cancelled()` entirely is a narrowing'); + assert(!conditionAtLeast("!cancelled() && a", "always() && a").holds, '`always()` rewritten to `!cancelled()` is a narrowing (an atom changed)'); + const PLAN_JOB = 'test-ui-plan'; + const planIf = realPin.conditions[PLAN_JOB] ?? ''; + const PLAN_LINE = ` if: \${{ ${planIf} }}\n`; + assert(/^!cancelled\(\) && /.test(planIf) && realSource.includes(PLAN_LINE), `the real \`${PLAN_JOB}\` job carries its pinned \`!cancelled() && ...\` \`if:\` verbatim`); + assert( + narrowedIds(pinOf(realSource.replace(PLAN_LINE, ` if: \${{ ${planIf.replace(/^!cancelled\(\) && /, '')} }}\n`))) === PLAN_JOB, + `on the real ci.yml, \`!cancelled()\` dropped from \`${PLAN_JOB}\` reds it as narrowed`, + ); + + const newUiJob = `${realSource}\n probe-ui:\n needs: filter\n if: \${{ needs.filter.outputs.ui != 'false' }}\n runs-on: ubuntu-latest\n steps:\n - run: echo probe\n`; + assert((pinOf(newUiJob).unpinnedJobs ?? []).join(',') === 'probe-ui', 'a new job reading a ui output with no pinned condition reds by name'); + const LINT_UI_KEY = '\n lint-ui:\n'; + assert(realSource.split(LINT_UI_KEY).length === 2, 'the real ci.yml carries the `lint-ui` job key once'); + assert((pinOf(realSource.replace(LINT_UI_KEY, '\n lint-ui-renamed:\n')).vanishedJobs ?? []).join(',') === 'lint-ui', 'a pinned ui job renamed away reds as vanished (and its new name as unpinned)'); + assert(quietly(() => reportUiScheduling(ifTo(`${pinnedTestUi} && false`))) === 1, 'the report path returns 1 over a narrowed condition'); + + // Refusals: a pin that cannot be read is never a clean zero. + const refusesPin = (pin) => typeof pinOf(realSource, pin).refusal === 'string'; + assert(refusesPin(null) && refusesPin([]) && refusesPin({}), 'refuses a missing, non-object or empty pin'); + assert(refusesPin({ ...realPin, inputs: [] }), 'refuses a pin with no inputs'); + assert(refusesPin({ ...realPin, conditions: {} }), 'refuses a pin with no conditions'); + const { ui: _droppedUi, ...outputsWithoutUi } = realPin.outputs; + assert(refusesPin({ ...realPin, outputs: outputsWithoutUi }), 'refuses a pin that pins no `ui` output'); + assert(inScratchTree(realSource, (root) => { rmSync(join(root, UI_PIN_FILE)); return quietly(() => main(root, undefined, realUiReads)); }) === 1, 'main() returns 1 when the pin file is absent from the tree'); + // ── The floor: every declared battery RAN, and ran its cases (#13489) ─── // // Evaluated after every battery has had its chance and BEFORE the verdict, so @@ -2279,7 +3085,23 @@ export async function selfTest() { `and Test UI's root ADR reads: a ui test's ADR read found through the shared walker and observed red by path, ` + `covered verbatim, by its subtree and by \`ui_consumers\`, a directory read needing its subtree, a bound-then-listed directory classified as one, a path not on disk read as nothing, a wildcard row ` + `covering nothing, a reader-less row reported as a leftover, five refusals, and the checked-in tree green with ` + - `the #37935 row dropped observed red through the report path.`, + `the #37935 row dropped observed red through the report path, generalised to every read outside ui/ (a root ` + + `document and an extensionless server import found, covered by a row or by \`ui_consumers\`, a declared trade-off ` + + `green, a stale or redundant trade-off red, a malformed one and a missing heading refused, a row above the heading ` + + `never a leftover, and each #38133 row and the trade-off rolled back off the real tree observed red), a ` + + `\`new URL(literal, import.meta.url)\` import outside ui/ read with the module's own first-party imports ` + + `attributed through it, a directory literal read as nothing, an unresolvable module import refused, and the ` + + `platform-objects translation pack and the walker's imported module read on the real tree, a .ts module's ` + + `\`.js\` import walked to its .ts source with a type-only import skipped, a module read as text not walked, ` + + `a traded-off module's imports inheriting its trade-off unless a test loads them directly, and the real ` + + `\`ask-skill.generated.ts\` inheriting the mcp trade-off; ` + + `and the ui scheduling pin: the real tree green against it, the condition clauses and their at-least-as-wide ` + + `relation, and on the real ci.yml a paths-filter input added, the \`ui\` output rewritten, a \`ui\` and a ` + + `\`ui_consumers\` row dropped, a \`test-ui\` conjunct added, a disjunct dropped and an atom rewritten each observed ` + + `red, the ratchet: a row added and a conjunct dropped each observed red until the pin names them, the ` + + `rework's walker-module row pinned, the implicit \`success()\` clause making a dropped \`!cancelled()\` or ` + + `\`always()\` a narrowing (and on the real \`test-ui-plan\` job), a new unpinned ui job and a renamed pinned ` + + `one red, five pin refusals, and main() red over a missing pin file.`, ); selfTestReachedVerdict = true; return 0; diff --git a/scripts/check-cross-package-test-inputs.mjs b/scripts/check-cross-package-test-inputs.mjs index b12462d6702..ad840c8d5d4 100644 --- a/scripts/check-cross-package-test-inputs.mjs +++ b/scripts/check-cross-package-test-inputs.mjs @@ -744,7 +744,7 @@ export function importSpecifiers(src) { */ const KNOWN_MODULE_EXTENSION = /\.(?:[cm]?[jt]sx?|json|node)$/; -function resolveImportTarget(name) { +export function resolveImportTarget(name, root = REPO_ROOT) { const candidates = [name]; if (/\.js$/.test(name)) candidates.push(name.replace(/\.js$/, '.ts'), name.replace(/\.js$/, '.tsx')); else if (/\.mjs$/.test(name)) candidates.push(name.replace(/\.mjs$/, '.mts')); @@ -752,7 +752,7 @@ function resolveImportTarget(name) { else if (!KNOWN_MODULE_EXTENSION.test(name)) candidates.push(`${name}.ts`, `${name}.tsx`, `${name}.mts`); for (const c of candidates) { try { - if (statSync(join(REPO_ROOT, c)).isFile()) return c; + if (statSync(join(root, c)).isFile()) return c; } catch { // Not this candidate — try the next. } diff --git a/scripts/ci-filter-parity.ui-pin.json b/scripts/ci-filter-parity.ui-pin.json new file mode 100644 index 00000000000..f9e88255aab --- /dev/null +++ b/scripts/ci-filter-parity.ui-pin.json @@ -0,0 +1,57 @@ +{ + "about": "The ui scheduling pin of scripts/check-ci-filter-parity.mjs (objectstack#38132, its sixth subject): how .github/workflows/ci.yml schedules the ui jobs, held EXACTLY as a ratchet. `inputs` (the paths-filter step with: keys), `outputs` (the filter job outputs the ui jobs read), `rows` (per filter; the `ui` list above its UI TEST READS OUTSIDE ui/ heading, the reads group being the fifth subject's) and `conditions` (per ui job if:, compared in CNF with GitHub's implicit success()) must each equal ci.yml: an edit that schedules less reds as a narrowing, and one that schedules more reds until this file names it, so that undoing it later is caught.", + "inputs": [ + "filters" + ], + "outputs": { + "core": "github.event_name != 'merge_group' && steps.changes.outputs.core || 'true'", + "ui": "steps.changes.outputs.ui || 'true'", + "ui_consumers": "steps.changes.outputs.ui_consumers || 'true'", + "ui_tree": "steps.ui-tree.outputs.present || 'true'" + }, + "rows": { + "ui": [ + "ui/**", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "turbo.json", + ".github/workflows/**", + ".github/prompts/**", + "skills/objectui/**", + "content/docs/frontend/**", + "content/docs/ui/pages.mdx", + "tsconfig.json", + "tsconfig.base.json", + "tsconfig.test.base.json", + "tsup.config.ts", + "sdui.manifest.json", + "scripts/sdui-manifest.record.json", + "scripts/gen-sdui-manifest-node.mjs", + "scripts/check-sdui-manifest.mjs", + ".nvmrc", + ".github/actions/setup-pnpm/**", + "package.json", + "scripts/check-cross-package-test-inputs.mjs" + ], + "ui_consumers": [ + "packages/spec/**", + "packages/client/**", + "packages/core/**", + "packages/formula/**", + "packages/lint/**", + "packages/sdui-parser/**", + "packages/types/**" + ] + }, + "conditions": { + "ui-deps": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false')", + "type-check-ui": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false')", + "test-ui-plan": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false') && needs.borrowed-verdict.outputs.test_ui != 'skip'", + "test-ui": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false') && needs.borrowed-verdict.outputs.test_ui != 'skip' && needs.test-ui-plan.outputs.shards != '[]'", + "test-ui-gate": "always() && needs.queue-verdict.outputs.covered != 'true'", + "lint-ui": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && needs.filter.outputs.ui != 'false'", + "build-e2e-ui": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false') && needs.queue-verdict.outputs.covered != 'true'", + "live-e2e-ui": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false' || needs.filter.outputs.core != 'false') && needs.queue-verdict.outputs.covered != 'true'", + "ui-published-artifacts": "!cancelled() && needs.filter.outputs.ui_tree != 'false' && (needs.filter.outputs.ui != 'false' || needs.filter.outputs.ui_consumers != 'false') && github.event_name != 'pull_request' && github.event_name != 'merge_group'" + } +} diff --git a/ui/scripts/__tests__/markdown-test-inputs.test.ts b/ui/scripts/__tests__/markdown-test-inputs.test.ts index c6fc22fa75a..2e73e9a8a13 100644 --- a/ui/scripts/__tests__/markdown-test-inputs.test.ts +++ b/ui/scripts/__tests__/markdown-test-inputs.test.ts @@ -63,6 +63,8 @@ */ import { describe, expect, it } from 'vitest'; import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -74,9 +76,11 @@ import { auditTree, declaredEntries, deriveCandidates, + filterGlobMatches, markdownTestInputsAmong, matchesEntry, missingDocuments, + uiSchedulingGlobsOf, } from '../markdown-test-inputs.mjs'; const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); @@ -153,6 +157,102 @@ describe('the derived class', () => { }); }); +/* ── objectstack#38134: a markdown read outside this tree is a candidate ──── */ + +describe('objectstack#38134 — every markdown read outside ui/ reaches the ledger', () => { + /** The root ADR a ui test reads, and the test. */ + const ROOT_ADR = '../docs/adr/0084-application-builder-information-architecture.md'; + const ADR_READER = 'packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts'; + + it('the scanner offers the root `docs/adr` read, and the ledger declares it', () => { + const candidates = deriveCandidates(); + expect(candidates.get(ADR_READER)?.documents).toContain(ROOT_ADR); + expect(ADJUDICATED.get(ADR_READER)?.reads).toContain(ROOT_ADR); + expect(markdownTestInputsAmong([ROOT_ADR]).flatMap((hit) => hit.readers)).toContain(ADR_READER); + }); + + it('a scratch monorepo: a ui test reading a root document outside `content/docs` is a candidate', () => { + const scratch = mkdtempSync(path.join(tmpdir(), 'markdown-test-inputs-38134-')); + try { + // The monorepo is `repo/`; `outside.md` sits ABOVE its root. + const write = (rel: string, text: string) => { + mkdirSync(path.dirname(path.join(scratch, rel)), { recursive: true }); + writeFileSync(path.join(scratch, rel), text); + }; + const uiRoot = path.join(scratch, 'repo', 'ui'); + write('repo/docs/notes/root-doc.md', '# root\n'); + write('repo/content/docs/page.mdx', '# page\n'); + write('outside.md', '# not this repository\n'); + write( + 'repo/ui/packages/p/src/reads-root.test.ts', + "const HERE = '.';\nreadFileSync(resolve(HERE, '../../../../docs/notes/root-doc.md'));\n" + + "readFileSync(resolve(HERE, '../../../../content/docs/page.mdx'));\n", + ); + const candidates = deriveCandidates({ root: uiRoot, roots: ['packages'] }); + // The control: `content/docs`, the one tree admitted before this card. + expect(candidates.get('packages/p/src/reads-root.test.ts')?.documents).toEqual([ + '../content/docs/page.mdx', + '../docs/notes/root-doc.md', + ]); + // ...and a path above the monorepo root is no document of this repository. + write('repo/ui/packages/p/src/escapes.test.ts', "readFileSync(resolve(HERE, '../../../../../outside.md'));\n"); + expect(deriveCandidates({ root: uiRoot, roots: ['packages'] }).has('packages/p/src/escapes.test.ts')).toBe(false); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + }); + + it('narrowed (S3): an out-of-tree document the root `ui:` filter does not cover is no candidate', () => { + const scratch = mkdtempSync(path.join(tmpdir(), 'markdown-test-inputs-38134-s3-')); + try { + const write = (rel: string, text: string) => { + mkdirSync(path.dirname(path.join(scratch, rel)), { recursive: true }); + writeFileSync(path.join(scratch, rel), text); + }; + const uiRoot = path.join(scratch, 'repo', 'ui'); + write('repo/docs/notes/root-doc.md', '# root\n'); + write('repo/ROADMAP.md', '# roadmap\n'); + write('repo/packages/spec/guide.md', '# guide\n'); + write( + 'repo/.github/workflows/ci.yml', + "jobs:\n filter:\n steps:\n - with:\n filters: |\n ui:\n - 'ui/**'\n" + + " # a comment line is skipped\n - 'docs/notes/**'\n ui_consumers:\n - 'packages/spec/**'\n", + ); + write( + 'repo/ui/packages/p/src/reads-root.test.ts', + "readFileSync(resolve(HERE, '../../../../docs/notes/root-doc.md'));\nconst name = 'ROADMAP.md';\n" + + "readFileSync(resolve(HERE, '../../../../packages/spec/guide.md'));\n", + ); + const candidates = deriveCandidates({ root: uiRoot, roots: ['packages'] }); + // The covered read is admitted; the bare root `ROADMAP.md` (the monorepo + // root is a base) is not, since editing it starts no ui job. + // A read under a `ui_consumers` row (N5) is admitted too: the job ORs that list. + expect(candidates.get('packages/p/src/reads-root.test.ts')?.documents).toEqual(['../docs/notes/root-doc.md', '../packages/spec/guide.md']); + // The control: with no filter to consult, the same name IS a candidate. + expect(deriveCandidates({ root: uiRoot, roots: ['packages'], uiGlobs: null }).get('packages/p/src/reads-root.test.ts')?.documents).toEqual([ + '../ROADMAP.md', + '../docs/notes/root-doc.md', + '../packages/spec/guide.md', + ]); + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + }); + + it('every out-of-tree entry the ledger names is a path whose change starts the ui jobs', () => { + const globs = uiSchedulingGlobsOf(rootCi()); + expect(globs).toEqual(expect.arrayContaining(uiFilterGlobs(rootCi()))); + const outOfTree = [...ADJUDICATED.values()] + .flatMap((verdict) => [...(verdict.reads ?? []), ...(verdict.notRead ?? [])]) + .filter((entry) => entry.startsWith('../')); + expect(outOfTree.length).toBeGreaterThan(0); + const unscheduled = [...new Set(outOfTree)] + .map((entry) => entry.slice('../'.length)) + .filter((file) => !globs.some((glob) => filterGlobMatches(glob, file) || filterGlobMatches(glob, file.replace(/\*\*$/, 'x')))); + expect(unscheduled, 'a ledger entry outside ui/ that no `ui:` or `ui_consumers:` row covers ties this test to a diff that never runs it').toEqual([]); + }); +}); + /* ── objectui#9096: the ruling, stated as an assertion ───────────────────── */ describe('objectui#9096 — `scripts` is a scan root, and the class is now total', () => { diff --git a/ui/scripts/__tests__/select-affected-tests.test.ts b/ui/scripts/__tests__/select-affected-tests.test.ts index 95cadf55b0f..bc367f00d3e 100644 --- a/ui/scripts/__tests__/select-affected-tests.test.ts +++ b/ui/scripts/__tests__/select-affected-tests.test.ts @@ -25,6 +25,7 @@ import { scanMemo, selectAffectedTests, trackedFiles, + urlLiteralsLeavingTree, } from '../select-affected-tests.mjs'; import { shardTotal } from '../../../scripts/ci-shard-matrix.mjs'; import { parse as parseYaml } from 'yaml'; @@ -619,6 +620,32 @@ describe('select-affected-tests — readers', () => { }); }); +describe('select-affected-tests — a `new URL` literal that leaves the tree (objectstack#38133)', () => { + // `metadata-form-option-names.test.ts` loads the platform pack with + // `await import(new URL('../../../../../../packages/...', import.meta.url).href)`: + // no specifier the graph follows, so before this rule the test was placed in + // its package and a diff confined to the pack selected nothing. + const leaving = "const P = new URL(\n '../../outside/pack.ts',\n import.meta.url,\n).href;\nawait import(P);\n"; + const staying = "const P = new URL('./local.ts', import.meta.url).href;\nawait import(P);\n"; + + it('names the literal that resolves outside the tree, and not one that stays in it', () => { + expect(urlLiteralsLeavingTree('p/a.test.ts', leaving)).toEqual(['../../outside/pack.ts']); + expect(urlLiteralsLeavingTree('p/a.test.ts', staying)).toEqual([]); + }); + + it('makes the closure unbounded, so the test is always on', () => { + const { root } = fixture({ 'p/a.test.ts': leaving, 'p/b.test.ts': staying, 'p/local.ts': 'export {};\n' }); + const summaries = closureSummaries(root, ['p/a.test.ts', 'p/b.test.ts'], new Set(), () => 'p'); + expect(summaries.get('p/a.test.ts')?.readsDisk).toBe(true); + expect(summaries.get('p/b.test.ts')?.readsDisk).toBe(false); + }); + + it('the live reader is always on', () => { + const rel = 'packages/app-shell/src/views/metadata-admin/metadata-form-option-names.test.ts'; + expect(urlLiteralsLeavingTree(rel, fs.readFileSync(path.join(repoRoot, rel), 'utf8'))).toHaveLength(1); + }); +}); + describe('select-affected-tests — the live tree', () => { const packages = listWorkspacePackages(repoRoot); const { dependentClosure } = packageClosures(packages); diff --git a/ui/scripts/markdown-test-inputs.mjs b/ui/scripts/markdown-test-inputs.mjs index ffd35b01207..c0648b1e799 100644 --- a/ui/scripts/markdown-test-inputs.mjs +++ b/ui/scripts/markdown-test-inputs.mjs @@ -178,8 +178,65 @@ import { stripComments } from './js-comment-mask.mjs'; export const REPO_ROOT = path.resolve(fileURLToPath(import.meta.url), '..', '..'); -/** The monorepo's docs tree, which holds the ObjectUI pages (objectstack#27145). */ -const MONOREPO_DOCS = path.resolve(REPO_ROOT, '..', 'content', 'docs'); +/* + * The monorepo root is this tree's parent (`deriveCandidates`'s `monorepoRoot` + * default), whose markdown a ui test may read from outside this tree: the docs + * pages under `content/docs` (objectstack#27145), a root ADR, the root + * `CONTRIBUTING.md`. Such a read is labelled `../`, relative to this root + * like every other entry (objectstack#38134). + */ + +/** The root workflow whose `ui:` paths filter starts the ui jobs. */ +export const ROOT_CI = path.join('.github', 'workflows', 'ci.yml'); + +/** + * The `ui:` globs of the root `ci.yml`'s paths filter, read as text the way the + * filter itself is a YAML string (the same reading as the test helper + * `uiFilterGlobs`). Throws on an empty list: an empty reading would admit no + * out-of-tree document and say nothing. + */ +export function uiFilterGlobsOf(ci, list = 'ui') { + const lines = String(ci).split('\n'); + const at = lines.findIndex((line) => new RegExp(`^ +${list}:[ \\t]*$`).test(line)); + if (at === -1) throw new Error(`${ROOT_CI}: the paths filter declares no \`${list}:\` list`); + const indent = lines[at].search(/\S/); + const globs = []; + for (const line of lines.slice(at + 1)) { + if (/^\s*(#.*)?$/.test(line)) continue; + if (line.search(/\S/) <= indent) break; + const m = line.match(/^\s+-\s+'([^']+)'\s*$/); + if (!m) throw new Error(`${ROOT_CI}: cannot read the \`${list}:\` filter entry ${JSON.stringify(line)}`); + globs.push(m[1]); + } + if (globs.length === 0) throw new Error(`${ROOT_CI}: the \`${list}:\` paths filter lists no globs`); + return globs; +} + +/** A paths-filter glob against a monorepo path: `**` crosses separators, `*` does not. */ +export function filterGlobMatches(glob, file) { + return new RegExp( + `^${glob + .split('**') + .map((part) => part.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')) + .join('.*')}$`, + ).test(file); +} + +/** + * The globs whose change starts the ui test job: the `ui:` list and the + * `ui_consumers:` list the job's `if:` ORs with it (N5), read from a root + * `ci.yml` source. A source with no `ui_consumers:` list contributes `ui:` alone. + */ +export function uiSchedulingGlobsOf(ci) { + const consumers = /^ +ui_consumers:[ \t]*$/m.test(String(ci)) ? uiFilterGlobsOf(ci, 'ui_consumers') : []; + return [...uiFilterGlobsOf(ci), ...consumers]; +} + +/** The ui scheduling globs of `/.github/workflows/ci.yml`, or null when that file is absent. */ +function uiGlobsAt(monorepoRoot) { + const file = path.join(monorepoRoot, ROOT_CI); + return existsSync(file) ? uiSchedulingGlobsOf(readFileSync(file, 'utf8')) : null; +} /** * Where `deriveCandidates()` looks for tests. @@ -206,7 +263,9 @@ const SKIP_DIRS = new Set(['node_modules', 'dist', '.git', '.turbo', 'coverage', * `'README.md'` against the test's directory AND every ancestor of * it, so a package-local read also lands on the root README. Which * one is real is a question about the code, and the answer belongs - * where the next reader will find it. + * where the next reader will find it. The monorepo root is one more + * base (objectstack#38134), so a bare `'README.md'` lands on + * `../README.md` too, and is rejected here when it is not the read. * `walker` -- present when the scanner saw a directory walk in the file. * `'markdown-tree'` means the walk IS the markdown read and the * tree is in `reads`; `'not-markdown'` means the walk collects @@ -246,6 +305,12 @@ export const ADJUDICATED = new Map([ 'packages/app-shell/src/views/metadata-admin/previews/readme-flow-canvas-draft.test.ts', { reads: ['packages/app-shell/README.md'] }, ], + // Holds ADR-0084's type-to-group table equal to the Studio menu code, reading + // the ADR from the monorepo's root `docs/adr/` (objectstack#37935, #38134). + [ + 'packages/app-shell/src/views/studio-design/studioMenuPlacement.test.ts', + { reads: ['../docs/adr/0084-application-builder-information-architecture.md'] }, + ], [ 'packages/auth/src/__tests__/reserved-auth-features.test.ts', { @@ -319,18 +384,23 @@ export const ADJUDICATED = new Map([ ], // The three guides it reads moved with the published bundle into the objectstack // monorepo's `skills/` catalog at the cutover (decision C, objectstack#25803), outside - // this tree, so this ledger can no longer name them; their trigger is the monorepo's. + // this tree, and are named `../skills/objectui/…` like every out-of-tree read + // (objectstack#38134). [ 'packages/components/src/__tests__/skill-guide-data-table-binding.test.tsx', { - reads: [], + reads: [ + '../skills/objectui/guides/data-integration.md', + '../skills/objectui/guides/schema-expressions.md', + '../skills/objectui/rules/protocol.md', + ], walker: 'not-markdown: concatenates plugin package `.tsx` sources', }, ], [ 'packages/components/src/__tests__/skill-guide-provider-envelope.test.tsx', { - reads: ['skills/objectui/**'], + reads: ['../skills/objectui/**'], walker: 'markdown-tree: walks the published skill package and asserts over every `.md` in it', }, ], @@ -400,6 +470,12 @@ export const ADJUDICATED = new Map([ 'packages/layout/src/__tests__/readme-sidebar-nav-example.test.ts', { reads: ['packages/layout/README.md'] }, ], + // Pins the permission-config example of the published skill guide, read from + // the monorepo's `skills/` catalog (objectstack#38134). + [ + 'packages/permissions/src/__tests__/skill-guide-permission-config.test.tsx', + { reads: ['../skills/objectui/guides/auth-permissions.md'] }, + ], [ 'packages/plugin-calendar/src/readme-calendar-view-schema.test.ts', { reads: ['packages/plugin-calendar/README.md'] }, @@ -496,6 +572,12 @@ export const ADJUDICATED = new Map([ 'packages/types/src/__tests__/held-public-block-arms-10872.test.ts', { reads: ['../content/docs/frontend/quick-start.mdx'] }, ], + // objectui#11405: scans the `list` fences of two published skill guides, read + // from the monorepo's `skills/` catalog (objectstack#38134). + [ + 'packages/types/src/__tests__/list-bind-only-11405.test.ts', + { reads: ['../skills/objectui/guides/data-integration.md', '../skills/objectui/guides/schema-expressions.md'] }, + ], // objectui#6152 round 9 -- the corpus census of `object-calendar` containers. // It walks the authored trees, reads every markdown document in them that // names `object-calendar`, and parses each fenced element's `calendar` @@ -662,6 +744,15 @@ export const ADJUDICATED = new Map([ notRead: ['packages/core/README.md'], }, ], + // Runs the gate over its real scan surface (`listDocuments(repoRoot)`): the + // ObjectUI docs pages, every package README and the published skill bundle. + // Its other document literals are fixture pages handed to `run()`. + [ + 'scripts/__tests__/check-doc-json-fences.test.ts', + { + reads: ['../content/docs/frontend/**', '../skills/objectui/**', 'packages/**'], + }, + ], // `./*` rather than the eight root documents it used to list, and the // distinction is the whole of objectui#9142. This test does not read a list // of root documents -- it runs `git ls-files -- '*.md'`, keeps the paths with @@ -673,7 +764,10 @@ export const ADJUDICATED = new Map([ [ 'scripts/__tests__/check-doc-links.test.ts', { - reads: ['./*', 'apps/**', '../content/docs/frontend/**', 'docs/adr/**', 'docs/audits/**', 'examples/**', 'packages/**'], + reads: ['./*', 'apps/**', '../content/docs/frontend/**', '../skills/objectui/**', 'docs/adr/**', 'docs/audits/**', 'examples/**', 'packages/**'], + // A scratch-fixture link (`../packages/core/README.md` from a fixture + // `docs/`), which the ui-root base also resolves to the root package. + notRead: ['../packages/core/README.md'], }, ], [ @@ -722,13 +816,21 @@ export const ADJUDICATED = new Map([ [ 'scripts/__tests__/check-shell-escape-residue.test.ts', { - reads: ['.claude/skills/**', 'AGENTS.md', 'CLAUDE.md', '../content/docs/frontend/**', 'skills/objectui/**'], + reads: ['.claude/skills/**', 'AGENTS.md', 'CLAUDE.md', '../content/docs/frontend/**', '../skills/objectui/**'], + }, + ], + // Judges every page of the published skill bundle through `listGuides(repoRoot)`, + // in the monorepo's `skills/` catalog; its other literals are fixture pages. + [ + 'scripts/__tests__/check-skill-examples.test.ts', + { + reads: ['../skills/objectui/**'], }, ], [ 'scripts/__tests__/check-skills-paths.test.ts', { - reads: ['.claude/skills/**', 'skills/objectui/**'], + reads: ['.claude/skills/**', '../skills/objectui/**'], }, ], [ @@ -749,7 +851,7 @@ export const ADJUDICATED = new Map([ [ 'scripts/__tests__/doc-version-claims.test.ts', { - reads: ['../content/docs/frontend/**', 'docs/rfcs/**', 'packages/**', 'skills/objectui/**'], + reads: ['../content/docs/frontend/**', 'docs/rfcs/**', 'packages/**', '../skills/objectui/**'], walker: 'markdown-tree', }, ], @@ -760,13 +862,13 @@ export const ADJUDICATED = new Map([ [ 'scripts/__tests__/dollar-dialect-alias-census.test.ts', { - reads: ['./*', '.changeset/**', '.claude/skills/**', 'apps/**', '../content/docs/frontend/**', 'docs/adr/**', 'docs/audits/**', 'examples/**', 'packages/**', 'patches/README.md', 'skills/objectui/**'], + reads: ['./*', '.changeset/**', '.claude/skills/**', 'apps/**', '../content/docs/frontend/**', 'docs/adr/**', 'docs/audits/**', 'examples/**', 'packages/**', 'patches/README.md', '../skills/objectui/**'], }, ], [ 'scripts/__tests__/layered-read-declared-path-4016.test.ts', { - reads: ['skills/objectui/**'], + reads: ['../skills/objectui/**'], walker: 'not-markdown: package `src/` directories', }, ], @@ -789,16 +891,16 @@ export const ADJUDICATED = new Map([ 'scripts/__tests__/markdown-test-inputs.test.ts', { reads: [], - notRead: ['AGENTS.md', 'packages/app-shell/README.md', 'packages/plugin-dashboard/README.md'], + notRead: ['../docs/adr/0084-application-builder-information-architecture.md', 'AGENTS.md', 'packages/app-shell/README.md', 'packages/plugin-dashboard/README.md'], }, ], // objectstack#26080 folded `QUICK_REFERENCE.md` into the repository root's - // `CONTRIBUTING.md`; this test reads that file's UI section, which is outside - // this tree, so it reads no markdown document this ledger can name. + // `CONTRIBUTING.md`; this test reads that file's UI section, outside this tree, + // named `../CONTRIBUTING.md` (objectstack#38134). [ 'scripts/__tests__/quick-reference-commands-4149.test.ts', { - reads: [], + reads: ['../CONTRIBUTING.md'], walker: 'not-markdown: directory listings that test whether a documented path exists', }, ], @@ -996,7 +1098,7 @@ function pathFragments(source) { * candidate is one line in `ADJUDICATED` while the cost of a missed one is the * defect this file exists to close. */ -export function deriveCandidates({ root = REPO_ROOT, roots = SCAN_ROOTS } = {}) { +export function deriveCandidates({ root = REPO_ROOT, roots = SCAN_ROOTS, monorepoRoot = path.dirname(root), uiGlobs = uiGlobsAt(monorepoRoot) } = {}) { const files = []; for (const top of roots) collectTests(path.join(root, top), files); @@ -1005,22 +1107,43 @@ export function deriveCandidates({ root = REPO_ROOT, roots = SCAN_ROOTS } = {}) const source = stripComments(readFileSync(file, 'utf8')); const bases = []; for (let dir = path.dirname(file); dir.startsWith(root); dir = path.dirname(dir)) bases.push(dir); - // …and the monorepo root, for a test that names a docs page from there. - bases.push(path.dirname(root)); + // …and the monorepo root, for a test that names a root document from there. + bases.push(monorepoRoot); const documents = new Set(); for (const fragment of pathFragments(source)) { if (!isMarkdown(fragment)) continue; if (/[\s*!:?<>|]/.test(fragment)) continue; // a message or a pathspec, not a path if (/^\.mdx?$/.test(fragment)) continue; // the bare extension + let inTreeHit = false; for (const base of bases) { + // The monorepo root is a FALLBACK base: a fragment one of the test's + // own directories already resolved to a document in this tree means + // that document, not a same-named one at the root (the ui + // `packages/core/README.md` against the root `packages/core/README.md`). + if (base === monorepoRoot && inTreeHit) continue; const resolved = path.resolve(base, fragment); - // The one tree outside this root a test may read: the monorepo's docs, - // where the ObjectUI pages live since objectstack#27145. It is labelled - // `../content/docs/…`, relative to this root like every other entry. - if (!resolved.startsWith(`${root}${path.sep}`) && !resolved.startsWith(`${MONOREPO_DOCS}${path.sep}`)) continue; + // A markdown document outside this tree is a candidate too + // (objectstack#38134): admitting only `content/docs` dropped the root + // `docs/adr` read of `studioMenuPlacement.test.ts` from the ledger + // without a word. An out-of-tree read is labelled `../`. It is + // admitted only when the root `ci.yml`'s `ui:` or `ui_consumers:` filter + // (the two the ui test job ORs) covers it, so a + // change to it starts the job that runs this ledger's test: a root + // README or CHANGELOG a test merely names would otherwise tie the + // ledger to a file whose edit starts no ui job, and red the NEXT ui PR. + // A read the filter does not cover is the fifth subject of + // scripts/check-ci-filter-parity.mjs, which asks that question of every + // ui test. `uiGlobs: null` (no ci.yml above a scratch root) admits all. + // A path above the monorepo root is no document of this repository. + if (!resolved.startsWith(`${monorepoRoot}${path.sep}`)) continue; if (resolved.includes(`${path.sep}node_modules${path.sep}`)) continue; + if (!resolved.startsWith(`${root}${path.sep}`) && uiGlobs) { + const monorepoPath = path.relative(monorepoRoot, resolved).split(path.sep).join('/'); + if (!uiGlobs.some((glob) => filterGlobMatches(glob, monorepoPath))) continue; + } if (existsSync(resolved) && statSync(resolved).isFile()) { + if (resolved.startsWith(`${root}${path.sep}`)) inTreeHit = true; documents.add(path.relative(root, resolved)); } } diff --git a/ui/scripts/select-affected-tests.mjs b/ui/scripts/select-affected-tests.mjs index 6df73a0134a..ed62a136e0a 100644 --- a/ui/scripts/select-affected-tests.mjs +++ b/ui/scripts/select-affected-tests.mjs @@ -410,6 +410,19 @@ export function moduleSpecifiers(source) { return { specifiers: [...specifiers], globsTheTree: /\bimport\.meta\.glob(?:Eager)?\s*\(/.test(source) }; } +/** + * The relative literals `rel` hands to `new URL(literal, import.meta.url)` + * that resolve outside this tree (a `../` past its root), as written. Pure: it + * reads no disk, so a literal naming nothing still counts -- the safe direction. + */ +export function urlLiteralsLeavingTree(rel, source) { + const out = []; + for (const m of String(source).matchAll(/\bnew\s+URL\(\s*(['"`])(\.{1,2}\/[^'"`\n$]*)\1\s*,\s*import\.meta\.url\s*,?\s*\)/g)) { + if (path.posix.normalize(path.posix.join(path.posix.dirname(rel), m[2])).startsWith('../')) out.push(m[2]); + } + return out; +} + /** A relative specifier resolved against the importer, as a repository-relative path, or null. */ export function resolveRelative(root, importerRel, specifier) { const base = path.join(root, path.dirname(importerRel), specifier); @@ -659,6 +672,12 @@ export function closureSummaries(root, seeds, names, dirOf, radiusOf = () => nul const name = workspaceNameOf(spec, names); if (name) node.packageNames.add(name); } + // A file named by a relative `new URL(literal, import.meta.url)` that + // resolves OUTSIDE this tree is loaded with no specifier this graph can + // follow (`await import(url.href)`, `readFileSync(url)`), and nothing + // inside the tree can bound it: unbounded, so the test is always on + // (objectstack#38133, `metadata-form-option-names.test.ts`). + if (/\.(?:[cm]?[jt]sx?)$/.test(rel) && urlLiteralsLeavingTree(rel, source).length > 0) node.readsDisk = true; // Item 2d: a library program reads the disk with or without `fs`. if (!touchesDisk && /\.(?:[cm]?[jt]sx?)$/.test(rel) && libraryReadsDisk(source, info.specifiers)) touchesDisk = true; // Item 2c: a module whose disk use is pinned as no test input.