Files
clean-architecture-frontend…/scripts/lib/removal-fixture.ts
DongHyeonka ede99cb9b9 fix(test-run): FE-GATE-009와 test:e2e:dev가 e2e 결과를 덮지 않는다
문제: `test:a11y`(FE-GATE-009)가 `playwright.config.ts`를 그대로 써서
e2e의 결과 폴더·HTML report·`results.xml`에 쓴다. merge browser job은
한 checkout에서 FE-GATE-008 다음 FE-GATE-009를 돌고 `artifacts/`를
올리므로, 올린 e2e 증거는 a11y 실행의 것이다. FE-GATE-009에는 자기
JUnit·report 증거가 없다. 게이트 밖 `test:e2e:dev`도 e2e 설정을 펼쳐
같은 경로에 쓰므로, 로컬 실행이 FE-GATE-008 결과를 지운다
(Playwright는 시작할 때 결과 폴더를 비운다).

고른 방법:
- `playwright.a11y.config.ts`가 e2e 설정을 펼치고 결과 경로만
  `artifacts/tests/a11y/`로 바꾼다. `forbidOnly: true`는 글자로 둔다
  (`check-test-evidence.ts`가 등록 설정마다 그 글자를 찾는다).
  `test:a11y`는 `--config playwright.a11y.config.ts --grep @a11y`.
- `playwright.dev.config.ts`도 결과 경로를 `artifacts/tests/e2e-dev/`로
  둔다.
- `config/ci/gates.json`: a11y `results.xml`·`report/index.html`
  증거(producer `test-a11y`)를 더하고 FE-GATE-009 증거에 넣는다.
- 새 시험 `tests/unit/playwright-result-paths.test.ts`: package script가
  부르는 Playwright 설정을 run ID 없이 불러 결과 경로를 모은다.
  (1) 서로 다른 설정 둘이 같은 경로(또는 한쪽 안의 경로)에 쓰면 실패,
  (2) 게이트 명령 둘이 같은 경로에 쓰면 실패, (3) 게이트 명령이 쓰는
  JUnit·report가 그 게이트의 증거이고 producer가 그 명령이 아니면 실패.
- FE-6 시험의 Playwright 쪽(`test:e2e`·`test:a11y`의 `playwright test`
  두 줄과 「같은 설정이라 project가 같다」)을
  `ci-workflow-generation.test.ts`에서 새 시험으로 옮긴다. 글자로 보던
  것을, 같은 포트로 두 설정을 불러 결과 경로 밖 설정 전체가 같은지 보는
  단언으로 바꾼다. gate 계약 쪽(008·009의 commandIds, merge browser
  job)은 그 자리에 둔다.
- 제거 fixture 사본(FE-GATE-013·020)은 `artifacts/`에서 재생성 트리만
  빼고 복사한다. 결과 경로를 옮기면 a11y·dev 결과와 report(실패하면
  trace까지)가 사본에 들어가므로, `scripts/lib/removal-fixture.ts`의
  목록에 `artifacts/tests/a11y`·`artifacts/tests/e2e-dev`를 더한다.
  새 시험 (4): 각 Playwright 설정의 results·report 폴더가 그 목록 안에
  있다. `a11y.json`·`a11y-data-state/`는 계속 복사되는지 fixture 시험이
  본다.
- `playwright.a11y.config.ts`가 `testDir: "./tests/e2e"`를 글자로 둔다.
  FE-GATE-029는 게이트 명령이 부르는 설정 파일 본문에서 `testDir:`를
  찾으므로, 펼치기만 하면 `test:a11y`가 게이트하는 폴더가 0개다.
  새 시험(`ungated-tests.test.ts`): 게이트 명령이 닿는
  `playwright test`마다 testDir을 찾는다.
