feat(artifacts): inspect classic iNES container regions
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
artifactExtractionResultSchema,
|
||||
} from "../../src/domain/artifactGraph.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { inesFixture } from "../fixtures/ines.js";
|
||||
|
||||
const inventoryFrom = (input: unknown) => {
|
||||
const evidence = parseEvidence(input);
|
||||
expect(evidence.subject).toMatchObject({
|
||||
format: "ines",
|
||||
architecture: null,
|
||||
});
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(inspection.coverage.status).toBe("complete-within-substeps");
|
||||
expect(inspection.observations.map(({ kind }) => kind)).toEqual([
|
||||
"root-manifest",
|
||||
"container-header",
|
||||
"reconstruction",
|
||||
]);
|
||||
const substep = inspection.substeps[0];
|
||||
if (substep === undefined) throw new Error("Missing inventory substep");
|
||||
parseEvidence(substep.evidence);
|
||||
return artifactInventoryResultSchema.parse(
|
||||
substep.evidence.normalized_result,
|
||||
);
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"classic iNES has the same complete byte inventory through compiled CLI and stdio MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-ines-public-");
|
||||
const path = join(root, "卡带.data");
|
||||
const bytes = inesFixture({
|
||||
trainer: true,
|
||||
trailing: Buffer.from([0, 255, 3, 0]),
|
||||
});
|
||||
await writeFile(path, bytes);
|
||||
const cliResult = await cli.run({
|
||||
arguments: ["inspect-artifact", path, "--json"],
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
|
||||
const inventory = inventoryFrom(cliResult.json);
|
||||
const digest = createHash("sha256").update(bytes).digest("hex");
|
||||
expect(inventory.ines).toMatchObject({
|
||||
header: {
|
||||
mapper: 19,
|
||||
trainer_present: true,
|
||||
prg_rom_units_16k: 2,
|
||||
chr_rom_units_8k: 1,
|
||||
},
|
||||
reconstruction: { bytes: bytes.length, sha256: digest, verified: true },
|
||||
});
|
||||
const expected = [
|
||||
["header.bin", 0, 16],
|
||||
["trainer.bin", 16, 512],
|
||||
["prg/000.bin", 528, 16_384],
|
||||
["prg/001.bin", 16_912, 16_384],
|
||||
["chr/000.bin", 33_296, 8_192],
|
||||
["trailing.bin", 41_488, 4],
|
||||
] as const;
|
||||
const nodes = new Map(
|
||||
inventory.nodes.map((node) => [node.artifact_id, node]),
|
||||
);
|
||||
for (const [logical_path, offset, length] of expected) {
|
||||
const occurrence = inventory.occurrences.find(
|
||||
(item) => item.logical_path === logical_path,
|
||||
);
|
||||
if (
|
||||
occurrence?.artifact_id === undefined ||
|
||||
occurrence.artifact_id === null
|
||||
)
|
||||
throw new Error(`Missing region ${logical_path}`);
|
||||
expect(occurrence.source_location).toEqual({ offset, length });
|
||||
expect(nodes.get(occurrence.artifact_id)?.sha256).toBe(
|
||||
createHash("sha256")
|
||||
.update(bytes.subarray(offset, offset + length))
|
||||
.digest("hex"),
|
||||
);
|
||||
}
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const opened = await call("open_binary", { path });
|
||||
if (opened.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(opened)));
|
||||
const inspected = await call("inspect_artifact", {});
|
||||
expect(
|
||||
inspected.isError,
|
||||
JSON.stringify(inspected.structuredContent),
|
||||
).not.toBe(true);
|
||||
expect(inventoryFrom(inspected.structuredContent)).toEqual(inventory);
|
||||
const extracted = await call("extract_artifact", {});
|
||||
expect(
|
||||
extracted.isError,
|
||||
JSON.stringify(extracted.structuredContent),
|
||||
).not.toBe(true);
|
||||
const extraction = artifactExtractionResultSchema.parse(
|
||||
parseEvidence(extracted.structuredContent).normalized_result,
|
||||
);
|
||||
try {
|
||||
expect(extraction.artifacts).toHaveLength(expected.length);
|
||||
expect(
|
||||
Buffer.concat(
|
||||
await Promise.all(
|
||||
expected.map(([region]) =>
|
||||
readFile(join(extraction.output_root, region)),
|
||||
),
|
||||
),
|
||||
),
|
||||
).toEqual(bytes);
|
||||
} finally {
|
||||
// The successful extraction transfers this exact output directory to the caller.
|
||||
await rm(extraction.output_root, { recursive: true, force: true });
|
||||
}
|
||||
await call("close_binary", {});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"unsupported NES containers fail explicitly and leave a valid MCP session usable",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-ines-public-refusal-");
|
||||
const validPath = join(root, "valid.nes");
|
||||
await writeFile(validPath, inesFixture({ chrUnits: 0 }));
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const opened = await call("open_binary", { path: validPath });
|
||||
if (opened.isError)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(opened)));
|
||||
for (const [name, bytes, reason] of [
|
||||
["truncated", inesFixture().subarray(0, 20), "truncated iNES payload"],
|
||||
[
|
||||
"nes2",
|
||||
(() => {
|
||||
const bytes = inesFixture();
|
||||
bytes[7] = 8;
|
||||
return bytes;
|
||||
})(),
|
||||
"nes-2.0",
|
||||
],
|
||||
["unif", Buffer.from("UNIF"), "unif"],
|
||||
] as const) {
|
||||
const path = join(root, `${name}.nes`);
|
||||
await writeFile(path, bytes);
|
||||
const refused = await cli.run({
|
||||
arguments: ["inspect-artifact", path, "--json"],
|
||||
});
|
||||
expect(refused.exitCode).not.toBe(0);
|
||||
expect(JSON.stringify(refused.json)).toContain(reason);
|
||||
const switched = await call("open_binary", { path });
|
||||
expect(switched.isError).toBe(true);
|
||||
expect(JSON.stringify(parseMcpToolError(switched))).toContain(reason);
|
||||
}
|
||||
const retained = await call("inspect_artifact", {});
|
||||
expect(
|
||||
retained.isError,
|
||||
JSON.stringify(retained.structuredContent),
|
||||
).not.toBe(true);
|
||||
const inventory = inventoryFrom(retained.structuredContent);
|
||||
expect(inventory.ines?.header.chr_rom_units_8k).toBe(0);
|
||||
expect(
|
||||
inventory.occurrences.some(({ logical_path }) =>
|
||||
logical_path.startsWith("chr/"),
|
||||
),
|
||||
).toBe(false);
|
||||
await call("close_binary", {});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,212 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstat, open, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { inesFixture } from "../../fixtures/ines.js";
|
||||
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
|
||||
import { InesArtifactReader } from "../../../src/artifacts/InesArtifactReader.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import { extractArtifact } from "../../../src/artifacts/extraction/ArtifactExtraction.js";
|
||||
|
||||
const sha256 = (bytes: Buffer) =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
it("routes iNES bytes as an archive independently of the file suffix", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-target-");
|
||||
const path = join(root, "cartridge.data");
|
||||
await writeFile(path, inesFixture());
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (!target.ok) throw target.error;
|
||||
expect(target.value).toMatchObject({ kind: "archive", format: "ines" });
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"inventories and reconstructs all bytes with trainer=%s",
|
||||
async (trainer) => {
|
||||
const root = await createTestTempDirectory("rea-ines-inventory-");
|
||||
const path = join(root, "fixture.nes");
|
||||
const bytes = inesFixture({
|
||||
trainer,
|
||||
chrUnits: trainer ? 1 : 0,
|
||||
trailing: Buffer.from("retained tail"),
|
||||
});
|
||||
await writeFile(path, bytes);
|
||||
const inventory = await inventoryArtifact(path);
|
||||
expect(inventory.ines?.header).toMatchObject({
|
||||
header_hex: bytes.subarray(0, 16).toString("hex"),
|
||||
mapper: 19,
|
||||
trainer_present: trainer,
|
||||
chr_rom_units_8k: trainer ? 1 : 0,
|
||||
});
|
||||
expect(inventory.ines?.reconstruction).toMatchObject({
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
verified: true,
|
||||
});
|
||||
const children = inventory.occurrences.filter(
|
||||
({ logical_path }) => logical_path !== ".",
|
||||
);
|
||||
const ordered = [...children].sort(
|
||||
(a, b) =>
|
||||
(a.source_location?.offset ?? 0) - (b.source_location?.offset ?? 0),
|
||||
);
|
||||
const nodes = new Map(
|
||||
inventory.nodes.map((node) => [node.artifact_id, node]),
|
||||
);
|
||||
const headerRegion = children.find(
|
||||
({ logical_path }) => logical_path === "header.bin",
|
||||
);
|
||||
if (
|
||||
headerRegion?.artifact_id === undefined ||
|
||||
headerRegion.artifact_id === null
|
||||
)
|
||||
throw new Error("Missing header region");
|
||||
expect(nodes.get(headerRegion.artifact_id)?.format).toBe("file");
|
||||
let offset = 0;
|
||||
for (const occurrence of ordered) {
|
||||
const range = occurrence.source_location;
|
||||
if (range === null || occurrence.artifact_id === null)
|
||||
throw new Error("Missing region identity");
|
||||
expect(range.offset).toBe(offset);
|
||||
const original = bytes.subarray(
|
||||
range.offset,
|
||||
range.offset + range.length,
|
||||
);
|
||||
expect(nodes.get(occurrence.artifact_id)).toMatchObject({
|
||||
sha256: sha256(original),
|
||||
size: range.length,
|
||||
});
|
||||
offset += range.length;
|
||||
}
|
||||
expect(offset).toBe(bytes.length);
|
||||
expect(inventory.ines?.reconstruction.region_order).toEqual(
|
||||
ordered.map(({ logical_path }) => logical_path),
|
||||
);
|
||||
expect(await inventoryArtifact(path)).toEqual(inventory);
|
||||
|
||||
const scope = new ArtifactResourceScope();
|
||||
const outputRoot = join(root, "extracted");
|
||||
try {
|
||||
const extraction = await extractArtifact({
|
||||
inputPath: path,
|
||||
inputFormat: "ines",
|
||||
outputRoot,
|
||||
environment: process.env,
|
||||
integrityPolicy: "fail",
|
||||
resourceScope: scope,
|
||||
});
|
||||
expect(extraction.artifacts).toHaveLength(children.length);
|
||||
const reconstructed = Buffer.concat(
|
||||
await Promise.all(
|
||||
ordered.map(({ logical_path }) =>
|
||||
readFile(join(outputRoot, logical_path)),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(reconstructed).toEqual(bytes);
|
||||
} finally {
|
||||
await scope.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "NES 2.0",
|
||||
bytes: () => {
|
||||
const bytes = inesFixture();
|
||||
bytes[7] = 8;
|
||||
return bytes;
|
||||
},
|
||||
reason: "nes-2.0",
|
||||
},
|
||||
{ name: "UNIF", bytes: () => Buffer.from("UNIF"), reason: "unif" },
|
||||
{
|
||||
name: "truncated",
|
||||
bytes: () => inesFixture().subarray(0, 20),
|
||||
reason: "truncated iNES payload",
|
||||
},
|
||||
])(
|
||||
"refuses $name explicitly through both file entry points",
|
||||
async ({ bytes, reason }) => {
|
||||
const root = await createTestTempDirectory("rea-ines-refusal-");
|
||||
const path = join(root, "invalid.nes");
|
||||
await writeFile(path, bytes());
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: expect.stringContaining(reason) },
|
||||
});
|
||||
await expect(inventoryArtifact(path)).rejects.toMatchObject({
|
||||
reason: "format",
|
||||
message: expect.stringContaining(reason),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("does not select iNES from a .nes suffix", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-suffix-");
|
||||
const path = join(root, "not-a-rom.nes");
|
||||
await writeFile(path, "ordinary bytes");
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("rejects forged region ranges, cancellation and a changed retained source", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-reader-");
|
||||
const path = join(root, "source.nes");
|
||||
await writeFile(path, inesFixture());
|
||||
const handle = await open(path, "r");
|
||||
const reader = new InesArtifactReader(path, {
|
||||
handle,
|
||||
initial: await lstat(path),
|
||||
});
|
||||
try {
|
||||
const iterator = reader.entries()[Symbol.asyncIterator]();
|
||||
const first = await iterator.next();
|
||||
if (first.done) throw new Error("No header region");
|
||||
await expect(
|
||||
reader.open({ ...first.value, byteOffset: 16 }),
|
||||
).rejects.toMatchObject({ reason: "integrity" });
|
||||
await expect(
|
||||
reader.open(first.value, AbortSignal.abort()),
|
||||
).rejects.toMatchObject({ reason: "cancelled" });
|
||||
await writeFile(
|
||||
path,
|
||||
Buffer.concat([inesFixture(), Buffer.from("changed")]),
|
||||
);
|
||||
await expect(reader.open(first.value)).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
});
|
||||
await iterator.return?.();
|
||||
await reader.close();
|
||||
expect((await handle.stat()).size).toBeGreaterThan(0);
|
||||
await expect(reader.open(first.value)).rejects.toMatchObject({
|
||||
reason: "unavailable",
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
await handle.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("releases an extraction-owned source descriptor on repeated close", async () => {
|
||||
const root = await createTestTempDirectory("rea-ines-owned-source-");
|
||||
const path = join(root, "source.nes");
|
||||
await writeFile(path, inesFixture());
|
||||
const handle = await open(path, "r");
|
||||
const owner = new OwnedFileHandle(handle);
|
||||
const reader = new InesArtifactReader(
|
||||
path,
|
||||
{ handle, initial: await handle.stat() },
|
||||
owner,
|
||||
);
|
||||
try {
|
||||
await reader.close();
|
||||
await expect(handle.stat()).rejects.toMatchObject({ code: "EBADF" });
|
||||
await reader.close();
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
/** Source-owned iNES bytes; the payload is test data, not a game ROM. */
|
||||
export const inesFixture = (
|
||||
options: {
|
||||
readonly trainer?: boolean;
|
||||
readonly chrUnits?: number;
|
||||
readonly trailing?: Buffer;
|
||||
} = {},
|
||||
): Buffer => {
|
||||
const header = Buffer.alloc(16);
|
||||
header.write("NES\x1a", "latin1");
|
||||
header[4] = 2;
|
||||
header[5] = options.chrUnits ?? 1;
|
||||
header[6] = 0x31 | (options.trainer === true ? 4 : 0);
|
||||
header[7] = 0x10;
|
||||
return Buffer.concat([
|
||||
header,
|
||||
...(options.trainer === true ? [Buffer.alloc(512, 0x54)] : []),
|
||||
Buffer.alloc(16_384, 0x41),
|
||||
Buffer.alloc(16_384, 0x42),
|
||||
...Array.from({ length: header.readUInt8(5) }, () =>
|
||||
Buffer.alloc(8_192, 0x43),
|
||||
),
|
||||
options.trailing ?? Buffer.alloc(0),
|
||||
]);
|
||||
};
|
||||
Reference in New Issue
Block a user