fix(providers): preserve observations and primary cleanup failures

This commit is contained in:
morluto
2026-10-09 21:01:52 +08:00
parent 88640f60fe
commit 0696bde266
18 changed files with 629 additions and 232 deletions
@@ -5,7 +5,15 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { translateArtifactFailure } from "../../../src/artifacts/ArtifactProvider.js";
import {
ArtifactReaderFailure,
type ArtifactReader,
} from "../../../src/artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js";
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
describe("artifact inventory snapshot", () => {
it("retains the complete scan after the source directory changes", async () => {
@@ -22,4 +30,54 @@ describe("artifact inventory snapshot", () => {
]);
expect(snapshot.manifest.occurrence_count).toBe(3);
});
it("projects the complete inventory when reader cleanup fails after scanning", async () => {
const root = await createTestTempDirectory("rea-inventory-cleanup-");
await writeFile(join(root, "observed.txt"), "observed");
const directory = new DirectoryArtifactReader(root);
const reader: ArtifactReader = {
format: directory.format,
entries: (signal) => directory.entries(signal),
open: (entry, signal) => directory.open(entry, signal),
provenance: () => directory.provenance(),
async close() {
await directory.close();
throw new ArtifactReaderFailure("unavailable", "mount still attached", {
cleanup: {
reason: "DMG detach failed",
resources: ["/dev/disk-test", "/tmp/rea-mount-test"],
},
});
},
};
const failure = await scanCanonicalArtifactInventory(
root,
{},
async () => reader,
).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
if (!(failure instanceof ArtifactReaderFailure))
throw failure instanceof Error
? failure
: new Error("Expected the reader cleanup failure", { cause: failure });
const projection = projectAnalysisError(
translateArtifactFailure("inventory_artifact", failure),
);
expect(projection).toMatchObject({
code: "cleanup_incomplete",
details: {
execution_failure: "artifact_operation_failed",
resources: ["/dev/disk-test", "/tmp/rea-mount-test"],
partial_observation: {
kind: "artifact-inventory",
inventory: {
manifest: { occurrence_count: 2 },
occurrences: expect.arrayContaining([
expect.objectContaining({ logical_path: "observed.txt" }),
]),
},
},
},
});
});
});
@@ -1,5 +1,12 @@
import { createHash } from "node:crypto";
import { access, readFile, readdir, readlink, rm } from "node:fs/promises";
import {
access,
chmod,
readFile,
readdir,
readlink,
rm,
} from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
@@ -8,6 +15,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";
import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
describe("safe artifact output tree", () => {
it.skipIf(process.platform !== "linux")(
@@ -49,6 +57,32 @@ describe("safe artifact output tree", () => {
expect(await readdir(parent)).toEqual([]);
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"reports the owned residual root when rollback lacks directory permissions",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-rollback-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("retained until rollback can retry");
await tree.write(
"nested/file.txt",
Readable.from(bytes),
createHash("sha256").update(bytes).digest("hex"),
);
try {
await chmod(output, 0o500);
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({
cleanup: { resources: [output] },
});
} finally {
await chmod(output, 0o700).catch(() => undefined);
await tree.rollback();
}
},
);
it("publishes files while building and preserves them after sealing", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
@@ -113,143 +113,141 @@ describe("Inspector execution-context lifecycle metadata", () => {
});
});
describe("passive V8 Inspector provider", () => {
test("rejects unknown runtime observation fields", () => {
expect(
observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target-1",
unknown_field: true,
}).success,
).toBe(false);
});
test("rejects unknown runtime observation fields", () => {
expect(
observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target-1",
unknown_field: true,
}).success,
).toBe(false);
});
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetCount: 205,
test("returns every target exposed by the selected Inspector endpoint inline", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetCount: 205,
});
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
try {
const listed = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
} finally {
await fake.close();
}
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
} finally {
await fake.close();
}
});
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetUrl: pathToFileURL(outside).href,
test("includes targets outside the old caller root filter", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("outside.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
additionalTargetUrl: pathToFileURL(outside).href,
});
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
try {
const result = await new V8InspectorProvider().listTargets({
inspector_endpoint: fake.endpoint,
});
if (!result.ok) throw result.error;
expect(result.value.targets).toHaveLength(2);
expect(
result.value.targets.map(({ location }) => location),
).toContainEqual(expect.objectContaining({ file_path: outside }));
} finally {
await fake.close();
}
});
if (!result.ok) throw result.error;
expect(result.value.targets).toHaveLength(2);
expect(result.value.targets.map(({ location }) => location)).toContainEqual(
expect.objectContaining({ file_path: outside }),
);
} finally {
await fake.close();
}
});
test("captures complete metadata with two enable commands", async () => {
test("captures complete metadata with two enable commands", async () => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("secret.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls: [
pathToFileURL(fixture.entry).href,
"node:fs",
pathToFileURL(outside).href,
],
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "1",
state: "created",
name: "node[fixture]",
origin: "",
},
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
);
} finally {
await fake.close();
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
["electron-preload", "page"],
["electron-renderer", "page"],
] as const)(
"admits declared %s only on its protocol target family",
async (runtimeKind, targetType) => {
const fixture = await runtimeFixture();
const outside = await temporaryFile("secret.js");
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
scriptUrls: [
pathToFileURL(fixture.entry).href,
"node:fs",
pathToFileURL(outside).href,
],
targetType,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, "node"),
);
if (!result.ok) throw result.error;
expect(result.value.scripts.items).toHaveLength(3);
expect(result.value.scripts.excluded.unsupported_location).toBe(0);
expect(result.value.execution_contexts).toEqual([
{
context_key: "1",
state: "created",
name: "node[fixture]",
origin: "",
},
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
await fake.close();
}
});
test("excludes an Electron main target that reports only bare file://", async () => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: "file://",
scriptUrls: [pathToFileURL(fixture.entry).href],
});
try {
const provider = new V8InspectorProvider();
const listed = await provider.listTargets({
inspector_endpoint: fake.endpoint,
});
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toEqual([]);
const observed = await provider.observe(
observeInput(fake.endpoint, fake.targetId, "electron-main"),
);
expect(observed.ok).toBe(false);
if (observed.ok) return;
expect(observed.error.message).toMatch(/target/u);
} finally {
await fake.close();
}
});
test.each([
["node", "node"],
["electron-main", "node"],
["electron-preload", "page"],
["electron-renderer", "page"],
] as const)(
"admits declared %s only on its protocol target family",
async (runtimeKind, targetType) => {
const fixture = await runtimeFixture();
const fake = await startFakeV8Inspector({
targetUrl: pathToFileURL(fixture.entry).href,
targetType,
});
try {
const result = await new V8InspectorProvider().observe(
observeInput(fake.endpoint, fake.targetId, runtimeKind),
);
expect(result.ok).toBe(true);
} finally {
await fake.close();
}
},
);
});
},
);
describe("complete Inspector script hashes", () => {
test("keeps more than one hundred long script hashes distinct", async () => {
@@ -1,11 +1,4 @@
import {
access,
mkdir,
readFile,
readdir,
symlink,
writeFile,
} from "node:fs/promises";
import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -14,7 +7,6 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { TOOL_EFFECTS } from "../../../../src/contracts/toolEffects.js";
import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
@@ -22,33 +14,6 @@ import {
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction", () => {
it("declares possible native mounts and fresh extraction directories", () => {
for (const platform of ["linux", "darwin"] as const) {
const provider = new ArtifactProvider(process.env, platform);
for (const operation of [
"inventory_artifact",
"inspect_artifact",
"extract_artifact",
] as const) {
expect(
provider
.capabilities()
.find((capability) => capability.operation === operation)?.effects,
).toMatchObject({ launchesProcess: true, mayWriteFilesystem: true });
}
}
expect(TOOL_EFFECTS.inspect_artifact).toMatchObject({
launchesProcess: true,
writesFilesystem: true,
mutatesTarget: false,
});
expect(TOOL_EFFECTS.extract_artifact).toMatchObject({
launchesProcess: true,
writesFilesystem: true,
idempotent: false,
mutatesTarget: false,
});
});
it("extracts all regular occurrences through an exclusively owned output tree", async () => {
const root = await createTestTempDirectory("rea-extract-");
const source = join(root, "source");
@@ -140,39 +105,6 @@ describe("artifact extraction", () => {
"source",
]);
});
it("refuses a format without an extraction reader before inventory or output", async () => {
const root = await createTestTempDirectory("rea-extract-dmg-");
const image = join(root, "Image.dmg");
await writeFile(image, "not mounted");
// A caller-specific alias must be the path the refusal reports.
const alias = join(root, "Alias.dmg");
await symlink(image, alias);
const output = join(root, "output");
const extract = (signal?: AbortSignal) =>
new ArtifactProvider(process.env)
.createClient(target(alias, "dmg"))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
signal === undefined ? undefined : { signal },
);
expect(await extract()).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
operation: "extract_artifact",
path: alias,
reason: "Artifact format has no extraction reader: dmg",
},
});
const controller = new AbortController();
controller.abort();
expect(await extract(controller.signal)).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
await expect(access(output)).rejects.toThrow();
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider(process.env)
@@ -0,0 +1,56 @@
import { access, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction format support", () => {
it("refuses unsupported formats before inventory or output", async () => {
const root = await createTestTempDirectory("rea-extract-format-");
const image = join(root, "Image.dmg");
await writeFile(image, "not mounted");
const alias = join(root, "Alias.dmg");
await symlink(image, alias);
const output = join(root, "output");
const extract = (signal?: AbortSignal) =>
new ArtifactProvider(process.env)
.createClient(archiveTarget(alias, "dmg"))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
signal === undefined ? undefined : { signal },
);
expect(await extract()).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
operation: "extract_artifact",
path: alias,
reason: "Artifact format has no extraction reader: dmg",
},
});
const controller = new AbortController();
controller.abort();
expect(await extract(controller.signal)).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
await expect(access(output)).rejects.toThrow();
});
});
const archiveTarget = (
path: string,
format: Extract<BinaryTarget, { kind: "archive" }>["format"],
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "archive",
format,
});
@@ -0,0 +1,45 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
describe("artifact extraction identity", () => {
it("uses code-point order for path-independent extraction identities", async () => {
const root = await createTestTempDirectory("rea-extract-order-");
const source = join(root, "source");
await mkdir(source);
for (const name of ["ä.js", "a.js", "Z.js"])
await writeFile(join(source, name), `${name}\n`);
const result = await new ArtifactProvider(process.env)
.createClient(directoryTarget(source))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({
output_root: join(root, "output"),
}),
);
if (!result.ok) throw result.error;
const extracted = artifactExtractionResultSchema.parse(result.value.result);
expect(
extracted.artifacts.map(({ relative_path }) => relative_path),
).toEqual(["Z.js", "a.js", "ä.js"]);
expect(extracted.extraction_manifest.selected_occurrence_ids).toEqual(
[...extracted.extraction_manifest.selected_occurrence_ids].sort(),
);
});
});
const directoryTarget = (path: string): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "archive",
format: "asar",
});
@@ -121,7 +121,14 @@ describe("native DMG artifact reader", () => {
undefined,
host,
),
).rejects.toThrow("cleanup could not detach every device");
).rejects.toMatchObject({
cleanup: {
resources: expect.arrayContaining([
"DMG device /dev/disk-fixture",
expect.stringMatching(/^DMG mount root /u),
]),
},
});
});
});
@@ -570,6 +577,12 @@ describe("APFS disk image detach", () => {
await expect(reader.close()).rejects.toMatchObject({
reason: "unavailable",
message: expect.stringContaining("No such file or directory"),
cleanup: {
resources: expect.arrayContaining([
"DMG device /dev/disk4",
expect.stringMatching(/^DMG mount root /u),
]),
},
});
});