chore: merge main into feat/pkg-inventory

Resolve conflicts against main:
- Inventory moved to src/artifacts/inventory (#1032); point the xar and
  cpio reader imports at their new relative paths.
- README.md: take main's simplified English README, which no longer
  lists individual package formats. PKG coverage stays documented in
  the skill reference and docs/testing.md.
- Skill: the references gain the PKG paragraph, so the version moves to
  29 (main already uses 28).
- Regenerate the product catalog, conformance manifest, skill digest and
  package metadata. The MCP tool catalog is now built rather than
  committed (#997), so it is removed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-08 04:49:54 +00:00
co-authored by Claude Opus 5.5
581 changed files with 29518 additions and 12109 deletions
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
@@ -31,10 +31,7 @@ const observe = async (path: string) => {
describe("artifact comparison summary", () => {
it.each([
{ removed: 1, added: 1 },
{ removed: 1, added: 2 },
{ removed: 2, added: 1 },
{ removed: 0, added: 1 },
{ removed: 1, added: 0 },
{ removed: 0, added: 0 },
])(
"counts unchanged paths with $removed removals and $added additions",
@@ -74,15 +71,6 @@ describe("artifact comparison summary", () => {
contradiction: 0,
});
expect(comparison.changes).toHaveLength(removed + added + changed);
expect(comparison.summary.unchanged + comparison.changes.length).toBe(
3 + removed + added,
);
expect(
comparison.changes.map(({ logical_path }) => logical_path),
).not.toContain("same.txt");
expect(
comparison.changes.map(({ logical_path }) => logical_path),
).not.toContain("duplicate.txt");
},
);
});
@@ -5,7 +5,7 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { canonicalDigest } from "../../../src/domain/comparisonSemantics.js";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { compareArtifacts } from "../../../src/domain/artifactComparison.js";
import type { ArtifactInventoryResult } from "../../../src/domain/artifactGraph.js";
import { createEvidence } from "../../../src/domain/evidence.js";
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { createPackage } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import {
artifactOccurrenceAt,
artifactParentPaths,
@@ -14,10 +14,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const permutations = [
["pkg/", "pkg/sub/", "pkg/sub/data.txt"],
["pkg/", "pkg/sub/data.txt", "pkg/sub/"],
["pkg/sub/", "pkg/", "pkg/sub/data.txt"],
["pkg/sub/", "pkg/sub/data.txt", "pkg/"],
["pkg/sub/data.txt", "pkg/", "pkg/sub/"],
["pkg/sub/data.txt", "pkg/sub/", "pkg/"],
];
const expectedParents = {
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
describe("artifact inventory snapshot", () => {
it("retains the complete scan after the source directory changes", async () => {
@@ -3,15 +3,12 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { classifyArtifactContent } from "../../../src/application/ArtifactGraphConstruction.js";
import { classifyRoot } from "../../../src/application/ArtifactInventory/classify.js";
import { classifyArtifactContent } from "../../../src/artifacts/inventory/ArtifactGraphConstruction.js";
import { classifyRoot } from "../../../src/artifacts/inventory/classify.js";
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../../src/artifacts/ArtifactHash.js";
import { scanCanonicalArtifactInventory } from "../../../src/application/ArtifactInventory/scanCanonical.js";
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
import { targetFormatSchema } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { identifyRuntimes } from "../../../src/domain/runtimeIdentification.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("MZ artifact classification", () => {
@@ -62,7 +59,7 @@ describe("MZ artifact classification", () => {
expect(targetFormatSchema.parse("dos-mz")).toBe("dos-mz");
});
it("keeps standalone and embedded DOS identities through inventory and runtime evidence", async () => {
it("keeps standalone and embedded DOS identities through inventory", async () => {
const directory = await createTestTempDirectory("rea-mz-inventory-");
const dosPath = join(directory, "LEGACY.EXE");
const pePath = join(directory, "NATIVE.EXE");
@@ -88,30 +85,6 @@ describe("MZ artifact classification", () => {
expect(inventory.nodes.map(({ format }) => format)).toEqual(
expect.arrayContaining(["dos-mz", "pe"]),
);
const evidence = createEvidence(
{
path: tree,
sha256: inventory.manifest.root_sha256,
format: "directory",
},
{ id: "inventory-fixture", name: "Inventory fixture", version: null },
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(inventory),
},
);
const runtimes = identifyRuntimes({ inventory_evidence: [evidence] });
expect(runtimes.runtimes).toContainEqual(
expect.objectContaining({
family: "native",
inspection: "provider-selection-required",
observations: expect.arrayContaining([
expect.objectContaining({ path: "LEGACY.EXE", format: "dos-mz" }),
expect.objectContaining({ path: "NATIVE.EXE", format: "pe" }),
]),
}),
);
});
});
@@ -0,0 +1,113 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
it("rejects overlapping ZIP member data ranges through artifact inventory", async () => {
const root = await createTestTempDirectory("rea-zip-overlap-");
const path = join(root, "overlap.zip");
await writeOrderedZip(path, ["a.txt", "b.txt"]);
const bytes = await readFile(path);
const centralDirectorySignature = Buffer.from([0x50, 0x4b, 0x01, 0x02]);
const first = bytes.indexOf(centralDirectorySignature);
const second = bytes.indexOf(centralDirectorySignature, first + 4);
if (first < 0 || second <= first)
throw new Error("Expected two ZIP central-directory entries");
const firstLocalOffset = bytes.readUInt32LE(first + 42);
const secondLocalOffset = bytes.readUInt32LE(second + 42);
expect(secondLocalOffset).not.toBe(firstLocalOffset);
bytes.writeUInt32LE(firstLocalOffset, second + 42);
await writeFile(path, bytes);
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await new ArtifactProvider()
.createClient(target.value)
.execute("inventory_artifact", {});
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("preserves encrypted-member and corrupt-CRC observations", async () => {
const root = await createTestTempDirectory("rea-zip-integrity-");
const encryptedPath = join(root, "encrypted.zip");
const encryptedWriter = new ZipWriter(new Uint8ArrayWriter());
await encryptedWriter.add("secret.txt", new TextReader("secret bytes"), {
password: "fixture-password",
});
await writeFile(encryptedPath, await encryptedWriter.close());
const encryptedTarget = await parseBinaryTarget(encryptedPath);
if (!encryptedTarget.ok) throw encryptedTarget.error;
const encryptedResult = await new ArtifactProvider()
.createClient(encryptedTarget.value)
.execute("inventory_artifact", {});
if (!encryptedResult.ok) throw encryptedResult.error;
const encryptedInventory = artifactInventoryResultSchema.parse(
encryptedResult.value.result,
);
expect(encryptedInventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: "secret.txt",
encrypted: true,
hash_status: "unavailable",
}),
);
const corruptPath = join(root, "corrupt-crc.zip");
const corruptWriter = new ZipWriter(new Uint8ArrayWriter());
await corruptWriter.add("data.txt", new TextReader("evidence\n"));
await writeFile(corruptPath, await corruptWriter.close());
const bytes = await readFile(corruptPath);
const localFileHeaderSignature = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
const localHeader = bytes.indexOf(localFileHeaderSignature);
if (localHeader < 0) throw new Error("Expected a ZIP local-file header");
const dataOffset =
localHeader +
30 +
bytes.readUInt16LE(localHeader + 26) +
bytes.readUInt16LE(localHeader + 28);
const firstByte = bytes[dataOffset];
if (firstByte === undefined) throw new Error("Expected ZIP member bytes");
bytes[dataOffset] = firstByte ^ 1;
await writeFile(corruptPath, bytes);
const corruptTarget = await parseBinaryTarget(corruptPath);
if (!corruptTarget.ok) throw corruptTarget.error;
const corruptResult = await new ArtifactProvider()
.createClient(corruptTarget.value)
.execute("inventory_artifact", {});
expect(corruptResult).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
it("rejects a truncated ZIP through artifact inventory", async () => {
const root = await createTestTempDirectory("rea-zip-malformed-");
const path = join(root, "truncated.zip");
await writeFile(path, Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await new ArtifactProvider()
.createClient(target.value)
.execute("inventory_artifact", {});
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
@@ -11,7 +11,7 @@ import {
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import {
artifactOccurrenceAt,
artifactParentPaths,
@@ -5,7 +5,7 @@ import { buffer } from "node:stream/consumers";
import { createPackage, listPackage, uncache } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
import { inventoryArtifact } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -0,0 +1,474 @@
import { createHash } from "node:crypto";
import { fstatSync, type Stats } from "node:fs";
import {
open as openFile,
lstat,
mkdir,
rm,
readdir,
writeFile,
truncate,
} from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { buffer } from "node:stream/consumers";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import {
closeAsarHandle,
readValidatedAsarEntry,
} from "../../../src/artifacts/AsarEntryStream.js";
import { hashReadable } from "../../../src/artifacts/ArtifactHash.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const memberBytes = 64 * 1024 * 1024;
const expectedSha256 = (): string => {
const hash = createHash("sha256");
const zeros = Buffer.alloc(64 * 1024);
for (let written = 0; written < memberBytes; written += zeros.length)
hash.update(zeros);
return hash.digest("hex");
};
const descriptorDirectory =
process.platform === "darwin" ? "/dev/fd" : "/proc/self/fd";
const matchingDescriptorCount = async (identity: Stats): Promise<number> => {
const descriptors = await readdir(descriptorDirectory);
return descriptors.filter((descriptor) => {
if (!/^\d+$/u.test(descriptor)) return false;
try {
const observed = fstatSync(Number(descriptor));
return observed.dev === identity.dev && observed.ino === identity.ino;
} catch {
return false;
}
}).length;
};
const waitForNoMatchingDescriptor = async (identity: Stats): Promise<void> => {
for (let attempt = 0; attempt < 100; attempt += 1) {
if ((await matchingDescriptorCount(identity)) === 0) return;
await new Promise((resolve) => setTimeout(resolve, 10));
}
expect(await matchingDescriptorCount(identity)).toBe(0);
};
describe("ASAR entry streaming", () => {
it.skipIf(process.platform === "win32")(
"closes a packed member handle when its unopened output stream is destroyed",
async () => {
const root = await createTestTempDirectory(
"rea-asar-destroy-before-read-",
);
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {});
const identity = await lstat(archive);
const probe = await openFile(archive, "r");
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await probe.close();
await waitForNoMatchingDescriptor(identity);
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) {
entries.push(entry);
}
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member");
expect(await matchingDescriptorCount(identity)).toBe(0);
const output = await reader.open(entry);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
const closed = new Promise<void>((resolve) =>
output.once("close", resolve),
);
output.destroy();
await closed;
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"closes a packed member handle when cancellation arrives during open",
async () => {
const root = await createTestTempDirectory("rea-asar-abort-during-stat-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {});
const identity = await lstat(archive);
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member");
const controller = new AbortController();
const opening = reader.open(entry, controller.signal);
controller.abort();
await expect(opening).rejects.toMatchObject({ reason: "cancelled" });
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it("classifies a missing packed member container as an I/O failure", async () => {
const root = await createTestTempDirectory("rea-asar-missing-member-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member");
await rm(archive);
await expect(reader.open(entry)).rejects.toMatchObject({
reason: "io",
cause: { code: "ENOENT" },
});
} finally {
await reader.close();
}
});
});
describe("ASAR entry producer identity", () => {
it.each([false, true] as const)(
"rejects a copied entry with a changed unpacked flag for unpacked=%s",
async (unpacked) => {
const root = await createTestTempDirectory("rea-asar-entry-identity-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(
source,
archive,
unpacked ? { unpack: "small.js" } : {},
);
const selectedPath = unpacked
? join(`${archive}.unpacked`, "small.js")
: archive;
const identity = await lstat(selectedPath);
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected ASAR file entry");
expect(entry.unpacked).toBe(unpacked);
expect(await matchingDescriptorCount(identity)).toBe(0);
if (entry.declaredSize === null)
throw new Error("Expected ASAR file size metadata");
for (const changedEntry of [
{ ...entry, unpacked: !entry.unpacked },
{ ...entry, path: `stale/${entry.path}` },
{ ...entry, declaredSize: entry.declaredSize + 1 },
])
await expect(reader.open(changedEntry)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "integrity",
message: expect.stringContaining(
`ASAR entry metadata changed since inventory: ${entry.path}`,
),
});
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.each([
["packed to unpacked", false],
["unpacked to packed", true],
] as const)(
"rejects a retained %s entry after a new entries pass",
async (_transition, wasUnpacked) => {
const root = await createTestTempDirectory("rea-asar-entry-refresh-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
const memberContents = "module.exports = 1;\n";
await mkdir(source);
await writeFile(join(source, "small.js"), memberContents);
const reader = new AsarArtifactReader(archive);
try {
await createPackageWithOptions(
source,
archive,
wasUnpacked ? { unpack: "small.js" } : {},
);
const firstEntries = [];
for await (const entry of reader.entries()) firstEntries.push(entry);
const retained = firstEntries.find(({ path }) => path === "small.js");
if (retained === undefined)
throw new Error("Expected first ASAR file entry");
const copiedRetained = {
...retained,
limitations: [...retained.limitations],
};
await createPackageWithOptions(
source,
archive,
wasUnpacked ? {} : { unpack: "small.js" },
);
const currentEntries = [];
for await (const entry of reader.entries()) currentEntries.push(entry);
const current = currentEntries.find(({ path }) => path === "small.js");
if (current === undefined)
throw new Error("Expected refreshed ASAR file entry");
expect(current.unpacked).toBe(!wasUnpacked);
await expect(reader.open(copiedRetained)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "integrity",
message: expect.stringContaining(
"ASAR entry metadata changed since inventory",
),
});
expect((await buffer(await reader.open(current))).toString()).toBe(
memberContents,
);
} finally {
await reader.close();
}
},
);
});
describe("ASAR read failures", () => {
it.skipIf(process.platform === "win32")(
"checks cancellation after closing an empty member handle",
async () => {
const root = await createTestTempDirectory("rea-asar-empty-close-");
const archive = join(root, "container.asar");
await writeFile(archive, "container bytes");
const identity = await lstat(archive);
const handle = await openFile(archive, "r");
try {
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
const controller = new AbortController();
await expect(
closeAsarHandle(async () => {
await handle.close();
controller.abort();
}, controller.signal),
).rejects.toMatchObject({ reason: "cancelled" });
await waitForNoMatchingDescriptor(identity);
} finally {
await handle.close().catch(() => undefined);
}
},
);
it.skipIf(process.platform === "win32")(
"closes the opened unpacked file and retains ASAR context when handle stat fails",
async () => {
const root = await createTestTempDirectory("rea-asar-unpacked-stat-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
const unpackedPath = join(`${archive}.unpacked`, "small.js");
const identity = await lstat(unpackedPath);
const ioError = Object.assign(new Error("device stat failed"), {
code: "EIO",
errno: -5,
syscall: "fstat",
});
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
let statCount = 0;
return {
async stat() {
statCount += 1;
if (statCount === 2) throw ioError;
return handle.stat();
},
async close() {
closeCount += 1;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
};
});
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined)
throw new Error("Expected unpacked ASAR member");
await expect(reader.open(entry)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "io",
message: expect.stringContaining(
`Could not read ${entry.path} ASAR at ${archive}: device stat failed`,
),
cause: { code: "EIO", errno: -5, syscall: "fstat" },
});
expect(closeCount).toBe(1);
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.each(["missing", "replaced"] as const)(
"validates the container before returning a zero-length member when it is %s",
async (change) => {
const root = await createTestTempDirectory("rea-asar-empty-member-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "empty.js"), "");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "empty.js");
if (entry === undefined) throw new Error("Expected empty ASAR member");
if (change === "missing") await rm(archive);
else await writeFile(archive, "replacement container");
await expect(reader.open(entry)).rejects.toMatchObject(
change === "missing"
? { reason: "io", cause: { code: "ENOENT" } }
: { reason: "integrity" },
);
} finally {
await reader.close();
}
},
);
it("preserves filesystem errors raised while consuming a member stream", async () => {
const ioError = Object.assign(new Error("device read failed"), {
code: "EIO",
errno: -5,
syscall: "read",
});
const source = Readable.from(
(async function* () {
yield Buffer.from("partial");
throw ioError;
})(),
);
const output = readValidatedAsarEntry(
source,
undefined,
"nested/member.bin",
"/tmp/source.asar",
);
await expect(async () => {
for await (const _chunk of output) {
// Consume through the source failure.
}
}).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "io",
message: expect.stringContaining(
"Could not read nested/member.bin ASAR at /tmp/source.asar",
),
cause: { code: "EIO", errno: -5, syscall: "read" },
});
});
});
describe("ASAR entry streaming", () => {
it("reports the observed digest when an unpacked member changes size", async () => {
const root = await createTestTempDirectory(
"rea-asar-unpacked-size-change-",
);
const source = join(root, "source");
const archive = join(root, "fixture.asar");
const original = join(source, "small.js");
const changed = "changed();\n";
await mkdir(source);
await writeFile(original, "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
await writeFile(join(`${archive}.unpacked`, "small.js"), changed);
await expect(scanArtifactInventory(archive)).rejects.toMatchObject({
reason: "integrity",
details: {
logicalPath: "small.js",
calculatedSha256: createHash("sha256").update(changed).digest("hex"),
unpacked: true,
},
});
});
it.each([
["packed", {}],
["unpacked", { unpack: "large.bin" }],
] as const)(
"opens a %s member without allocating its full contents",
async (_kind, options) => {
const root = await createTestTempDirectory("rea-asar-streaming-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
const member = join(source, "large.bin");
await mkdir(source);
await writeFile(member, Buffer.alloc(0));
await truncate(member, memberBytes);
await createPackageWithOptions(source, archive, options);
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "large.bin");
if (entry === undefined) throw new Error("Expected large ASAR member");
const before = process.memoryUsage().arrayBuffers;
const stream = await reader.open(entry);
const afterOpen = process.memoryUsage().arrayBuffers;
const observed = await hashReadable(stream);
const allocation = afterOpen - before;
expect(allocation).toBeLessThan(memberBytes / 2);
expect(observed).toMatchObject({
sha256: expectedSha256(),
bytes: memberBytes,
});
} finally {
await reader.close();
}
},
120_000,
);
});
@@ -1,18 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { scanAuthorizedArtifactInventory } from "../../../src/application/AuthorizedArtifactInventory.js";
describe("authorized artifact inventory", () => {
it("scans a local artifact without configured input roots", async () => {
const root = await createTestTempDirectory("rea-artifact-roots-");
const path = join(root, "artifact.js");
await writeFile(path, "export const value = 1;\n");
const inventory = await scanAuthorizedArtifactInventory(path);
expect(inventory.manifest.root_format).toBe("javascript-bundle");
});
});
@@ -7,7 +7,7 @@ import { readBoundedFileBytes } from "../../../src/process/BoundedFileBytes.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("bounded file byte reads", () => {
it.each([0, 1, 65_536, 65_537])(
it.each([0, 65_536])(
"accepts a file exactly at the %i byte limit",
async (limit) => {
const root = await createTestTempDirectory("rea-bounded-bytes-");
+29 -6
View File
@@ -7,13 +7,18 @@ import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("CLI JSON input", () => {
it("preserves JSON scalars and distinguishes malformed inline text from files", async () => {
for (const value of [null, false, 0, "text", [], {}])
expect(
await parseCliJsonInput(JSON.stringify(value), "test-input"),
).toEqual({ ok: true, value });
expect(await parseCliJsonInput("{", "test-input")).toMatchObject({
it("distinguishes malformed inline text from files and preserves bracket-prefixed paths", async () => {
expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
ok: false,
error: {
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
},
});
expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
ok: false,
error: {
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
},
});
const root = await createTestTempDirectory("rea-json-input-");
const path = join(root, "input.json");
@@ -22,6 +27,24 @@ describe("CLI JSON input", () => {
ok: true,
value: { value: 1 },
});
expect(await parseCliJsonInput("false", "test-input")).toEqual({
ok: true,
value: false,
});
const bracketPath = join(root, "[input].json");
await writeFile(bracketPath, '["preserved"]');
expect(await parseCliJsonInput(bracketPath, "test-input")).toEqual({
ok: true,
value: ["preserved"],
});
for (const missingPath of [
join(root, "{capture}.json"),
join(root, "[missing].json"),
])
expect(await parseCliJsonInput(missingPath, "test-input")).toMatchObject({
ok: false,
error: { input_path: missingPath, input_reason: "read-failed" },
});
expect(await parseCliJsonInput(root, "test-input")).toMatchObject({
ok: false,
error: { input_reason: "read-failed" },
@@ -15,7 +15,6 @@ import {
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe.each([
@@ -46,68 +45,55 @@ describe.each([
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, original);
const currentCommandPath = join(home, "rea");
for (const command of [
["npx", "-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
[currentCommandPath, "mcp"],
]) {
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
status: "update",
backupPath: `${client.configPath}.rea.backup`,
});
expect(await clientConfigurationAligned(client, {}, command)).toBe(
false,
);
expect(await configureClientConfiguration(client, {}, command)).toEqual(
{
status: "configured",
backupPath: `${client.configPath}.rea.backup`,
},
);
const updated = await readFile(client.configPath, "utf8");
expect(
updated.startsWith(`${bom}// Keep the client preferences.\r\n`),
).toBe(true);
expect(
parseClientConfiguration(updated, client.format).document,
).toEqual({
const command = [currentCommandPath, "mcp"];
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
status: "update",
backupPath: `${client.configPath}.rea.backup`,
});
expect(await clientConfigurationAligned(client, {}, command)).toBe(false);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "configured",
backupPath: `${client.configPath}.rea.backup`,
});
const updated = await readFile(client.configPath, "utf8");
expect(
updated.startsWith(`${bom}// Keep the client preferences.\r\n`),
).toBe(true);
expect(parseClientConfiguration(updated, client.format).document).toEqual(
{
label: "left\uFEFFright",
[serversKey]: {
other: { command: "other" },
rea: clientRegistrationEntry(client.format, command, {}),
},
theme: "dark",
});
expect(await clientConfigurationAligned(client, {}, command)).toBe(
true,
);
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
status: "already_current",
});
expect(
await readClientRegistrationStatuses(home, currentCommandPath, {
platform: "linux",
environment: {},
}),
).toEqual([
{
client: name,
config_path: client.configPath,
state: "aligned",
command,
remediation: null,
},
]);
expect(await configureClientConfiguration(client, {}, command)).toEqual(
{
status: "unchanged",
},
);
expect(await readFile(client.configPath)).toEqual(Buffer.from(updated));
expect(await readFile(`${client.configPath}.rea.backup`)).toEqual(
Buffer.from(original),
);
}
},
);
expect(await clientConfigurationAligned(client, {}, command)).toBe(true);
expect(await inspectClientConfiguration(client, {}, command)).toEqual({
status: "already_current",
});
expect(
await readClientRegistrationStatuses(home, currentCommandPath, {
platform: "linux",
environment: {},
}),
).toEqual([
{
client: name,
config_path: client.configPath,
state: "aligned",
command,
remediation: null,
},
]);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await readFile(client.configPath)).toEqual(Buffer.from(updated));
expect(await readFile(`${client.configPath}.rea.backup`)).toEqual(
Buffer.from(original),
);
},
);
});
@@ -34,25 +34,23 @@ describe("client configuration write failures", () => {
});
describe("TOML client configuration comparison", () => {
it.each(["nan", "inf", "-inf"])(
"replaces a registration containing %s and preserves unrelated settings",
async (value) => {
const root = await createTestTempDirectory("rea-client-toml-");
const configPath = join(root, "config.toml");
const original = `unrelated = ${value}\n[mcp_servers.rea]\ncommand = "old"\nstartup_timeout_sec = ${value}\n`;
await writeFile(configPath, original);
const client = { name: "codex", format: "toml", configPath } as const;
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "configured",
backupPath: `${configPath}.rea.backup`,
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(configPath, "utf8")).toContain(
`unrelated = ${value}`,
);
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "unchanged",
});
},
);
it("replaces a registration containing a non-finite TOML float and preserves unrelated settings", async () => {
const value = "-inf";
const root = await createTestTempDirectory("rea-client-toml-");
const configPath = join(root, "config.toml");
const original = `unrelated = ${value}\n[mcp_servers.rea]\ncommand = "old"\nstartup_timeout_sec = ${value}\n`;
await writeFile(configPath, original);
const client = { name: "codex", format: "toml", configPath } as const;
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "configured",
backupPath: `${configPath}.rea.backup`,
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(configPath, "utf8")).toContain(
`unrelated = ${value}`,
);
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "unchanged",
});
});
});
@@ -1,12 +1,20 @@
import { copyFile, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import { spawn, spawnSync } from "node:child_process";
import {
copyFile,
mkdir,
readFile,
readdir,
writeFile,
symlink,
} from "node:fs/promises";
import { dirname, join, relative } 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,
@@ -88,4 +96,175 @@ describe("dependency install freshness", () => {
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.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);
});
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 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/clean-build-output.mjs",
"scripts/generate-package-metadata.mjs",
"scripts/lib/generated-file.mjs",
"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,
build: "node scripts/cache-fixture-build.mjs",
},
}),
);
await writeFile(
join(root, "scripts/cache-fixture-build.mjs"),
'import { mkdir, writeFile } from "node:fs/promises"; await mkdir("dist", { recursive: true }); await writeFile("dist/cache-fixture.js", "built");\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[]) =>
run("npm", arguments_, cwd);
const runTurbo = (cwd: string) =>
run(
process.execPath,
[
join(cwd, "node_modules", "turbo", "bin", "turbo"),
"run",
"build",
"--output-logs=full",
],
cwd,
);
const run = (
command: string,
arguments_: readonly string[],
cwd: string,
): Promise<{
readonly status: number;
readonly stdout: string;
readonly stderr: string;
}> =>
new Promise((resolve, reject) => {
const child = spawn(command, [...arguments_], {
cwd,
env: process.env,
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;
@@ -54,7 +54,7 @@ describe("direct analysis snapshot files", () => {
});
});
it("replays a cache hit from the supplied path without root configuration", async () => {
it("does not replay unbound historical Evidence from a supplied snapshot", async () => {
const directory = await createTestTempDirectory("rea-direct-snapshot-");
const snapshotPath = join(directory, "analysis.json");
const launcherPath = join(directory, "hopper-launcher");
@@ -97,6 +97,6 @@ describe("direct analysis snapshot files", () => {
snapshotPath,
},
),
).resolves.toEqual(evidence);
).resolves.not.toEqual(evidence);
});
});
+26 -29
View File
@@ -6,36 +6,33 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("DOS COM admission", () => {
it.each(["fixture.com", "fixture.hop", "fixture.js", "fixture.bin"])(
"requires explicit interpretation for %s",
async (name) => {
const directory = await createTestTempDirectory("rea-com-target-");
const path = join(directory, name);
const bytes = Buffer.from("b83412c3", "hex");
await writeFile(path, bytes);
const target = await parseBinaryTarget(
it("requires explicit interpretation even when a DOS COM uses a misleading suffix", async () => {
const directory = await createTestTempDirectory("rea-com-target-");
const path = join(directory, "fixture.js");
const bytes = Buffer.from("b83412c3", "hex");
await writeFile(path, bytes);
const target = await parseBinaryTarget(
path,
directory,
"arm64",
undefined,
"dos-com",
);
expect(target).toMatchObject({
ok: true,
value: {
path,
directory,
"arm64",
undefined,
"dos-com",
);
expect(target).toMatchObject({
ok: true,
value: {
path,
format: "dos-com",
kind: "executable",
architecture: "x86",
availableArchitectures: ["x86"],
sha256: createHash("sha256").update(bytes).digest("hex"),
},
});
expect(await readFile(path)).toEqual(bytes);
const detected = await parseBinaryTarget(path);
expect(detected.ok && detected.value.format).not.toBe("dos-com");
},
);
format: "dos-com",
kind: "executable",
architecture: "x86",
availableArchitectures: ["x86"],
sha256: createHash("sha256").update(bytes).digest("hex"),
},
});
expect(await readFile(path)).toEqual(bytes);
const detected = await parseBinaryTarget(path);
expect(detected.ok && detected.value.format).not.toBe("dos-com");
});
it.each([0, 0xff01])("rejects invalid file extent %i", async (length) => {
const directory = await createTestTempDirectory("rea-com-target-");
const path = join(directory, "fixture.com");
+138 -41
View File
@@ -30,18 +30,22 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
expect(await readdir(fixture.temporary)).toEqual([]);
});
it.each(["22.19.0", "24.11.0", "26.0.0", "27.0.0"])(
it.each(["22.19.0", "24.11.0", "26.0.0"])(
"accepts supported Node %s without installing or replacing it",
async (version) => {
const fixture = await createFixture();
const result = await runInstaller(fixture, ["--version", "0.3.0"], {
FAKE_NODE_VERSION: version,
});
const result = await runInstaller(
fixture,
["--version", "0.3.0", "--dry-run"],
{
FAKE_NODE_VERSION: version,
},
);
expect(result.stdout).toContain(`Runtime: Node.js ${version}`);
},
);
it.each(["22.18.9", "23.0.0", "24.10.9", "25.1.0", "26.0.0-rc.1"])(
it.each(["22.18.9", "24.10.9", "23.0.0", "26.0.0-rc.1"])(
"rejects unsupported Node %s before invoking npm",
async (version) => {
const fixture = await createFixture();
@@ -77,15 +81,7 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
});
});
// Every installer failure must carry a recovery action. AGENTS.md requires
// actionable diagnostics, including for mismatch locations, so a failure that
// only states what went wrong is a regression.
// The installer is the one surface whose output is read directly by a person
// in a terminal, so the exact wording is a real contract and stays pinned.
// Alongside it, each row asserts the two properties that matter
// independently of phrasing: the failure is announced as a REA installation
// failure, and the message carries a recovery action. A copy edit then shows
// up as one reviewable diff instead of silently losing the guidance.
// Keep each distinct failure route while checking its reason and recovery.
it.each([
[
"unsupported Node",
@@ -158,11 +154,6 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
expect(failure).toBeInstanceOf(Error);
const stderr = String((failure as { stderr?: unknown }).stderr ?? "");
expect(stderr).toBe(message);
expect(stderr.startsWith("REA installation failed: ")).toBe(true);
// Actionable guidance must survive any rewording.
expect(stderr).toMatch(
/\b(?:Check|Repair|Reinstall|Install|Retry|then retry|use Node)\b/,
);
expect(await readdir(fixture.temporary)).toEqual([]);
},
);
@@ -181,6 +172,95 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
});
});
describe("installer semantic version parsing", { timeout: 20_000 }, () => {
it.each(["1.2.3-01"])(
"rejects malformed semantic versions before invoking npm: %s",
async (version) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, ["--version", version, "--dry-run"]),
).rejects.toMatchObject({
stderr:
"REA installation failed: version must be an exact semantic version.\n",
});
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
it("rejects valid build metadata before printing a plan or invoking npm", async () => {
const fixture = await createFixture();
const failure = await runInstaller(fixture, [
"--version",
"1.2.3+build.01",
"--dry-run",
]).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(Error);
const stderr = getProcessOutput(failure, "stderr");
expect(stderr).toBe(
"REA installation failed: npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry.\n",
);
expect(getProcessOutput(failure, "stdout")).not.toContain(
"REA install plan",
);
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("accepts a valid prerelease version without build metadata", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, [
"--version",
"1.2.3-alpha.0",
"--dry-run",
]);
expect(result.stdout).toContain("Version: 1.2.3-alpha.0");
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("rejects build metadata in the latest release tag before printing a plan", async () => {
const fixture = await createFixture();
const failure = await runInstaller(fixture, [], {
FAKE_CURL_BODY: '{"tag_name":"rea-agents-1.2.3+build.01"}',
}).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(Error);
expect(getProcessOutput(failure, "stderr")).toBe(
"REA installation failed: npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry.\n",
);
expect(getProcessOutput(failure, "stdout")).not.toContain(
"REA install plan",
);
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("rejects an invalid semantic version from the latest release tag", async () => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, [], {
FAKE_CURL_BODY: '{"tag_name":"rea-agents-1.2.3-01"}',
}),
).rejects.toMatchObject({
stderr:
"REA installation failed: the latest release tag was invalid. Retry later or pass --version VERSION.\n",
});
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
});
interface InstallerFixture {
readonly home: string;
readonly bin: string;
@@ -189,6 +269,20 @@ interface InstallerFixture {
readonly reaLog: string;
}
const getProcessOutput = (
failure: unknown,
stream: "stdout" | "stderr",
): string => {
if (!(failure instanceof Error)) return "";
if (stream === "stdout" && "stdout" in failure) {
return typeof failure.stdout === "string" ? failure.stdout : "";
}
if (stream === "stderr" && "stderr" in failure) {
return typeof failure.stderr === "string" ? failure.stderr : "";
}
return "";
};
const createFixture = async (): Promise<InstallerFixture> => {
const root = await createTestTempDirectory("rea-install-test-");
const home = join(root, "home");
@@ -197,19 +291,20 @@ const createFixture = async (): Promise<InstallerFixture> => {
const npmLog = join(root, "npm.log");
const reaLog = join(root, "rea.log");
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
await executable(
join(bin, "uname"),
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
);
await executable(
join(bin, "node"),
`#!/bin/sh
await Promise.all([
executable(
join(bin, "uname"),
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
),
executable(
join(bin, "node"),
`#!/bin/sh
if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else exec ${shellQuote(process.execPath)} "$@"; fi
`,
);
await executable(
join(bin, "npm"),
`#!/bin/sh
),
executable(
join(bin, "npm"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
[ "$1" = "prefix" ] && { [ "\${FAKE_NPM_PREFIX_FAIL:-}" = "1" ] && exit 1; printf '%s\n' "$FAKE_NPM_PREFIX"; exit 0; }
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
@@ -223,25 +318,27 @@ mkdir -p "$prefix/bin"
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
chmod +x "$prefix/bin/rea"
`,
);
await executable(
join(bin, "curl"),
`#!/bin/sh
),
executable(
join(bin, "curl"),
`#!/bin/sh
[ "\${FAKE_CURL_FAIL:-}" = "1" ] && exit 1
if [ -n "\${FAKE_CURL_BODY:-}" ]; then printf '%s' "$FAKE_CURL_BODY"; else printf '%s' '{"tag_name":"rea-agents-0.3.0"}'; fi
`,
);
await executable(
join(bin, "rea-source"),
`#!/bin/sh
),
executable(
join(bin, "rea-source"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
[ "\${FAKE_REA_VERSION_FAIL:-}" = "1" ] && exit 1
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
exit 0
`,
);
for (const command of ["chmod", "cp", "mkdir", "tr"])
await symlink(`/usr/bin/${command}`, join(bin, command));
),
...["chmod", "cp", "mkdir", "tr"].map((command) =>
symlink(`/usr/bin/${command}`, join(bin, command)),
),
]);
return { home, bin, temporary, npmLog, reaLog };
};
@@ -13,6 +13,57 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const compile = promisify(execFile);
type PlistValue =
| string
| number
| boolean
| Date
| Uint8Array
| PlistValue[]
| { [key: string]: PlistValue }
| null;
const keyedArchiveHierarchy = (
nodes: readonly {
readonly id: string;
readonly children: readonly number[];
}[],
) => {
const nodeClass = 1 + nodes.length * 2;
const arrayClass = nodeClass + 1;
const objects: PlistValue[] = Array.from(
{ length: arrayClass + 1 },
() => null,
);
objects[0] = "$null";
for (const [index, node] of nodes.entries()) {
const nodeUid = 1 + index * 2;
objects[nodeUid] = {
$class: { UID: nodeClass },
objectID: node.id,
children: { UID: nodeUid + 1 },
};
objects[nodeUid + 1] = {
$class: { UID: arrayClass },
"NS.objects": node.children.map((child) => ({ UID: 1 + child * 2 })),
};
}
objects[nodeClass] = {
$classname: "FixtureHierarchyNode",
$classes: ["FixtureHierarchyNode", "NSObject"],
};
objects[arrayClass] = {
$classname: "__NSArrayI",
$classes: ["__NSArrayI", "NSArray", "NSObject"],
};
return buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: objects,
$top: { root: { UID: 1 } },
});
};
describe("compiled Interface Builder bundle reader", () => {
it("reads nib plist archives and reports provenance", async () => {
const root = await createTestTempDirectory("rea-ib-test-");
@@ -149,7 +200,118 @@ describe("compiled Interface Builder bundle reader", () => {
},
]);
});
});
describe("keyed archive hierarchy coverage", () => {
it("projects a deep keyed-archive hierarchy through NSArray wrappers", async () => {
const root = await createTestTempDirectory("rea-ib-test-");
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const nodes = Array.from({ length: 40 }, (_, index) => ({
id: `view-${index}`,
children: index === 39 ? [] : [index + 1],
}));
await writeFile(join(resources, "Deep.nib"), keyedArchiveHierarchy(nodes));
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "f".repeat(64),
});
expect(analysis.documents[0]?.hierarchy_complete).toBe(true);
expect(analysis.graph.truncated).toBe(false);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Contents/Resources/Deep.nib",
status: "complete",
omitted: 0,
}),
);
expect(
analysis.graph.edges.filter(
({ relation, id }) =>
relation === "contains" && id.includes(":hierarchy:"),
),
).toHaveLength(40);
});
it("preserves source order for children in an archived collection", async () => {
const root = await createTestTempDirectory("rea-ib-test-");
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await writeFile(
join(resources, "Branching.nib"),
keyedArchiveHierarchy([
{ id: "root", children: [1, 2] },
{ id: "first", children: [] },
{ id: "second", children: [] },
]),
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "e".repeat(64),
});
const archiveIdsByNodeId = new Map(
analysis.graph.nodes.map(({ id, attributes }) => [
id,
attributes.interface_builder_object_id,
]),
);
const rootId = analysis.graph.nodes.find(
({ attributes }) => attributes.interface_builder_object_id === "root",
)?.id;
const childNames = analysis.graph.edges
.filter(
({ from, relation, id }) =>
from === rootId &&
relation === "contains" &&
id.includes(":hierarchy:"),
)
.map(({ to }) => (to === null ? null : archiveIdsByNodeId.get(to)));
expect(childNames).toEqual(["first", "second"]);
});
it.skipIf(process.platform !== "darwin")(
"projects a deep NSView archive produced by Foundation NSKeyedArchiver",
async () => {
const root = await createTestTempDirectory("rea-ib-test-");
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const archive = join(resources, "Foundation.nib");
await compile("/usr/bin/xcrun", [
"swift",
"tests/conformance/native/keyed-archive-hierarchy.swift",
archive,
"40",
]);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "d".repeat(64),
});
expect(analysis.documents[0]?.hierarchy_complete).toBe(true);
expect(analysis.graph.truncated).toBe(false);
expect(
analysis.graph.coverage.find(
({ facet }) =>
facet === "hierarchy:Contents/Resources/Foundation.nib",
),
).toMatchObject({ status: "complete", examined: 41, omitted: 0 });
expect(
analysis.graph.edges.filter(
({ relation, id }) =>
relation === "contains" && id.includes(":hierarchy:"),
),
).toHaveLength(41);
},
);
});
describe("compiled Interface Builder bundle reader cancellation", () => {
it("honors cancellation during directory traversal", async () => {
const root = await createTestTempDirectory("rea-ib-test-");
const controller = new AbortController();
@@ -1,10 +1,10 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { lstat, mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { DirectoryArtifactReader } from "../../../src/artifacts/DirectoryArtifactReader.js";
@@ -86,6 +86,24 @@ describe("JavaScript artifact ingestion content identities", () => {
}
});
it("rejects a same-size ASAR replacement against the inventoried root digest", async () => {
const { source, archive } = await fixture();
const snapshot = await scanArtifactInventory(archive);
const original = await lstat(archive);
await writeFile(join(source, "main.js"), "module.exports = 43;\n");
await createPackage(source, archive);
expect((await lstat(archive)).size).toBe(original.size);
const reader = new AsarArtifactReader(archive);
try {
await expect(
readJavaScriptArtifactFiles(reader, snapshot),
).rejects.toMatchObject({ reason: "integrity" });
} finally {
await reader.close();
}
});
it("preserves typed cancellation when the direct ASAR filesystem stream aborts", async () => {
const { archive } = await fixture();
const snapshot = await scanArtifactInventory(archive);
@@ -8,7 +8,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
import { reconstructJavaScriptArtifact } from "../../../src/application/javascript/JavaScriptArtifactReconstruction.js";
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
import { scanArtifactInventory } from "../../../src/artifacts/inventory/ArtifactInventory.js";
import {
type ArtifactEntry,
type ArtifactReader,
@@ -88,6 +88,21 @@ describe("JavaScript export return-shape comparison", () => {
expect(result.coverage.status).toBe("partial");
});
it("orders multiple changed paths deterministically across Unicode names", async () => {
const graphs = await analyzeSources({
left: `export default () => ({ type: "item", zeta: 1, alpha: 1, "éclair": 1 });`,
right: `export default () => ({ type: "item", zeta: 2, alpha: 2, "éclair": 2 });`,
});
const first = compare(...graphs);
const second = compare(...graphs);
expect(new Set(first.changes.map(({ path }) => path))).toEqual(
new Set(["/alpha", "/zeta", "/éclair"]),
);
expect(first.changes).toEqual(second.changes);
expect(first.comparison_id).toBe(second.comparison_id);
});
it("does not pair discriminants that an unknown trailing spread can overwrite", async () => {
const [left, right] = await analyzeSources({
left: `
+22 -25
View File
@@ -5,31 +5,28 @@ import { readJsonFile } from "../../../src/application/JsonFiles.js";
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("JSON file UTF-8 byte integrity", () => {
it.each([0x80, 0xe9, 0xff])(
"rejects invalid UTF-8 byte %s through both file input boundaries",
async (invalidByte) => {
const root = await createTestTempDirectory("rea-json-utf8-");
const path = join(root, "input.json");
await writeFile(
path,
Buffer.concat([
Buffer.from('{"message":"'),
Buffer.from([invalidByte]),
Buffer.from('"}'),
]),
);
const fileInput = await readJsonFile(path);
const cliInput = await parseCliJsonInput(path, "compare_web_captures");
expect(fileInput).toMatchObject({
ok: false,
error: { reason: "invalid-json" },
});
expect(cliInput).toMatchObject({
ok: false,
error: { input_reason: "invalid-json" },
});
},
);
it("rejects invalid UTF-8 through both file input boundaries", async () => {
const root = await createTestTempDirectory("rea-json-utf8-");
const path = join(root, "input.json");
await writeFile(
path,
Buffer.concat([
Buffer.from('{"message":"'),
Buffer.from([0x80]),
Buffer.from('"}'),
]),
);
const fileInput = await readJsonFile(path);
const cliInput = await parseCliJsonInput(path, "compare_web_captures");
expect(fileInput).toMatchObject({
ok: false,
error: { reason: "invalid-json" },
});
expect(cliInput).toMatchObject({
ok: false,
error: { input_reason: "invalid-json" },
});
});
it("preserves a legitimate UTF-8 replacement character", async () => {
const root = await createTestTempDirectory("rea-json-utf8-control-");
const path = join(root, "input.json");
@@ -11,16 +11,12 @@ it("imports test-suffixed filenames with unchanged paths, hashes, and languages"
const root = await createTestTempDirectory("rea-reference-test-filenames-");
const files = [
["main_test.go", "package main\n", ["source", "test"], "Go"],
["main_test.py", "assert True\n", ["source", "test"], "Python"],
["test_helper.py", "assert True\n", ["source", "test"], "Python"],
["parser_spec.rs", "fn checks() {}\n", ["source", "test"], "Rust"],
["Widget_SPEC.TS", "export {};\n", ["source", "test"], "TypeScript"],
["main_test", "test fixture\n", ["test"], null],
["main_spec", "spec fixture\n", ["test"], null],
["test_helper.py", "assert True\n", ["source", "test"], "Python"],
["main.test.js", "export {};\n", ["source", "test"], "JavaScript"],
["main.go", "package main\n", ["source"], "Go"],
["main_test_helper.py", "value = 1\n", ["source"], "Python"],
["main_specimen.rs", "fn main() {}\n", ["source"], "Rust"],
["main_test.py.bak", "backup\n", ["unknown"], null],
] as const;
await Promise.all(
@@ -1,8 +1,420 @@
import { readFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execFileAsync = promisify(execFile);
const stepSchema = z.object({
name: z.string().optional(),
uses: z.string().optional(),
run: z.string().optional(),
if: z.string().optional(),
with: z.record(z.string(), z.unknown()).optional(),
env: z.record(z.string(), z.unknown()).optional(),
});
const jobSchema = z.object({
if: z.string().optional(),
outputs: z.record(z.string(), z.string()).optional(),
steps: z.array(stepSchema),
});
async function readReleaseWorkflow() {
return z
.object({
on: z.record(z.string(), z.unknown()),
jobs: z.object({
"release-please": jobSchema,
publish: jobSchema,
"publish-mcp": jobSchema,
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/release.yml", import.meta.url),
"utf8",
),
),
);
}
it("requires explicit release preparation or publication instead of main pushes", async () => {
const workflow = await readReleaseWorkflow();
expect(Object.keys(workflow.on)).toEqual(["workflow_dispatch"]);
expect(workflow.on.workflow_dispatch).toMatchObject({
inputs: {
release_branch: { required: true, type: "string" },
phase: {
required: true,
type: "choice",
default: "prepare",
options: ["prepare", "publish"],
},
},
});
const release = workflow.jobs["release-please"].steps.find((step) =>
step.uses?.startsWith("googleapis/release-please-action@"),
);
expect(release?.with).toMatchObject({
token: "${{ secrets.RELEASE_PLEASE_TOKEN || secrets.GITHUB_TOKEN }}",
"target-branch": "${{ inputs.release_branch }}",
"skip-github-release": "${{ inputs.phase == 'prepare' }}",
"skip-github-pull-request": "${{ inputs.phase == 'publish' }}",
});
const catalogCommit = workflow.jobs["release-please"].steps.find(
(step) => step.name === "Commit canonical release catalog",
);
expect(catalogCommit?.env?.GH_TOKEN).toBe(
"${{ secrets.RELEASE_PLEASE_TOKEN || secrets.GITHUB_TOKEN }}",
);
});
it.skipIf(process.platform === "win32").each([
{ phase: "prepare", customToken: "" },
{ phase: "publish", customToken: "" },
{ phase: "prepare", customToken: "fixture-custom-token" },
{ phase: "publish", customToken: "fixture-custom-token" },
])(
"accepts $phase with optional custom credentials: $customToken",
async ({ phase, customToken }) => {
const workflow = await readReleaseWorkflow();
const steps = workflow.jobs["release-please"].steps;
const actionIndex = steps.findIndex((step) =>
step.uses?.startsWith("googleapis/release-please-action@"),
);
expect(actionIndex).toBeGreaterThanOrEqual(0);
const commands = steps
.slice(0, actionIndex)
.filter(
(step) =>
step.if === undefined ||
(phase === "publish" && step.if === "inputs.phase == 'publish'"),
)
.map((step) => z.string().parse(step.run));
const directory = await createTestTempDirectory("rea-release-credential-");
const output = join(directory, "github-output");
await writeFile(
join(directory, "gh"),
'#!/bin/sh\nprintf "%s\\n" "$GITHUB_SHA"\n',
{ mode: 0o755 },
);
await expect(
execFileAsync(
"bash",
["-e", "-o", "pipefail", "-c", commands.join("\n")],
{
env: {
...process.env,
PATH: `${directory}${delimiter}${process.env.PATH ?? ""}`,
RELEASE_PLEASE_TOKEN: customToken,
GH_TOKEN: customToken || "fixture-built-in-token",
RELEASE_PHASE: phase,
RELEASE_BRANCH: "release/5.0.0",
GITHUB_REF:
phase === "prepare"
? "refs/heads/main"
: "refs/heads/release/5.0.0",
GITHUB_REPOSITORY: "fixture/fixture",
GITHUB_SHA: "1111111111111111111111111111111111111111",
BRANCH_SHA: "1111111111111111111111111111111111111111",
GITHUB_OUTPUT: output,
},
},
),
).resolves.toMatchObject({ stderr: "" });
expect(await readFile(output, "utf8")).toBe(
"sha=1111111111111111111111111111111111111111\n",
);
},
);
it("binds npm and MCP publication to the same immutable release SHA", async () => {
const workflow = await readReleaseWorkflow();
expect(workflow.jobs["release-please"].outputs).toEqual({
release_created: "${{ steps.release.outputs.release_created }}",
sha: "${{ steps.release.outputs.sha }}",
});
expect(workflow.jobs.publish.if).toBe(
"inputs.phase == 'publish' && needs.release-please.outputs.release_created == 'true'",
);
expect(workflow.jobs["publish-mcp"].if).toBe(
"inputs.phase == 'publish' && needs.release-please.outputs.release_created == 'true' && needs.publish.result == 'success'",
);
for (const job of [workflow.jobs.publish, workflow.jobs["publish-mcp"]]) {
const checkout = job.steps.find((step) =>
step.uses?.startsWith("actions/checkout@"),
);
expect(checkout?.with).toMatchObject({
ref: "${{ needs.release-please.outputs.sha }}",
"persist-credentials": false,
});
}
const preparation = [
"Check out release pull request",
"Set up Node.js for generated documentation",
"Install dependencies",
"Regenerate release documentation",
"Commit canonical release catalog",
];
for (const name of preparation) {
expect(
workflow.jobs["release-please"].steps.find((step) => step.name === name)
?.if,
).toBe(
"inputs.phase == 'prepare' && steps.release.outputs.prs_created == 'true'",
);
}
});
it
.skipIf(process.platform === "win32")
.each(["main", "feature/new-work", "release/", "release/../main"])(
"rejects %s as a checkpoint before contacting GitHub",
async (releaseBranch) => {
const workflow = await readReleaseWorkflow();
const command = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) => step.name === "Validate release selection",
)?.run,
);
await expect(
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
env: {
...process.env,
GITHUB_REF: "refs/heads/main",
RELEASE_BRANCH: releaseBranch,
RELEASE_PHASE: "prepare",
},
}),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringMatching(/release_branch/u),
});
},
);
it.skipIf(process.platform === "win32").each([
{ phase: "prepare", ref: "refs/heads/feature/unreviewed-workflow" },
{ phase: "publish", ref: "refs/heads/main" },
{ phase: "publish", ref: "refs/heads/release/another-version" },
])(
"rejects $phase from $ref before contacting GitHub",
async ({ phase, ref }) => {
const workflow = await readReleaseWorkflow();
const command = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) => step.name === "Validate release selection",
)?.run,
);
await expect(
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
env: {
...process.env,
GITHUB_REF: ref,
RELEASE_BRANCH: "release/5.0.0",
RELEASE_PHASE: phase,
},
}),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(`Run ${phase} from`),
});
},
);
it.skipIf(process.platform === "win32")(
"checks the checkpoint locally and resolves the branch tip separately",
async () => {
const workflow = await readReleaseWorkflow();
const validate = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) => step.name === "Validate release selection",
)?.run,
);
expect(validate).not.toMatch(/\bgh\b/u);
const resolve = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) => step.name === "Resolve release branch tip",
)?.run,
);
expect(resolve).toContain("gh api");
for (const releaseBranch of ["release/5.0.0", "release/5.0.0-rc.1"]) {
await expect(
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", validate], {
env: {
...process.env,
GITHUB_REF: "refs/heads/main",
RELEASE_BRANCH: releaseBranch,
RELEASE_PHASE: "prepare",
},
}),
).resolves.toMatchObject({ stderr: "" });
}
},
);
it
.skipIf(process.platform === "win32")
.each(["", "release", "prepare ", "true"])(
"rejects phase %j before contacting GitHub",
async (phase) => {
const workflow = await readReleaseWorkflow();
const command = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) => step.name === "Validate release selection",
)?.run,
);
await expect(
execFileAsync("bash", ["-e", "-o", "pipefail", "-c", command], {
env: {
...process.env,
GITHUB_REF: "refs/heads/main",
RELEASE_BRANCH: "release/5.0.0",
RELEASE_PHASE: phase,
},
}),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("phase must be prepare or publish"),
});
},
);
it.skipIf(process.platform === "win32").each([true, false])(
"creates a release only when the branch tip is the dispatched checkpoint (match: %s)",
async (match) => {
const workflow = await readReleaseWorkflow();
const command = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) =>
step.name ===
"Require the publish dispatch to match the branch tip",
)?.run,
);
const result = execFileAsync(
"bash",
["-e", "-o", "pipefail", "-c", command],
{
env: {
...process.env,
GITHUB_SHA: "1111111111111111111111111111111111111111",
BRANCH_SHA: match
? "1111111111111111111111111111111111111111"
: "2222222222222222222222222222222222222222",
},
},
);
if (match) {
await expect(result).resolves.toMatchObject({ stderr: "" });
} else {
await expect(result).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(
"refusing to create a release for a moved source",
),
});
}
},
);
it.skipIf(process.platform === "win32").each([true, false])(
"publishes only when the tag and provenance source match (match: %s)",
async (match) => {
const workflow = await readReleaseWorkflow();
const command = z
.string()
.parse(
workflow.jobs["release-please"].steps.find(
(step) =>
step.name === "Bind publication to the dispatched checkpoint",
)?.run,
);
const result = execFileAsync(
"bash",
["-e", "-o", "pipefail", "-c", command],
{
env: {
...process.env,
GITHUB_SHA: "1111111111111111111111111111111111111111",
RELEASE_SHA: match
? "1111111111111111111111111111111111111111"
: "2222222222222222222222222222222222222222",
},
},
);
if (match) {
await expect(result).resolves.toMatchObject({ stderr: "" });
} else {
await expect(result).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(
"refusing to publish mismatched source provenance",
),
});
}
},
);
it("runs release PR CI without enabling implementation pushes on release branches", async () => {
const workflow = z
.object({
on: z.object({
push: z.object({ branches: z.array(z.string()) }),
pull_request: z.object({ branches: z.array(z.string()) }),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
),
);
expect(workflow.on.push.branches).toEqual(["main"]);
expect(workflow.on.pull_request.branches).toEqual(
expect.arrayContaining(["main", "release/*"]),
);
});
it("checks website changes on release-branch pull requests", async () => {
const workflow = z
.object({
on: z.object({
pull_request: z.object({ branches: z.array(z.string()) }),
}),
})
.parse(
parse(
await readFile(
new URL(
"../../../.github/workflows/website-check.yml",
import.meta.url,
),
"utf8",
),
),
);
expect(workflow.on.pull_request.branches).toEqual(["main", "release/*"]);
});
// Publishing is irreversible. Keep the release authority invariant as a static
// boundary check; it is not proof that package installation or publishing works.
it("requires package verification before publishing and retains the registry canary", async () => {
@@ -1,191 +0,0 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { runProviderAnalysis } from "../../../src/composition/directAnalysis.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
identifyRuntimes,
runtimeIdentificationResultSchema,
} from "../../../src/domain/runtimeIdentification.js";
describe("runtime identification", () => {
it("identifies APK runtime families and exposes missing semantic providers", async () => {
const root = await createTestTempDirectory("rea-runtime-");
const path = join(root, "Fixture.apk");
await writeApkRuntimeFixture(path);
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const first = identifyRuntimes({ inventory_evidence: [inventory] });
const second = identifyRuntimes({ inventory_evidence: [inventory] });
expect(first).toEqual(second);
expect(runtimeIdentificationResultSchema.parse(first)).toMatchObject({
root_format: "apk",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
},
});
expect(first.runtimes.map(({ family }) => family)).toEqual([
"android",
"javascript",
"jvm",
"native",
"webassembly",
]);
expect(first.runtimes).toEqual(
expect.arrayContaining([
expect.objectContaining({
family: "android",
inspection: "available",
provider_id: "rea-android-application",
}),
expect.objectContaining({
family: "jvm",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "webassembly",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "javascript",
inspection: "available",
provider_id: "rea-javascript-application",
}),
expect.objectContaining({
family: "native",
inspection: "provider-selection-required",
provider_id: null,
}),
]),
);
const widened = runtimeIdentificationResultSchema.parse({
...first,
root_format: "x".repeat(101),
source_evidence_ids: Array.from(
{ length: 101 },
() => inventory.evidence_id,
),
limitations: Array.from({ length: 101 }, () => "x".repeat(4_097)),
runtimes: first.runtimes.map((runtime) => ({
...runtime,
...(runtime.provider_id === null
? { reason: "x".repeat(1_001) }
: { provider_id: `provider-${"x".repeat(200)}` }),
observations: runtime.observations.map((observation) => ({
...observation,
path: "x".repeat(4_097),
format: "x".repeat(101),
})),
})),
});
expect(widened.limitations).toHaveLength(101);
expect(widened.runtimes[0]?.observations[0]?.path).toHaveLength(4_097);
const available = first.runtimes.find(
({ inspection }) => inspection === "available",
);
if (available === undefined)
throw new TypeError("Expected an available runtime provider");
expect(
runtimeIdentificationResultSchema.safeParse({
...first,
runtimes: [{ ...available, provider_id: null, reason: "Missing." }],
}).success,
).toBe(false);
});
it("accepts more than 100 supplied inventory Evidence records", async () => {
const root = await createTestTempDirectory("rea-runtime-pages-");
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("one.js", new TextReader("one"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = identifyRuntimes({
inventory_evidence: Array.from({ length: 101 }, () => inventory),
});
expect(result.source_evidence_ids).toHaveLength(101);
expect(result.coverage.status).toBe("complete-within-inventory");
expect(result.runtimes).toContainEqual(
expect.objectContaining({
family: "javascript",
observations: expect.arrayContaining([
expect.objectContaining({ path: "one.js" }),
]),
}),
);
});
it("does not route nested DEX content to the APK-only provider", async () => {
const root = await createTestTempDirectory("rea-runtime-dex-");
const path = join(root, "Fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = identifyRuntimes({ inventory_evidence: [inventory] });
expect(result.runtimes).toContainEqual(
expect.objectContaining({
family: "android",
inspection: "provider-selection-required",
provider_id: null,
}),
);
});
});
const writeApkRuntimeFixture = async (path: string): Promise<void> => {
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0, 8, 0, 0, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
),
);
await writer.add(
"assets/Fixture.class",
new Uint8ArrayReader(
Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]),
),
);
await writer.add(
"assets/module.wasm",
new Uint8ArrayReader(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])),
);
await writer.add("assets/main.js", new TextReader("bridge.call();"));
await writer.add(
"lib/arm64-v8a/libfixture.so",
new Uint8ArrayReader(Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0])),
);
await writeFile(path, await writer.close());
};
+29 -31
View File
@@ -243,36 +243,34 @@ describe("JSON client configuration migration and provider paths", () => {
expect(await readFile(configPath, "utf8")).toBe("not-json");
});
it.each(["null", "[]", '"value"'])(
"refuses a non-object JSON root without overwriting %s",
async (original) => {
const directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
{ status: "failed", reason: "readback" },
);
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
},
);
it("refuses a non-object JSON root without overwriting it", async () => {
const original = "null";
const directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it.each(["null", "[]", '"value"'])(
"preserves a non-object mcpServers value %s",
async (servers) => {
const directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const original = `{"mcpServers":${servers}}`;
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
{ status: "failed", reason: "readback" },
);
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
},
);
it("preserves a non-object mcpServers value", async () => {
const servers = "[]";
const directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const original = `{"mcpServers":${servers}}`;
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
});
@@ -1,81 +0,0 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { lstat, readdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
createStoreFileLock,
removeStaleStoreFileLock,
} from "../../../src/application/StoreFileLock.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("store lock cleanup ownership", () => {
it.each(["released", "replaced"] as const)(
"preserves a successor lock when an old %s owner cleans up",
async (state) => {
const root = await createTestTempDirectory("rea-store-lock-owner-");
const path = join(root, "transaction.lock");
const previous = await createStoreFileLock(path);
if (state === "released") await previous.release();
else await rm(path, { recursive: true });
const successor = await createStoreFileLock(path);
try {
await previous.release();
await expect(lstat(path)).resolves.toBeDefined();
await expect(createStoreFileLock(path)).rejects.toMatchObject({
code: "EEXIST",
});
} finally {
await successor.release();
}
},
);
});
describe("store lock acquisition and recovery", () => {
it("admits one concurrent owner and removes all preparation directories", async () => {
const root = await createTestTempDirectory("rea-store-lock-contenders-");
const path = join(root, "transaction.lock");
const results = await Promise.allSettled(
Array.from({ length: 8 }, () => createStoreFileLock(path)),
);
try {
expect(
results.filter((result) => result.status === "fulfilled"),
).toHaveLength(1);
for (const result of results)
if (result.status === "rejected")
expect(result.reason).toMatchObject({ code: "EEXIST" });
expect(await readdir(root)).toEqual(["transaction.lock"]);
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await Promise.all(
results.map((result) =>
result.status === "fulfilled" ? result.value.release() : undefined,
),
);
}
expect(await readdir(root)).toEqual([]);
});
it("recovers a directory lock abandoned by an exited process", async () => {
const root = await createTestTempDirectory("rea-store-lock-exited-");
const path = join(root, "transaction.lock");
await promisify(execFile)(
process.execPath,
["tests/fixtures/abandonStoreFileLock.mjs", path],
{ timeout: 5_000 },
);
expect((await lstat(path)).isDirectory()).toBe(true);
expect(await removeStaleStoreFileLock(path)).toBe(true);
const successor = await createStoreFileLock(path);
try {
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await successor.release();
}
expect(await readdir(root)).toEqual([]);
});
});
@@ -1,36 +0,0 @@
import { access, realpath, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("test temporary directory ownership", { concurrent: false }, () => {
let completedDirectory: string | undefined;
it("creates a canonical directory owned by the current test", async () => {
const directory = await createTestTempDirectory("rea-owned-temp-");
completedDirectory = directory;
expect(directory).toBe(await realpath(directory));
expect(dirname(directory)).toBe(await realpath(tmpdir()));
await writeFile(join(directory, "nested.txt"), "owned");
});
it("removes the prior test directory after that test finishes", async () => {
const directory = completedDirectory;
if (directory === undefined)
throw new Error("Prior test did not create a directory");
await expect(access(directory)).rejects.toMatchObject({
code: "ENOENT",
});
});
it.each(["", "../escape-", "/absolute-", "missing-dash"])(
"rejects unsafe prefix %j",
async (prefix) => {
await expect(createTestTempDirectory(prefix)).rejects.toThrow(TypeError);
},
);
});
+8 -13
View File
@@ -3,27 +3,22 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { classifyRoot } from "../../../src/application/ArtifactInventory/classify.js";
import { classifyRoot } from "../../../src/artifacts/inventory/classify.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("ZIP signature detection", () => {
it.each([
[0x03, 0x04, true],
[0x05, 0x06, true],
[0x07, 0x08, true],
[0x03, 0x06, false],
[0x03, 0x08, false],
[0x05, 0x04, false],
[0x05, 0x08, false],
[0x07, 0x04, false],
[0x07, 0x06, false],
{ signature: [0x50, 0x4b, 0x05, 0x06], archive: true },
{ signature: [0x50, 0x4b, 0x03, 0x06], archive: false },
{ signature: [0x50, 0x4b, 0x03, 0x04], archive: true },
{ signature: [0x50, 0x4b, 0x07, 0x08], archive: true },
] as const)(
"classifies PK %i %i with archive signature %s",
async (third, fourth, archive) => {
"routes representative ZIP signature $signature through inventory and target parsing",
async ({ signature, archive }) => {
const root = await createTestTempDirectory("rea-zip-signature-");
const path = join(root, "input");
await writeFile(path, Buffer.from([0x50, 0x4b, third, fourth]));
await writeFile(path, Buffer.from(signature));
expect(await classifyRoot(path, false)).toBe(archive ? "zip" : "file");
const target = await parseBinaryTarget(path);
if (archive)