From 0e91e70121fc5eb55b11aa0c55d054b8f1f241e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:53:56 +0000 Subject: [PATCH 1/4] ci: guard that every source a live-server test loads is on the temporal_live list (wip) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn --- scripts/check-temporal-live-filter.mjs | 904 +++++++++++++++++++++++++ 1 file changed, 904 insertions(+) create mode 100644 scripts/check-temporal-live-filter.mjs diff --git a/scripts/check-temporal-live-filter.mjs b/scripts/check-temporal-live-filter.mjs new file mode 100644 index 00000000000..1496e8770f7 --- /dev/null +++ b/scripts/check-temporal-live-filter.mjs @@ -0,0 +1,904 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * check-temporal-live-filter -- every workspace source a live-server test + * loads must be on the `temporal_live` list that decides whether the merge + * queue runs that test at all. + * + * node scripts/check-temporal-live-filter.mjs # judge the checked-in ci.yml + * node scripts/check-temporal-live-filter.mjs --list # each live test, its closure, the row covering each file + * node scripts/check-temporal-live-filter.mjs --match P.. # which `temporal_live` rows match these paths + * node scripts/check-temporal-live-filter.mjs --self-test # prove the battery can go red + * + * ## The gap this closes + * + * `Temporal Conformance (live PG + MySQL)` never runs on `pull_request` (its + * `if:`), and on a `merge_group` entry it runs only when the entry's diff + * matches the `temporal_live` paths of ci.yml's `filter` job. The list named + * the live test files and the packages they live in, but not the sources those + * tests LOAD from other packages. `capability-mount.live-postgres.test.ts` + * loads `packages/core/src/capability-composition.ts` through the vitest + * alias; an entry that changed only that file skipped the live job in the + * queue, landed, and the next `main` push run went red with the queue's green + * already spent. A path filter is only as good as the closure it was cut from, + * and nothing held the list to the closure. + * + * ## The rule + * + * For every test in the POPULATION, every workspace file in its run-time + * import closure is matched by some `temporal_live` row. + * + * POPULATION: the test files under `packages/` that a `temporal_live` row + * matches (the list's own statement of which tests this job runs live), plus + * every test file whose path carries `live-postgres` or `live-mysql` -- the + * substrings the job's filtered `vitest run` steps select by -- whether or not + * a row names it yet. A test file is `*.test.*` / `*.spec.*` in a JS or TS + * extension. + * + * CLOSURE: the files a test loads when vitest runs it, walked the way vitest + * resolves them, transitively from the test itself: + * + * - a relative specifier resolves the way TypeScript reads it: the file as + * written, a `.js` naming its `.ts`/`.tsx`, an extensionless one gaining + * an extension or `/index.*`; + * - a bare specifier goes through the TEST PACKAGE's `resolve.alias` first + * -- the real table, loaded from its `vitest.config.*`, applied the way + * `@rollup/plugin-alias` (Vite's) applies it: entries in order, first match + * wins, a string `find` matching the specifier or a `find + '/'` prefix, a + * RegExp by `test`, then `String.replace`. Vite applies that table to every + * module it loads, aliased source and inlined workspace `dist/` alike, so + * it is the consumer's table at every depth; + * - a bare workspace specifier no entry matches resolves through the package + * link to its `exports` target in `dist/`, which the job's `turbo run + * build --filter=...` step builds from that package's `src/`; the walk + * continues at the source the target is built from (`dist/x.js` -> + * `src/x.ts`), because that source is what a diff changes; + * - a third-party specifier (`pg`, `vitest`, `node:fs`) ends the walk. + * + * Edges are read with the TypeScript parser, not a regex: static `import` / + * `export ... from` (less `import type` / `export type`, which are erased and + * load nothing), `import x = require()`, and `import()` / `require()` / + * `vi.importActual()` calls with a string-literal argument wherever they sit. + * An import the parser sees inside a string or a comment is not an edge. + * + * ## Matching -- the subset of picomatch this gate reads, and the refusal past it + * + * `dorny/paths-filter` matches with picomatch (`dot: true`). The rows in + * `temporal_live` use literal paths, `*` (within one segment) and `**` (any + * number of segments); this gate implements exactly those three and REFUSES a + * row carrying any other picomatch syntax (`?`, `[`, `{`, `!`, `(`, `+`, `@`) + * rather than guess at it. A refused row is one line of YAML to rewrite; a + * guessed one is a silent scheduling gap, which is the subject of this file. + * + * ## Refusals -- what this gate does instead of reporting a clean zero + * + * A coverage gate that cannot read its subject compares two empty sets and + * passes. Each of these is exit 1 naming what could not be read: ci.yml + * unreadable or unparseable, no single `dorny/paths-filter` step in the + * `filter` job, no `temporal_live` filter, the `temporal-conformance` job gone + * or no longer reading `needs.filter.outputs.temporal_live` in its `if:` (a + * list nothing reads schedules nothing), a row in syntax the matcher does not + * read, an empty population, a vitest config that does not load or whose + * `projects` carry a `resolve` of their own, a relative import that resolves + * to no file, and a workspace import whose `dist/` target maps to no source. + * + * ## Bounds, stated so they are not rediscovered as bugs + * + * - Module loads only. A file a test READS (`readFileSync`, `new URL(...)`) + * is not an import; that axis is `check:cross-package-test-inputs`', for + * Test Core. A non-literal `import(expr)` cannot be resolved and is not + * followed. + * - It counts an `import { T }` whose bindings are all types (esbuild drops + * such a statement): over-scheduling, the safe direction. + * - It never says a row is too wide. A row covering no closure file is not + * reported: that error over-schedules a job, it never skips one. + * - Third-party code (the lockfile) is not followed. + */ + +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import ts from 'typescript'; +import { parse } from 'yaml'; +import { isEntrypoint } from './invoked-as.mjs'; + +const HERE = resolve(fileURLToPath(import.meta.url), '..'); +const REPO_ROOT = resolve(HERE, '..'); + +/** The workflow that owns the scheduling decision. */ +export const CI_WORKFLOW = '.github/workflows/ci.yml'; +/** The filter this gate holds to the closure. */ +export const LIVE_FILTER = 'temporal_live'; +/** The job that list schedules, by job id. */ +export const LIVE_JOB = 'temporal-conformance'; +/** The substrings the job's filtered `vitest run` steps select live files by. */ +export const LIVE_SUBSTRINGS = Object.freeze(['live-postgres', 'live-mysql']); +/** The tree the population is drawn from. */ +const POPULATION_ROOT = 'packages'; + +const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/; +const MODULE_FILE = /\.[cm]?[jt]sx?$/; +const SKIP_DIRS = new Set(['node_modules', 'dist', '.turbo', 'coverage', '.objectstack', '.next']); +const CONFIG_NAMES = ['vitest.config.ts', 'vitest.config.mts', 'vitest.config.js', 'vitest.config.mjs']; +/** picomatch syntax this gate does not implement; a row carrying any of it is refused. */ +const UNSUPPORTED_GLOB = /[?[\]{}!()+@]/; + +const toPosix = (p) => p.split(sep).join('/'); + +// ── Matching ──────────────────────────────────────────────────────────────── + +/** + * A `temporal_live` row as a RegExp over repo-relative POSIX paths, or null + * when the row carries syntax outside the literal / `*` / `**` subset. + */ +export function globToRegExp(glob) { + if (typeof glob !== 'string' || glob === '' || UNSUPPORTED_GLOB.test(glob)) return null; + const segments = glob.split('/'); + let source = '^'; + segments.forEach((segment, i) => { + const last = i === segments.length - 1; + if (segment === '**') { + source += last ? '.*' : '(?:[^/]*/)*'; + return; + } + source += segment.split('*').map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*'); + if (!last) source += '/'; + }); + return new RegExp(`${source}$`); +} + +/** The first row matching `path`, or null. */ +export function coveringRow(path, rows) { + for (const row of rows) if (row.re.test(path)) return row.glob; + return null; +} + +// ── Reading ci.yml ────────────────────────────────────────────────────────── + +/** + * The `temporal_live` rows out of a ci.yml SOURCE STRING, compiled, or + * `{ refusal }` for every state in which the subject was not read. + * `dorny/paths-filter` takes `filters` as a string and parses it as YAML + * itself, so this is two parses, in the action's order. + */ +export function readLiveRows(source) { + let doc; + try { + doc = parse(source); + } catch (err) { + return { refusal: `${CI_WORKFLOW} could not be read as YAML: ${err?.message ?? err}` }; + } + const jobs = doc?.jobs; + if (!jobs || typeof jobs !== 'object') return { refusal: `${CI_WORKFLOW} declares no \`jobs:\` map.` }; + const steps = Array.isArray(jobs.filter?.steps) ? jobs.filter.steps : []; + const filterSteps = steps.filter((s) => String(s?.uses ?? '').startsWith('dorny/paths-filter')); + if (filterSteps.length !== 1) { + return { + refusal: + `${CI_WORKFLOW}'s \`filter\` job has ${filterSteps.length} \`dorny/paths-filter\` step(s); this gate reads ` + + 'exactly one. The scheduling decision has moved or been split.', + }; + } + const raw = filterSteps[0]?.with?.filters; + if (typeof raw !== 'string') return { refusal: `${CI_WORKFLOW}'s \`dorny/paths-filter\` step carries no \`with.filters\` STRING.` }; + let filters; + try { + filters = parse(raw); + } catch (err) { + return { refusal: `${CI_WORKFLOW}'s \`filters:\` input is not parseable YAML: ${err?.message ?? err}` }; + } + const list = filters?.[LIVE_FILTER]; + if (!Array.isArray(list) || list.length === 0 || list.some((e) => typeof e !== 'string')) { + return { refusal: `${CI_WORKFLOW}'s \`filters:\` input declares no \`${LIVE_FILTER}:\` list of path strings.` }; + } + const job = jobs[LIVE_JOB]; + if (!job) return { refusal: `${CI_WORKFLOW} has no \`${LIVE_JOB}\` job -- the list schedules nothing this gate knows.` }; + const condition = typeof job.if === 'string' ? job.if : ''; + if (!condition.includes(`needs.filter.outputs.${LIVE_FILTER}`)) { + return { + refusal: + `${CI_WORKFLOW}'s \`${LIVE_JOB}\` job no longer reads \`needs.filter.outputs.${LIVE_FILTER}\` in its \`if:\`, ` + + `so the list schedules nothing and coverage against it means nothing.\n if: ${condition || '(absent)'}`, + }; + } + const rows = []; + const unreadable = []; + for (const glob of list) { + const re = globToRegExp(glob); + if (re) rows.push({ glob, re }); + else unreadable.push(glob); + } + if (unreadable.length > 0) { + return { + refusal: + `${CI_WORKFLOW}'s \`${LIVE_FILTER}:\` carries row(s) outside the literal / \`*\` / \`**\` subset this gate ` + + `matches: ${unreadable.map((g) => JSON.stringify(g)).join(', ')}. Rewrite the row in that subset, or teach ` + + 'globToRegExp the syntax with a --self-test case.', + }; + } + return { rows }; +} + +// ── The workspace ─────────────────────────────────────────────────────────── + +/** Every file under `rel` (repo-relative POSIX), skipping build and dependency trees. */ +function walkFiles(root, rel) { + const out = []; + const visit = (dirRel) => { + let entries; + try { + entries = readdirSync(join(root, dirRel), { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const childRel = dirRel ? `${dirRel}/${entry.name}` : entry.name; + if (entry.isDirectory()) { + if (!SKIP_DIRS.has(entry.name)) visit(childRel); + } else if (entry.isFile()) { + out.push(childRel); + } + } + }; + visit(rel); + return out.sort(); +} + +/** Workspace package name -> { dir, manifest } for every manifest under `packages/`. */ +export function workspacePackages(root) { + const map = new Map(); + for (const rel of walkFiles(root, POPULATION_ROOT)) { + if (!rel.endsWith('/package.json')) continue; + let manifest; + try { + manifest = JSON.parse(readFileSync(join(root, rel), 'utf8')); + } catch { + continue; + } + if (typeof manifest?.name === 'string') map.set(manifest.name, { dir: rel.slice(0, -'/package.json'.length), manifest }); + } + return map; +} + +/** The package directory (repo-relative) holding `rel`: the nearest manifest above it. */ +function packageDirOf(root, rel) { + let dir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : ''; + while (dir) { + if (existsSync(join(root, dir, 'package.json'))) return dir; + dir = dir.includes('/') ? dir.slice(0, dir.lastIndexOf('/')) : ''; + } + return null; +} + +/** + * The POPULATION: test files a row matches, plus test files carrying a live + * substring. Each comes back with why it is in. + */ +export function populationOf(root, rows) { + const out = []; + for (const rel of walkFiles(root, POPULATION_ROOT)) { + if (!TEST_FILE.test(rel)) continue; + const row = coveringRow(rel, rows); + const substring = LIVE_SUBSTRINGS.find((s) => rel.includes(s)) ?? null; + if (row || substring) out.push({ test: rel, row, substring }); + } + return out; +} + +// ── Resolution ────────────────────────────────────────────────────────────── + +/** The file a relative target names, read the way TypeScript does, or null. */ +export function resolveFileTarget(absTarget) { + const isFile = (p) => { + try { + return statSync(p).isFile(); + } catch { + return false; + } + }; + if (isFile(absTarget)) return absTarget; + const candidates = []; + const ext = absTarget.match(/\.[cm]?js$/)?.[0]; + if (ext) { + const stem = absTarget.slice(0, -ext.length); + candidates.push(...(ext === '.mjs' ? ['.mts'] : ext === '.cjs' ? ['.cts'] : ['.ts', '.tsx']).map((e) => stem + e)); + } + candidates.push(...['.ts', '.tsx', '.mts', '.js', '.mjs'].map((e) => absTarget + e)); + candidates.push(...['index.ts', 'index.tsx', 'index.js', 'index.mjs'].map((f) => join(absTarget, f))); + return candidates.find(isFile) ?? null; +} + +/** + * The alias entry `specifier` resolves through, applied the way + * `@rollup/plugin-alias` applies Vite's table: first match wins; a string + * `find` matches the specifier itself or as a `find + '/'` prefix, a RegExp by + * `test`; the result is `specifier.replace(find, replacement)`. + */ +export function applyAlias(specifier, aliases) { + for (const { find, replacement } of aliases) { + const hit = + find instanceof RegExp + ? (() => { + find.lastIndex = 0; + return find.test(specifier); + })() + : specifier === find || specifier.startsWith(`${find}/`); + if (hit) { + if (find instanceof RegExp) find.lastIndex = 0; + return specifier.replace(find, replacement); + } + } + return null; +} + +/** `@scope/name/sub` -> { name: '@scope/name', subpath: './sub' }. */ +function splitBare(specifier) { + const parts = specifier.split('/'); + const take = specifier.startsWith('@') ? 2 : 1; + const name = parts.slice(0, take).join('/'); + const rest = parts.slice(take).join('/'); + return { name, subpath: rest ? `./${rest}` : '.' }; +} + +/** The `import`-side target string of one `exports` entry. */ +function exportTarget(entry) { + if (typeof entry === 'string') return entry; + if (!entry || typeof entry !== 'object') return null; + for (const key of ['import', 'default', 'node', 'require']) { + if (key in entry) { + const found = exportTarget(entry[key]); + if (found) return found; + } + } + return null; +} + +/** + * The SOURCE a workspace package's `exports` target is built from, repo- + * relative, or `{ unresolved }`. `dist/x.js` -> `src/x.ts` (or `.tsx`, + * `src/x/index.ts`); a target already outside `dist/` is resolved as written. + */ +export function workspaceSource(root, pkg, subpath) { + const { dir, manifest } = pkg; + let target = null; + const exp = manifest.exports; + if (exp && typeof exp === 'object' && !Array.isArray(exp) && Object.keys(exp).some((k) => k.startsWith('.'))) { + target = exportTarget(exp[subpath]); + } else if (subpath === '.') { + target = exportTarget(exp) ?? manifest.module ?? manifest.main ?? null; + } + if (!target) return { unresolved: `${manifest.name} publishes no \`exports\` entry for ${JSON.stringify(subpath)}` }; + const clean = target.replace(/^\.\//, ''); + const distMatch = clean.match(/^dist\/(.+?)\.(?:d\.)?[cm]?[jt]s$/); + const abs = distMatch ? resolveFileTarget(join(root, dir, 'src', distMatch[1])) : resolveFileTarget(join(root, dir, clean)); + if (!abs) { + return { + unresolved: + `${manifest.name}${subpath === '.' ? '' : subpath.slice(1)} resolves to ${dir}/${clean}, and no source under ` + + `${dir}/src builds it`, + }; + } + return { rel: toPosix(relative(root, abs)) }; +} + +// ── Edges ─────────────────────────────────────────────────────────────────── + +/** The run-time module specifiers one source file names, in source order, deduped. */ +export function runtimeSpecifiers(source, fileName = 'x.ts') { + const kind = /\.tsx$/.test(fileName) ? ts.ScriptKind.TSX : /\.[cm]?jsx?$/.test(fileName) ? ts.ScriptKind.JS : ts.ScriptKind.TS; + const sf = ts.createSourceFile(fileName, String(source ?? ''), ts.ScriptTarget.Latest, false, kind); + const out = []; + const add = (node) => { + if (node && ts.isStringLiteralLike(node) && !out.includes(node.text)) out.push(node.text); + }; + const visit = (node) => { + if (ts.isImportDeclaration(node)) { + if (!node.importClause?.isTypeOnly) add(node.moduleSpecifier); + } else if (ts.isExportDeclaration(node)) { + if (!node.isTypeOnly) add(node.moduleSpecifier); + } else if (ts.isImportEqualsDeclaration(node)) { + if (!node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)) add(node.moduleReference.expression); + } else if (ts.isCallExpression(node) && node.arguments.length > 0) { + const callee = node.expression; + const isImport = callee.kind === ts.SyntaxKind.ImportKeyword; + const isRequire = ts.isIdentifier(callee) && callee.text === 'require'; + const isImportActual = + ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === 'vi' && callee.name.text === 'importActual'; + if (isImport || isRequire || isImportActual) add(node.arguments[0]); + } + ts.forEachChild(node, visit); + }; + visit(sf); + return out; +} + +// ── Configs ───────────────────────────────────────────────────────────────── + +/** + * A config's `resolve.alias` as an ordered `{ find, replacement }` list, or + * `{ refusal }`. Object form keeps its key order, as Vite normalizes it. + */ +export function aliasesOf(config, configRel) { + const projects = config?.test?.projects; + if (Array.isArray(projects) && projects.some((p) => p && typeof p === 'object' && p.resolve)) { + return { refusal: `${configRel}: a \`test.projects\` entry carries its own \`resolve\`; this gate reads the root table only.` }; + } + const alias = config?.resolve?.alias; + if (alias == null) return { aliases: [] }; + if (Array.isArray(alias)) return { aliases: alias.map((a) => ({ find: a.find, replacement: a.replacement })) }; + if (typeof alias === 'object') return { aliases: Object.entries(alias).map(([find, replacement]) => ({ find, replacement })) }; + return { refusal: `${configRel}: \`resolve.alias\` is neither a list nor a map.` }; +} + +/** + * The `setupFiles` / `globalSetup` a config names (root and `projects`), + * repo-relative: vitest loads them around every test, through the same alias + * table, so they are closure roots beside the test itself. + */ +export function setupFilesOf(config, pkgDir) { + const out = []; + const tests = [config?.test, ...(Array.isArray(config?.test?.projects) ? config.test.projects.map((p) => p?.test) : [])]; + for (const t of tests) { + for (const key of ['setupFiles', 'globalSetup']) { + const v = t?.[key]; + for (const f of Array.isArray(v) ? v : v ? [v] : []) { + if (typeof f !== 'string') continue; + const rel = toPosix(relative('.', join(pkgDir, f))); + if (!out.includes(rel)) out.push(rel); + } + } + } + return out; +} + +/** Load the vitest config of `pkgDir` and return its alias table, or `{ refusal }`. */ +export async function loadAliases(root, pkgDir) { + const name = CONFIG_NAMES.find((n) => existsSync(join(root, pkgDir, n))); + if (!name) return { aliases: [], config: null }; + const configRel = `${pkgDir}/${name}`; + try { + // Through tsx's ESM loader (a config may import an ESM-only module such as + // `vitest/node`). Vite's own loader bundles the config and defines + // `__dirname` / `__filename` for it, and most configs here spell their + // replacements with `__dirname`, which an ESM module does not have: the + // free identifier is supplied on `globalThis` for the one load, the way + // Vite supplies it, and restored after. Configs load one at a time. + const { tsImport } = await import('tsx/esm/api'); + const saved = { dirname: globalThis.__dirname, filename: globalThis.__filename }; + globalThis.__dirname = join(root, pkgDir); + globalThis.__filename = join(root, configRel); + let mod; + try { + mod = await tsImport(pathToFileURL(join(root, configRel)).href, import.meta.url); + } finally { + globalThis.__dirname = saved.dirname; + globalThis.__filename = saved.filename; + } + let config = mod?.default ?? mod; + if (typeof config === 'function') config = await config({ command: 'serve', mode: 'test' }); + const resolved = await config; + return { ...aliasesOf(resolved, configRel), config: configRel, setupFiles: setupFilesOf(resolved, pkgDir) }; + } catch (err) { + return { refusal: `${configRel} did not load: ${err?.message ?? err}` }; + } +} + +// ── The walk ──────────────────────────────────────────────────────────────── + +/** + * The run-time closure of one test: Map of repo-relative file -> the file that + * first reached it (null for the test itself). Throws on a relative import that + * resolves to nothing or a workspace target with no source. + */ +export function closureOf(root, testRel, aliases, packages, edgeCache = new Map()) { + const parent = new Map([[testRel, null]]); + const queue = [testRel]; + for (let head = 0; head < queue.length; head++) { + const rel = queue[head]; + if (!edgeCache.has(rel)) edgeCache.set(rel, targetsOf(root, rel, aliases, packages)); + for (const targetRel of edgeCache.get(rel)) { + if (!parent.has(targetRel)) { + parent.set(targetRel, rel); + queue.push(targetRel); + } + } + } + return parent; +} + +/** + * The workspace files ONE module loads, repo-relative, under one alias table. + * Cached per table by the caller: the edges of a file do not depend on which + * test reached it. + */ +function targetsOf(root, rel, aliases, packages) { + const out = []; + if (!MODULE_FILE.test(rel)) return out; + const abs = join(root, rel); + { + for (const spec of runtimeSpecifiers(readFileSync(abs, 'utf8'), rel)) { + let target = null; + if (spec.startsWith('.') || spec.startsWith('/')) { + const found = resolveFileTarget(resolve(dirname(abs), spec)); + if (!found) throw new Error(`${rel} imports ${JSON.stringify(spec)}, which resolves to no file`); + target = found; + } else { + const aliased = applyAlias(spec, aliases); + if (aliased != null) { + const found = resolveFileTarget(resolve(root, aliased)); + if (!found) throw new Error(`${rel} imports ${JSON.stringify(spec)}; the test package's alias sends it to ${aliased}, which is no file`); + target = found; + } else { + const { name, subpath } = splitBare(spec); + const pkg = packages.get(name); + if (!pkg) continue; // third-party: the walk ends + const src = workspaceSource(root, pkg, subpath); + if (src.unresolved) throw new Error(`${rel} imports ${JSON.stringify(spec)}: ${src.unresolved}`); + target = join(root, src.rel); + } + } + const targetRel = toPosix(relative(root, target)); + if (targetRel.startsWith('..') || targetRel.includes('/node_modules/')) continue; + if (!out.includes(targetRel)) out.push(targetRel); + } + } + return out; +} + +/** The import chain from the test down to `file`. */ +function chainTo(parent, file) { + const chain = []; + for (let at = file; at != null; at = parent.get(at)) chain.unshift(at); + return chain; +} + +/** + * The verdict over a tree: per test its closure; every closure file no row + * matches, with the tests reaching it. Async because configs are loaded. + */ +export async function judge(root, source) { + const read = readLiveRows(source); + if (read.refusal) return { refusal: read.refusal }; + const { rows } = read; + const population = populationOf(root, rows); + if (population.length === 0) { + return { refusal: `no test under ${POPULATION_ROOT}/ is matched by a \`${LIVE_FILTER}\` row or carries ${LIVE_SUBSTRINGS.join(' / ')}: the gate would judge nothing.` }; + } + const packages = workspacePackages(root); + const aliasCache = new Map(); + const tests = []; + const uncovered = new Map(); + for (const member of population) { + const pkgDir = packageDirOf(root, member.test); + if (!aliasCache.has(pkgDir)) { + const loaded = pkgDir ? await loadAliases(root, pkgDir) : { aliases: [], config: null }; + aliasCache.set(pkgDir, { ...loaded, edges: new Map() }); + } + const loaded = aliasCache.get(pkgDir); + if (loaded.refusal) return { refusal: loaded.refusal }; + let parent; + try { + parent = closureOf(root, member.test, loaded.aliases, packages, loaded.edges); + // The config and what it imports decide how every specifier resolves, so + // they are inputs of the test's verdict too: walked once per package, + // WITHOUT the alias table (Vite loads its own config unaliased); the + // setup files it names are walked WITH it, as vitest loads them. + if (!loaded.harness) { + loaded.harness = new Map(); + if (loaded.config) { + for (const [f, from] of closureOf(root, loaded.config, [], packages, (loaded.configEdges = new Map()))) loaded.harness.set(f, from); + } + for (const setup of loaded.setupFiles ?? []) { + for (const [f, from] of closureOf(root, setup, loaded.aliases, packages, loaded.edges)) if (!loaded.harness.has(f)) loaded.harness.set(f, from); + } + } + for (const [f, from] of loaded.harness) if (!parent.has(f)) parent.set(f, from); + } catch (err) { + return { refusal: `walking ${member.test}: ${err?.message ?? err}` }; + } + const files = [...parent.keys()]; + tests.push({ ...member, config: loaded.config, files, parent }); + for (const file of files) { + if (coveringRow(file, rows)) continue; + if (!uncovered.has(file)) uncovered.set(file, { file, tests: [], chain: chainTo(parent, file) }); + uncovered.get(file).tests.push(member.test); + } + } + return { rows, tests, uncovered: [...uncovered.values()].sort((a, b) => a.file.localeCompare(b.file)) }; +} + +// ── Reporting ─────────────────────────────────────────────────────────────── + +const REMEDY = + `Add a \`${LIVE_FILTER}\` row in ${CI_WORKFLOW} covering each file -- a glob at the grain of what the live\n` + + 'tests load (a directory a test pulls in whole, or the files themselves), with a comment naming the test that\n' + + 'loads it. Without it a merge-queue entry changing only that file skips `Temporal Conformance (live PG + MySQL)`,\n' + + 'lands, and the live test goes red first on `main`. `--list` prints every closure and the row covering each file.'; + +function report(verdict) { + if (verdict.refusal) { + console.error(`✗ check-temporal-live-filter: REFUSED -- ${verdict.refusal}`); + return 1; + } + const closureSize = new Set(verdict.tests.flatMap((t) => t.files)).size; + if (verdict.uncovered.length > 0) { + console.error( + `✗ check-temporal-live-filter: ${verdict.uncovered.length} workspace file(s) a live test loads are on no ` + + `\`${LIVE_FILTER}\` row (${verdict.tests.length} live test(s), ${closureSize} closure file(s)):\n`, + ); + for (const u of verdict.uncovered) { + console.error(` ${u.file}`); + console.error(` loaded by ${u.tests.length} test(s), e.g. ${u.chain.join(' -> ')}`); + } + console.error(`\n${REMEDY}`); + return 1; + } + console.log( + `✓ check-temporal-live-filter: every workspace file the ${verdict.tests.length} live test(s) load ` + + `(${closureSize} file(s)) is on a \`${LIVE_FILTER}\` row of ${CI_WORKFLOW} (${verdict.rows.length} row(s)).`, + ); + return 0; +} + +function list(verdict) { + if (verdict.refusal) return report(verdict); + const byRow = new Map(); + for (const t of verdict.tests) { + console.log(`${t.test} [${t.row ? `row ${t.row}` : `substring ${t.substring}`}; config ${t.config ?? '(none)'}]`); + const counts = new Map(); + for (const f of t.files) { + const row = coveringRow(f, verdict.rows) ?? 'UNCOVERED'; + counts.set(row, (counts.get(row) ?? 0) + 1); + if (!byRow.has(row)) byRow.set(row, new Set()); + byRow.get(row).add(f); + } + for (const [row, n] of [...counts].sort()) console.log(` ${String(n).padStart(5)} ${row}`); + } + console.log('\nUnion of closures, by covering row:'); + for (const [row, files] of [...byRow].sort()) console.log(` ${String(files.size).padStart(5)} ${row}`); + return report(verdict); +} + +function match(source, paths) { + const read = readLiveRows(source); + if (read.refusal) return report(read); + let unmatched = 0; + for (const p of paths) { + const row = coveringRow(p, read.rows); + console.log(`${row ? 'MATCH ' : 'NO MATCH'} ${p}${row ? ` <- ${row}` : ''}`); + if (!row) unmatched += 1; + } + return unmatched === 0 ? 0 : 1; +} + +// ── Self-test ─────────────────────────────────────────────────────────────── + +// Set by `selfTest()` only after its verdict prints, and read at the dispatch: +// a `return` above that line would print nothing and exit 0 -- a self-test that +// never finished, reported as one that passed. +let selfTestReachedVerdict = false; + +// The roster: battery NAME -> minimum case count. Every assertion is filed under +// the battery most recently opened; the floor requires the opened set to equal +// the declared set, each at or above its count. ⛔ Not one pinned total. +const SELF_TEST_BATTERIES = Object.freeze({ + '(1) the matcher: literal, `*`, `**`, and the refused syntax': 12, + '(2) reading ci.yml: the rows, and every refusal over a subject not read': 8, + '(3) edges: the parser, not a regex': 8, + '(4) resolution: relative, alias, workspace dist -> src, third-party': 9, + '(5) the verdict, end to end over a fixture tree': 9, + '(6) the real tree': 4, + '(7) WIRING: the gate and its self-test run in CI': 3, +}); +// Deleting a battery deletes its own floor, so the roster's size is pinned too. +const SELF_TEST_BATTERY_FLOOR = 7; +const UNATTRIBUTED_BATTERY = '(no battery open)'; + +async function selfTest() { + let failed = 0; + let current = UNATTRIBUTED_BATTERY; + const seen = new Map(); + const battery = (name) => { + current = name; + if (!seen.has(name)) seen.set(name, 0); + console.log(`\n${name}`); + }; + const assert = (cond, label) => { + seen.set(current, (seen.get(current) ?? 0) + 1); + if (cond) console.log(` ✓ ${label}`); + else { + failed += 1; + console.error(` ✗ ${label}`); + } + }; + + battery('(1) the matcher: literal, `*`, `**`, and the refused syntax'); + const m = (glob, path) => globToRegExp(glob)?.test(path) ?? false; + assert(m('packages/core/src/a.ts', 'packages/core/src/a.ts'), 'a literal row matches its own path'); + assert(!m('packages/core/src/a.ts', 'packages/core/src/a.tsx'), 'a literal row does not match a longer path'); + assert(m('packages/core/**', 'packages/core/src/deep/a.ts'), '`dir/**` matches any depth below dir'); + assert(!m('packages/core/**', 'packages/core-x/src/a.ts'), '`dir/**` does not match a sibling sharing the prefix'); + assert(m('packages/x/src/**/*live-mysql*', 'packages/x/src/migrations/a.live-mysql.test.ts'), '`**/*sub*` matches a nested file carrying the substring'); + assert(m('packages/x/src/**/*live-mysql*', 'packages/x/src/a.live-mysql.test.ts'), '`**/` matches zero directories'); + assert(!m('packages/x/src/**/*live-mysql*', 'packages/x/src/a.live-postgres.test.ts'), '`**/*sub*` does not match a file without the substring'); + assert(!m('packages/x/src/*.ts', 'packages/x/src/sub/a.ts'), '`*` stays inside one segment'); + assert(m('packages/x/src/*.ts', 'packages/x/src/.hidden.ts'), '`*` matches a dot file (picomatch `dot: true`, as dorny/paths-filter sets it)'); + assert(m('packages/a.b/c.ts', 'packages/a.b/c.ts') && !m('packages/a.b/c.ts', 'packages/aXb/c.ts'), 'a `.` is literal, not a regex wildcard'); + assert(['a/{b,c}/**', 'a/!(b)/**', 'a/?.ts', 'a/[ab].ts', 'a/@(b)/c', 'a/+(b)'].every((g) => globToRegExp(g) === null), 'every picomatch syntax outside the subset is REFUSED, never guessed'); + assert(globToRegExp('') === null && globToRegExp(7) === null, 'an empty or non-string row is refused'); + + battery('(2) reading ci.yml: the rows, and every refusal over a subject not read'); + const ci = ({ rows = ["- 'packages/a/**'"], uses = 'dorny/paths-filter@v4', ifLine = "${{ needs.filter.outputs.temporal_live != 'false' }}", job = true, filterName = 'temporal_live' } = {}) => + [ + 'jobs:', + ' filter:', + ' steps:', + ` - uses: ${uses}`, + ' with:', + ' filters: |', + ` ${filterName}:`, + ...rows.map((r) => ` ${r}`), + ...(job ? [' temporal-conformance:', ` if: ${ifLine}`] : []), + '', + ].join('\n'); + const okRead = readLiveRows(ci()); + assert(!okRead.refusal && okRead.rows.length === 1 && okRead.rows[0].glob === 'packages/a/**', 'a well-formed ci.yml yields its rows'); + assert(/YAML/.test(readLiveRows('jobs: [unclosed').refusal ?? ''), 'unparseable YAML ⇒ REFUSAL'); + assert(/paths-filter/.test(readLiveRows(ci({ uses: 'actions/checkout@v7' })).refusal ?? ''), 'no paths-filter step ⇒ REFUSAL'); + assert(/temporal_live/.test(readLiveRows(ci({ filterName: 'other' })).refusal ?? ''), 'no `temporal_live` list ⇒ REFUSAL'); + assert(/no `temporal-conformance` job/.test(readLiveRows(ci({ job: false })).refusal ?? ''), 'the job gone ⇒ REFUSAL'); + assert(/no longer reads/.test(readLiveRows(ci({ ifLine: "${{ needs.filter.outputs.core != 'false' }}" })).refusal ?? ''), 'the job no longer reading the output ⇒ REFUSAL'); + assert(/outside the literal/.test(readLiveRows(ci({ rows: ["- 'packages/{a,b}/**'"] })).refusal ?? ''), 'a row in unread syntax ⇒ REFUSAL naming it'); + assert(/declares no/.test(readLiveRows(ci({ rows: ['- 7'] })).refusal ?? ''), 'a non-string row ⇒ REFUSAL'); + + battery('(3) edges: the parser, not a regex'); + const edges = (src, name) => runtimeSpecifiers(src, name); + assert(edges("import { a } from './a.js';\nexport * from './b';").join() === './a.js,./b', 'static import and export-from are edges'); + assert(edges("import type { A } from './t.js';\nexport type { B } from './u.js';").length === 0, '`import type` / `export type` are erased and load nothing'); + assert(edges("const s = \"import { x } from './fixture.js'\";\n// import { y } from './c.js'").length === 0, 'an import inside a string or a comment is not an edge'); + assert(edges("async function f() { await import('./lazy.js'); }").join() === './lazy.js', 'a dynamic import inside a function body is an edge'); + assert(edges("const m = require('./cjs.cjs');", 'x.cjs').join() === './cjs.cjs', 'a `require()` call is an edge'); + assert(edges("const a = await vi.importActual('@objectstack/core');").join() === '@objectstack/core', '`vi.importActual()` is an edge'); + assert(edges('const n = "./x"; await import(n);').length === 0, 'a non-literal import() is not followed (a stated bound)'); + assert(edges("import x = require('./eq');").join() === './eq', '`import x = require()` is an edge'); + + battery('(4) resolution: relative, alias, workspace dist -> src, third-party'); + assert(applyAlias('@objectstack/core', [{ find: '@objectstack/core', replacement: '/r/core/src/index.ts' }]) === '/r/core/src/index.ts', 'a string `find` matches the specifier itself'); + assert(applyAlias('@objectstack/core/logger', [{ find: '@objectstack/core', replacement: '/r/i.ts' }]) === '/r/i.ts/logger', 'a string `find` matches a `find/` prefix (and mangles a file replacement -- what Vite does)'); + assert(applyAlias('@objectstack/core-x', [{ find: '@objectstack/core', replacement: '/r/i.ts' }]) === null, 'a string `find` does not match a longer package name'); + assert(applyAlias('@objectstack/spec/data', [{ find: /^@objectstack\/spec\/([a-z-]+)$/, replacement: '/r/spec/src/$1/index.ts' }]) === '/r/spec/src/data/index.ts', 'a RegExp `find` replaces with its back-reference'); + assert( + applyAlias('@objectstack/core', [{ find: /^@objectstack\/core$/, replacement: '/first' }, { find: '@objectstack/core', replacement: '/second' }]) === '/first', + 'the first matching entry wins', + ); + const fx = mkdtempSync(join(tmpdir(), 'temporal-live-filter-')); + const put = (rel, text) => { + mkdirSync(dirname(join(fx, rel)), { recursive: true }); + writeFileSync(join(fx, rel), text); + }; + try { + put('packages/lib/package.json', JSON.stringify({ name: '@objectstack/lib', exports: { '.': { import: { default: './dist/index.js' } }, './sub': { import: './dist/sub.js' } } })); + put('packages/lib/src/index.ts', 'export const lib = 1;\n'); + put('packages/lib/src/sub/index.ts', 'export const sub = 1;\n'); + put('packages/bare/package.json', JSON.stringify({ name: '@objectstack/bare', exports: { '.': './dist/gone.js' } })); + const pkgs = workspacePackages(fx); + assert(workspaceSource(fx, pkgs.get('@objectstack/lib'), '.').rel === 'packages/lib/src/index.ts', 'a `dist/index.js` export maps to the `src/index.ts` it is built from'); + assert(workspaceSource(fx, pkgs.get('@objectstack/lib'), './sub').rel === 'packages/lib/src/sub/index.ts', 'a subpath export maps to its source, `/index.ts` included'); + assert(/no source/.test(workspaceSource(fx, pkgs.get('@objectstack/bare'), '.').unresolved ?? ''), 'a `dist/` target with no source is UNRESOLVED, never skipped'); + put('packages/lib/src/rel.ts', "import { lib } from './index.js';\nimport 'pg';\n"); + const walked = closureOf(fx, 'packages/lib/src/rel.ts', [], pkgs); + assert(walked.has('packages/lib/src/index.ts') && walked.size === 2, 'a `.js` relative specifier resolves to its `.ts` source; a third-party one ends the walk'); + + battery('(5) the verdict, end to end over a fixture tree'); + put('packages/live/package.json', JSON.stringify({ name: '@objectstack/live' })); + put( + 'packages/live/vitest.config.mjs', + "import path from 'node:path';\nexport default { resolve: { alias: [{ find: /^@objectstack\\/lib$/, replacement: path.resolve(import.meta.dirname, '../lib/src/index.ts') }] } };\n", + ); + put('packages/live/src/a.live-postgres.test.ts', "import { lib } from '@objectstack/lib';\nimport { sub } from '@objectstack/lib/sub';\nimport { h } from './helper.js';\n"); + put('packages/live/src/helper.ts', 'export const h = 1;\n'); + put('packages/live/src/unit.test.ts', "import { h } from './helper.js';\n"); + const tree = (rows) => judge(fx, ci({ rows: rows.map((r) => `- '${r}'`) })); + const full = await tree(['packages/live/**', 'packages/lib/src/**']); + assert(!full.refusal && full.uncovered.length === 0, 'every closure file on a row ⇒ GREEN'); + const aliased = full.tests.find((t) => t.test.endsWith('a.live-postgres.test.ts')); + assert(aliased?.files.includes('packages/lib/src/index.ts'), 'the vitest alias is LOADED from the config and followed into the dependency source'); + assert(aliased?.files.includes('packages/lib/src/sub/index.ts'), 'an unaliased workspace subpath is followed through `dist/` to its source'); + const gap = await tree(['packages/live/**', 'packages/lib/src/sub/**']); + assert(gap.uncovered.map((u) => u.file).join() === 'packages/lib/src/index.ts', 'the source a live test loads from ANOTHER package, on no row ⇒ RED naming exactly that file'); + assert(gap.uncovered[0]?.chain.join(' -> ') === 'packages/live/src/a.live-postgres.test.ts -> packages/lib/src/index.ts', 'the finding carries the import chain that reaches it'); + const unlisted = await tree(['packages/lib/src/**']); + assert( + unlisted.uncovered.some((u) => u.file === 'packages/live/src/a.live-postgres.test.ts') && !unlisted.tests.some((t) => t.test.endsWith('unit.test.ts')), + 'a live-substring test on no row is in the population and reds; a unit test on no row is not judged', + ); + assert(full.tests.some((t) => t.test.endsWith('unit.test.ts')), 'a unit test a row matches IS judged (the row says the job runs it)'); + put('packages/live/src/broken.live-mysql.test.ts', "import './missing.js';\n"); + assert(/resolves to no file/.test((await tree(['packages/**'])).refusal ?? ''), 'a relative import resolving to nothing ⇒ REFUSAL, never a short closure'); + rmSync(join(fx, 'packages/live/src/broken.live-mysql.test.ts')); + const empty = mkdtempSync(join(tmpdir(), 'temporal-live-empty-')); + try { + assert(/judge nothing/.test((await judge(empty, ci())).refusal ?? ''), 'an empty population ⇒ REFUSAL, never a clean zero'); + } finally { + rmSync(empty, { recursive: true, force: true }); + } + } finally { + rmSync(fx, { recursive: true, force: true }); + } + + battery('(6) the real tree'); + const realSource = readFileSync(join(REPO_ROOT, CI_WORKFLOW), 'utf8'); + const real = await judge(REPO_ROOT, realSource); + assert(!real.refusal, `the checked-in ${CI_WORKFLOW} is read without refusal${real.refusal ? ` -- ${real.refusal}` : ''}`); + const tests = real.tests ?? []; + assert(tests.filter((t) => LIVE_SUBSTRINGS.some((s) => t.test.includes(s))).length >= 10, 'the population holds the live-postgres / live-mysql files (at least ten)'); + const mount = tests.find((t) => t.test.endsWith('knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts')); + assert(mount?.files.includes('packages/core/src/capability-composition.ts'), 'the closure of capability-mount.live-postgres reaches packages/core/src/capability-composition.ts (the file whose skip turned main red)'); + assert( + coveringRow('packages/core/src/capability-composition.ts', real.rows ?? []) !== null, + 'a change to packages/core/src/capability-composition.ts alone matches a `temporal_live` row', + ); + + battery('(7) WIRING: the gate and its self-test run in CI'); + const manifest = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')); + assert( + manifest.scripts?.['check:temporal-live-filter'] === 'node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs', + 'the root alias runs the self-test, then the gate', + ); + const lint = readFileSync(join(REPO_ROOT, '.github/workflows/lint.yml'), 'utf8'); + assert(/run: pnpm check:temporal-live-filter\s*$/m.test(lint), 'lint.yml runs `pnpm check:temporal-live-filter`'); + assert(/temporal_live/.test(realSource) && /check-temporal-live-filter/.test(realSource), `${CI_WORKFLOW} names this gate beside the list it holds`); + + // ── The floor: every declared battery ran, at or above its count ────── + const declared = Object.keys(SELF_TEST_BATTERIES); + const floor = (message) => { + failed += 1; + console.error(`✗ self-test floor: ${message}`); + }; + if (declared.length < SELF_TEST_BATTERY_FLOOR) floor(`SELF_TEST_BATTERIES declares ${declared.length} batteries, below the pinned ${SELF_TEST_BATTERY_FLOOR}.`); + for (const [name, count] of seen) if (!declared.includes(name)) floor(`battery "${name}" registered ${count} case(s) but is not declared.`); + for (const name of declared) { + const count = seen.get(name) ?? 0; + if (count < SELF_TEST_BATTERIES[name]) { + floor(count === 0 ? `battery "${name}" DID NOT RUN (${SELF_TEST_BATTERIES[name]} pinned).` : `battery "${name}" ran ${count} case(s), below its floor of ${SELF_TEST_BATTERIES[name]}.`); + } + } + if (failed > 0) { + console.error(`\n✗ check-temporal-live-filter self-test: ${failed} failure(s) (cases and floor).`); + process.exitCode = 1; + return; + } + const total = [...seen.values()].reduce((a, b) => a + b, 0); + console.log(`\n✓ check-temporal-live-filter self-test: ${total} case(s) across ${declared.length} batteries hold.`); + selfTestReachedVerdict = true; +} + +// ── Dispatch ──────────────────────────────────────────────────────────────── + +async function main(argv) { + if (argv.includes('--self-test')) { + await selfTest(); + if (process.exitCode) return process.exitCode; + if (!selfTestReachedVerdict) { + console.error('\n✗ check-temporal-live-filter self-test: selfTest() returned without reaching its verdict; exiting 0 would report a self-test that never finished as one that passed.'); + return 1; + } + return 0; + } + let source; + try { + source = readFileSync(join(REPO_ROOT, CI_WORKFLOW), 'utf8'); + } catch (err) { + return report({ refusal: `${CI_WORKFLOW} could not be read: ${err?.message ?? err}` }); + } + const at = argv.indexOf('--match'); + if (at !== -1) return match(source, argv.slice(at + 1)); + const verdict = await judge(REPO_ROOT, source); + return argv.includes('--list') ? list(verdict) : report(verdict); +} + +if (isEntrypoint(import.meta.url)) { + process.exitCode = await main(process.argv.slice(2)); +} From fc5b37fd97f26524d90e15cead09ac28b71c276a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 07:59:01 +0000 Subject: [PATCH 2/4] ci: temporal_live covers every source the live tests load, held by check:temporal-live-filter Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn --- .github/workflows/ci.yml | 131 ++++++++++++----- .github/workflows/lint.yml | 6 + package.json | 1 + scripts/check-temporal-live-filter.mjs | 193 ++++++++++++++++++++----- 4 files changed, 259 insertions(+), 72 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 247a913f3b4..7105c4208e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -837,44 +837,107 @@ jobs: # [#37095] What makes the merge queue run `temporal-conformance` # (ruling record 7146156389): the pgvector store, the driver whose # whole suite that job runs against the live servers, the - # live-server files its filtered steps select (the two - # metadata-protocol globs spell that step's `live-mysql - # live-postgres` substrings), the service-analytics files whose - # live-PostgreSQL cells key on OS_TEST_POSTGRES_URL (#21564; no glob - # selects exactly these, so they are listed: a NEW such file must - # be added here by hand), and this file. + # live-server files its filtered steps select, the service-analytics + # files whose live-PostgreSQL cells key on OS_TEST_POSTGRES_URL + # (#21564), and this file. + # + # [#38528] AND every workspace source those tests LOAD. A live test + # reaches other packages' source through its vitest alias, and their + # `dist/` (built from `src/` by the job's build steps) through the + # package link; a row for the test alone left the source under test + # unscheduled, so a queue entry changing only that source skipped + # this job, landed, and went red first on `main`. + # `pnpm check:temporal-live-filter` (scripts/check-temporal-live-filter.mjs) + # walks each live test's run-time import closure the way vitest + # resolves it and reds on a closure file no row below matches; + # `--list` prints each closure and the row covering each file. A row + # is a package's `src/**` where the closure enters through the + # package's barrel (it then reaches nearly every module, and a + # file-by-file list would red on the next re-export), a narrower + # directory where it reaches one corner of a package, and a literal + # path for a single file. The service-analytics `src/**` row and the + # metadata-protocol `src/**` row replace the per-file and per-glob + # rows those packages carried, which they cover. temporal_live: - 'packages/plugins/knowledge-pgvector/**' - # [#37100] The adapter contract suite the pgvector store runs - # against the live PostgreSQL: a change to it is a change to that - # step's verdict. - - 'packages/services/service-knowledge/src/testing.ts' - 'packages/drivers/driver-sql/**' - - 'packages/metadata-protocol/src/**/*live-mysql*' - - 'packages/metadata-protocol/src/**/*live-postgres*' - 'packages/runtime/src/**/cascade-delete-multivalue-lookup-real-driver*' - - 'packages/services/service-analytics/src/__tests__/analytics-faces-one-lowering.test.ts' - - 'packages/services/service-analytics/src/__tests__/cube-measure-field-type-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/cube-measure-relationship-path-type.test.ts' - - 'packages/services/service-analytics/src/__tests__/dataset-duration-measure.test.ts' - - 'packages/services/service-analytics/src/__tests__/dataset-tools.test.ts' - - 'packages/services/service-analytics/src/__tests__/home-amount-consolidated-measure.test.ts' - - 'packages/services/service-analytics/src/__tests__/json-stored-door-live-drivers.test.ts' - - 'packages/services/service-analytics/src/__tests__/json-stored-door-undeclared-join.test.ts' - - 'packages/services/service-analytics/src/__tests__/list-at-scalar-operator-both-faces.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-aggregate-policies.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-base-column-qualify.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-boolean-comparand-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-empty-sum-order-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-measure-number-presentation.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-number-comparand-door.test.ts' - - 'packages/services/service-analytics/src/__tests__/native-sql-offset-only-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-echo-offset-only-window.test.ts' - - 'packages/services/service-analytics/src/__tests__/objectql-face-order-limit.test.ts' - - 'packages/services/service-analytics/src/__tests__/order-key-selected.test.ts' - - 'packages/services/service-analytics/src/__tests__/read-scope-temporal-coercion.test.ts' + # [#37100] The adapter contract suite the pgvector store runs + # against the live PostgreSQL (`src/testing.ts`), and [#38528] + # the service it is a store of: every knowledge-pgvector live + # file loads `KnowledgeServicePlugin` through the alias. + - 'packages/services/service-knowledge/src/**' + # [#38528] The migration statements the metadata-protocol live + # files execute (they import the migration beside them, and the + # package barrel through objectql), and the manifest + # `discovery-version.ts` imports. + - 'packages/metadata-protocol/src/**' + - 'packages/metadata-protocol/package.json' + # [#21564] The live-PostgreSQL cells of service-analytics, and + # [#38528] the service they test. + - 'packages/services/service-analytics/src/**' + # [#38528] The packages every live test loads through the alias + # or the package link, each reached through its barrel: + # `@objectstack/core` (capability-mount.live-postgres loads + # `capability-composition.ts`; driver-sql's `sql-driver.ts` + # imports the barrel), objectql (the knowledge-pgvector and + # analytics files run ObjectQL over SqlDriver), and what those + # barrels import in turn. + - 'packages/core/src/**' + - 'packages/objectql/src/**' + - 'packages/types/src/**' + - 'packages/formula/src/**' + - 'packages/metadata/src/**' + - 'packages/metadata-core/src/**' + - 'packages/metadata-fs/src/**' + - 'packages/lint/src/**' + - 'packages/sdui-parser/src/**' + - 'packages/observability/src/**' + - 'packages/services/service-settings/src/**' + # [#38528] KnowledgeServicePlugin's default embedder and the + # `@objectstack/platform-objects/system` objects it registers. + - 'packages/plugins/embedder-openai/src/**' + - 'packages/platform-objects/src/system/**' + # [#38528] The analytics bucket-enumeration live file runs the + # wasm SQLite driver beside PostgreSQL. + - 'packages/drivers/driver-sqlite-wasm/src/**' + # [#38528] `@objectstack/spec`, loaded through the alias by its + # barrel: every namespace it re-exports and the root modules. + # Not `src/**`: `src/migrations/` (two thirds of the tree, the + # conversion kits) and `src/studio/` are outside every closure. + - 'packages/spec/src/*.ts' + - 'packages/spec/src/ai/**' + - 'packages/spec/src/api/**' + - 'packages/spec/src/automation/**' + - 'packages/spec/src/contracts/**' + - 'packages/spec/src/conversions/**' + - 'packages/spec/src/data/**' + - 'packages/spec/src/identity/**' + - 'packages/spec/src/integration/**' + - 'packages/spec/src/kernel/**' + - 'packages/spec/src/marketplace/**' + - 'packages/spec/src/meta-spelling/**' + - 'packages/spec/src/qa/**' + - 'packages/spec/src/security/**' + - 'packages/spec/src/shared/**' + - 'packages/spec/src/system/**' + - 'packages/spec/src/ui/**' + # The manifest `metadata-core`'s artifact conversion reads. + - 'packages/spec/package.json' + # [#38528] What the live tests' vitest configs load before any + # test: the configs outside a row above, the preflight runtime's + # config runs, the memory-tmp env helper, and the comment mask + # driver-sql's isolation test imports. + - 'packages/metadata-protocol/vitest.config.ts' + - 'packages/runtime/vitest.config.ts' + - 'packages/services/service-analytics/vitest.config.ts' + - 'packages/qa/vitest-filter-preflight/src/**' + - 'packages/runtime/src/expected-read-refusal-noise.ts' + - 'scripts/vitest-memory-tmp.mjs' + - 'scripts/js-comment-mask.mjs' + - 'scripts/invoked-as.mjs' + # [#38528] The guard that holds this list to the closures. + - 'scripts/check-temporal-live-filter.mjs' - '.github/workflows/ci.yml' # ── WHICH TEST CORE SHARDS START (#26084) ───────────────────────────── diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 7db581b6fd4..41339885cfa 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -3562,6 +3562,12 @@ jobs: continue-on-error: true run: pnpm check:ci-filter-parity + # Rationale: `scripts/check-temporal-live-filter.mjs` header (#38528). + - name: Temporal live filter covers every source a live test loads + id: temporal-live-filter-covers-every-source + continue-on-error: true + run: pnpm check:temporal-live-filter + # The READING half of the gate above (#10046). `--union-into` appends the # cross-package scans to the `turbo ls` document ci.yml is about to shard, # and `scripts/partition-test-shards.mjs` is the only thing that reads it. diff --git a/package.json b/package.json index 63b028a864f..d0fb4461c58 100644 --- a/package.json +++ b/package.json @@ -172,6 +172,7 @@ "check:required-contexts": "node scripts/check-required-contexts.mjs --self-test && node scripts/check-required-contexts.mjs", "check:aggregator-roster": "node scripts/check-aggregator-roster.mjs --self-test && node scripts/check-aggregator-roster.mjs", "check:ci-filter-parity": "node scripts/check-ci-filter-parity.mjs --self-test && node scripts/check-ci-filter-parity.mjs", + "check:temporal-live-filter": "node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs", "check:cross-package-test-inputs": "node scripts/check-cross-package-test-inputs.mjs --self-test && node scripts/check-cross-package-test-inputs.mjs", "check:live-db-isolation": "node scripts/check-live-db-isolation.mjs --self-test && node scripts/check-live-db-isolation.mjs", "check:tier-file-adoption": "node scripts/check-tier-file-adoption.mjs --self-test && node scripts/check-tier-file-adoption.mjs", diff --git a/scripts/check-temporal-live-filter.mjs b/scripts/check-temporal-live-filter.mjs index 1496e8770f7..093cded7d31 100644 --- a/scripts/check-temporal-live-filter.mjs +++ b/scripts/check-temporal-live-filter.mjs @@ -29,12 +29,19 @@ * For every test in the POPULATION, every workspace file in its run-time * import closure is matched by some `temporal_live` row. * - * POPULATION: the test files under `packages/` that a `temporal_live` row - * matches (the list's own statement of which tests this job runs live), plus - * every test file whose path carries `live-postgres` or `live-mysql` -- the - * substrings the job's filtered `vitest run` steps select by -- whether or not - * a row names it yet. A test file is `*.test.*` / `*.spec.*` in a JS or TS - * extension. + * POPULATION, read out of the `temporal-conformance` job rather than kept + * here: every step that hands a test run a live URL (`OS_TEST_POSTGRES_URL` / + * `OS_TEST_MYSQL_URL` in its `env:`) and runs `pnpm --filter ...` either + * as `exec vitest run ...` -- each positional a SUBSTRING of the + * test path, as vitest reads it, so every test it selects is live -- or as a + * whole `test` run, where a test is live only when its own closure reads one + * of those URLs (driver-sql's live matrix cells, service-analytics' live + * PostgreSQL cells; a server-free test in the same suite is judged by Test + * Core on the PR already). Plus every test under `packages/` whose path + * carries `live-postgres` or `live-mysql`, whichever step runs it. A test file + * is `*.test.*` / `*.spec.*` in a JS or TS extension. Measured when this + * landed, the derivation reproduces the 22 service-analytics files the list + * used to name by hand, exactly. * * CLOSURE: the files a test loads when vitest runs it, walked the way vitest * resolves them, transitively from the test itself: @@ -79,7 +86,8 @@ * `filter` job, no `temporal_live` filter, the `temporal-conformance` job gone * or no longer reading `needs.filter.outputs.temporal_live` in its `if:` (a * list nothing reads schedules nothing), a row in syntax the matcher does not - * read, an empty population, a vitest config that does not load or whose + * read, no live step in the job or one whose `run:` this gate cannot read, an + * empty population, a vitest config that does not load or whose * `projects` carry a `resolve` of their own, a relative import that resolves * to no file, and a workspace import whose `dist/` target maps to no source. * @@ -94,6 +102,9 @@ * - It never says a row is too wide. A row covering no closure file is not * reported: that error over-schedules a job, it never skips one. * - Third-party code (the lockfile) is not followed. + * - The vitest config, what it imports, and the `setupFiles` / + * `globalSetup` it names are closure files of every test in the package; + * a file the config only READS (`vitest.repo-tests.json`) is not. */ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; @@ -218,7 +229,59 @@ export function readLiveRows(source) { 'globToRegExp the syntax with a --self-test case.', }; } - return { rows }; + const live = liveStepsOf(job); + if (live.refusal) return { refusal: live.refusal }; + return { rows, steps: live.steps }; +} + +/** The env keys that hand a step a live server. */ +export const LIVE_URL_KEYS = Object.freeze(['OS_TEST_POSTGRES_URL', 'OS_TEST_MYSQL_URL']); +/** A file that reads one of them: the mark of a live cell. */ +const LIVE_URL_READ = /\bOS_TEST_(?:POSTGRES|MYSQL)_URL\b/; +/** `vitest run` options that take a value, so the value is not read as a positional. */ +const VALUE_OPTIONS = new Set(['--project', '--config', '-c', '--root', '-r', '--dir', '--shard', '--reporter', '--maxWorkers', '--pool']); + +/** + * The job's steps that hand a test run a live server, read out of the job: + * each `run:` whose `env:` carries a live URL, parsed for its `pnpm --filter + * ...` and either a whole `test` run or `exec vitest run ...` + * (vitest reads each positional as a SUBSTRING of the test path). Returns + * `{ steps: [{ name, packages, positionals }] }` -- `positionals` null for a + * whole-suite run -- or `{ refusal }`. + */ +export function liveStepsOf(job) { + const out = []; + for (const step of Array.isArray(job?.steps) ? job.steps : []) { + const env = step?.env && typeof step.env === 'object' ? Object.keys(step.env) : []; + if (typeof step?.run !== 'string' || !env.some((k) => LIVE_URL_KEYS.includes(k))) continue; + const text = step.run.replace(/\\\n/g, ' '); + const at = text.search(/(?:^|\s)pnpm\s+(?:\\\s*)?--filter\b/); + if (at === -1) return { refusal: `${CI_WORKFLOW}: the \`${LIVE_JOB}\` step ${JSON.stringify(step.name ?? '')} hands a live URL to no \`pnpm --filter\` run this gate can read.` }; + const tokens = text.slice(at).trim().split(/\s+/).filter((t) => t !== '\\'); + const packages = []; + let i = 1; + while (tokens[i] === '--filter' && tokens[i + 1]) { + packages.push(tokens[i + 1]); + i += 2; + } + let positionals = null; + if (tokens[i] === 'test') positionals = null; + else if (tokens[i] === 'exec' && tokens[i + 1] === 'vitest' && tokens[i + 2] === 'run') { + positionals = []; + for (let j = i + 3; j < tokens.length; j++) { + const t = tokens[j]; + if (/^[;&|]/.test(t)) break; + if (VALUE_OPTIONS.has(t)) j += 1; + else if (!t.startsWith('-')) positionals.push(t); + } + } else { + return { refusal: `${CI_WORKFLOW}: the \`${LIVE_JOB}\` step ${JSON.stringify(step.name ?? '')} runs \`pnpm --filter ... ${tokens[i] ?? ''}\`, neither \`test\` nor \`exec vitest run\`.` }; + } + if (packages.length === 0) return { refusal: `${CI_WORKFLOW}: the \`${LIVE_JOB}\` step ${JSON.stringify(step.name ?? '')} names no package.` }; + out.push({ name: String(step.name ?? ''), packages, positionals }); + } + if (out.length === 0) return { refusal: `${CI_WORKFLOW}'s \`${LIVE_JOB}\` job has no step handing a live URL to a test run: nothing is live to judge.` }; + return { steps: out }; } // ── The workspace ─────────────────────────────────────────────────────────── @@ -273,18 +336,41 @@ function packageDirOf(root, rel) { } /** - * The POPULATION: test files a row matches, plus test files carrying a live - * substring. Each comes back with why it is in. + * The CANDIDATES: per live step, the test files of its packages (filtered by + * its positionals when it has them), plus every test under `packages/` whose + * path carries a live substring. A whole-suite candidate joins the population + * only if its closure reads a live URL (`judge` decides that, once it has the + * closure); a positional-selected one is live because the step selects it. */ -export function populationOf(root, rows) { - const out = []; +export function candidatesOf(root, steps, packages) { + const out = new Map(); + for (const step of steps) { + for (const name of step.packages) { + const pkg = packages.get(name); + if (!pkg) continue; + for (const rel of walkFiles(root, pkg.dir)) { + if (!TEST_FILE.test(rel)) continue; + if (step.positionals && !step.positionals.some((p) => rel.includes(p))) continue; + const mode = step.positionals ? 'selected' : 'suite'; + const prior = out.get(rel); + if (!prior || (prior.mode === 'suite' && mode === 'selected')) out.set(rel, { test: rel, mode, step: step.name }); + } + } + } for (const rel of walkFiles(root, POPULATION_ROOT)) { - if (!TEST_FILE.test(rel)) continue; - const row = coveringRow(rel, rows); - const substring = LIVE_SUBSTRINGS.find((s) => rel.includes(s)) ?? null; - if (row || substring) out.push({ test: rel, row, substring }); + if (!TEST_FILE.test(rel) || out.get(rel)?.mode === 'selected') continue; + const substring = LIVE_SUBSTRINGS.find((sub) => rel.includes(sub)); + if (substring) out.set(rel, { test: rel, mode: 'substring', step: null }); } - return out; + return [...out.values()].sort((a, b) => a.test.localeCompare(b.test)); +} + +/** Does any file of this closure read a live URL? */ +function readsLiveUrl(root, files, cache) { + return files.some((f) => { + if (!cache.has(f)) cache.set(f, MODULE_FILE.test(f) && LIVE_URL_READ.test(readFileSync(join(root, f), 'utf8'))); + return cache.get(f); + }); } // ── Resolution ────────────────────────────────────────────────────────────── @@ -561,16 +647,14 @@ function chainTo(parent, file) { export async function judge(root, source) { const read = readLiveRows(source); if (read.refusal) return { refusal: read.refusal }; - const { rows } = read; - const population = populationOf(root, rows); - if (population.length === 0) { - return { refusal: `no test under ${POPULATION_ROOT}/ is matched by a \`${LIVE_FILTER}\` row or carries ${LIVE_SUBSTRINGS.join(' / ')}: the gate would judge nothing.` }; - } + const { rows, steps } = read; const packages = workspacePackages(root); + const candidates = candidatesOf(root, steps, packages); const aliasCache = new Map(); + const urlCache = new Map(); const tests = []; const uncovered = new Map(); - for (const member of population) { + for (const member of candidates) { const pkgDir = packageDirOf(root, member.test); if (!aliasCache.has(pkgDir)) { const loaded = pkgDir ? await loadAliases(root, pkgDir) : { aliases: [], config: null }; @@ -581,6 +665,10 @@ export async function judge(root, source) { let parent; try { parent = closureOf(root, member.test, loaded.aliases, packages, loaded.edges); + // A whole-suite candidate is live only if the test itself loads a live + // cell; the harness (driver-sql's globalSetup reads the URL for every + // file) does not make a server-free test live. + if (member.mode === 'suite' && !readsLiveUrl(root, [...parent.keys()], urlCache)) continue; // The config and what it imports decide how every specifier resolves, so // they are inputs of the test's verdict too: walked once per package, // WITHOUT the alias table (Vite loads its own config unaliased); the @@ -606,7 +694,10 @@ export async function judge(root, source) { uncovered.get(file).tests.push(member.test); } } - return { rows, tests, uncovered: [...uncovered.values()].sort((a, b) => a.file.localeCompare(b.file)) }; + if (tests.length === 0) { + return { refusal: `the \`${LIVE_JOB}\` job's live steps select no test that loads a live cell, and no test carries ${LIVE_SUBSTRINGS.join(' / ')}: the gate would judge nothing.` }; + } + return { rows, steps, tests, uncovered: [...uncovered.values()].sort((a, b) => a.file.localeCompare(b.file)) }; } // ── Reporting ─────────────────────────────────────────────────────────────── @@ -646,7 +737,7 @@ function list(verdict) { if (verdict.refusal) return report(verdict); const byRow = new Map(); for (const t of verdict.tests) { - console.log(`${t.test} [${t.row ? `row ${t.row}` : `substring ${t.substring}`}; config ${t.config ?? '(none)'}]`); + console.log(`${t.test} [${t.mode}${t.step ? ` by step "${t.step}"` : ''}; config ${t.config ?? '(none)'}]`); const counts = new Map(); for (const f of t.files) { const row = coveringRow(f, verdict.rows) ?? 'UNCOVERED'; @@ -685,10 +776,10 @@ let selfTestReachedVerdict = false; // the declared set, each at or above its count. ⛔ Not one pinned total. const SELF_TEST_BATTERIES = Object.freeze({ '(1) the matcher: literal, `*`, `**`, and the refused syntax': 12, - '(2) reading ci.yml: the rows, and every refusal over a subject not read': 8, + '(2) reading ci.yml: the rows, the live steps, and every refusal over a subject not read': 12, '(3) edges: the parser, not a regex': 8, '(4) resolution: relative, alias, workspace dist -> src, third-party': 9, - '(5) the verdict, end to end over a fixture tree': 9, + '(5) the verdict, end to end over a fixture tree': 10, '(6) the real tree': 4, '(7) WIRING: the gate and its self-test run in CI': 3, }); @@ -729,8 +820,10 @@ async function selfTest() { assert(['a/{b,c}/**', 'a/!(b)/**', 'a/?.ts', 'a/[ab].ts', 'a/@(b)/c', 'a/+(b)'].every((g) => globToRegExp(g) === null), 'every picomatch syntax outside the subset is REFUSED, never guessed'); assert(globToRegExp('') === null && globToRegExp(7) === null, 'an empty or non-string row is refused'); - battery('(2) reading ci.yml: the rows, and every refusal over a subject not read'); - const ci = ({ rows = ["- 'packages/a/**'"], uses = 'dorny/paths-filter@v4', ifLine = "${{ needs.filter.outputs.temporal_live != 'false' }}", job = true, filterName = 'temporal_live' } = {}) => + battery('(2) reading ci.yml: the rows, the live steps, and every refusal over a subject not read'); + const SUITE_STEP = [' - name: suite', ' env:', ' OS_TEST_POSTGRES_URL: postgres://x', ' run: |', ' pnpm \\', ' --filter @objectstack/suite \\', ' test']; + const SELECT_STEP = [' - name: selected', ' env:', ' OS_TEST_MYSQL_URL: mysql://x', ' run: pnpm --filter @objectstack/live exec vitest run --project local live-postgres live-mysql']; + const ci = ({ rows = ["- 'packages/a/**'"], uses = 'dorny/paths-filter@v4', ifLine = "${{ needs.filter.outputs.temporal_live != 'false' }}", job = true, filterName = 'temporal_live', steps = [...SUITE_STEP, ...SELECT_STEP] } = {}) => [ 'jobs:', ' filter:', @@ -740,11 +833,19 @@ async function selfTest() { ' filters: |', ` ${filterName}:`, ...rows.map((r) => ` ${r}`), - ...(job ? [' temporal-conformance:', ` if: ${ifLine}`] : []), + ...(job ? [' temporal-conformance:', ` if: ${ifLine}`, ' steps:', ' - name: no url', ' run: pnpm --filter @objectstack/other test', ...steps] : []), '', ].join('\n'); const okRead = readLiveRows(ci()); assert(!okRead.refusal && okRead.rows.length === 1 && okRead.rows[0].glob === 'packages/a/**', 'a well-formed ci.yml yields its rows'); + assert( + okRead.steps?.length === 2 && okRead.steps[0].packages.join() === '@objectstack/suite' && okRead.steps[0].positionals === null, + 'a step handing a live URL to `pnpm --filter X test` (continued lines) is a whole-suite live step; a step with no URL is not one', + ); + assert( + okRead.steps?.[1]?.packages.join() === '@objectstack/live' && okRead.steps[1].positionals?.join() === 'live-postgres,live-mysql', + '`exec vitest run` positionals are read as the selectors, an option value (`--project local`) is not', + ); assert(/YAML/.test(readLiveRows('jobs: [unclosed').refusal ?? ''), 'unparseable YAML ⇒ REFUSAL'); assert(/paths-filter/.test(readLiveRows(ci({ uses: 'actions/checkout@v7' })).refusal ?? ''), 'no paths-filter step ⇒ REFUSAL'); assert(/temporal_live/.test(readLiveRows(ci({ filterName: 'other' })).refusal ?? ''), 'no `temporal_live` list ⇒ REFUSAL'); @@ -752,6 +853,11 @@ async function selfTest() { assert(/no longer reads/.test(readLiveRows(ci({ ifLine: "${{ needs.filter.outputs.core != 'false' }}" })).refusal ?? ''), 'the job no longer reading the output ⇒ REFUSAL'); assert(/outside the literal/.test(readLiveRows(ci({ rows: ["- 'packages/{a,b}/**'"] })).refusal ?? ''), 'a row in unread syntax ⇒ REFUSAL naming it'); assert(/declares no/.test(readLiveRows(ci({ rows: ['- 7'] })).refusal ?? ''), 'a non-string row ⇒ REFUSAL'); + assert(/nothing is live/.test(readLiveRows(ci({ steps: [] })).refusal ?? ''), 'a job with no step handing a test run a live URL ⇒ REFUSAL'); + assert( + /neither/.test(readLiveRows(ci({ steps: [' - name: odd', ' env:', ' OS_TEST_POSTGRES_URL: x', ' run: pnpm --filter @objectstack/x lint'] })).refusal ?? ''), + 'a live step whose run this gate cannot read ⇒ REFUSAL, never skipped', + ); battery('(3) edges: the parser, not a regex'); const edges = (src, name) => runtimeSpecifiers(src, name); @@ -792,6 +898,7 @@ async function selfTest() { assert(walked.has('packages/lib/src/index.ts') && walked.size === 2, 'a `.js` relative specifier resolves to its `.ts` source; a third-party one ends the walk'); battery('(5) the verdict, end to end over a fixture tree'); + // `live`: selected by the step's positionals; its config aliases `lib` to source. put('packages/live/package.json', JSON.stringify({ name: '@objectstack/live' })); put( 'packages/live/vitest.config.mjs', @@ -800,21 +907,31 @@ async function selfTest() { put('packages/live/src/a.live-postgres.test.ts', "import { lib } from '@objectstack/lib';\nimport { sub } from '@objectstack/lib/sub';\nimport { h } from './helper.js';\n"); put('packages/live/src/helper.ts', 'export const h = 1;\n'); put('packages/live/src/unit.test.ts', "import { h } from './helper.js';\n"); + // `suite`: run whole; only the test whose closure reads a live URL is live. + put('packages/suite/package.json', JSON.stringify({ name: '@objectstack/suite' })); + put('packages/suite/src/kit.ts', "import { sub } from '@objectstack/lib/sub';\nexport const url = process.env.OS_TEST_POSTGRES_URL;\n"); + put('packages/suite/src/cell.test.ts', "import { url } from './kit.js';\n"); + put('packages/suite/src/pure.test.ts', "import { lib } from '@objectstack/lib';\n"); const tree = (rows) => judge(fx, ci({ rows: rows.map((r) => `- '${r}'`) })); - const full = await tree(['packages/live/**', 'packages/lib/src/**']); + const full = await tree(['packages/live/**', 'packages/suite/**', 'packages/lib/src/**']); assert(!full.refusal && full.uncovered.length === 0, 'every closure file on a row ⇒ GREEN'); const aliased = full.tests.find((t) => t.test.endsWith('a.live-postgres.test.ts')); assert(aliased?.files.includes('packages/lib/src/index.ts'), 'the vitest alias is LOADED from the config and followed into the dependency source'); assert(aliased?.files.includes('packages/lib/src/sub/index.ts'), 'an unaliased workspace subpath is followed through `dist/` to its source'); - const gap = await tree(['packages/live/**', 'packages/lib/src/sub/**']); - assert(gap.uncovered.map((u) => u.file).join() === 'packages/lib/src/index.ts', 'the source a live test loads from ANOTHER package, on no row ⇒ RED naming exactly that file'); - assert(gap.uncovered[0]?.chain.join(' -> ') === 'packages/live/src/a.live-postgres.test.ts -> packages/lib/src/index.ts', 'the finding carries the import chain that reaches it'); - const unlisted = await tree(['packages/lib/src/**']); + assert(aliased?.files.includes('packages/live/vitest.config.mjs'), 'the vitest config is part of every closure of its package'); + const names = (full.tests ?? []).map((t) => t.test).sort().join(); assert( - unlisted.uncovered.some((u) => u.file === 'packages/live/src/a.live-postgres.test.ts') && !unlisted.tests.some((t) => t.test.endsWith('unit.test.ts')), - 'a live-substring test on no row is in the population and reds; a unit test on no row is not judged', + names === 'packages/live/src/a.live-postgres.test.ts,packages/suite/src/cell.test.ts', + 'the population: the positional-selected file and the whole-suite file reading a live URL -- not the unselected unit test, not the server-free suite test', ); - assert(full.tests.some((t) => t.test.endsWith('unit.test.ts')), 'a unit test a row matches IS judged (the row says the job runs it)'); + const gap = await tree(['packages/live/**', 'packages/suite/**', 'packages/lib/src/sub/**']); + assert(gap.uncovered.map((u) => u.file).join() === 'packages/lib/src/index.ts', 'the source a live test loads from ANOTHER package, on no row ⇒ RED naming exactly that file'); + assert(gap.uncovered[0]?.chain.join(' -> ') === 'packages/live/src/a.live-postgres.test.ts -> packages/lib/src/index.ts', 'the finding carries the import chain that reaches it'); + put('packages/stray/package.json', JSON.stringify({ name: '@objectstack/stray' })); + put('packages/stray/src/b.live-mysql.test.ts', 'export {};\n'); + const stray = await tree(['packages/live/**', 'packages/suite/**', 'packages/lib/src/**']); + assert(stray.uncovered.map((u) => u.file).join() === 'packages/stray/src/b.live-mysql.test.ts', 'a live-substring test outside every step is still judged, and reds when no row lists it'); + rmSync(join(fx, 'packages/stray'), { recursive: true, force: true }); put('packages/live/src/broken.live-mysql.test.ts', "import './missing.js';\n"); assert(/resolves to no file/.test((await tree(['packages/**'])).refusal ?? ''), 'a relative import resolving to nothing ⇒ REFUSAL, never a short closure'); rmSync(join(fx, 'packages/live/src/broken.live-mysql.test.ts')); From 2092fb3793995fe8f08d0ebc495928042b268c0b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:27:12 +0000 Subject: [PATCH 3/4] ci: run the temporal_live coverage gate in Build Core instead of a lint lane The gate and its self-test run as one Build Core step, and a core row starts Build Core on a change to the gate. The root package.json alias and the lint.yml step are withdrawn. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn --- .github/workflows/ci.yml | 18 +++++++++++++++++- .github/workflows/lint.yml | 6 ------ package.json | 1 - scripts/check-temporal-live-filter.mjs | 24 ++++++++++++++++++------ 4 files changed, 35 insertions(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7105c4208e0..93f7c57423d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -612,6 +612,10 @@ jobs: - 'scripts/ci/assert-turbo-remote-cache.mjs' - 'scripts/ci/prune-turbo-cache.mjs' - 'scripts/population-floor.mjs' + # [#38528] The temporal_live coverage gate Build Core runs before + # the build (its step says why there): a change to the gate runs + # the gate. + - 'scripts/check-temporal-live-filter.mjs' # Test inputs that live OUTSIDE every package (#9829, #10015). Packages # whose suites read across their own boundary declare that radius in # scripts/check-cross-package-test-inputs.mjs, and turbo.json mirrors each @@ -847,7 +851,7 @@ jobs: # package link; a row for the test alone left the source under test # unscheduled, so a queue entry changing only that source skipped # this job, landed, and went red first on `main`. - # `pnpm check:temporal-live-filter` (scripts/check-temporal-live-filter.mjs) + # `node scripts/check-temporal-live-filter.mjs` (`--self-test` beside it) # walks each live test's run-time import closure the way vitest # resolves it and reds on a closure file no row below matches; # `--list` prints each closure and the row covering each file. A row @@ -3482,6 +3486,18 @@ jobs: - name: prune-turbo-cache self-test run: node scripts/ci/prune-turbo-cache.mjs --self-test + # [#38528] The `temporal_live` filter above must hold every workspace + # source the live-server tests of `temporal-conformance` load, or a queue + # entry changing only that source skips the live job and goes red first on + # `main`. This gate walks those tests' import closures and reds on a file + # no row matches (its header is the authority). Here because Build Core + # starts on every diff that can move a closure or the list (`packages/**`, + # this file, the gate itself are `core` rows) and installs the workspace + # the gate reads vitest configs with; it reads no `dist/`, so it runs + # before the build, like the self-tests above. + - name: temporal_live covers every source a live test loads + run: node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs + # ── Turbo remote cache (#21186) ───────────────────────────────────── # Vercel's managed Turborepo remote cache. objectstack-ai/cloud's # test.yml builds this repo at its pinned SHA with the same command and diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 41339885cfa..7db581b6fd4 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -3562,12 +3562,6 @@ jobs: continue-on-error: true run: pnpm check:ci-filter-parity - # Rationale: `scripts/check-temporal-live-filter.mjs` header (#38528). - - name: Temporal live filter covers every source a live test loads - id: temporal-live-filter-covers-every-source - continue-on-error: true - run: pnpm check:temporal-live-filter - # The READING half of the gate above (#10046). `--union-into` appends the # cross-package scans to the `turbo ls` document ci.yml is about to shard, # and `scripts/partition-test-shards.mjs` is the only thing that reads it. diff --git a/package.json b/package.json index d0fb4461c58..63b028a864f 100644 --- a/package.json +++ b/package.json @@ -172,7 +172,6 @@ "check:required-contexts": "node scripts/check-required-contexts.mjs --self-test && node scripts/check-required-contexts.mjs", "check:aggregator-roster": "node scripts/check-aggregator-roster.mjs --self-test && node scripts/check-aggregator-roster.mjs", "check:ci-filter-parity": "node scripts/check-ci-filter-parity.mjs --self-test && node scripts/check-ci-filter-parity.mjs", - "check:temporal-live-filter": "node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs", "check:cross-package-test-inputs": "node scripts/check-cross-package-test-inputs.mjs --self-test && node scripts/check-cross-package-test-inputs.mjs", "check:live-db-isolation": "node scripts/check-live-db-isolation.mjs --self-test && node scripts/check-live-db-isolation.mjs", "check:tier-file-adoption": "node scripts/check-tier-file-adoption.mjs --self-test && node scripts/check-tier-file-adoption.mjs", diff --git a/scripts/check-temporal-live-filter.mjs b/scripts/check-temporal-live-filter.mjs index 093cded7d31..875d5debafe 100644 --- a/scripts/check-temporal-live-filter.mjs +++ b/scripts/check-temporal-live-filter.mjs @@ -11,6 +11,10 @@ * node scripts/check-temporal-live-filter.mjs --match P.. # which `temporal_live` rows match these paths * node scripts/check-temporal-live-filter.mjs --self-test # prove the battery can go red * + * Wired in ci.yml's Build Core (one step, self-test then gate), which starts on + * every diff that can move a closure or the list; the step's comment says why + * there. + * * ## The gap this closes * * `Temporal Conformance (live PG + MySQL)` never runs on `pull_request` (its @@ -959,14 +963,22 @@ async function selfTest() { ); battery('(7) WIRING: the gate and its self-test run in CI'); - const manifest = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')); + const wired = parse(realSource); + const buildSteps = Array.isArray(wired?.jobs?.['build-core']?.steps) ? wired.jobs['build-core'].steps : []; assert( - manifest.scripts?.['check:temporal-live-filter'] === 'node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs', - 'the root alias runs the self-test, then the gate', + buildSteps.some((s) => s?.run === 'node scripts/check-temporal-live-filter.mjs --self-test && node scripts/check-temporal-live-filter.mjs'), + 'Build Core runs the self-test, then the gate, in one step', ); - const lint = readFileSync(join(REPO_ROOT, '.github/workflows/lint.yml'), 'utf8'); - assert(/run: pnpm check:temporal-live-filter\s*$/m.test(lint), 'lint.yml runs `pnpm check:temporal-live-filter`'); - assert(/temporal_live/.test(realSource) && /check-temporal-live-filter/.test(realSource), `${CI_WORKFLOW} names this gate beside the list it holds`); + const coreRows = (() => { + try { + return parse(wired.jobs.filter.steps.find((s) => String(s?.uses ?? '').startsWith('dorny/paths-filter')).with.filters).core ?? []; + } catch { + return []; + } + })(); + assert(coreRows.includes('scripts/check-temporal-live-filter.mjs'), 'a `core` row starts Build Core on a change to the gate itself'); + const listAt = realSource.search(new RegExp(`\\n {12}${LIVE_FILTER}:\\n`)); + assert(listAt > 0 && /check-temporal-live-filter\.mjs/.test(realSource.slice(Math.max(0, listAt - 3000), listAt)), `${CI_WORKFLOW} names this gate in the comment above the list it holds`); // ── The floor: every declared battery ran, at or above its count ────── const declared = Object.keys(SELF_TEST_BATTERIES); From e0de164758e9275e243b56a8495a55b5873c7b9c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:51:55 +0000 Subject: [PATCH 4/4] ci: the temporal_live gate parses through ts-parse, declares its population, and names real packages in its fixtures Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn --- scripts/check-temporal-live-filter.mjs | 35 +++++++++++++++++--------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/scripts/check-temporal-live-filter.mjs b/scripts/check-temporal-live-filter.mjs index 875d5debafe..3d4abc9f484 100644 --- a/scripts/check-temporal-live-filter.mjs +++ b/scripts/check-temporal-live-filter.mjs @@ -118,6 +118,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import ts from 'typescript'; import { parse } from 'yaml'; import { isEntrypoint } from './invoked-as.mjs'; +import { parseSourceFile } from './ts-parse.mjs'; const HERE = resolve(fileURLToPath(import.meta.url), '..'); const REPO_ROOT = resolve(HERE, '..'); @@ -132,6 +133,14 @@ export const LIVE_JOB = 'temporal-conformance'; export const LIVE_SUBSTRINGS = Object.freeze(['live-postgres', 'live-mysql']); /** The tree the population is drawn from. */ const POPULATION_ROOT = 'packages'; +/** + * The population, declared for `scripts/pm/dispatch-gates.mjs` (the + * `ROOT_DIR_WATCH_HINTS` idiom): the gate walks every test, manifest and vitest + * config under `packages/` and follows imports anywhere beneath it, so a change + * anywhere in that subtree can move its verdict. `--self-test` holds it to + * POPULATION_ROOT. + */ +const ROOT_DIR_WATCH_HINTS = ['packages/**']; const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/; const MODULE_FILE = /\.[cm]?[jt]sx?$/; @@ -477,8 +486,9 @@ export function workspaceSource(root, pkg, subpath) { /** The run-time module specifiers one source file names, in source order, deduped. */ export function runtimeSpecifiers(source, fileName = 'x.ts') { - const kind = /\.tsx$/.test(fileName) ? ts.ScriptKind.TSX : /\.[cm]?jsx?$/.test(fileName) ? ts.ScriptKind.JS : ts.ScriptKind.TS; - const sf = ts.createSourceFile(fileName, String(source ?? ''), ts.ScriptTarget.Latest, false, kind); + // Through the one checked parser: a source TypeScript cannot read is a + // loud refusal there, never a recovered tree read here as "no imports". + const sf = parseSourceFile(fileName, String(source ?? '')); const out = []; const add = (node) => { if (node && ts.isStringLiteralLike(node) && !out.includes(node.text)) out.push(node.text); @@ -784,7 +794,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ '(3) edges: the parser, not a regex': 8, '(4) resolution: relative, alias, workspace dist -> src, third-party': 9, '(5) the verdict, end to end over a fixture tree': 10, - '(6) the real tree': 4, + '(6) the real tree': 5, '(7) WIRING: the gate and its self-test run in CI': 3, }); // Deleting a battery deletes its own floor, so the roster's size is pinned too. @@ -825,8 +835,8 @@ async function selfTest() { assert(globToRegExp('') === null && globToRegExp(7) === null, 'an empty or non-string row is refused'); battery('(2) reading ci.yml: the rows, the live steps, and every refusal over a subject not read'); - const SUITE_STEP = [' - name: suite', ' env:', ' OS_TEST_POSTGRES_URL: postgres://x', ' run: |', ' pnpm \\', ' --filter @objectstack/suite \\', ' test']; - const SELECT_STEP = [' - name: selected', ' env:', ' OS_TEST_MYSQL_URL: mysql://x', ' run: pnpm --filter @objectstack/live exec vitest run --project local live-postgres live-mysql']; + const SUITE_STEP = [' - name: suite', ' env:', ' OS_TEST_POSTGRES_URL: postgres://x', ' run: |', ' pnpm \\', ' --filter @objectstack/types \\', ' test']; + const SELECT_STEP = [' - name: selected', ' env:', ' OS_TEST_MYSQL_URL: mysql://x', ' run: pnpm --filter @objectstack/core exec vitest run --project local live-postgres live-mysql']; const ci = ({ rows = ["- 'packages/a/**'"], uses = 'dorny/paths-filter@v4', ifLine = "${{ needs.filter.outputs.temporal_live != 'false' }}", job = true, filterName = 'temporal_live', steps = [...SUITE_STEP, ...SELECT_STEP] } = {}) => [ 'jobs:', @@ -837,17 +847,17 @@ async function selfTest() { ' filters: |', ` ${filterName}:`, ...rows.map((r) => ` ${r}`), - ...(job ? [' temporal-conformance:', ` if: ${ifLine}`, ' steps:', ' - name: no url', ' run: pnpm --filter @objectstack/other test', ...steps] : []), + ...(job ? [' temporal-conformance:', ` if: ${ifLine}`, ' steps:', ' - name: no url', ' run: pnpm --filter @objectstack/formula test', ...steps] : []), '', ].join('\n'); const okRead = readLiveRows(ci()); assert(!okRead.refusal && okRead.rows.length === 1 && okRead.rows[0].glob === 'packages/a/**', 'a well-formed ci.yml yields its rows'); assert( - okRead.steps?.length === 2 && okRead.steps[0].packages.join() === '@objectstack/suite' && okRead.steps[0].positionals === null, - 'a step handing a live URL to `pnpm --filter X test` (continued lines) is a whole-suite live step; a step with no URL is not one', + okRead.steps?.length === 2 && okRead.steps[0].packages.join() === '@objectstack/types' && okRead.steps[0].positionals === null, + 'a step handing a live URL to a whole `test` run of one filtered package (continued lines) is a whole-suite live step; a step with no URL is not one', ); assert( - okRead.steps?.[1]?.packages.join() === '@objectstack/live' && okRead.steps[1].positionals?.join() === 'live-postgres,live-mysql', + okRead.steps?.[1]?.packages.join() === '@objectstack/core' && okRead.steps[1].positionals?.join() === 'live-postgres,live-mysql', '`exec vitest run` positionals are read as the selectors, an option value (`--project local`) is not', ); assert(/YAML/.test(readLiveRows('jobs: [unclosed').refusal ?? ''), 'unparseable YAML ⇒ REFUSAL'); @@ -859,7 +869,7 @@ async function selfTest() { assert(/declares no/.test(readLiveRows(ci({ rows: ['- 7'] })).refusal ?? ''), 'a non-string row ⇒ REFUSAL'); assert(/nothing is live/.test(readLiveRows(ci({ steps: [] })).refusal ?? ''), 'a job with no step handing a test run a live URL ⇒ REFUSAL'); assert( - /neither/.test(readLiveRows(ci({ steps: [' - name: odd', ' env:', ' OS_TEST_POSTGRES_URL: x', ' run: pnpm --filter @objectstack/x lint'] })).refusal ?? ''), + /neither/.test(readLiveRows(ci({ steps: [' - name: odd', ' env:', ' OS_TEST_POSTGRES_URL: x', ' run: pnpm --filter @objectstack/spec lint'] })).refusal ?? ''), 'a live step whose run this gate cannot read ⇒ REFUSAL, never skipped', ); @@ -903,7 +913,7 @@ async function selfTest() { battery('(5) the verdict, end to end over a fixture tree'); // `live`: selected by the step's positionals; its config aliases `lib` to source. - put('packages/live/package.json', JSON.stringify({ name: '@objectstack/live' })); + put('packages/live/package.json', JSON.stringify({ name: '@objectstack/core' })); put( 'packages/live/vitest.config.mjs', "import path from 'node:path';\nexport default { resolve: { alias: [{ find: /^@objectstack\\/lib$/, replacement: path.resolve(import.meta.dirname, '../lib/src/index.ts') }] } };\n", @@ -912,7 +922,7 @@ async function selfTest() { put('packages/live/src/helper.ts', 'export const h = 1;\n'); put('packages/live/src/unit.test.ts', "import { h } from './helper.js';\n"); // `suite`: run whole; only the test whose closure reads a live URL is live. - put('packages/suite/package.json', JSON.stringify({ name: '@objectstack/suite' })); + put('packages/suite/package.json', JSON.stringify({ name: '@objectstack/types' })); put('packages/suite/src/kit.ts', "import { sub } from '@objectstack/lib/sub';\nexport const url = process.env.OS_TEST_POSTGRES_URL;\n"); put('packages/suite/src/cell.test.ts', "import { url } from './kit.js';\n"); put('packages/suite/src/pure.test.ts', "import { lib } from '@objectstack/lib';\n"); @@ -950,6 +960,7 @@ async function selfTest() { } battery('(6) the real tree'); + assert(ROOT_DIR_WATCH_HINTS.length === 1 && ROOT_DIR_WATCH_HINTS[0] === `${POPULATION_ROOT}/**`, 'the dispatch-gates declaration names exactly the subtree the population is walked from'); const realSource = readFileSync(join(REPO_ROOT, CI_WORKFLOW), 'utf8'); const real = await judge(REPO_ROOT, realSource); assert(!real.refusal, `the checked-in ${CI_WORKFLOW} is read without refusal${real.refusal ? ` -- ${real.refusal}` : ''}`);