Files
rea/tests/boundary/filesystem/dependencyInstall.test.ts
morluto 1b97b0f370 fix(lifecycle): preserve observations and cleanup ownership (#4274)
* fix(application): retain completed evidence through cancellation

Validate completed provider reports before classifying cancellation and preserve Evidence and captured diagnostics. Share MCP recording and delivery across custom observation handlers. Add source-owned completion and public SDK recording controls. Refs #3923, #3927, #4261.

* fix(wasm): retain final observations through cancellation

Keep completed Evidence after finalization and through CLI/MCP delivery. Preserve output and cleanup failure precedence. Refs #4254.

* fix(browser): retain final observations and forward cancellation

Classify final CDP detach and completed scenario cleanup at the provider boundary. Translate completed partials into canonical Evidence for MCP recording, and forward CLI cancellation to passive Electron tools. Refs #4255, #4256, #4257.

* fix(ghidra): isolate cancellation of shared startup waiters

Keep startup group-owned while each caller has an independent abortable wait. Await final-owner cleanup and preserve cleanup facts before retrying. Reuse the shared abortable promise helper. Refs #3983.

* fix(mcp): keep shutdown registrations until cleanup succeeds

Retain repeated event requests while unresolved owners need cleanup, and unregister only after success. Verify coalescing and failed-owner retry. Refs #4253.

* fix(adb): own transfer snapshots and stage screen publication

Bind transfer digests to the exact private input bytes and preserve caller APK names. Retain failed descriptors and private-root owners with typed cleanup evidence; publish captures exclusively after the cancellation cutoff. Refs #4251, #4252.

* fix(verification): report ADB cleanup failures

Always close after attempted verification and keep unexpected primary failures and cleanup details visible. Exercise the production script with controlled imports, including null and undefined throws. Refs #4260.

* fix(runner): stop owned Windows commands on cancellation

Use the retained ChildProcess handle for IPC cancellation and parent disconnection. Keep the SQLite lock until observed child close, and include native Windows regressions in the curated CI lane. Native Windows results remain pending. Refs #4258.

* fix(website): canonicalize link containment boundaries

Compare resolved targets with resolved repository and site roots. Accept directory aliases while preserving escape checks and keep fixtures within their temporary owner. Refs #4264.

* docs(testing): cover completion races and cleanup retry

Clarify validation-before-cancellation, independent startup waiter controls, producer and adapter coverage, and repeated shutdown events.

* fix(filesystem): retain file owners and completed reads after close failure

* fix(session): report retained snapshot staging in cleanup status

Fixes #4277. Include both snapshot and profile file-resource scopes in the owning status fact, preserving publication receipts and cleanup retry.

* docs(mcp): clarify recovery of raw partial observations

Document the observed SDK cancellation boundary and the open design decision in #4276 without promoting raw errors to Evidence.

* fix(kuna): own the complete installation inspection lifetime

* test(kuna): cover session cleanup of shared cache resources

* fix(hopper): isolate publisher operation resource admission

* fix(hopper): preserve launcher cleanup failure classification

* fix(adb): retain ordered cleanup and screen publication outcomes

* fix(runner): retain Windows job ownership through cleanup retries

* docs: clarify inspection admission and ordered cleanup regressions

* fix(ghidra): preserve startup cleanup and request deadlines

* fix(runner): supervise stdin errors and bootstrap native controls

* docs: require queued lifecycle controls to survive admission

* fix(cli): leave cleanup resolution with resource owners

* test(adb): verify owned install snapshots through CLI

* fix(errors): exclude resolved primary cleanup resources

* fix(adb): resolve publication cleanup after its handle closes

* fix(android): resolve JADX hash cleanup after owned close

* refactor(android): share hash failure cause options

* fix(kuna): gate commands on retained descriptor cleanup

* docs: cover cleanup admission and owner-confirmed recovery

* refactor(artifacts): bind cleanup errors to confirmed release

* fix(adb): resolve recovered cleanup at retained owners

* fix(kuna): resolve installation cleanup after owned close

* fix(kuna): gate cache reads on retained hash cleanup

* fix(setup): preserve publisher cleanup admission failures

* fix(android): resolve the reported retirement cleanup error

* test(runner): scope post-spawn fault control to POSIX

* test(adb): cover persistent snapshot owner retirement

* fix(kuna): preserve file outcomes with explicit cleanup ownership

* fix(artifacts): resolve errors through retained cleanup owners

* docs(lifecycle): carry cleanup ownership in typed outcomes

* fix(adb): bind staged screen errors to their cleanup lease

* fix(kuna): bind profile cleanup through a close capability

* fix(artifacts): retain descriptor resources in cleanup errors

* fix(pcap): bind existing errors to snapshot retirement

* fix(windows): load source owner through its file URL

* test(build): copy the command runner helper into fixtures

* fix(mcp): own shared observation providers in the transport

* fix(jadx): resolve every retained cleanup retry error

* fix(kuna): bind retry errors to every retained cleanup owner

* fix(adb): bind admission and shutdown errors to exact cleanup leases

* fix(windows): resolve command paths before native ownership

* test(publisher): assert exact descriptor recovery without release metadata

* docs(lifecycle): require every retry error to follow its owners

* fix(kuna): keep hash cleanup state stable across concurrent retries

* test(windows): exercise surviving descendants with scoped shutdown deadlines

* fix(uninstall): preserve primary read errors through cleanup failure

* test(publisher): assert cleanup Result and exact owner recovery

* test(windows): observe supervisor resources through IPC disconnect

* fix(browser): retain typed cancellation after interrupted actions

* test(publisher): assert ownership phases without retry-count coupling

* fix(lifecycle): preserve abort reasons through shared provider execution

* fix(jadx): preserve execution and late hash cancellation causes

* fix(adb): compose late cancellation with exact cleanup failures

* test(mcp): use the shared budget for session workflows
2026-10-16 11:48:59 +08:00

321 lines
11 KiB
TypeScript

import { spawn, spawnSync } from "node:child_process";
import {
copyFile,
mkdir,
readFile,
readdir,
writeFile,
symlink,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const script = join(process.cwd(), "scripts", "check-dependency-install.mjs");
const sourceRoot = process.cwd();
const fixture = async (
installedVersion?: string,
omitDevDependency = false,
) => {
const root = await createTestTempDirectory("rea-deps-");
await mkdir(join(root, "node_modules"));
await writeFile(
join(root, "package-lock.json"),
JSON.stringify({
packages: {
"": {
dependencies: { alpha: "1.0.0" },
devDependencies: { beta: "2.0.0" },
},
"node_modules/alpha": { version: "1.0.0" },
"node_modules/beta": { version: "2.0.0" },
},
}),
);
await writeFile(
join(root, "node_modules", ".package-lock.json"),
JSON.stringify({
packages: {
"node_modules/alpha": { version: installedVersion ?? "1.0.0" },
...(omitDevDependency
? {}
: { "node_modules/beta": { version: "2.0.0" } }),
"node_modules/unrelated": { version: "9.0.0" },
},
}),
);
return root;
};
describe("dependency install freshness", () => {
it("accepts matching direct packages and ignores extraneous packages", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture(),
encoding: "utf8",
});
expect(result.status, result.stderr).toBe(0);
});
it("reports a direct version mismatch with one remediation", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture("0.9.0"),
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
expect(result.stderr).toContain("npm ci");
});
it("reports a missing direct development dependency", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture(undefined, true),
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"beta: missing from the installed dependency lockfile",
);
expect(result.stderr).toContain("npm ci");
});
it("runs from a script path containing URL-escaped characters", async () => {
const root = await fixture("0.9.0");
const scriptDirectory = join(root, "path with spaces");
const copiedScript = join(scriptDirectory, "check-dependency-install.mjs");
await mkdir(scriptDirectory);
await copyFile(script, copiedScript);
const result = spawnSync(process.execPath, [copiedScript], {
cwd: root,
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
});
it("checks installed dependencies before restoring a cached build", async () => {
const root = await createBuildCacheFixture();
const seeded = await runNpm(root, ["run", "build:cached"]);
expect(seeded.status, `${seeded.stdout}${seeded.stderr}`).toBe(0);
const rootLock = asRecord(
JSON.parse(await readFile(join(root, "package-lock.json"), "utf8")),
);
const lockPackages = asRecord(rootLock?.packages);
const rootPackage = asRecord(lockPackages?.[""]);
const directDependencies = {
...asRecord(rootPackage?.dependencies),
...asRecord(rootPackage?.devDependencies),
};
const dependencyName = Object.keys(directDependencies).sort()[0];
if (dependencyName === undefined)
throw new Error("fixture has no direct dependencies");
const dependencyPath = `node_modules/${dependencyName}`;
const expectedDependency = asRecord(lockPackages?.[dependencyPath]);
if (typeof expectedDependency?.version !== "string")
throw new Error(
`fixture is missing the locked ${dependencyName} version`,
);
const installedLockPath = join(root, "node_modules", ".package-lock.json");
const installedLock = asRecord(
JSON.parse(await readFile(installedLockPath, "utf8")),
);
const packages = asRecord(installedLock?.packages);
const installedDependency = asRecord(packages?.[dependencyPath]);
if (installedDependency === undefined)
throw new Error(`fixture is missing installed ${dependencyName}`);
installedDependency.version = "0.0.0";
await writeFile(installedLockPath, JSON.stringify(installedLock));
const blocked = await runNpm(root, ["run", "build:cached"]);
expect(blocked.status).toBe(1);
expect(blocked.stderr).toContain(
`${dependencyName}: installed 0.0.0, expected ${expectedDependency.version}`,
);
const cached = await runTurbo(root);
expect(cached.status, cached.stderr).toBe(0);
expect(`${cached.stdout}${cached.stderr}`).toMatch(/cache hit/u);
}, 60_000);
it("preserves caller resource controls in strict cached builds without hashing their values", async () => {
const root = await createBuildCacheFixture();
const environment = {
...process.env,
TURBO_ENV_MODE: "strict",
GOMAXPROCS: "1",
GOMEMLIMIT: "384MiB",
UV_THREADPOOL_SIZE: "2",
REA_TEST_UNLISTED_ENV: "filtered",
};
const built = await runNpm(root, ["run", "build:cached"], environment);
expect(built.status, `${built.stdout}${built.stderr}`).toBe(0);
expect(
JSON.parse(await readFile(join(root, "resource-controls.json"), "utf8")),
).toEqual({
GOMAXPROCS: "1",
GOMEMLIMIT: "384MiB",
UV_THREADPOOL_SIZE: "2",
REA_TEST_UNLISTED_ENV: null,
});
const cached = await runTurbo(root, {
...environment,
GOMAXPROCS: "2",
GOMEMLIMIT: "512MiB",
UV_THREADPOOL_SIZE: "4",
});
expect(cached.status, `${cached.stdout}${cached.stderr}`).toBe(0);
expect(`${cached.stdout}${cached.stderr}`).toMatch(/cache hit/u);
expect(`${cached.stdout}${cached.stderr}`).not.toMatch(/cache miss/u);
}, 60_000);
});
const createBuildCacheFixture = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-build-cache-guard-");
const packageJson = asRecord(
JSON.parse(await readFile(join(sourceRoot, "package.json"), "utf8")),
);
const scripts = asRecord(packageJson?.scripts);
if (
packageJson === undefined ||
typeof packageJson.name !== "string" ||
typeof packageJson.version !== "string" ||
typeof scripts?.["build:cached"] !== "string"
)
throw new Error("package is missing its cached build command");
const paths = [
".nvmrc",
"package-lock.json",
"turbo.json",
"tsconfig.json",
"tsconfig.build.json",
"scripts/check-dependency-install.mjs",
"scripts/run-exclusive.mjs",
"scripts/run-exclusive-command.mjs",
"scripts/lib/windows-owned-command.mjs",
"scripts/generate-skill-metadata.mjs",
"scripts/clean-build-output.mjs",
"scripts/generate-package-metadata.mjs",
"scripts/lib/generated-file.mjs",
".agents/skills/reverse-engineer-anything/SKILL.md",
"src/generatedPackageMetadata.ts",
];
await Promise.all(
paths.map(async (path) => {
const destination = join(root, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(sourceRoot, path), destination);
}),
);
await writeFile(
join(root, "package.json"),
JSON.stringify({
...packageJson,
scripts: {
...scripts,
compile: "node scripts/cache-fixture-build.mjs",
},
}),
);
await writeFile(
join(root, "scripts/cache-fixture-build.mjs"),
`import { mkdir, writeFile } from "node:fs/promises";
await writeFile("resource-controls.json", JSON.stringify(Object.fromEntries(["GOMAXPROCS", "GOMEMLIMIT", "UV_THREADPOOL_SIZE", "REA_TEST_UNLISTED_ENV"].map((name) => [name, process.env[name] ?? null]))));
await mkdir("dist", { recursive: true });
await writeFile("dist/cache-fixture.js", "built");
await writeFile("dist/catalogIdentity.js", "export const CATALOG_IDENTITY = { counts: { mcp_tools: 1 } };\\n");
await writeFile("dist/identity.js", ${JSON.stringify(`export const PRODUCT_IDENTITY = ${JSON.stringify({ packageSpecifier: `${packageJson.name}@latest`, registrationPackageSpecifier: `${packageJson.name}@${packageJson.version}` })};\n`)});
`,
);
await createNodeModulesLinks(root);
await writeFile(
join(root, "node_modules", ".package-lock.json"),
await readFile(join(sourceRoot, "node_modules", ".package-lock.json")),
);
return root;
};
const createNodeModulesLinks = async (root: string): Promise<void> => {
const source = join(sourceRoot, "node_modules");
const destination = join(root, "node_modules");
await mkdir(destination);
for (const entry of await readdir(source, { withFileTypes: true })) {
if (entry.name === ".package-lock.json") continue;
const sourcePath = join(source, entry.name);
const destinationPath = join(destination, entry.name);
if (entry.name.startsWith("@") && entry.isDirectory()) {
await mkdir(destinationPath);
for (const packageName of await readdir(sourcePath))
await symlink(
join(sourcePath, packageName),
join(destinationPath, packageName),
process.platform === "win32" ? "junction" : undefined,
);
} else {
await symlink(
sourcePath,
destinationPath,
process.platform === "win32" ? "junction" : undefined,
);
}
}
};
const runNpm = (
cwd: string,
arguments_: readonly string[],
environment: NodeJS.ProcessEnv = process.env,
) => run("npm", arguments_, cwd, environment);
const runTurbo = (cwd: string, environment: NodeJS.ProcessEnv = process.env) =>
run(
process.execPath,
[
join(cwd, "node_modules", "turbo", "bin", "turbo"),
"run",
"artifacts:skills",
"--output-logs=full",
],
cwd,
environment,
);
const run = (
command: string,
arguments_: readonly string[],
cwd: string,
environment: NodeJS.ProcessEnv,
): Promise<{
readonly status: number;
readonly stdout: string;
readonly stderr: string;
}> =>
new Promise((resolve, reject) => {
const child = spawn(command, [...arguments_], {
cwd,
env: environment,
shell: process.platform === "win32",
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
child.once("error", reject);
child.once("close", (status) =>
resolve({ status: status ?? 1, stdout, stderr }),
);
});
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
isRecord(value) ? value : undefined;