- decisions.md FE-6 행은 옮긴 단언의 자리
  `tests/unit/playwright-result-paths.test.ts`를 백틱으로 적는다.
  샘플 제거 드릴(FE-GATE-020)은 사본에서 `ci-workflow-generation.test.ts`를
  지우고, 사본의 `verify:documentation`은 살아 있는 문서의 백틱 경로를
  대조한다. 그 시험 경로를 백틱으로 적은 첫 판은 020에서 실패했다.
  버린 안: 경로를 백틱 없이 적기. `.claude/rules/docs.md`가 「검사를
  피하려고 백틱을 빼지 않는다」고 정한다(1105/14-03). 드릴 쪽(문서
  검사에 예외 경로 넘기기, 그 시험을 지우지 않기)은 b6bfc9b7에서 버린
  안이라 손대지 않는다. 다른 살아 있는 문서에는 드릴이 지우는 네
  파일을 백틱으로 적은 곳이 없다(`git grep`).
- 시험 helper(설정 찾기·경로 겹침)에 거절 입력 시험을 둔다.
- 버린 안: `test:a11y`에 `--output`·`--reporter` 인자를 붙이기. 결과
  경로가 설정과 script 두 곳에 나뉘고, run ID 격리(`testRunPath`)를
  다시 만들어야 한다.
- 막지 않은 것: `test:visual:update`는 `test:visual`과 같은 설정이라 같은
  경로에 쓴다. 같은 시험을 골든 갱신으로 도는 것이라 그 결과가 visual
  결과다. 시험 (1)은 설정 단위라 이것을 막지 않는다.

위험·한계: FE-GATE-009의 증거가 둘 늘어 그 게이트가 JUnit·report 없이
끝나면 실패한다. 하류 프로젝트가 `test:a11y`를 고쳐 `--config` 없이 쓰면
새 시험이 실패한다(CHANGELOG 「먼저 할 일」). 결과 경로를 script 인자로
바꾸는 설정(`--output` 등)은 새 시험이 읽지 않는다. FE-GATE-029
파서는 `--grep-invert @a11y`를 읽지 않아 `@a11y` 시험을 008이 도는
것으로 센다(FE-6부터 있던 것, 이 커밋 밖).

검증(desktop `scripts/verify.sh exec`):
- RED(트리 1e2c4a8f, 고치기 전): 새 시험 3개 모두 실패. dev 설정이 e2e
  경로 셋, test-e2e·test-a11y가 같은 경로 셋, test-a11y의 JUnit·report가
  FE-GATE-009 증거가 아니고 producer가 test-e2e.
- GREEN: 새 시험, playwright-run-isolation, ci-workflow-generation,
  repository-layout, test-evidence-repository-configs 503개 통과.
- 변이: a11y 결과 경로를 e2e로 → 새 시험 3개와 a11y 결과 폴더 시험
  실패. dev 설정의 결과 경로 빼기 → 새 시험 (1)과 dev 결과 폴더 시험
  실패. a11y 설정에 `workers: 1` → FE-6 시험 실패.
- `check:types`·바꾼 파일 eslint·`check:ci` rc=0.
- 리뷰 반영 RED(트리 a36e8676, 시험만 더함): 새 시험 (4)가 a11y·dev의
  results·report 4개로, testDir 시험이 `test:a11y` 한 줄로 실패.
  거절 입력 시험 둘과 fixture 형제 경로 단언은 통과.
- 리뷰 반영 GREEN(트리 155a93de): 위 시험과 removal-fixture,
  ungated-tests, documentation-readiness 7파일 549개 통과,
  `check:types`·바꾼 파일 eslint rc=0.
- FE-GATE-020: 첫 판(트리 ac0ea6d7)의 desktop merge에서 rc=1
  (「decisions.md names paths that do not exist」).
- FE-6 단언 옮김 RED(트리 eed3c87f): a11y 설정에 `retries: 7` 변이 →
  옮긴 단언이 새 시험에서 실패(1 failed, 6 passed). 옛 자리에 그 단언이
  없다(`ci-workflow-generation.test.ts`에서 `loadConfigFile`·
  `withoutResultPaths`·`playwrightRuns` grep 0건).
- GREEN(트리 d2d941c3): 새 시험, ci-workflow-generation, ungated-tests,
  removal-fixture 4파일 485개 통과, `check:types`·바꾼 파일 eslint rc=0.

Refs: 1106 리뷰 11 영역 3.2 (3) 증거 읽기 주의
2026-11-20 22:20:28 +09:00

570 lines
22 KiB
TypeScript

