Files
clean-architecture-frontend…/scripts/test-sample-removal.ts
T
DongHyeonkaandClaude Opus 5.5 ad0e83c867 fix(features): make feature add and removal work from the feature directory (09-07, 14-03)
A feature directory without feature-module.ts vanished silently, registry
consumers listed only the sample's directories, and the removal gate only knew
the sample. The generator now fails unless a NOT_INSTALLED marker says so
(D-10), consumer directories are globs over every feature, and the removal
script takes --feature=<id>. starter-experience.md documents the current
ownership declarations and the files a new feature touches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:10:19 +09:00

483 lines
17 KiB
TypeScript

import {
access,
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import path from "node:path";
import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts";
import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts";
import { isProductionModulePath } from "./lib/risk-coverage.ts";
import {
filesBelow,
prepareRemovalFixture,
pruneRemovalFixtureCiContract,
pruneScriptOrchestration,
regenerateRemovalFixtureWorkflow,
requireRemovalFixtureEnvironment,
runRemovalFixturePnpm,
} from "./lib/removal-fixture.ts";
/**
* 09-07 (D-10). Removes one installed feature, `--feature=<id>` (default: the
* reference sample), from a copy of the repository and proves the rest still
* typechecks, tests, covers and builds. Every feature loses its directory, its
* tests/features directory, its context when no other feature is left in it,
* its runtime-profile override and its central policy rows. The sample also
* owns the extra paths and scripts listed in SAMPLE_EXTRAS.
*/
const featureId =
process.argv.find((argument) => argument.startsWith("--feature="))
?.slice("--feature=".length) ?? "reference-feature";
type FeatureExtras = Readonly<{
paths: readonly string[];
ciScripts: readonly string[];
evidencePathFragments: readonly string[];
residue: RegExp;
}>;
const SAMPLE_EXTRAS: Readonly<Record<string, FeatureExtras>> = Object.freeze({
"reference-feature": Object.freeze({
paths: [
"tests/integration/http-scenario-catalog.test.ts",
"tests/component/product-feature-switch.test.tsx",
"tests/e2e/reference-form.spec.ts",
"tests/e2e/reference-route.spec.ts",
"tests/mocks",
"tests/fixtures/typecheck/invalid-feature-input.ts",
"tests/fixtures/typecheck/invalid-reference-operation.ts",
"tests/fixtures/typecheck/invalid-http-operation-input.ts",
"tests/fixtures/typecheck/invalid-http-wire-mapper.ts",
"tests/fixtures/typecheck/invalid-http-operation-id.ts",
"tests/fixtures/typecheck/invalid-http-route-id.ts",
"tests/fixtures/typecheck/invalid-feature-contribution-input.ts",
"tests/fixtures/typecheck/invalid-feature-capability-selection.ts",
"tests/fixtures/typecheck/tsconfig.feature-input.json",
"tests/fixtures/typecheck/tsconfig.reference-operation.json",
"tests/fixtures/typecheck/tsconfig.http-operation-input.json",
"tests/fixtures/typecheck/tsconfig.http-wire-mapper.json",
"tests/fixtures/typecheck/tsconfig.http-operation-id.json",
"tests/fixtures/typecheck/tsconfig.http-route-id.json",
"tests/fixtures/typecheck/tsconfig.feature-contribution-input.json",
"tests/fixtures/typecheck/tsconfig.feature-capability-selection.json",
],
ciScripts: [
"check:types:fixture:feature-input",
"check:types:fixture:reference-operation",
"check:types:fixture:http-operation-input",
"check:types:fixture:http-wire-mapper",
"check:types:fixture:http-operation-id",
"check:types:fixture:http-route-id",
"check:types:fixture:feature-contribution-input",
"check:types:fixture:feature-capability-selection",
"test:http-scenario-evidence",
"test:reference-feature",
],
evidencePathFragments: [
"reference-feature.xml",
"http-scenario-executions",
"http-scenario-evidence",
],
residue: /REFERENCE_RESOURCE|reference-feature|reference-resource/i,
}),
});
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
}
async function locateFeature(id: string) {
const source = await createFileSystemDeclarationSource(process.cwd());
for (const appId of source.appIds()) {
for (const context of source.contextsOf(appId)) {
const features = source.featuresOf(context.id);
const feature = features.find((candidate) => candidate.id === id);
if (!feature) continue;
let contextDirectory: string | null = null;
for (const entry of await readdir("src/contexts", { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const declaration = await readFile(
path.join("src/contexts", entry.name, "context-module.ts"),
"utf8",
).catch(() => "");
if (
new RegExp(`CONTEXT_MODULE_ID\\s*=\\s*["']${escapeRegExp(context.id)}["']`, "u")
.test(declaration)
) {
contextDirectory = `src/contexts/${entry.name}`;
}
}
return Object.freeze({
directory: feature.directory,
// The context goes with its last feature.
contextDirectory: features.length === 1 ? contextDirectory : null,
});
}
}
throw new Error(`No installed feature declares FEATURE_MODULE_ID "${id}"`);
}
const located = await locateFeature(featureId);
const extras: FeatureExtras = SAMPLE_EXTRAS[featureId] ?? Object.freeze({
paths: [],
ciScripts: [],
evidencePathFragments: [],
residue: new RegExp(
`${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`,
"i",
),
});
// Captured from this repository before the copy loses them.
const featureRouteIds = Object.entries(ROUTE_FEATURE_OWNER)
.filter(([, owner]) => owner === featureId)
.map(([routeId]) => routeId);
const fixtureParent = path.resolve(".tmp");
await mkdir(fixtureParent, { recursive: true });
const fixtureRoot = await mkdtemp(
path.join(fixtureParent, `${featureId}-removal-`),
);
const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath");
const featureSource = `src/features/${located.directory}`;
const featureTests = `tests/features/${located.directory}`;
const isSample = featureId in SAMPLE_EXTRAS;
/**
* Platform tests that must survive the sample feature's removal. Asserting they
* are still present is what stops the removal fixture from "passing" by having
* quietly deleted the platform's own coverage along with the feature.
*/
const commonTestPaths = [
"tests/unit/external-contract-runtime.test.ts",
"tests/unit/http-execution-v3.test.ts",
"tests/unit/runtime-adapters.test.ts",
"tests/integration/http-execution-v3-observability.test.ts",
];
const featureOwnedPaths = [
featureSource,
featureTests,
// The feature's bounded-context declaration when it was the last feature in
// it; the template app stays.
...(located.contextDirectory === null ? [] : [located.contextDirectory]),
...extras.paths,
];
type CoveragePolicy = {
repositoryBaseline: number;
generatedPaths: string[];
criticalModules: Array<{
path?: string;
minimum?: Record<string, number>;
}>;
highRiskPaths: string[];
waivers: Array<{ path?: string }>;
};
type EvidenceContribution = Readonly<{ owner?: string }>;
type EvidencePolicy = Record<
"scenarioCatalogs" | "sourceContracts",
unknown
>;
type GovernanceConsumer = Readonly<{ path?: string }>;
type GovernanceRegistry = Record<string, unknown> & {
consumers?: unknown;
consumerDirectories?: unknown;
};
type RemovalGovernance = { registries: GovernanceRegistry[] };
function runPnpm(script: string, extra: string[] = []): boolean {
return runRemovalFixturePnpm(fixtureRoot, pnpmCli, script, extra);
}
try {
await prepareRemovalFixture(fixtureRoot);
for (const excludedFixtureTest of [
"tests/unit/ci-workflow-generation.test.ts",
"tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap",
"tests/unit/removal-fixture.test.ts",
"tests/unit/http-scenario-evidence.test.ts",
]) {
await rm(path.join(fixtureRoot, excludedFixtureTest), { force: true });
}
const coveragePolicyFile = path.join(
fixtureRoot,
"config/testing/risk-coverage.json",
);
const coveragePolicy = JSON.parse(
await readFile(coveragePolicyFile, "utf8"),
) as CoveragePolicy;
const generatedProductionModules = new Set(coveragePolicy.generatedPaths);
const removedProductionModuleCount = (
await filesBelow(path.join(fixtureRoot, featureSource))
)
.map((file) => path.relative(fixtureRoot, file).split(path.sep).join("/"))
.filter(
(file) =>
isProductionModulePath(file) && !generatedProductionModules.has(file),
).length;
for (const ownedPath of featureOwnedPaths) {
await rm(path.join(fixtureRoot, ownedPath), {
recursive: true,
force: true,
});
}
if (!runPnpm("generate:feature-index")) {
throw new Error("Feature topology indexes failed to regenerate after sample removal");
}
// Runtime profiles are product configuration. Once the feature is physically
// removed, its override key must disappear too or the built config still
// advertises a source capability that no longer exists.
for (const profile of [
"local",
"development",
"staging",
"production",
] as const) {
const profilePath = path.join(
fixtureRoot,
"config/runtime",
`${profile}.json`,
);
const runtimeConfig = JSON.parse(
await readFile(profilePath, "utf8"),
) as {
FEATURE_OVERRIDES?: Record<string, string>;
};
if (runtimeConfig.FEATURE_OVERRIDES) {
delete runtimeConfig.FEATURE_OVERRIDES[featureId];
}
await writeFile(
profilePath,
`${JSON.stringify(runtimeConfig, null, 2)}\n`,
);
}
const retainedCriticalModules = coveragePolicy.criticalModules.filter(
(modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`),
);
if (
isSample &&
retainedCriticalModules.length === coveragePolicy.criticalModules.length
) {
throw new Error("Reference feature coverage policy is not registered");
}
coveragePolicy.criticalModules = retainedCriticalModules;
coveragePolicy.highRiskPaths = coveragePolicy.highRiskPaths.filter(
(modulePath) => !modulePath.startsWith(`${featureSource}/`),
);
coveragePolicy.waivers = coveragePolicy.waivers.filter(
(waiver) => !waiver.path?.startsWith(`${featureSource}/`),
);
coveragePolicy.generatedPaths = coveragePolicy.generatedPaths.filter(
(modulePath) => !modulePath.startsWith(`${featureSource}/`),
);
coveragePolicy.repositoryBaseline -= removedProductionModuleCount;
if (coveragePolicy.repositoryBaseline <= 0) {
throw new Error("Reference feature removal produced an invalid coverage baseline");
}
await writeFile(
coveragePolicyFile,
`${JSON.stringify(coveragePolicy, null, 2)}\n`,
);
const evidencePolicyFile = path.join(
fixtureRoot,
"config/testing/test-evidence.json",
);
const evidencePolicy = JSON.parse(
await readFile(evidencePolicyFile, "utf8"),
) as EvidencePolicy;
let removedEvidenceContributions = 0;
for (const policyKey of ["scenarioCatalogs", "sourceContracts"] as const) {
const contributions = evidencePolicy[policyKey];
if (!Array.isArray(contributions)) {
throw new Error(`Test evidence policy is missing ${policyKey}`);
}
evidencePolicy[policyKey] = contributions.filter((candidate: unknown) => {
const contribution = candidate as EvidenceContribution;
const retained = contribution.owner !== featureId;
if (!retained) removedEvidenceContributions += 1;
return retained;
});
}
if (isSample && removedEvidenceContributions === 0) {
throw new Error("Reference feature test evidence policy is not registered");
}
await writeFile(
evidencePolicyFile,
`${JSON.stringify(evidencePolicy, null, 2)}\n`,
);
const governanceFile = path.join(
fixtureRoot,
"config/contracts/registry-governance.json",
);
const removalGovernance = JSON.parse(
await readFile(governanceFile, "utf8"),
) as RemovalGovernance;
removalGovernance.registries = removalGovernance.registries.map(
(registry) => ({
...registry,
...(Array.isArray(registry.consumers)
? {
consumers: registry.consumers.filter(
(candidate: unknown) => {
const consumer = candidate as GovernanceConsumer;
return !consumer.path?.includes(featureSource);
},
),
}
: {}),
...(Array.isArray(registry.consumerDirectories)
? {
consumerDirectories: registry.consumerDirectories.filter(
(directory: unknown) =>
typeof directory !== "string" ||
!directory.includes(featureSource),
),
}
: {}),
}),
);
await writeFile(
governanceFile,
`${JSON.stringify(removalGovernance, null, 2)}\n`,
);
const removedCiScripts = new Set(extras.ciScripts);
const fixturePackagePath = path.join(fixtureRoot, "package.json");
const fixturePackage = JSON.parse(await readFile(fixturePackagePath, "utf8")) as {
scripts: Record<string, string>;
};
pruneScriptOrchestration(fixturePackage.scripts, "test:all", removedCiScripts);
if (isSample) {
delete fixturePackage.scripts["check:http-scenario-evidence"];
delete fixturePackage.scripts["check:http-scenario-evidence:fixture"];
}
await writeFile(fixturePackagePath, `${JSON.stringify(fixturePackage, null, 2)}\n`);
await pruneRemovalFixtureCiContract({
root: fixtureRoot,
removedScripts: removedCiScripts,
removedEvidencePathFragments: extras.evidencePathFragments,
});
// D-13: removing the sample is a breaking registry change. The fixture
// records the new registry baseline the way a downstream project does, and
// the canonical check:registries then runs against it.
if (!runRemovalFixturePnpm(fixtureRoot, pnpmCli, "update:registry-baseline", [], {
REGISTRY_BASELINE_OWNER: "removal-fixture",
REGISTRY_BASELINE_REASON: `${featureId} removed`,
})) {
throw new Error("Registry baseline failed to update after sample removal");
}
await regenerateRemovalFixtureWorkflow(fixtureRoot);
const residue: string[] = [];
for (const root of ["src", "tests"]) {
for (const file of await filesBelow(path.join(fixtureRoot, root))) {
const relative = path.relative(fixtureRoot, file);
const content = await readFile(file, "utf8");
if (extras.residue.test(`${relative}\n${content}`)) {
residue.push(relative);
}
}
}
const checks: Array<[string, boolean]> = [
[
"common-test-evidence",
(
await Promise.all(
commonTestPaths.map(async (testPath) => {
try {
await access(path.join(fixtureRoot, testPath));
return true;
} catch {
return false;
}
}),
)
).every(Boolean),
],
["typecheck", runPnpm("check:types")],
["architecture", runPnpm("check:architecture")],
["registries", runPnpm("check:registries")],
["unit-integration", runPnpm("test:all")],
["coverage", runPnpm("test:coverage")],
["test-evidence-source", runPnpm("check:test-evidence:source")],
["ci-contract", runPnpm("check:ci")],
[
"home-smoke",
runPnpm("exec", [
"vitest",
"run",
"tests/component/router.test.tsx",
"--reporter=default",
]),
],
["build", runPnpm("build")],
];
const builtResidue: string[] = [];
const buildSucceeded =
checks.find(([name]) => name === "build")?.[1] === true;
if (buildSucceeded) {
for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) {
if (!/\.(?:js|css|html|json)$/.test(file)) continue;
const content = await readFile(file, "utf8");
if (extras.residue.test(content)) {
builtResidue.push(path.relative(fixtureRoot, file));
}
}
}
const routeCatalog = await import(
`${new URL(
"../src/features/installed-feature-contracts.ts",
`file://${fixtureRoot}/scripts/`,
).href}?removed=${Date.now()}`
) as { ROUTE_REGISTRY: Readonly<Record<string, unknown>> };
const routeIds = new Set(Object.keys(routeCatalog.ROUTE_REGISTRY));
const routeAbsent = featureRouteIds.every((routeId) => !routeIds.has(routeId));
checks.push(["route-absent", routeAbsent]);
checks.push(["fixture-id-residue", residue.length === 0]);
checks.push(["built-fixture-id-residue", builtResidue.length === 0]);
const passed = checks.every(([, result]) => result);
await mkdir("artifacts/tests", { recursive: true });
await writeFile(
isSample
? "artifacts/tests/sample-removal.xml"
: `artifacts/tests/feature-removal-${featureId}.xml`,
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<testsuite name="${featureId}-removal" tests="${checks.length}" failures="${passed ? 0 : 1}">` +
checks
.map(
([name, result]) =>
`<testcase name="${name}">${result ? "" : `<failure>${[...residue, ...builtResidue].join(", ")}</failure>`}</testcase>`,
)
.join("") +
`</testsuite>\n`,
);
if (!passed) {
const failures = checks
.filter(([, result]) => !result)
.map(([name]) => name);
process.stderr.write(
`${featureId} removal failed: ${failures.join(", ")}; residue: ${[...residue, ...builtResidue].join(", ")}\n`,
);
process.exitCode = 1;
} else {
process.stdout.write(
`${featureId} removal: PASS (${checks.length} checks, no fixture IDs)\n`,
);
}
} finally {
await rm(fixtureRoot, { recursive: true, force: true });
}