* fix(#2931): preserve protected regions and cap emitted per-runtime bytes Route every runtime brand swap through applyClaudeCodeBrandSwap so "Claude Code" survives verbatim inside <runtime_compatibility> regions (#2284b). The fix existed only in bin/install.js's local copies; the src/*.cts exports still used a naive replace, so binding install.js to the single source -- as this phase does for the Windsurf family -- would have silently regressed those runtimes. A table-driven parity guard now covers all nine brand-swapping converters. De-duplicate the Windsurf converter family: delete the six local copies in bin/install.js and bind the four exported ones by reference, guarded by reference-identity assertions (the ADR-1508/#1675 pattern). The two unexported helpers and an unused tool table go with them. Replace the Windsurf 12,000-byte throw with description truncation, matching the bound its sibling skill converter already applied. The throw could only fire on an ~11.7 KB frontmatter description: the largest emitted workflow is 311 bytes. Truncation makes the cap unreachable by construction and leaves 12,000 in exactly one place, eliminating the dual-surface duplication rather than testing for it. Add the emitted-byte cap gate: buildEmittedSizes captures LF- and <HOME>-normalized bytes from the walk buildParityManifest already performs, and evaluateEmittedCaps asserts them against a per-runtime cap table with dead-rule detection. buildParityManifest's return shape is deliberately unchanged -- diffEmitted compares its values with ===, so making them objects would report all 8,529 emitted paths as moved. A regression test pins the values as strings. Add a deterministic trim-safety gate over composeWithinBudget's omitted/shrunk/floored/isolatePrefix metadata, with an anti-vacuity rule, replacing the model-graded eval gate the issue described. * docs(#2931): correct ADR-1671 windsurf premise and trim-safety contract * fix(#2931): bound the windsurf command name and single-source the brand swap Review findings from the orthogonal passes, all fixed inline. The claim that removing the 12,000-byte throw left total emission "bounded by construction" was false. The #1615 regex constrains the character class but not the length, and commandName is interpolated three times into the emitted workflow: a 20,000-character name emitted 60,162 bytes silently. Add WINDSURF_COMMAND_NAME_MAX=128 as a separate, clearly-labelled size control that THROWS -- commandName is the @-ref path target, so truncating it would point the workflow at a file that does not exist (DEFECT.WORKFLOW-DELEGATION-TARGET-NOT-INSTALLED). The #1615 security regex is untouched and still runs first. 128 is generous: the longest shipped name is gsd-plan-review-convergence at 27. Harmonize convertClaudeCommandToWindsurfSkill onto the code-point-safe truncation helper. It still used a UTF-16 slice(0,177) -- the exact surrogate-splitting bug the helper was written to avoid, in the very sibling the helper's comment cites as its model. Bounds are unchanged, so output is byte-identical for every shipped command (descriptions max out at 99 chars). Export applyClaudeCodeBrandSwap and bind it in bin/install.js, deleting the local copy. Adding it to the .cts left two unlinked implementations of identical logic -- the drift class this change exists to remove. Verified byte-identical across eight fixtures and five sequential calls before merging, and guarded by a reference-identity assertion. Convert three try/finally test bodies to t.after (CONTRIBUTING.md:344), add fast-check property coverage for the trim-safety contract, and use fc.pre instead of a bare return in a property callback. * test(#2931): fix three test-authoring bugs the remote matrix caught The remote runner returned 8 unique failures on 6f15cdeb8. All three causes were in the test files, not the modules under test -- local harnesses exercise the modules directly, so nothing executed the test bodies until the matrix did. `{ __proto__: [...] }` in an object literal sets the prototype instead of an own key, so the JSON round-trip erased it and the cap table never saw a reserved runtime key. The production rejection was already correct; the test could not reach it. Use a computed key. Two cap fixtures tripped orthogonal error paths rather than the paths they name: one declared windsurf in the cap table but omitted it from sizes (UNKNOWN_RUNTIME), the other left the sole windsurf pattern matching nothing (a genuine dead rule). Both now include a compliant artifact so the intended branch is what is asserted. The dead-rule and unknown-runtime contracts are deliberate and unchanged. `const { root } = makeSyntheticConfig({ ... `${root}` })` referenced `root` from inside its own initializer -- a temporal dead zone error. makeSyntheticConfig now optionally takes a (root) => files factory. Also raise the npm pack --dry-run bound 60s -> 120s in the shipped- scripts packaging test. That failure is NOT from this branch: the file is byte-identical to next, a fresh tsc measures 1.98s there vs 2.14s here, and the run recorded 60,637ms against a 60,000ms bound -- a timeout under 28,948-test parallel contention, not a slowdown. Fixed rather than deferred because a bound that tight is fragile regardless of which branch trips it. * chore(#2931): backfill changeset pr number to 2984 --------- Co-authored-by: sim <sim@local>
190 lines
7.8 KiB
JavaScript
190 lines
7.8 KiB
JavaScript
// allow-test-rule: integration-test-input (see #2858)
|
|
// #2858 — class-extinction guard: every shipped scripts/**/*.cjs must be
|
|
// require-able using only shipped paths. A script that ships in the npm tarball
|
|
// but requires a module from tests/ (which does not ship) is MODULE_NOT_FOUND
|
|
// at load time in a published install.
|
|
//
|
|
// This test statically checks each shipped .cjs's require() calls against the
|
|
// resolved tarball file list (npm pack --dry-run --json), so adding a new entry
|
|
// to `files` cannot silently opt out. It does NOT execute the scripts — it parses
|
|
// their require() calls and resolves them against the shipped set.
|
|
|
|
'use strict';
|
|
|
|
process.env.GSD_TEST_MODE = '1';
|
|
|
|
const { describe, test, before } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { execFileSync } = require('node:child_process');
|
|
|
|
const REPO_ROOT = path.join(__dirname, '..');
|
|
|
|
/**
|
|
* Resolve the tarball file list via `npm pack --dry-run --json`.
|
|
* This is the ACTUAL set of files that ship — not a hardcoded list — so adding
|
|
* a new entry to package.json `files` cannot silently bypass the guard.
|
|
*/
|
|
function resolveTarballFiles() {
|
|
const raw = execFileSync('npm', ['pack', '--dry-run', '--json'], {
|
|
cwd: REPO_ROOT,
|
|
encoding: 'utf-8',
|
|
shell: true, // Windows: npm is npm.cmd and needs a shell
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
// package.json's `prepack`/`prepare` runs a full `npm run build:lib`
|
|
// (tsc) before `npm pack` computes the file list — a bounded but
|
|
// non-trivial subprocess (~2s in isolation). Under the full parallel
|
|
// 28,000+-test CI matrix this has been observed to take 60.6s and trip
|
|
// a 60_000ms bound (#2931 gsd-test run d52d2ee4, linux-node24,
|
|
// duration_ms 60637.56), aborting this file's `before()` hook and
|
|
// cascading every sibling test to "cancelled". 120s keeps the bound
|
|
// finite (never unbounded, per the subprocess-timeout convention) while
|
|
// giving real headroom for a contended CI box.
|
|
timeout: 120_000,
|
|
});
|
|
const parsed = JSON.parse(raw);
|
|
return new Set(parsed[0].files.map((f) => f.path.replace(/\\/g, '/')));
|
|
}
|
|
|
|
/**
|
|
* Extract all require('...') string-literal calls from a .cjs source.
|
|
* Only static string-literal requires are checked — dynamic require(variable)
|
|
* is out of scope (and would itself be a red flag in a shipped script).
|
|
*/
|
|
function extractRequires(source) {
|
|
const requires = [];
|
|
// Strip block comments (/* ... */) and inline line comments (// ...) before
|
|
// matching, so a require() appearing in a doc comment or fenced code block
|
|
// inside a /* */ does not produce a false positive.
|
|
const stripped = source
|
|
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
.replace(/\/\/.*$/gm, '');
|
|
const requireRe = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
let m;
|
|
while ((m = requireRe.exec(stripped)) !== null) {
|
|
requires.push(m[1]);
|
|
}
|
|
return requires;
|
|
}
|
|
|
|
/**
|
|
* Classify a require specifier from a given file path:
|
|
* - 'builtin' — node: prefix or a Node builtin (fs, path, etc.)
|
|
* - 'shipped' — resolves to a file within the shipped tarball set
|
|
* - 'external' — an npm dependency (resolvable from node_modules)
|
|
* - 'unshipped' — resolves to a repo path that is NOT in the shipped set (VIOLATION)
|
|
*/
|
|
function classifyRequire(spec, fromFile, shippedFiles) {
|
|
// Node builtins (including node: prefix)
|
|
if (spec.startsWith('node:')) return 'builtin';
|
|
const BUILTINS = ['fs', 'path', 'os', 'child_process', 'crypto', 'util', 'url', 'events', 'stream', 'http', 'https', 'net', 'tls', 'zlib', 'querystring', 'string_decoder', 'timers', 'vm', 'worker_threads', 'buffer', 'process'];
|
|
const bare = spec.split('/')[0];
|
|
if (BUILTINS.includes(bare)) return 'builtin';
|
|
|
|
// Relative/absolute requires — resolve against the file's directory
|
|
if (spec.startsWith('.') || spec.startsWith('/')) {
|
|
const fromDir = path.dirname(fromFile);
|
|
const resolved = path.posix.normalize(path.posix.join(fromDir, spec));
|
|
// Try exact, .cjs, .js, .json, /index.cjs, /index.js
|
|
const candidates = [
|
|
resolved,
|
|
resolved + '.cjs',
|
|
resolved + '.js',
|
|
resolved + '.json',
|
|
resolved + '/index.cjs',
|
|
resolved + '/index.js',
|
|
];
|
|
for (const c of candidates) {
|
|
const normalized = c.replace(/\\/g, '/');
|
|
if (shippedFiles.has(normalized)) return 'shipped';
|
|
}
|
|
// If it resolves to a real file on disk but is NOT shipped → violation
|
|
const absResolved = path.resolve(REPO_ROOT, resolved);
|
|
const absCandidates = [
|
|
absResolved,
|
|
absResolved + '.cjs',
|
|
absResolved + '.js',
|
|
absResolved + '.json',
|
|
path.join(absResolved, 'index.cjs'),
|
|
path.join(absResolved, 'index.js'),
|
|
];
|
|
for (const c of absCandidates) {
|
|
if (fs.existsSync(c)) return 'unshipped';
|
|
}
|
|
// Doesn't resolve to anything — likely a typo or generated artifact; flag it
|
|
return 'unshipped';
|
|
}
|
|
|
|
// Bare specifier (not relative, not builtin) → npm dependency
|
|
return 'external';
|
|
}
|
|
|
|
describe('#2858 — shipped scripts require only shipped paths', () => {
|
|
let shippedFiles;
|
|
let shippedScripts;
|
|
|
|
before(() => {
|
|
shippedFiles = resolveTarballFiles();
|
|
// Filter to scripts/**/*.{cjs,js} (the shipped script surface — both .cjs
|
|
// and .js files ship under scripts/, e.g. build-hooks.js is required by
|
|
// bin/install.js). Both extensions are checked so a broken require() in a
|
|
// .js file is caught just the same as one in a .cjs file.
|
|
shippedScripts = [...shippedFiles]
|
|
.filter((f) => f.startsWith('scripts/') && /\.(cjs|js)$/.test(f))
|
|
.sort();
|
|
});
|
|
|
|
test('every shipped scripts/*.{cjs,js} is require-able from a shipped-only tree', () => {
|
|
assert.ok(shippedScripts.length > 0, 'expected at least one shipped script');
|
|
|
|
const violations = [];
|
|
for (const scriptRel of shippedScripts) {
|
|
const absPath = path.join(REPO_ROOT, scriptRel);
|
|
if (!fs.existsSync(absPath)) continue; // generated artifact, skip
|
|
const source = fs.readFileSync(absPath, 'utf-8');
|
|
const requires = extractRequires(source);
|
|
|
|
for (const spec of requires) {
|
|
const classification = classifyRequire(spec, scriptRel, shippedFiles);
|
|
if (classification === 'unshipped') {
|
|
violations.push({
|
|
script: scriptRel,
|
|
require: spec,
|
|
classification,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (violations.length > 0) {
|
|
const details = violations
|
|
.map((v) => ` ${v.script}: require('${v.require}') → ${v.classification}`)
|
|
.join('\n');
|
|
assert.fail(
|
|
`${violations.length} shipped script(s) require modules outside the shipped tree (MODULE_NOT_FOUND in a published install):\n${details}`,
|
|
);
|
|
}
|
|
});
|
|
|
|
test('gen-emitted-baseline.cjs does NOT ship (repo-only CI tooling)', () => {
|
|
// This script requires ../tests/helpers/* which does not ship. It is
|
|
// repo-only CI tooling (CI workflows + test fixtures spawn it from a
|
|
// checkout). It must be excluded from the npm tarball.
|
|
assert.ok(
|
|
!shippedFiles.has('scripts/gen-emitted-baseline.cjs'),
|
|
'scripts/gen-emitted-baseline.cjs must NOT ship — it requires tests/ which does not ship (#2858)',
|
|
);
|
|
});
|
|
|
|
test('a script requiring a sibling in the same shipped dir resolves as shipped (positive case)', () => {
|
|
// Sanity: scripts/lib/cli-exit.cjs ships and is required by shipped scripts.
|
|
// This confirms the guard's positive path works — a valid intra-shipped require
|
|
// is NOT flagged.
|
|
assert.ok(shippedFiles.has('scripts/lib/cli-exit.cjs'), 'scripts/lib/cli-exit.cjs should ship');
|
|
const classification = classifyRequire('./lib/cli-exit.cjs', 'scripts/gen-adr-index.cjs', shippedFiles);
|
|
assert.strictEqual(classification, 'shipped',
|
|
`a sibling require within scripts/ must classify as 'shipped'; got '${classification}'`);
|
|
});
|
|
});
|