fix(artifacts): reuse current classification and region reads
This commit is contained in:
@@ -1,13 +1,91 @@
|
||||
import { chmod, readFile, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
|
||||
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
||||
import {
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "../../../src/application/SetupClientConfiguration.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("accepts a literal UTF-8 replacement character without changing its value", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-config-utf8-");
|
||||
const configPath = join(root, "config.json");
|
||||
const original = Buffer.concat([
|
||||
Buffer.from('{"label":"'),
|
||||
Buffer.from("\uFFFD"),
|
||||
Buffer.from('"}'),
|
||||
]);
|
||||
await writeFile(configPath, original);
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", format: "json", configPath },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
expect(result.status).toBe("configured");
|
||||
expect(await readFile(`${configPath}.rea.backup`)).toEqual(original);
|
||||
expect(JSON.parse(await readFile(configPath, "utf8")).label).toBe("\uFFFD");
|
||||
});
|
||||
|
||||
it("previews and creates a current recovery backup while preserving the first backup", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-current-recovery-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(await inspectClientConfiguration(client, {}, ["rea", "mcp"])).toEqual({
|
||||
status: "update",
|
||||
backupPath: recoveryPath,
|
||||
});
|
||||
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "configured", backupPath: recoveryPath });
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("blocks configuration when the planned content-addressed backup is occupied", async () => {
|
||||
const root = await createTestTempDirectory("rea-client-recovery-conflict-");
|
||||
const configPath = join(root, "config.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
const client = { name: "cursor", format: "json", configPath } as const;
|
||||
await writeFile(configPath, currentOriginal);
|
||||
await writeFile(`${configPath}.rea.backup`, firstOriginal);
|
||||
const recoveryPath = `${configPath}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
await writeFile(recoveryPath, "occupied by other data");
|
||||
|
||||
expect(
|
||||
await inspectClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toMatchObject({
|
||||
status: "invalid",
|
||||
remediation: expect.stringContaining(recoveryPath),
|
||||
});
|
||||
expect(
|
||||
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
||||
).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(configPath, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(
|
||||
firstOriginal,
|
||||
);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe("occupied by other data");
|
||||
});
|
||||
|
||||
describe("client configuration write failures", () => {
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0).each([
|
||||
["json", configureClientConfiguration],
|
||||
|
||||
@@ -191,12 +191,9 @@ describe.skipIf(process.platform === "win32")(
|
||||
it.each([
|
||||
["name=other\nversion=12.1.3\n", "does not match"],
|
||||
["name=ghidra-allegrex\nversion=12.1.4\n", "does not match"],
|
||||
[
|
||||
"name=ghidra-allegrex\nversion=12.1.3\nversion=12.1.3\n",
|
||||
"exactly one version",
|
||||
],
|
||||
["name=ghidra-allegrex\nversion=12.1.\\uZZZZ\n", "Unicode escape"],
|
||||
])(
|
||||
"rejects incompatible or ambiguous extension metadata %s",
|
||||
"rejects mismatched or malformed extension metadata %s",
|
||||
async (properties, reason) => {
|
||||
const { root } = await installation();
|
||||
await writeFile(join(root, "extension.properties"), properties);
|
||||
@@ -504,3 +501,38 @@ describe.skipIf(process.platform === "win32")(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"PSP extension property syntax",
|
||||
() => {
|
||||
it.each([
|
||||
{
|
||||
form: "escaped key and value with colon separator",
|
||||
properties: "n\\u0061me : ghidra-allegrex\nver\\u0073ion=12.1.3\n",
|
||||
},
|
||||
{
|
||||
form: "continued key and value lines",
|
||||
properties: "name=ghidra-\\\n allegrex\nversion=12.1.\\\n 3\n",
|
||||
},
|
||||
{
|
||||
form: "duplicate keys use the last value",
|
||||
properties:
|
||||
"name=wrong\nname=ghidra-allegrex\nversion=12.1.4\nversion=12.1.3\n",
|
||||
},
|
||||
])(
|
||||
"accepts Java Properties $form and hashes raw bytes",
|
||||
async ({ properties }) => {
|
||||
const { root } = await installation();
|
||||
const canonical = await inspectGhidraPspExtension(root, "12.1.3");
|
||||
const latin1Properties = Buffer.from(
|
||||
`${properties}author=caf\u00e9\n`,
|
||||
"latin1",
|
||||
);
|
||||
await writeFile(join(root, "extension.properties"), latin1Properties);
|
||||
const extension = await inspectGhidraPspExtension(root, "12.1.3");
|
||||
expect(extension.id).toBe("ghidra-allegrex");
|
||||
expect(extension.sha256).not.toBe(canonical.sha256);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -30,6 +30,81 @@ import {
|
||||
const sha256 = (bytes: Buffer) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
it("reuses scanned iNES region bytes for reconstruction without another full read", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-read-budget-");
|
||||
const path = join(root, "large-tail.nes");
|
||||
const bytes = inesFixture({ trailing: Buffer.alloc(2 * 1024 * 1024, 0x5a) });
|
||||
await writeFile(path, bytes);
|
||||
const sample = await open(path, "r");
|
||||
const prototype = Object.getPrototypeOf(sample) as Pick<
|
||||
typeof sample,
|
||||
"read"
|
||||
>;
|
||||
await sample.close();
|
||||
const originalRead = prototype.read;
|
||||
let bytesRead = 0;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof sample,
|
||||
...args
|
||||
) {
|
||||
const result = await originalRead.call(this, ...args);
|
||||
bytesRead += result.bytesRead;
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
const result = await inventoryArtifact(path);
|
||||
expect(result.ines?.reconstruction).toMatchObject({
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
verified: true,
|
||||
});
|
||||
// Initial root hash, region scan, final freshness hash, plus bounded headers.
|
||||
expect(bytesRead).toBeLessThanOrEqual(3 * bytes.length + 64 * 1024);
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects region bytes that disagree with stable whole-file hashes", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-region-digest-");
|
||||
const path = join(root, "source.nes");
|
||||
const bytes = inesFixture();
|
||||
await writeFile(path, bytes);
|
||||
const sample = await open(path, "r");
|
||||
const prototype = Object.getPrototypeOf(sample) as Pick<
|
||||
typeof sample,
|
||||
"read"
|
||||
>;
|
||||
await sample.close();
|
||||
const originalRead = prototype.read;
|
||||
let changed = false;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof sample,
|
||||
...args
|
||||
) {
|
||||
const result = await originalRead.call(this, ...args);
|
||||
const arguments_: readonly unknown[] = args;
|
||||
if (!changed && arguments_[3] === 16n && result.bytesRead === 16_384) {
|
||||
// Alter only the region observation, leaving both whole-file passes intact.
|
||||
if (!Buffer.isBuffer(result.buffer))
|
||||
throw new Error("Expected byte buffer");
|
||||
result.buffer.writeUInt8(result.buffer.readUInt8(0) ^ 0xff, 0);
|
||||
changed = true;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
message: "iNES reconstruction differs from the source",
|
||||
});
|
||||
expect(changed).toBe(true);
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["data", "hop", "HOP"])(
|
||||
"routes iNES bytes as an archive with a .%s suffix",
|
||||
async (suffix) => {
|
||||
@@ -124,7 +199,6 @@ it.each([true, false])(
|
||||
try {
|
||||
const extraction = await extractArtifact({
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -418,7 +492,6 @@ it.each(["removed", "directory", "malformed"])(
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -462,7 +535,6 @@ it.each(["EISDIR", "ENOTFILE", "EACCES", "cancelled"])(
|
||||
materializeArtifactInventory(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot: join(root, "output"),
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
@@ -503,7 +575,6 @@ it("retains a failed close after rejecting changed extraction bytes", async () =
|
||||
materializeInScope(
|
||||
{
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot: join(root, "output"),
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { InesArtifactReader } from "../../../src/artifacts/InesArtifactReader.js";
|
||||
import { scanReader } from "../../../src/artifacts/inventory/scanReader.js";
|
||||
import { hashStableRootArtifactHandle } from "../../../src/artifacts/inventory/hashStableRootArtifact.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { inesFixture } from "../../fixtures/ines.js";
|
||||
@@ -207,10 +208,20 @@ it.each(["stream", "reconstruction"])(
|
||||
if (last === undefined) throw new Error("Missing last iNES region");
|
||||
const result =
|
||||
operation === "reconstruction"
|
||||
? reader.verifyReconstruction(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
controller.signal,
|
||||
)
|
||||
? (async () => {
|
||||
const { inesRegionScan } = await scanReader(
|
||||
reader,
|
||||
[reader],
|
||||
controller.signal,
|
||||
);
|
||||
if (inesRegionScan === undefined)
|
||||
throw new Error("Missing region scan");
|
||||
return reader.verifyReconstruction(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
inesRegionScan,
|
||||
controller.signal,
|
||||
);
|
||||
})()
|
||||
: (async () => {
|
||||
for await (const chunk of await reader.open(
|
||||
last,
|
||||
|
||||
+54
@@ -15,6 +15,60 @@ import {
|
||||
} from "../../../support/javascriptApplicationFixture.js";
|
||||
|
||||
describe("TypeScript source module loader semantics", () => {
|
||||
it("keeps whole type-only declarations out of runtime module relationships", async () => {
|
||||
const root = await createTestTempDirectory("rea-type-module-links-");
|
||||
await writeFixtureFiles(root, {
|
||||
"main.ts": `
|
||||
import type { Whole } from "./whole";
|
||||
export type { Remote } from "./remote";
|
||||
import { type Inline } from "./inline";
|
||||
export type LocalType = string;
|
||||
export interface LocalInterface { value: string }
|
||||
`,
|
||||
"whole.ts": "export interface Whole { value: string }",
|
||||
"remote.ts": "export interface Remote { value: string }",
|
||||
"inline.ts": "export interface Inline { value: string }",
|
||||
});
|
||||
|
||||
const { graph } = await reconstructJavaScriptFixture(root);
|
||||
const source = findSourceModule(graph, "main.ts");
|
||||
const sourceProperties = source?.observations.find(
|
||||
({ properties }) => properties.semantic_role === "source-module",
|
||||
)?.properties;
|
||||
|
||||
expect(sourceProperties).toMatchObject({
|
||||
import_relationships: 0,
|
||||
type_relationships: 5,
|
||||
export_names: [],
|
||||
type_export_names: ["LocalInterface", "LocalType", "Remote"],
|
||||
});
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" &&
|
||||
["./whole", "./remote"].includes(String(properties.specifier)),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ source_node_id, relation, properties }) =>
|
||||
source_node_id === source?.node_id &&
|
||||
relation === "imports" &&
|
||||
properties.kind === "static-import" &&
|
||||
properties.specifier === "./inline",
|
||||
),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
source?.observations
|
||||
.flatMap(({ evidence }) => evidence.limitations)
|
||||
.join(" "),
|
||||
).toContain(
|
||||
"inline type-only imports or re-exports may preserve a module side-effect dependency",
|
||||
);
|
||||
expect(findExportNode(graph, "main.ts", "LocalType")).toBeUndefined();
|
||||
expect(findExportNode(graph, "main.ts", "LocalInterface")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses emitted TypeScript loader semantics without changing dynamic imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-cts-module-loader-");
|
||||
await writeFixtureFiles(root, {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type ApplicationVersionComparisonResult,
|
||||
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
|
||||
import { electronPageInspectionSchema } from "../../../src/domain/javascript/electronObservation.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
|
||||
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.js";
|
||||
@@ -444,6 +445,73 @@ describe("JavaScript application workflow error diagnostics", () => {
|
||||
});
|
||||
|
||||
describe("JavaScript runtime reconciliation local paths", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "case-sensitive POSIX input root",
|
||||
root: null,
|
||||
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "case-sensitive POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/app/renderer.js",
|
||||
status: "unknown",
|
||||
},
|
||||
{
|
||||
name: "matching POSIX mapping root",
|
||||
root: "/runtime/App",
|
||||
path: "/runtime/App/renderer.js",
|
||||
status: "matched",
|
||||
},
|
||||
{
|
||||
name: "case-insensitive Windows mapping root",
|
||||
root: String.raw`C:\runtime\App`,
|
||||
path: String.raw`c:\runtime\app\renderer.js`,
|
||||
status: "matched",
|
||||
},
|
||||
])("uses $name on every host", ({ root, path, status }) => {
|
||||
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
|
||||
const original = base.runtime_observations[0]!;
|
||||
const inspection = electronPageInspectionSchema.parse(
|
||||
original.normalized_result,
|
||||
);
|
||||
const runtime = createEvidence(undefined, original.provider, {
|
||||
predicateType: original.predicate_type,
|
||||
operation: original.operation,
|
||||
parameters: { ...original.parameters, include_script_sources: false },
|
||||
result: {
|
||||
...inspection,
|
||||
scripts: {
|
||||
...inspection.scripts,
|
||||
items: inspection.scripts.items.map((script) => ({
|
||||
...script,
|
||||
file_path: path,
|
||||
source: { included: false, reason: "not-requested" },
|
||||
})),
|
||||
},
|
||||
},
|
||||
confidence: original.confidence,
|
||||
authority: original.authority,
|
||||
});
|
||||
const reconciled = reconcileJavaScriptRuntimeEvidence({
|
||||
static_layers: base.static_layers.map((layer) => ({
|
||||
...layer,
|
||||
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
|
||||
})),
|
||||
runtime_observations: [runtime],
|
||||
});
|
||||
if (!reconciled.ok) throw reconciled.error;
|
||||
const result = javascriptRuntimeReconciliationResultSchema.parse(
|
||||
reconciled.value.normalized_result,
|
||||
);
|
||||
expect(
|
||||
result.reconciliations.find(
|
||||
({ entity_kind }) => entity_kind === "script",
|
||||
),
|
||||
).toMatchObject({ status });
|
||||
});
|
||||
|
||||
it("resolves relative file mapping roots before deriving result Evidence", () => {
|
||||
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
|
||||
const relativeRoot = relative(process.cwd(), absoluteRoot);
|
||||
|
||||
@@ -378,6 +378,44 @@ describe("reference source path selection", () => {
|
||||
});
|
||||
|
||||
describe("reference source rooted module specifiers", () => {
|
||||
it("keeps dot-prefixed bare specifiers external while resolving explicit relative paths", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-dot-prefix-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.js"),
|
||||
'import ".hidden.js"; import "..pkg.js"; import "./.hidden.js"; require(".hidden.js");\n',
|
||||
),
|
||||
writeFile(join(root, ".hidden.js"), "export {};\n"),
|
||||
writeFile(join(root, "..pkg.js"), "export {};\n"),
|
||||
]);
|
||||
const result = await importTree(root);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.relationships).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "imports",
|
||||
resolution: "external",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: "..pkg.js",
|
||||
kind: "imports",
|
||||
resolution: "external",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "imports",
|
||||
resolution: "internal",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
to: ".hidden.js",
|
||||
kind: "requires",
|
||||
resolution: "external",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not rebase an absolute import onto a coincidentally matching source member", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-rooted-");
|
||||
await mkdir(join(root, "src", "outside"), { recursive: true });
|
||||
|
||||
@@ -6,6 +6,31 @@ import { expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
|
||||
|
||||
it("imports valid CommonJS wrapper syntax without inventing a parse failure", async () => {
|
||||
const root = await createTestTempDirectory("rea-reference-commonjs-mode-");
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(root, "main.cjs"),
|
||||
'void new.target; require("./dep.cjs"); return;\n',
|
||||
),
|
||||
writeFile(join(root, "dep.cjs"), "module.exports = 1;\n"),
|
||||
]);
|
||||
const imported = await importReferenceSource({
|
||||
root,
|
||||
caller: "native-commonjs-source",
|
||||
policy: { secretPatterns: [] },
|
||||
});
|
||||
if (!imported.ok) throw imported.error;
|
||||
expect(imported.value.parse_failures).toEqual([]);
|
||||
expect(imported.value.relationships).toContainEqual({
|
||||
from_path: "main.cjs",
|
||||
to: "dep.cjs",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["main.ts", "dep.js", "dep.ts"],
|
||||
["main.mts", "dep.mjs", "dep.mts"],
|
||||
|
||||
@@ -10,6 +10,8 @@ const injectedFilesystemFailures = vi.hoisted(() => ({
|
||||
closeNext: false,
|
||||
blockCloseRetries: false,
|
||||
chmodNext: false,
|
||||
syncAbortAfter: undefined as AbortController | undefined,
|
||||
syncCount: 0,
|
||||
rootIdentityPath: undefined as string | undefined,
|
||||
}));
|
||||
|
||||
@@ -44,6 +46,15 @@ vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
await close();
|
||||
};
|
||||
}
|
||||
if (injectedFilesystemFailures.syncAbortAfter !== undefined) {
|
||||
const sync = handle.sync.bind(handle);
|
||||
handle.sync = async () => {
|
||||
await sync();
|
||||
injectedFilesystemFailures.syncCount += 1;
|
||||
if (injectedFilesystemFailures.syncCount === 2)
|
||||
injectedFilesystemFailures.syncAbortAfter?.abort();
|
||||
};
|
||||
}
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
@@ -82,6 +93,34 @@ describe("safe artifact output close failures", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps the tree unpublished when cancellation arrives during commit durability",
|
||||
async () => {
|
||||
const parent = await createTestTempDirectory("rea-safe-output-cancel-");
|
||||
const output = join(parent, "unpublished");
|
||||
const tree = await SafeOutputTree.create(output);
|
||||
const bytes = Buffer.from("pending output");
|
||||
await tree.write("file.txt", Readable.from(bytes), {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
});
|
||||
const controller = new AbortController();
|
||||
injectedFilesystemFailures.syncCount = 0;
|
||||
injectedFilesystemFailures.syncAbortAfter = controller;
|
||||
try {
|
||||
await expect(tree.commit(controller.signal)).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
});
|
||||
expect(tree.published).toBe(false);
|
||||
} finally {
|
||||
injectedFilesystemFailures.syncAbortAfter = undefined;
|
||||
injectedFilesystemFailures.syncCount = 0;
|
||||
}
|
||||
expect(await tree.rollback()).toMatchObject({ status: "complete" });
|
||||
await expect(access(output)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves setup failure when closing the staging handle also fails",
|
||||
async () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../../../src/application/SetupHost.js";
|
||||
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
|
||||
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
|
||||
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
@@ -31,6 +32,61 @@ beforeEach(async () => {
|
||||
|
||||
afterEach(() => openMock.mockReset());
|
||||
|
||||
const holdReadHandle = (path: string, reason: string) => {
|
||||
const closeAttempts: object[] = [];
|
||||
let released = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== path) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!released) throw new Error(reason);
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
return {
|
||||
closeAttempts,
|
||||
release: () => {
|
||||
released = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
|
||||
const path = join(home, "client.json");
|
||||
const original = Buffer.from([0xff]);
|
||||
await writeFile(path, original);
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
path,
|
||||
"held uninstall handle",
|
||||
);
|
||||
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
||||
try {
|
||||
expect(
|
||||
await host.removeClient({
|
||||
name: "cursor",
|
||||
format: "json",
|
||||
configPath: path,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
detail: expect.stringContaining("not valid UTF-8"),
|
||||
});
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
|
||||
describe("ZCode fallback cleanup ownership", () => {
|
||||
it.each(["preflight", "configure"])(
|
||||
"retains a failed ZCode fallback close during %s until host cleanup",
|
||||
@@ -49,19 +105,10 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await mkdir(dirname(fallback), { recursive: true });
|
||||
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
|
||||
await writeFile(fallback, original);
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== fallback) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("held fallback handle");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
fallback,
|
||||
"held fallback handle",
|
||||
);
|
||||
try {
|
||||
const action =
|
||||
operation === "preflight"
|
||||
@@ -79,12 +126,12 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
allowClose = true;
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
@@ -92,83 +139,87 @@ describe("ZCode fallback cleanup ownership", () => {
|
||||
});
|
||||
|
||||
describe("setup client configuration cleanup ownership", () => {
|
||||
it("stops client configuration and retries the same alignment handle from host close", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
const client = (await host.supportedClients()).find(
|
||||
({ name }) => name === "vscode",
|
||||
);
|
||||
if (client === undefined) throw new Error("VS Code setup client missing");
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
const original = Buffer.from('{"servers": {"other": {}}}\n');
|
||||
await writeFile(client.configPath, original);
|
||||
it.each([
|
||||
["valid UTF-8", Buffer.from('{"servers": {"other": {}}}\n')],
|
||||
["malformed UTF-8", Buffer.from([0xff])],
|
||||
] as const)(
|
||||
"stops configuration and retains the %s read owner until host close",
|
||||
async (encoding, original) => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-close-");
|
||||
const environment = {
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, "xdg"),
|
||||
};
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
||||
environment,
|
||||
);
|
||||
const client = (await host.supportedClients()).find(
|
||||
({ name }) => name === "vscode",
|
||||
);
|
||||
if (client === undefined) throw new Error("VS Code setup client missing");
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFile(client.configPath, original);
|
||||
|
||||
const closeAttempts: object[] = [];
|
||||
let allowClose = false;
|
||||
openMock.mockImplementation(async (...args) => {
|
||||
const handle = await actualFs.open(...args);
|
||||
if (String(args[0]) !== client.configPath) return handle;
|
||||
const nativeClose = handle.close.bind(handle);
|
||||
vi.spyOn(handle, "close").mockImplementation(async () => {
|
||||
closeAttempts.push(handle);
|
||||
if (!allowClose) throw new Error("test holds the config handle open");
|
||||
await nativeClose();
|
||||
});
|
||||
return handle;
|
||||
});
|
||||
const configure = vi.spyOn(host, "configureClient");
|
||||
const { closeAttempts, release } = holdReadHandle(
|
||||
client.configPath,
|
||||
"test holds the config handle open",
|
||||
);
|
||||
const configure = vi.spyOn(host, "configureClient");
|
||||
|
||||
try {
|
||||
const failure = await filterClientsNeedingConfigure(host, [client], {}, [
|
||||
"rea",
|
||||
"mcp",
|
||||
])
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
try {
|
||||
const failure = await filterClientsNeedingConfigure(
|
||||
host,
|
||||
[client],
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
expect(failure).toMatchObject({
|
||||
_tag: "ConfigurationError",
|
||||
cause: expect.any(RegularFileCleanupFailure),
|
||||
cleanup: {
|
||||
resources: [client.configPath],
|
||||
reason: expect.stringContaining("test holds the config handle open"),
|
||||
},
|
||||
});
|
||||
expect(configure).not.toHaveBeenCalled();
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
||||
expect(await readFile(client.configPath)).toEqual(original);
|
||||
.then((detectedClients) =>
|
||||
configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
providerEnvironment: {},
|
||||
command: ["rea", "mcp"],
|
||||
clients: {},
|
||||
appliedActions: [],
|
||||
}),
|
||||
)
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toBeInstanceOf(ConfigurationError);
|
||||
if (encoding === "malformed UTF-8")
|
||||
expect(failure).toMatchObject({
|
||||
cause: {
|
||||
outcome: { kind: "failed", cause: expect.any(TypeError) },
|
||||
},
|
||||
});
|
||||
expect(failure).toMatchObject({
|
||||
_tag: "ConfigurationError",
|
||||
cause: expect.any(RegularFileCleanupFailure),
|
||||
cleanup: {
|
||||
resources: [client.configPath],
|
||||
reason: expect.stringContaining(
|
||||
"test holds the config handle open",
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(configure).not.toHaveBeenCalled();
|
||||
expect(closeAttempts).toHaveLength(2);
|
||||
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
||||
expect(await readFile(client.configPath)).toEqual(original);
|
||||
|
||||
allowClose = true;
|
||||
const close = host.close;
|
||||
if (close === undefined) throw new Error("Setup host close is missing");
|
||||
expect(await close()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await host.close?.();
|
||||
}
|
||||
});
|
||||
release();
|
||||
expect(await host.close?.()).toBeUndefined();
|
||||
expect(closeAttempts).toHaveLength(3);
|
||||
expect(closeAttempts[2]).toBe(closeAttempts[0]);
|
||||
} finally {
|
||||
release();
|
||||
await host.close?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("waits for an admitted configuration read and rejects later admissions", async () => {
|
||||
const home = await createTestTempDirectory("rea-setup-config-inflight-");
|
||||
|
||||
Reference in New Issue
Block a user