#!/usr/bin/env bun // Enforce, as a ratchet, that a NUMERIC option defaulted with `??` is checked for finiteness. `??` // guards nullish and `NaN` is not nullish, so the default never fires and the number arrives at // whatever it bounds intact. // // THE DEFECT THIS EXISTS FOR, four outcomes, all measured in this tree in one day: // // a COMPARISON reads false forever `NaN < 1` — `AcceptBudget.tryAccept()` admitted every // accept, herd included; `bytes > NaN` — `SyncSocket.send()` // answered TRUE with 10 MB queued, so a frame the runtime // discarded was reported delivered and never reached // `channel_frames_dropped_total`; `visibleAt <= now` — a job // whose worker DIED was never claimable again. // an ARRAY LENGTH or SLICE collapses `Array.from({ length: NaN })` is `[]`, so `@ultimat3/ai`'s // `hive({ concurrency: NaN })` ran zero workers and reported // clean success; `slice(0, NaN)` is `[]`, so a worker claimed // nothing and reported healthy. // a TIMER reads as ZERO `setTimeout(fn, NaN)` and `setInterval(fn, NaN)` coerce to // 0: a poll becomes a spin, one round trip per event-loop // turn per replica. // a LOOP BOUND never terminates `@ultimat3/ai`'s `chunk({ size: NaN })` — a SYNCHRONOUS // infinite loop, past every `AbortSignal`, past the job // timeout, past the watchdog, on the worker's only thread. // // Which failure you get is decided by what the number lands on. The MISSING CHECK is the same one, // so that is what this rule reads — never the landing site, which no text rule can follow. // // `Math.max(1, x)` / `Math.min(x, y)` / `Math.floor(x)` ARE NOT VALIDATORS and are not accepted as // one. All three PROPAGATE `NaN`, and this repo has now relied on all three as guards: // `AcceptBudget` was `Math.max(1, options.perSecond)`, `presence.ts` was // `Math.max(1, options.maxMembers ?? …)`, `worker.ts` was `Math.max(0, slots - inFlight)`. A `??` // default is not a validator either, for the reason in the first line. // // WHAT COUNTS AS THE REPAIR: a call to one of `SCREENING_CALLEES` // (`scripts/lib/finite-screens.ts`) naming the option or the name it lands in. A DECLARED table — // one row, one sentence — and never the callee's spelling, which is what it replaced on // 2026-08-26: `[\w$]*[Ff]inite[\w$]*` read `InfiniteScroll(` as a repair, read a correct screen // called `toMs` as none, and had already put "the `Finite` in the name is load-bearing" into three // shipped files. In-repo form, eight times over: `packages/jobs/src/limits.ts:122`, // `backfill.ts:158`, `export.ts:142`, `job.ts:201`, `worker-options.ts`, // `scraping/src/scrape.ts:137`, `mail/src/driver-smtp.ts:97`. // // THE DETECTOR IS MATCHED ON SHAPE, NEVER ON NAME. A rule spelled `RenderMode` read straight past // `PwaRenderMode`, and a backoff rule looking for a roll called `random`/`rng`/`roll` read past a // copy whose parameter was `r`. Nothing here asks whether an option is called `timeout`, `limit` or // `size`. The repair is the one half a name cannot answer and a declaration can. // // WHAT IT THEREFORE CANNOT SEE, stated so nobody trusts it for more than it does: // 1. an option with NO `??` default — `AcceptBudget`'s required `perSecond` was exactly this, and // only its `burst` sibling was visible. A required numeric option is invisible to this rule. // 2. a number that arrives as a function PARAMETER rather than a property of an options object. // MEASURED 2026-08-26 and it is REAL: 32 numeric parameter defaults in `packages/*/src`, three // of them on a public secret-generating surface. `randomToken(NaN)` is `""` — the function // whose whole job is an unguessable secret returns the empty string; `nanoid(NaN)` likewise; // `generateRecoveryCodes(NaN)` enrols a user with ZERO recovery codes in a well-formed // `RecoveryCodeSet`. Issue #371, its own slice — a parameter default is not a `??` expression, // so closing it needs a SECOND matcher, and a matcher shipped without a measurement is how the // next blind spot hides. This line named the gap from day one and nobody had measured it, // which is the failure axiom 3 describes. // 3. a repair in a DIFFERENT file. `socket.ts` passing `maxFramesPerSecond` into `AcceptBudget`'s // own assert reads as unchecked here, and the answer is to refuse it where it is written too — // which is the layered form `backfill()` and `inBatches()` already use. // 4. a default that is not a numeric LITERAL and not a `SCREAMING_SNAKE` constant this corpus // declares as one. `?? 0` and `?? 1` are excluded: they are accumulator identities // (`map.get(k) ?? 0`), not configuration, and they were the whole of the noise floor — EXCEPT, // since plan 101 sweep 11, when the left side is read off an options bag (`options.`, `opts.`, // `config.`, `settings.`, at any depth) or the default lands straight on a // bound (`length:`, `new Array(`, `.slice(`, a timer's delay). `Array.from({ length: // options.concurrency ?? 1 })` is the `hive()` defect above, and the exemption hid it. // // WHAT WAS LOOKED FOR AND FOUND CLEAN, 2026-08-26, so the next agent does not re-derive it: // `Number(process.env.…)` — 24 hits, every one a COMMENT or a `fix:` string. This tree never does // it; the idiom is only ever quoted as the thing that produces the `NaN`. // `parseInt` / `parseFloat` — 42 call sites, all guarded. `realtime/src/pg-auth.ts:215` tests // `/^[1-9]\d*$/` BEFORE parsing, `auth/src/password.ts:86` checks `Number.isFinite` on both // parameters, `http/src/config.ts:213` feeds `assertFiniteCount`, and every remaining one reads a // regex capture group that is already `\d+`. // a DESTRUCTURED numeric default (`const { limit = 10 } = opts`) — zero in shipped source. // // bun run finite-bounds · bun run scripts/finite-bounds.ts [--json] [--explain] // bun run scripts/finite-bounds.ts --unpin [,] # shrink the ratchet import { renderFixShellArg } from '../packages/core/src/error-render'; import { maskLiterals } from '../packages/core/src/source-mask'; import type { SourceFile } from './boundaries'; import { balancedClose } from './lib/balanced-paren'; import { corpus } from './lib/corpus'; import { FINITE_BOUNDS_PINS, FINITE_BOUNDS_PINS_FILE } from './lib/finite-bounds-pins'; import { FINITE_SCREENS_FILE, SCREENING_CALL } from './lib/finite-screens'; import type { Finding } from './lib/log'; import type { PinTable, RatchetGap } from './lib/ratchet'; import { packageOf, ratchetGaps, ratchetMain } from './lib/ratchet'; import { leadSite, siteList, siteTarget } from './lib/ratchet-sites'; import { isTestPath, lineOf } from './lib/source-scan'; const SCRIPT = 'finite-bounds'; const EXPLAIN = 'bun run scripts/finite-bounds.ts --explain --json lists every one'; /** Source the CLI EMITS rather than executes, and generated fixtures. Neither is shipped logic. */ const TEMPLATE_ROOT = 'packages/cli/src/templates/'; const isFixture = (path: string): boolean => /-fixture\.tsx?$/.test(path); /** * `const DEFAULT_X = 1024;` — a `SCREAMING_SNAKE` constant this corpus declares as a NUMBER. * * Why the corpus and not the line: a default is routinely imported (`DEFAULT_VISIBILITY_TIMEOUT_MS` * lives in `driver.ts` and is read in `worker-options.ts`). Why numeric at all: the same spelling * carries strings and objects — `?? DEFAULT_QUEUE`, `?? NO_TENANT`, `?? DEFAULT_RETRY`, * `?? CLOUDFLARE_API_URL`, `?? NEVER_ABORTED` — and reporting those is the noise that gets a rule * switched off. A name declared numeric in one place and non-numeric in another is NOT numeric. */ const CONST_DECL = /(?:const|let)\s+([A-Z][A-Z0-9_]{2,})\s*(?::[^=]*)?=\s*([^;\n]+)/g; const TABLE_DECL = /(?:const|let)\s+([A-Z][A-Z0-9_]{2,})\s*(?::[^=]*)?=\s*\{/g; /** `key: ` up to the next `,` or `}` — the entry shape a table of numbers is made of. */ const TABLE_VALUE = /(?:[A-Za-z_$][\w$]*|'[^']*'|"[^"]*"|\[[^\]]*\])\s*:\s*([^,}\n]+)/g; const NUMERIC_LITERAL = /^-?\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?$/i; /** * Arithmetic over numeric literals and nothing else — `1024 * 1024`, `60 * 60 * 1000`. No letters, * so an identifier can never satisfy it. Without this, `DEFAULT_MAX_BUFFERED_BYTES = 1024 * 1024` * read as non-numeric and the four `change-buffer.ts` byte ceilings were invisible. */ const NUMERIC_EXPRESSION = /^[\d_.\s*+\-/()]+$/; const isNumericValue = (value: string): boolean => NUMERIC_LITERAL.test(value) || (/\d/.test(value) && NUMERIC_EXPRESSION.test(value)); export function numericConstants(files: readonly SourceFile[]): ReadonlySet { const numeric = new Set(); const other = new Set(); for (const file of files) { for (const match of CONST_DECL.exec.length > 0 ? file.source.matchAll(CONST_DECL) : []) { const name = match[1] as string; const value = (match[2] as string).trim(); if (isNumericValue(value)) numeric.add(name); else other.add(name); } } for (const name of other) numeric.delete(name); return numeric; } /** * A SCREAMING const bound to an object literal whose every value is a number — the table half of * `numericConstants`. `DEFAULT_VERIFICATION_TTL_MS[input.purpose]` is a default, and its NAME alone * cannot say so: the declaration spans lines, so `CONST_DECL`'s single-line value capture reads `{` * and files it under "not numeric", which is how a table-keyed default reads as noise and is * dropped. Kept SEPARATE from the scalar set deliberately — folding table names in would make a * bare `?? DEFAULT_OPTS` read as a numeric bound when it is an object default, which is the kind of * false report that gets a rule switched off. */ export function numericTables(files: readonly SourceFile[]): ReadonlySet { const tables = new Set(); const rejected = new Set(); for (const file of files) { for (const match of file.source.matchAll(TABLE_DECL)) { const name = match[1] as string; const open = (match.index as number) + (match[0] as string).length - 1; const body = file.source.slice(open + 1, closingBrace(file.source, open)); const values = [...body.matchAll(TABLE_VALUE)].map((entry) => (entry[1] as string).trim()); if (values.length > 0 && values.every(isNumericValue)) tables.add(name); else rejected.add(name); } } for (const name of rejected) tables.delete(name); return tables; } /** * `options.maxBytes ?? 1024` — a property read, nullish-coalesced to a number. * * The left side is a dotted path, optionally chained (`options?.ttlMs`), and it may NOT be reached * through a call or an index. That is what keeps `map.get(k) ?? 0`, `buffer[0] ?? 0`, * `rows[0]?.pending ?? 0` and `queue?.pending().length ?? 0` out — every one of which is an * accumulator or an element read, not configuration. The `.` in the LOOKBEHIND is what does that * work, and it does all of it: an identifier following a `]` is reached through `.` or `?.` either * way, so the dot is always the character immediately before it. A `\]` was added beside the dot * on 2026-08-26 to make the element case explicit and MEASURED INERT the same day — same 59 sites * with it and without — so it is not here. A clause that decides nothing reads as a rule holding a * line it is not holding. * * The right side may be an indexed default (`?? DEFAULT_TTL_MS[input.purpose]`), because a table of * defaults keyed by a variant is still a default. * * BOTH WIDENINGS WERE ADDED AFTER THEY LET A DEFECT THROUGH, 2026-08-26. `oauth-cookie.ts`'s * handshake `ttlMs` is `options?.ttlMs ?? C` and `verify.ts`'s is `?? DEFAULT_VERIFICATION_TTL_MS * [input.purpose]`; a NaN in the first accepts a year-old sealed OAuth handshake, and in the second * writes a verification row whose Invalid-Date expiry `consumeVerification` reads as never expired. * Both sat behind a green ratchet and a `packages/auth/CLAUDE.md` sentence claiming every runtime * number in that package was screened. */ const DEFAULTED = /(? path .split(/\??\./) .slice(0, -1) .some((segment) => OPTIONS_SEGMENT.test(segment.replace(/^#/, ''))) || BOUND_BEFORE.test(before); /** `DEFAULT_TTL_MS[input.purpose]` — a table read, whose TABLE name is what settles it. */ const INDEXED_FALLBACK = /^([A-Za-z_$][\w$]*)\[/; /** The `}` closing the `{` at `open`, or the end of the source. */ const closingBrace = (code: string, open: number): number => { let depth = 0; for (let index = open; index < code.length; index += 1) { const char = code[index] as string; if (char === '{') depth += 1; else if (char === '}') { depth -= 1; if (depth === 0) return index; } } return code.length; }; export interface FiniteBoundSite { readonly path: string; readonly line: number; /** The option's own property name — `maxBytes` in `options.maxBytes ?? 1024`. */ readonly option: string; /** The whole `a.b ?? DEFAULT` expression, so a finding can quote it back. */ readonly expression: string; } /** `this.#maxBytes =` / `const size =` / `let n =` on the text before the match, or nothing. */ const ASSIGNED = /(?:(?:const|let|var)\s+|this\.#?|#)([A-Za-z_$][\w$]*)\s*(?::[^=]*)?=\s*$/; /** * Every finiteness check in a file, as the text between its parentheses. * * The SPAN and not the line, because Biome wraps a call past 100 columns and the callee then sits * on a different line from its arguments — the first draft compared line by line and read nine of * its own repairs as unrepaired. Balanced parens, so a nested `toMs(...)` stays inside the span. * * WHICH callees count is `SCREENING_CALLEES`, a declared table, and never their spelling: the name * pattern this replaced read `InfiniteScroll(` as a repair and a correct screen called `toMs` as * none. That file carries the measurement. */ const repairSpans = (source: string, screens: RegExp): readonly string[] => { const spans: string[] = []; for (const match of source.matchAll(screens)) { const open = match.index + match[0].length - 1; const close = balancedClose(source, open); spans.push(source.slice(open, close === -1 ? source.length : close + 1)); } return spans; }; /** * Whether some check in this file NAMES one of these subjects. * * Whole file, because the assert is routinely a few lines from the read and sometimes above it — * but it must name the subject, so repairing one of `change-buffer.ts`'s four bounds does not * silence the other three. Naming is not the DETECTOR, which is shape only; it is how the rule * tells which repair belongs to which site. */ const repaired = (spans: readonly string[], subjects: readonly string[]): boolean => spans.some((span) => subjects.some((subject) => new RegExp(`(?, tables: ReadonlySet = new Set(), screens: RegExp = SCREENING_CALL, code: string = maskLiterals(source), ): readonly FiniteBoundSite[] { const spans = repairSpans(source, screens); const sites: FiniteBoundSite[] = []; for (const match of code.matchAll(DEFAULTED)) { const fallback = (match[2] as string).trim(); const lineStart = code.lastIndexOf('\n', match.index) + 1; const before = code.slice(lineStart, match.index); // Accumulator identities, not configuration — and the whole of the noise floor — unless the // read is an option or the answer is a bound. const identity = fallback === '0' || fallback === '1'; if (identity && !identityIsConfiguration(match[1] as string, before)) continue; const indexed = INDEXED_FALLBACK.exec(fallback); const isDefault = indexed === null ? NUMERIC_LITERAL.test(fallback) || numeric.has(fallback) : tables.has(indexed[1] as string); if (!isDefault) continue; const path0 = match[1] as string; const option = path0.slice(path0.lastIndexOf('.') + 1); const assigned = ASSIGNED.exec(before); const subjects = assigned === null ? [option] : [option, assigned[1] as string]; if (repaired(spans, subjects)) continue; sites.push({ path, line: lineOf(code, match.index), option, expression: match[0].trim(), }); } return sites; } const scannable = (file: SourceFile): boolean => !isTestPath(file.path) && !isFixture(file.path) && !file.path.startsWith(TEMPLATE_ROOT); export type FiniteBoundGap = RatchetGap; export interface FiniteBoundsInput { readonly files: readonly SourceFile[]; readonly pins: PinTable; } /** Every site per package, in source order — the one scan `--explain`, the ratchet and `--unpin` share. */ export function finiteBoundSites( files: readonly SourceFile[], ): ReadonlyMap { const numeric = numericConstants(files); const tables = numericTables(files); const found = new Map(); for (const file of files) { if (!scannable(file)) continue; // The corpus's cached mask when the reader holds one: masking is most of a scan's cost. const sites = scanFiniteBounds( file.path, file.source, numeric, tables, SCREENING_CALL, file.masked, ); for (const site of sites) { const list = found.get(packageOf(site.path)) ?? []; list.push(site); found.set(packageOf(site.path), list); } } return found; } const flat = (files: readonly SourceFile[]): readonly FiniteBoundSite[] => [ ...[...finiteBoundSites(files).values()].flat(), ]; /** The ratchet: a package may hold what it is pinned at, may fall, may never rise. */ export const checkFiniteBounds = (input: FiniteBoundsInput): readonly FiniteBoundGap[] => ratchetGaps(flat(input.files), input.pins, input.files.length > 0); const at = (site: FiniteBoundSite | undefined): string => site === undefined ? '' : `${site.path}:${String(site.line)}`; /** * Every site, never only the first: the package's first is usually one its pin already allows. * Which are NEW is not asked here — a site depends on numeric constants and tables read across the * whole corpus, so one file at the base ref cannot be re-scanned alone. */ const overFinding = (gap: FiniteBoundGap): Finding => ({ code: 'X_FINITE_BOUND_UNCHECKED', cause: `${gap.pkg} defaults ${String(gap.found)} numeric option(s) with ?? and never checks them for finiteness, and is pinned at ${String(gap.pinned)} — ${siteList(gap, (site) => `${at(site)} (${site.expression})`, EXPLAIN)} — and ?? guards nullish while NaN is not nullish, so Number(process.env.X) on an unset variable reaches the bound intact`, fix: `assert(Number.isFinite(${gap.found === 1 ? (leadSite(gap)?.option ?? 'value') : 'value'}), '…', '…') beside ${siteTarget(gap, at)} — as packages/jobs/src/limits.ts:122 does — or Number.isSafeInteger where it counts rows. Math.max/Math.min/Math.floor are NOT the fix: all three propagate NaN. If a helper already screens it, add that callee to SCREENING_CALLEES in ${FINITE_SCREENS_FILE} instead — the table is what this rule reads, never the callee's name`, at: at(leadSite(gap)), }); const staleFinding = (gap: FiniteBoundGap): Finding => ({ code: 'X_FINITE_BOUND_PIN_STALE', cause: `${gap.pkg} is pinned at ${String(gap.pinned)} unchecked numeric option(s) and has ${String(gap.found)} — the pin is above what this tree contains, so it would let ${String(gap.pinned - gap.found)} back in`, fix: `bun run scripts/finite-bounds.ts --unpin ${renderFixShellArg(gap.pkg, '')}`, at: FINITE_BOUNDS_PINS_FILE, }); const unscannedFinding = (): Finding => ({ code: 'X_FINITE_BOUND_UNSCANNED', cause: 'no source file was read, so every package reports zero and the ratchet enforces nothing — a glob that matches nothing reads exactly like a tree where every bound is checked', fix: "grep -n 'CORPUS_PATTERNS' scripts/lib/corpus.ts # edit it so it matches this repo layout, then: bun run scripts/finite-bounds.ts", at: 'scripts/lib/corpus.ts', }); /** A blank reason is not a pin: its sites are unchecked AND unexcused, so they report as such. */ const unexplainedFinding = (gap: FiniteBoundGap): Finding => ({ code: 'X_FINITE_BOUND_UNCHECKED', cause: `${gap.pkg} is pinned with a blank reason, so its ${String(gap.found)} unchecked numeric option(s) are held by nothing — a count with no sentence is the waiver axiom 3 refuses`, fix: `grep -n ${renderFixShellArg(gap.pkg, '')} ${FINITE_BOUNDS_PINS_FILE} # write in that row what each remaining option in ${gap.pkg} is and why it is not screened`, at: FINITE_BOUNDS_PINS_FILE, }); export const finiteBoundFindingFor = (gap: FiniteBoundGap): Finding => gap.kind === 'over' ? overFinding(gap) : gap.kind === 'stale' ? staleFinding(gap) : gap.kind === 'unexplained' ? unexplainedFinding(gap) : unscannedFinding(); const treeSites = async (root: string): Promise => flat(await corpus(root, 'source')); export const finiteBoundGaps = async (root: string): Promise => ratchetGaps(await treeSites(root), FINITE_BOUNDS_PINS, true); /** What this rule contributes to `x verify`'s `unit` step, through `finite-bounds.test.ts`. */ export const finiteBoundFindings = async (root: string): Promise => (await finiteBoundGaps(root)).map(finiteBoundFindingFor); if (import.meta.main) { await ratchetMain({ script: SCRIPT, pinsFile: FINITE_BOUNDS_PINS_FILE, pins: FINITE_BOUNDS_PINS, sites: treeSites, findingFor: finiteBoundFindingFor, clean: 'every numeric option defaulted with ?? across packages/*/src is at or under its pin', }); }