chore(#597): replace count-based ratchet guards with AST lint + named-set allowlists (#603)

The windows-test-parity ratchet greps test source for fs.rmSync-without-
maxRetries (and six other Windows-portability anti-patterns), failing when an
integer offender COUNT exceeds a frozen baseline (rmSync: 95). A count ratchet
is a Goodhart metric: fixing one offender and adding another keeps the count
constant, so a new defect slips through green. Replace it — and every other
count ratchet in the repo — with a layered, masking-proof design.

Behavioral seam test
- tests/helpers-cleanup.test.cjs proves helpers.cleanup() carries the Windows
  EBUSY retry budget. cleanup() delegates retries to Node's fs.rmSync via
  maxRetries (it owns no loop), so the test asserts the option contract
  (recursive/force/maxRetries>0/retryDelay>0) + real-FS removal + the cwd-guard,
  rather than a loop that does not exist. The EBUSY risk is now tested ONCE at
  the helper, not approximated textually at every call site.

Write-time ESLint rule (AST-accurate, replaces the grep)
- eslint-rules/no-raw-rmsync-in-tests.cjs (error in tests/**/*.test.cjs) bans
  raw fs.rmSync, steering to cleanup(). Catches member, computed (fs['rmSync']),
  destructured and aliased forms; escape hatch is inline
  `// eslint-disable-next-line local/no-raw-rmsync-in-tests -- <reason>` only.
- Migrated 336 raw fs.rmSync teardown calls across ~116 test files to cleanup().
  ~18 genuinely load-bearing sites (mid-test SUT/fault-injection removals,
  error-swallowing or name-colliding local teardown helpers) keep the raw call
  with an inline eslint-disable + reason.

Shared anti-ratchet primitive
- scripts/lib/allowlist-ratchet.cjs:
  - assertWithinAllowlist: fails on NOVEL ids (new offender introduced) AND on
    STALE ids (a known offender was fixed but not pruned) — identity, not count,
    and a ratchet DOWN toward zero.
  - assertTightCeiling: a size/length budget whose ceiling must stay within a
    grace band of the high-water mark, so budgets may only tighten, never creep.

Ratchets converted onto the primitive
- windows-test-parity-guard.test.cjs: rmSync rule deleted (now ESLint-enforced);
  the remaining six patterns moved from integer baselines to named-set
  allowlists with ratchet-down.
- scripts/lint-test-file-count.{cjs,allowlist.json}: per-module integer counts →
  named filename sets (closes the swap-a-file-keep-the-count blind spot); a
  module dropping under cap now FAILS to force pruning its allowlist entry.
- enh-2790 skill-count `<= 63` → named skill allowlist (ratchets toward ~58).

Size budgets hardened (tighten-only)
- agent-size / workflow-size / feat-3039 help-tiered: ceilings lowered to the
  current high-water mark and an assertTightCeiling anti-creep check added per
  tier. Fixed external-contract limits (description ≤100 chars, agent ≤100 KB)
  are intentionally left as-is — they are not grandfathered creeping budgets.

No user-facing behavior change (tests + tooling only); no USER_FACING_PREFIXES
touched, so no changeset fragment is required.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-06-01 22:43:49 -04:00
committed by GitHub
parent a594f5175c
commit a28dcec981
130 changed files with 2030 additions and 586 deletions

View File

@@ -3,47 +3,80 @@
process.env.GSD_TEST_MODE = '1';
/**
* Ratchet-style lint guard against Windows-test-parity regressions.
* Named-set allowlist guard against Windows-test-parity regressions.
*
* PR #3649 cleared ~270 Windows-only test failures from the chunking fix
* in #3597 surfaced. Each cluster reduced to a handful of repeating
* patterns. This guard prevents the patterns from being re-introduced.
*
* Strategy: per-pattern offender list is snapshotted at the count present
* at the time of PR #3649. The test fails if a NEW file is added that
* matches the anti-pattern (count grows above the baseline). Existing
* offenders are acknowledged as technical debt that can be cleared
* incrementally without blocking this PR.
* Strategy (updated from integer-count ratchet): each rule's known offenders
* are enumerated by filename in a frozen KNOWN_OFFENDERS set. The guard uses
* the shared assertWithinAllowlist primitive (scripts/lib/allowlist-ratchet.cjs)
* which enforces BOTH directions:
* - Novel offenders (current \ known) → fail immediately.
* - Stale allowlist entries (known \ current) → also fail, forcing the
* allowlist to shrink as defects are fixed (ratchet-DOWN enforcement).
*
* When you fix an existing offender, lower the corresponding BASELINE
* count by 1. When CI breaks because BASELINE is set higher than the
* actual offender count, lower BASELINE to match (one-way ratchet down).
* When you fix an existing offender, you MUST remove its entry from
* KNOWN_OFFENDERS — the guard will fail on stale entries to enforce progress.
* When CI breaks because a new file introduced an anti-pattern, fix the
* anti-pattern — do not just add the filename to the set to silence the guard.
*
* rmSync teardown safety is now enforced at write-time by the ESLint rule
* local/no-raw-rmsync-in-tests (see issue #597); it is no longer ratcheted here.
*
* Scope: tests/ only. Production-code Windows-compat is enforced via
* behavioural tests (see no-unconditional-win32-skip.test.cjs).
*/
// allow-test-rule: structural-regression-guard
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { assertWithinAllowlist } = require('../scripts/lib/allowlist-ratchet.cjs');
const TESTS_DIR = path.join(__dirname);
const SELF = path.basename(__filename);
// ── Baseline counts after PR #3649 batch ─────────────────────────────────
// Set these to the exact number of offending files at the time of merge.
// Each rule must not exceed its baseline; CI fails when a new offender appears.
// Decrement when an existing offender is fixed.
const BASELINE = {
splitNewlineOnFileContent: 3,
fenceRegexLiteralNewline: 2,
frontmatterAnchorLiteralNewline: 5,
hardcodedTmpToFsCall: 0,
bareNpmExecWithoutShell: 0,
stubsHomeNoUserProfile: 8,
rmSyncNoMaxRetries: 95,
};
// ── Known offenders after PR #3649 batch (named-set allowlist) ───────────
// These are the files that matched each anti-pattern at the time of writing.
// A test fails when a file NOT in the set starts matching (novel regression),
// OR when a file in the set stops matching (stale entry — must be pruned).
// Edit this object to update the allowlists:
// edit KNOWN_OFFENDERS in tests/windows-test-parity-guard.test.cjs
const KNOWN_OFFENDERS = Object.freeze({
splitNewlineOnFileContent: new Set([
'release-coverage-scope.test.cjs',
'secret-scan-lint.test.cjs',
'security-scan.test.cjs',
]),
fenceRegexLiteralNewline: new Set([
'bug-2995-post-install-script-paths.test.cjs',
'security-scan.test.cjs',
]),
frontmatterAnchorLiteralNewline: new Set([
'bug-1967-cache-invalidation.test.cjs',
'bug-2643-skill-frontmatter-name.test.cjs',
'bug-2808-skill-hyphen-name.test.cjs',
'bug-3168-task-to-agent-rename.test.cjs',
'qwen-skills-migration.test.cjs',
]),
hardcodedTmpToFsCall: new Set([
// (none at time of writing)
]),
bareNpmExecWithoutShell: new Set([
// (none at time of writing)
]),
stubsHomeNoUserProfile: new Set([
'bug-130-finishinstall-opencode-testmode.test.cjs',
'bug-2794-opencode-model-profile-overrides.test.cjs',
'claude-md.test.cjs',
'feat-443-effort-install-wiring.install.test.cjs',
'issue-2517-runtime-aware-profiles.test.cjs',
]),
});
function listTestFiles() {
return fs.readdirSync(TESTS_DIR)
@@ -77,107 +110,94 @@ function countMatchingFiles(predicate) {
return { count, offenders };
}
function ratchetAssert(rule, actualCount, baselineCount, offenders, guidance) {
if (actualCount > baselineCount) {
const newCount = actualCount - baselineCount;
assert.fail(
`Windows-parity guard "${rule}": ${actualCount} offenders, baseline is ${baselineCount} ` +
`(+${newCount} new). New occurrences of this anti-pattern were added. ` +
`${guidance}\n\nFull offender list (${actualCount}):\n ` +
offenders.join('\n '),
);
}
}
const PRUNE_HINT = 'edit KNOWN_OFFENDERS in tests/windows-test-parity-guard.test.cjs';
describe('Windows test-parity lint guards (ratchet baseline: PR #3649)', () => {
describe('Windows test-parity lint guards (named-set allowlist: PR #3649)', () => {
// ── G1 — CRLF: file-content split on literal '\n' ─────────────────────
test('split-on-newline after readFileSync (use /\\r?\\n/)', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
return /\.readFileSync\s*\([^)]*\)[^;]*\.split\(\s*['"]\\n['"]\s*\)/.test(text);
});
ratchetAssert(
'splitNewlineOnFileContent', count, BASELINE.splitNewlineOnFileContent, offenders,
"Replace .split('\\n') with .split(/\\r?\\n/) so the test tolerates CRLF " +
"checkout (autocrlf=true on Windows leaves trailing \\r on every line).",
);
assertWithinAllowlist({
label: 'splitNewlineOnFileContent',
current: offenders,
known: KNOWN_OFFENDERS.splitNewlineOnFileContent,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
});
// ── G2 — CRLF: ```bash|sh\n fence regex on file content ──────────────
test('markdown-fence regex with literal \\n after ```bash/sh', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
return /\/[^/]*```(?:bash|sh)\\n[^/]*\//.test(text);
});
ratchetAssert(
'fenceRegexLiteralNewline', count, BASELINE.fenceRegexLiteralNewline, offenders,
"Use /```(?:bash|sh)\\r?\\n([\\s\\S]*?)```/g — Windows CRLF makes the byte after " +
"`bash` be \\r, the regex never matches, and bash-block extraction returns empty.",
);
assertWithinAllowlist({
label: 'fenceRegexLiteralNewline',
current: offenders,
known: KNOWN_OFFENDERS.fenceRegexLiteralNewline,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
});
// ── G3 — CRLF: frontmatter regex with literal '\n' ────────────────────
test('frontmatter regex anchors on /^---\\n/', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
return /\/\^---\\n/.test(text);
});
ratchetAssert(
'frontmatterAnchorLiteralNewline', count, BASELINE.frontmatterAnchorLiteralNewline, offenders,
"Use /^---\\r?\\n/ — on Windows the byte after --- is \\r, not \\n, so the " +
"anchor fails to match and parseFrontmatter returns null/{}.",
);
assertWithinAllowlist({
label: 'frontmatterAnchorLiteralNewline',
current: offenders,
known: KNOWN_OFFENDERS.frontmatterAnchorLiteralNewline,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
});
// ── G4 — POSIX-tmp: hardcoded '/tmp/' literal passed to fs.* ─────────
test('fs.* call receives a hardcoded "/tmp/..." literal', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
return /\bfs\.[A-Za-z]+\s*\([^)]*['"]\/tmp\/[^'"]+['"][^)]*\)/.test(text);
});
ratchetAssert(
'hardcodedTmpToFsCall', count, BASELINE.hardcodedTmpToFsCall, offenders,
"Use os.tmpdir() — on Windows '/tmp/foo' becomes 'D:\\tmp\\foo' where D:\\tmp " +
"doesn't exist by default → ENOENT.",
);
assertWithinAllowlist({
label: 'hardcodedTmpToFsCall',
current: offenders,
known: KNOWN_OFFENDERS.hardcodedTmpToFsCall,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
});
// ── G5 — npm.cmd: bare 'npm' to exec*Sync without shell:true ─────────
test('bare npm exec without shell-true Windows fallback', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
const re = /\b(?:execFileSync|spawnSync)\s*\(\s*['"]npm['"]\s*,[^)]*\)/g;
const matches = text.match(re) || [];
return matches.some((m) =>
!/shell\s*:\s*true/.test(m) && !/shell\s*:\s*isWindows/.test(m),
);
});
ratchetAssert(
'bareNpmExecWithoutShell', count, BASELINE.bareNpmExecWithoutShell, offenders,
"On Windows npm is npm.cmd — pass {shell: process.platform === 'win32'} or " +
"use npm.cmd directly, otherwise execFileSync errors ENOENT.",
);
assertWithinAllowlist({
label: 'bareNpmExecWithoutShell',
current: offenders,
known: KNOWN_OFFENDERS.bareNpmExecWithoutShell,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
});
// ── G6 — Test stubs HOME without USERPROFILE ─────────────────────────
test('test stubs process.env.HOME but never references USERPROFILE', () => {
const { count, offenders } = countMatchingFiles((text) => {
const { offenders } = countMatchingFiles((text) => {
return /process\.env\.HOME\s*=\s*/.test(text) && !/USERPROFILE/.test(text);
});
ratchetAssert(
'stubsHomeNoUserProfile', count, BASELINE.stubsHomeNoUserProfile, offenders,
"On Windows os.homedir() reads USERPROFILE (not HOME). Tests redirecting ~ " +
"must override both, or the SUT sees the real user's home.",
);
});
// ── G7 — rmSync cleanup without retry budget ─────────────────────────
test('test teardown rmSync without maxRetries', () => {
const { count, offenders } = countMatchingFiles((text) => {
const re = /fs\.rmSync\s*\([^)]*recursive\s*:\s*true[^)]*force\s*:\s*true[^)]*\)/g;
const matches = text.match(re) || [];
return matches.some((m) => !/maxRetries/.test(m));
assertWithinAllowlist({
label: 'stubsHomeNoUserProfile',
current: offenders,
known: KNOWN_OFFENDERS.stubsHomeNoUserProfile,
fail: assert.fail,
pruneHint: PRUNE_HINT,
});
ratchetAssert(
'rmSyncNoMaxRetries', count, BASELINE.rmSyncNoMaxRetries, offenders,
"Use helpers.cleanup() (shared 5s retry budget) or pass " +
"{maxRetries: 10, retryDelay: 100} — Windows AV scanners can hold handles for " +
"seconds after a process exits, surfacing as flaky EBUSY teardown failures.",
);
});
});