import { spawnSync } from "node:child_process";
import {
cp,
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rm,
stat,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import {
loadCiGateContract,
parseCiGateContract,
} from "../contracts/ci-gates.ts";
import {
FIXTURE_PNPM_ENVIRONMENT,
linkFixtureNodeModules,
} from "./fixture-node-modules.ts";
import { generateCiWorkflow } from "../generate-ci-workflow.ts";
import {
REPOSITORY_LAYOUT,
REPOSITORY_LAYOUT_FILE,
selectRepositoryPaths,
} from "./repository-layout.ts";
/**
* The fixture-copy set of config/repository-layout.json (R2). It includes the
* install and workspace identity (`.npmrc`, `pnpm-lock.yaml`,
* `pnpm-workspace.yaml`): without them the fixture is not the same project,
* `corepack pnpm` resolves a different store, and the provider suites — which
* build a release candidate containing `pnpm-lock.yaml` — cannot assemble
* their fixture at all. It also carries the manual a11y review records
* (docs/accessibility/route-reviews), which unit tests read, without the rest
* of `docs/`.
*/
export const REMOVAL_FIXTURE_COPY_TARGETS = selectRepositoryPaths("fixture-copy");
/**
* This is the only copy-target list. Each removal script used to keep its own,
* and they drifted: the reference sample's fixture omitted
* `playwright.capabilities.config.ts`, which the repository file inventory
* requires, so supply-chain generation failed inside the fixture and took every
* provider suite down with it — twenty-odd failures with one cause.
*/
/**
* The repository's documents. A drill that adds or removes a feature copies
* them as well (REMOVAL_FIXTURE_COPY_TARGETS plus these), because the change
* must leave the documents valid (1103/14-04). The capability drills do not:
* the documents describe the capability they delete, and what those drills
* prove is that the code still builds and tests without it.
*/
export const REMOVAL_FIXTURE_DOCUMENT_TARGETS = selectRepositoryPaths("fixture-documents");
/**
* 1103/02-06. Tests that read REMOVAL_FIXTURE_DOCUMENT_TARGETS. A fixture
* copied without the documents cannot run them: every capability drill
* (FE-GATE-020) failed its `test` check on ENOENT for README.md and
* CHANGELOG.md, whatever the removal did. prepareRemovalFixture deletes them
* from such a fixture, and the repository's own test:unit keeps running them.
* This is the only list; the sample drill used to keep the exclusion to itself.
*
* 1106/12-01. The unit is a file, so every test in a listed file reads the
* documents. A test that reads none goes in another file: listing a file for
* one document test took the file's other tests out of those drills too.
*/
export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([
"tests/unit/changelog-review-ids.test.ts",
"tests/unit/documentation-readiness.test.ts",
// 1105/03-01. Reads the 6.1 table of the frontend contract document; the
// pin checks that read none are in backend-contract-pin.test.ts.
"tests/unit/backend-contract-pin-document.test.ts",
// 1105/16-01. Reads the 03 manual and docs/architecture/starter-experience.md;
// the generator's list is checked in feature-tracked-file-rewrites.test.ts.
"tests/unit/feature-tracked-files.test.ts",
// 1105/14-01
"tests/unit/template-feature-removal-documents.test.ts",
// 1105/14-02. Reads a code block of docs/manual.
"tests/unit/manual-paired-backend-settings.test.ts",
// Reads the marked code blocks of docs/manual.
"tests/unit/manual-code-blocks.test.ts",
// Reads the README deletable-files table and the docs/README.md index.
"tests/unit/template-contract-documents.test.ts",
] as const);
/** The tests a fixture copied from `copyTargets` cannot run. */
export function removalFixtureExcludedTests(
copyTargets: readonly string[],
): readonly string[] {
return REMOVAL_FIXTURE_DOCUMENT_TARGETS.every((target) => copyTargets.includes(target))
? []
: REMOVAL_FIXTURE_DOCUMENT_TESTS;
}
/**
* Regenerated result trees under `artifacts/`: traces, coverage HTML, recorded
* videos and Storybook bundles. They are tens of megabytes and mean nothing to
* a fixture. Everything else under `artifacts/` is release evidence a candidate
* is assembled from — and most of it is git-ignored too, so "is it tracked?"
* cannot be used to tell the two apart. `keepsReleaseEvidence` in
* tests/unit/removal-fixture.test.ts pins both halves of this split.
*/
// Each Playwright config's results and report folder is in one of these
// (tests/unit/playwright-result-paths.test.ts).
const REGENERATED_ARTIFACT_TREES: readonly string[] = Object.freeze([
"artifacts/storybook",
"artifacts/tests/a11y",
"artifacts/tests/browser-capabilities",
"artifacts/tests/coverage",
"artifacts/tests/e2e",
"artifacts/tests/e2e-dev",
"artifacts/tests/storybook",
"artifacts/tests/visual",
]);
/**
* Copies the release evidence a candidate build needs into a fixture root.
*
* A fixture that omits it cannot assemble a candidate archive at all, so every
* provider suite fails while constructing its own fixture — long before it
* reaches an assertion, and with an error that says nothing about the
* capability under test.
*/
export async function copyReleaseEvidenceTree(
sourceRoot: string,
destinationRoot: string,
): Promise<void> {
const source = path.join(sourceRoot, "artifacts");
try {
await stat(source);
} catch {
return;
}
await cp(source, path.join(destinationRoot, "artifacts"), {
recursive: true,
filter: (candidate) => {
const relative = path.relative(sourceRoot, candidate).split(path.sep).join("/");
return !REGENERATED_ARTIFACT_TREES.some(
(tree) => relative === tree || relative.startsWith(`${tree}/`),
);
},
});
// The result directories still have to exist: several are tracked through a
// `.gitkeep` the repository inventory expects to find.
for (const tree of REGENERATED_ARTIFACT_TREES) {
await mkdir(path.join(destinationRoot, tree), { recursive: true });
}
}
export const RELEASE_EVIDENCE_REGENERATED_TREES = REGENERATED_ARTIFACT_TREES;
export function requireRemovalFixtureEnvironment(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`${name} is required for removal verification`);
return value;
}
/**
* fe-ci-next (3a). The copy targets `sourceRoot` has. A target of an optional
* registry entry (a drill or a product copy may lack it) is left out when
* absent. Any other absent target ends the preparation before the fixture is
* touched, with the registry entry and field that select it: cp used to end
* on its own ENOENT, `recipes` included, and say nothing of the registry.
*/
async function presentCopyTargets(
sourceRoot: string,
copyTargets: readonly string[],
): Promise<string[]> {
const present: string[] = [];
const lacking: string[] = [];
for (const target of copyTargets) {
try {
await lstat(path.join(sourceRoot, target));
present.push(target);
continue;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
// Every root item has one entry, and a path a set selects inside one is
// under it in the entry's setPaths (repository-layout.ts), so the first
// segment names the entry.
const entry = REPOSITORY_LAYOUT.find(({ path: item }) => item === target.split("/")[0]);
const inSetPaths =
entry !== undefined && Object.values(entry.setPaths).some((paths) => paths?.includes(target));
if (entry === undefined || (entry.path !== target && !inSetPaths)) {
lacking.push(
`${target}: the fixture copy names it, but no ${REPOSITORY_LAYOUT_FILE} entry selects it and this checkout has no such path`,
);
} else if (!entry.optional) {
lacking.push(
entry.path === target
? `${target}: ${REPOSITORY_LAYOUT_FILE} entry ${target} is not optional, but this checkout has no such path; restore it or remove the entry`
: `${target}: ${REPOSITORY_LAYOUT_FILE} entry ${entry.path} selects it in setPaths and is not optional, but this checkout has no such path; restore it or remove it from that entry's setPaths`,
);
}
}
if (lacking.length > 0) {
throw new Error(`removal fixture: this checkout lacks what the fixture copies\n${lacking.join("\n")}`);
}
return present;
}
export async function prepareRemovalFixture(
root: string,
copyTargets: readonly string[] = REMOVAL_FIXTURE_COPY_TARGETS,
): Promise<void> {
const present = await presentCopyTargets(process.cwd(), copyTargets);
await rm(root, { recursive: true, force: true });
await mkdir(root, { recursive: true });
for (const target of present) {
await cp(target, path.join(root, target), { recursive: true });
}
for (const test of removalFixtureExcludedTests(present)) {
await rm(path.join(root, test), { force: true });
}
await copyReleaseEvidenceTree(process.cwd(), root);
runFixtureGit(root, ["init", "--quiet", "--initial-branch=fixture"]);
await linkFixtureNodeModules(root);
}
/**
* Records the fixture's post-removal contents as its repository state.
*
* The release candidate path asks `git ls-files` what the repository contains —
* the supply-chain inventory is defined as the tracked file set, not as
* whatever happens to be on disk. A fixture without a repository cannot answer
* that, so supply-chain generation failed and took every provider suite down
* with it; the claim "this build still produces a release candidate after the
* capability is removed" was never actually being tested.
*
* It runs after the removal, not during preparation: an index recorded before
* the deletions still lists the removed files, and the inventory then demands
* files the fixture exists to prove are gone.
*/
export function sealRemovalFixtureRepository(root: string): void {
// `.gitignore` travels with the fixture, so the tracked set it records is the
// same tracked set the real repository has. Without it every generated
// artifact and every linked module landed in the index, and the supply-chain
// inventory refused the fixture for having tracked and generated paths
// collide — the fixture disagreed with the repository it was copied from.
runFixtureGit(root, ["add", "--all"]);
runFixtureGit(root, ["commit", "--quiet", "--no-gpg-sign", "-m", "removal fixture"]);
}
function runFixtureGit(root: string, argv: readonly string[]): void {
const result = spawnSync("git", [...argv], {
cwd: root,
encoding: "utf8",
env: {
...process.env,
GIT_AUTHOR_NAME: "removal-fixture",
GIT_AUTHOR_EMAIL: "removal-fixture@localhost",
GIT_COMMITTER_NAME: "removal-fixture",
GIT_COMMITTER_EMAIL: "removal-fixture@localhost",
},
});
if (result.error || result.status !== 0) {
throw new Error(
`removal fixture repository setup failed at git ${argv[0]}: ${
result.stderr || result.error?.message || `exit ${result.status}`
}`,
);
}
}
/**
* 14-08. A fresh fixture directory per run: two runs, or a run after one that
* crashed, no longer share (and overwrite) one fixed path. Callers remove it
* in `finally`.
*/
export async function createRemovalFixtureRoot(name: string): Promise<string> {
const parent = path.resolve(".tmp");
await mkdir(parent, { recursive: true });
return mkdtemp(path.join(parent, `${name}-`));
}
export type RemovalCheck = Readonly<{
name: string;
passed: boolean;
/** Why this check failed; each check names its own cause. */
failure?: string;
}>;
export function runRemovalFixtureCheck(
name: string,
root: string,
pnpmCli: string,
script: string,
extra: readonly string[] = [],
): RemovalCheck {
const status = spawnSync(process.execPath, [pnpmCli, script, ...extra], {
cwd: root,
stdio: "inherit",
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT },
}).status;
return status === 0
? { name, passed: true }
: {
name,
passed: false,
failure: `corepack pnpm ${[script, ...extra].join(" ")} exited ${status ?? "on a signal"}`,
};
}
function escapeXml(value: string): string {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
/**
* 14-08. The report used to say `failures="1"` whatever failed, and put the
* residue list into every failed testcase, so a type error read as residue.
*/
export function renderRemovalJunit(
suite: string,
checks: readonly RemovalCheck[],
): string {
const failures = checks.filter((check) => !check.passed).length;
const cases = checks
.map((check) =>
`<testcase name="${escapeXml(check.name)}">${
check.passed
? ""
: `<failure message="${escapeXml(check.failure ?? "failed")}" />`
}</testcase>`,
)
.join("");
return (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<testsuite name="${escapeXml(suite)}" tests="${checks.length}" failures="${failures}">` +
`${cases}</testsuite>\n`
);
}
export function runRemovalFixturePnpm(
root: string,
pnpmCli: string,
script: string,
extra: readonly string[] = [],
env: Readonly<Record<string, string>> = {},
): boolean {
return spawnSync(process.execPath, [pnpmCli, script, ...extra], {
cwd: root,
stdio: "inherit",
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT, ...env },
}).status === 0;
}
export async function filesBelow(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true });
return (await Promise.all(entries.map((entry) => {
const target = path.join(directory, entry.name);
return entry.isDirectory() ? filesBelow(target) : [target];
}))).flat();
}
function isWithin(target: string, root: string): boolean {
const relative = path.relative(root, target);
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
export async function runtimeImportGraph(
root: string,
runtimeSourceRoots: readonly string[],
): Promise<Readonly<{ dependentTests: readonly string[]; importingFiles: readonly string[] }>> {
const files = (await filesBelow(root))
.filter((file) => /\.(?:[cm]?ts|tsx)$/u.test(file))
.map((file) => path.resolve(file));
if (files.length === 0) {
throw new Error("removal fixture scanned module universe is empty");
}
const sourceSet = new Set(files);
const runtimeRoots = runtimeSourceRoots.map((entry) => path.resolve(root, entry));
const imports = new Map<string, readonly string[]>();
for (const file of files) {
const source = await readFile(file, "utf8");
const specifiers = [...source.matchAll(/(?:from\s*|import\s*\(\s*|import\s*)["']([^"']+)["']/gu)]
.map((match) => match[1])
.filter((specifier): specifier is string => typeof specifier === "string" && specifier.startsWith("."));
imports.set(file, specifiers.map((specifier) => {
const base = path.resolve(path.dirname(file), specifier);
return [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, `${base}.cts`, path.join(base, "index.ts"), path.join(base, "index.tsx")]
.find((candidate) => sourceSet.has(candidate)) ?? base;
}));
}
const memo = new Map<string, boolean>();
const reachesRuntime = (file: string, visiting = new Set<string>()): boolean => {
if (runtimeRoots.some((runtimeRoot) => isWithin(file, runtimeRoot))) return true;
const known = memo.get(file);
if (known !== undefined) return known;
if (visiting.has(file)) return false;
visiting.add(file);
const reaches = (imports.get(file) ?? []).some((dependency) =>
runtimeRoots.some((runtimeRoot) => isWithin(dependency, runtimeRoot)) ||
(sourceSet.has(dependency) && reachesRuntime(dependency, visiting))
);
visiting.delete(file);
memo.set(file, reaches);
return reaches;
};
const testsRoot = path.resolve(root, "tests");
return Object.freeze({
dependentTests: Object.freeze(files.filter((file) => isWithin(file, testsRoot) && reachesRuntime(file))),
importingFiles: Object.freeze(files.filter((file) =>
!runtimeRoots.some((runtimeRoot) => isWithin(file, runtimeRoot)) &&
(imports.get(file) ?? []).some((dependency) =>
runtimeRoots.some((runtimeRoot) => isWithin(dependency, runtimeRoot))
)
)),
});
}
export async function removeRuntimeDependentTests(
root: string,
runtimeSourceRoots: readonly string[],
): Promise<number> {
const graph = await runtimeImportGraph(root, runtimeSourceRoots);
if (graph.dependentTests.length === 0) {
throw new Error("removal fixture: no runtime-dependent tests discovered");
}
await Promise.all(graph.dependentTests.map((file) => rm(file, { force: true })));
return graph.dependentTests.length;
}
export async function assertNoRuntimeImports(
root: string,
runtimeSourceRoots: readonly string[],
capability: string,
): Promise<void> {
const graph = await runtimeImportGraph(root, runtimeSourceRoots);
if (graph.importingFiles.length > 0) {
throw new Error(`Removed ${capability} runtime is still imported by: ${graph.importingFiles.map((file) => path.relative(root, file)).join(", ")}`);
}
}
export function pruneScriptOrchestration(
scripts: Record<string, string>,
orchestrationScript: string,
removedScripts: ReadonlySet<string>,
): void {
const command = scripts[orchestrationScript];
if (!command) return;
scripts[orchestrationScript] = command.split(" && ").filter((segment) =>
![...removedScripts].some((removed) =>
new RegExp(`(?:^|\\s)(?:corepack\\s+)?pnpm\\s+${removed.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?:\\s|$)`, "u").test(segment)
)
).join(" && ");
}
export async function regenerateRemovalFixtureWorkflow(root: string): Promise<void> {
const contract = await loadCiGateContract(root);
await generateCiWorkflow({ root, contract, check: false });
// Every removal script calls this once, after it has finished mutating the
// tree, so it is the one place where the fixture's contents are final.
await pruneRemovalFixtureInventoryRoots(root);
sealRemovalFixtureRepository(root);
}
/**
* Drops repository roots the removal deleted from the supply-chain inventory
* policy.
*
* The policy lists `recipes` as a required tracked root, and removing an
* optional recipe deletes exactly that directory. Supply-chain generation then
* refused the fixture for missing a root the removal was supposed to remove, so
* the capability could never be shown to be removable. A root that is not on
* disk after the removal is not required of the result.
*/
async function pruneRemovalFixtureInventoryRoots(root: string): Promise<void> {
const policyPath = path.join(root, "config/security/secret-scan-policy.json");
let policy: Record<string, unknown>;
try {
policy = JSON.parse(await readFile(policyPath, "utf8")) as Record<string, unknown>;
} catch {
return;
}
const tracked = policy["trackedRoots"];
if (!Array.isArray(tracked)) return;
const surviving: string[] = [];
for (const entry of tracked) {
if (typeof entry !== "string") continue;
try {
await stat(path.join(root, entry));
surviving.push(entry);
} catch {
// Deleted by the removal under test.
}
}
if (surviving.length === tracked.length) return;
policy["trackedRoots"] = surviving;
await writeFile(policyPath, `${JSON.stringify(policy, null, 2)}\n`, "utf8");
}
export async function pruneRemovalFixtureCiContract(options: Readonly<{
root: string;
removedScripts: ReadonlySet<string>;
removedEvidencePathFragments: readonly string[];
}>): Promise<void> {
const packagePath = path.join(options.root, "package.json");
const gatesPath = path.join(options.root, "config/ci/gates.json");
const packageDocument = JSON.parse(await readFile(packagePath, "utf8")) as {
scripts: Record<string, string>;
};
for (const script of options.removedScripts) delete packageDocument.scripts[script];
const contract = structuredClone(
parseCiGateContract(JSON.parse(await readFile(gatesPath, "utf8"))),
);
const removedCommandIds = new Set(
contract.commands
.filter(({ script }) => options.removedScripts.has(script))
.map(({ id }) => id),
);
const missing = [...options.removedScripts].filter(
(script) => !contract.commands.some((command) => command.script === script),
);
if (missing.length > 0) {
throw new Error(`removal fixture CI command set is incomplete: ${missing.join(", ")}`);
}
const removedArtifactIds = new Set(
contract.artifacts
.filter(({ path: artifactPath }) =>
options.removedEvidencePathFragments.some((fragment) => artifactPath.includes(fragment))
)
.map(({ id }) => id),
);
for (const fragment of options.removedEvidencePathFragments) {
if (!contract.artifacts.some(({ path: artifactPath }) => artifactPath.includes(fragment))) {
throw new Error(`removal fixture CI evidence is missing: ${fragment}`);
}
}
contract.commands = contract.commands.filter(({ id }) => !removedCommandIds.has(id));
contract.artifacts = contract.artifacts
.filter(({ id }) => !removedArtifactIds.has(id))
.map((artifact) => artifact.production === "command-generated"
? {
...artifact,
producerCommandIds: artifact.producerCommandIds.filter(
(commandId) => !removedCommandIds.has(commandId),
),
}
: artifact)
.filter((artifact) =>
artifact.production !== "command-generated" || artifact.producerCommandIds.length > 0
);
const retainedArtifactIds = new Set(contract.artifacts.map(({ id }) => id));
for (const gate of contract.gates) {
gate.commandIds = gate.commandIds.filter((commandId) => !removedCommandIds.has(commandId));
gate.evidenceArtifactIds = gate.evidenceArtifactIds.filter((artifactId) =>
retainedArtifactIds.has(artifactId)
);
}
const referencedSchemaIds = new Set(contract.artifacts.map(({ schemaId }) => schemaId));
contract.artifactSchemas = contract.artifactSchemas.filter(({ id }) =>
referencedSchemaIds.has(id)
);
const validated = parseCiGateContract(contract);
await Promise.all([
writeFile(packagePath, `${JSON.stringify(packageDocument, null, 2)}\n`),
writeFile(gatesPath, `${JSON.stringify(validated, null, 2)}\n`),
]);
}