test: prune redundant cases and promote configuration lifecycle coverage

This commit is contained in:
morluto
2026-10-09 02:58:03 +08:00
parent bef234d6ce
commit 5945915f91
18 changed files with 237 additions and 417 deletions
-15
View File
@@ -22,21 +22,6 @@ spec.loader.exec_module(tracer)
class NativeTraceBudgetTests(unittest.TestCase):
def test_journal_keeps_flushed_observations_when_later_execution_fails(self):
stream = BytesIO()
journal = tracer._ObservationJournal(stream)
event = {"sequence": 0, "symbol": "first"}
journal.append({"kind": "event", "event": event})
with self.assertRaisesRegex(RuntimeError, "later failure"):
raise RuntimeError("later failure")
stream.write(b'{"kind":"event"') # Simulate termination during a later row.
rows = stream.getvalue().splitlines()
self.assertEqual(
rows[0],
b'{"kind": "event", "event": {"sequence": 0, "symbol": "first"}}',
)
self.assertEqual(rows[1], b'{"kind":"event"')
def test_journal_checks_exact_byte_budget_before_writing(self):
record = {"kind": "other-stop", "reason": "signal"}
encoded_size = len((tracer.json.dumps(record) + "\n").encode("utf-8"))
@@ -2,48 +2,23 @@ import { describe, expect, it } from "vitest";
import {
clientConfigurationServersKey,
clientRegistrationEntry,
parseClientConfiguration,
serializeClientConfiguration,
} from "./ClientConfigurationDocument.js";
describe.each([
"json",
"vscode",
"copilot_cli",
"opencode",
"commandcode",
] as const)("%s client configuration BOM handling", (format) => {
describe("JSON client configuration BOM handling", () => {
const format = "json" as const;
const serversKey = clientConfigurationServersKey(format);
it.each(["", "\uFEFF"])("parses a document with prefix %j", (bom) => {
const registration = clientRegistrationEntry(format, ["rea", "mcp"], {});
const document = { [serversKey]: { rea: registration } };
it("reports malformed BOM-prefixed JSON at the original offset", () => {
const text = `\uFEFF{\r\n "${serversKey}": {"rea": @}\r\n}`;
expect(
parseClientConfiguration(`${bom}${JSON.stringify(document)}`, format),
).toEqual({
document,
servers: document[serversKey],
serversPath: [serversKey],
dialect: format,
legacyServers: {},
});
expect(() => parseClientConfiguration(text, format)).toThrow(
new SyntaxError(
`Invalid JSON/JSONC at offset ${text.indexOf("@")}: InvalidSymbol`,
),
);
});
it.each(["", "\uFEFF"])(
"reports malformed JSON at the original offset with prefix %j",
(bom) => {
const text = `${bom}{\r\n "${serversKey}": {"rea": @}\r\n}`;
expect(() => parseClientConfiguration(text, format)).toThrow(
new SyntaxError(
`Invalid JSON/JSONC at offset ${text.indexOf("@")}: InvalidSymbol`,
),
);
},
);
it.each([
["\uFEFF\uFEFF{}", 1],
[" \uFEFF{}", 1],
@@ -54,51 +29,6 @@ describe.each([
new SyntaxError(`Invalid JSON/JSONC at offset ${offset}: InvalidSymbol`),
);
});
it.each(["", "\uFEFF"])(
"preserves prefix %j and unrelated bytes across add, update, and removal",
(bom) => {
const prefix = `${bom}{\r\n // Keep \uFEFF in comments.\r\n "label": "left\uFEFFright",\r\n "${serversKey}": {\r\n // Other server.\r\n "other": {\r\n "command": "other\uFEFFtool"\r\n },\r\n`;
const suffix = ' },\r\n "theme": "dark",\r\n}\r\n';
const original = `${prefix}${suffix}`;
let text = original;
for (const registration of [
clientRegistrationEntry(format, ["rea", "mcp"], {}),
clientRegistrationEntry(format, ["rea-next", "mcp"], {
LABEL: "left\uFEFFright",
}),
undefined,
]) {
const parsed = parseClientConfiguration(text, format);
const servers = { ...parsed.servers };
if (registration === undefined) delete servers.rea;
else servers.rea = registration;
const document = { ...parsed.document, [serversKey]: servers };
text = serializeClientConfiguration(document, format, text, [
[serversKey, "rea"],
]);
expect(parseClientConfiguration(text, format)).toEqual({
document,
servers,
serversPath: [serversKey],
dialect: format,
legacyServers: {},
});
expect(Buffer.from(text.slice(0, prefix.length))).toEqual(
Buffer.from(prefix),
);
expect(Buffer.from(text.slice(-suffix.length))).toEqual(
Buffer.from(suffix),
);
expect(text.replaceAll("\r\n", "")).not.toContain("\n");
}
expect(text).toBe(original);
},
);
});
describe("TOML client configuration BOM handling", () => {
@@ -45,15 +45,10 @@ const graphIdentities = async (source: string) => {
// source locations and every derived identity stay comparable.
it.each([
"fetch('https://api.example.com/v1/users');",
"new WebSocket('wss://ws.example.com/socket');",
"const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://xhr.example.com/data');",
"localStorage.setItem('token', 1);",
"sessionStorage.getItem('session-id');",
"indexedDB.open('records');",
"new Worker('./worker.js');",
"const dep = require('./dep.js'); dep();",
"import('./dep.js');",
"navigator.serviceWorker.register('./worker.js');",
])(
"reads a template without substitutions as its exact string: %s",
async (quoted) => {
@@ -1,14 +0,0 @@
import { expect, it } from "vitest";
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
it("breaks locale-collation ties deterministically by code unit", () => {
const names = ["a\u200d.txt", "a.txt", "a\u200b.txt", "a\u200c.txt"];
expect("a\u200d.txt".localeCompare("a.txt")).toBe(0);
expect(names.sort(compareDirectoryChildNames)).toEqual([
"a.txt",
"a\u200b.txt",
"a\u200c.txt",
"a\u200d.txt",
]);
});
-39
View File
@@ -2,11 +2,9 @@ import { describe, expect, it } from "vitest";
import {
captureAccessibility,
captureDom,
captureFrames,
captureResources,
} from "./CdpCaptureDocuments.js";
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
const origin = "https://app.example.test";
@@ -33,43 +31,6 @@ describe("CDP document capture", () => {
expect(resources.items).toHaveLength(2_000);
});
it("rebases parent indexes when allowed DOM documents are combined", () => {
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
});
const snapshot = {
strings: [`${origin}/main`, `${origin}/frame`, "#document", "DIV", ""],
documents: [
{
documentURL: 0,
nodes: {
nodeType: [9, 1],
nodeName: [2, 3],
nodeValue: [4, 4],
parentIndex: [-1, 0],
attributes: [[], []],
},
},
{
documentURL: 1,
nodes: {
nodeType: [9, 1],
nodeName: [2, 3],
nodeValue: [4, 4],
parentIndex: [-1, 0],
attributes: [[], []],
},
},
],
};
const capture = captureDom(snapshot, new Set([origin]), input);
expect(capture.nodes.map((node) => node.parent_index)).toEqual([
-1, 0, -1, 2,
]);
});
it("retains full approved accessibility text", () => {
const capture = captureAccessibility(
[
+1 -19
View File
@@ -9,19 +9,13 @@ import {
const target = "draft-2020-12";
describe("advertised tool JSON Schema", () => {
it("projects each canonical contract once per target", () => {
it("keeps examples and output schemas aligned with canonical contracts", () => {
for (const contract of TOOL_CONTRACTS) {
const input = toolInputSchemaWithMetadata(contract)["~standard"];
const output = toolOutputSchemaWithMetadata(contract)["~standard"];
const advertisedInput = input.jsonSchema.input({ target });
const advertisedOutput = output.jsonSchema.output({ target });
expect(input.jsonSchema.input({ target }), contract.name).toBe(
advertisedInput,
);
expect(output.jsonSchema.output({ target }), contract.name).toBe(
advertisedOutput,
);
expect(advertisedInput.examples, contract.name).toEqual(
contract.examples.map(({ input: example }) => example),
);
@@ -36,20 +30,8 @@ describe("advertised tool JSON Schema", () => {
const input = toolInputSchemaWithMetadata(contract)["~standard"];
const latest = input.jsonSchema.input({ target });
const draft07 = input.jsonSchema.input({ target: "draft-07" });
const libraryOptions = { unrepresentable: "any" };
const configured = input.jsonSchema.input({ target, libraryOptions });
expect(latest.$schema).toBe("https://json-schema.org/draft/2020-12/schema");
expect(draft07.$schema).toBe("http://json-schema.org/draft-07/schema#");
expect(input.jsonSchema.input({ target: "draft-07" })).toBe(draft07);
expect(configured).not.toBe(latest);
expect(input.jsonSchema.input({ target, libraryOptions })).not.toBe(
configured,
);
expect(
toolInputSchemaWithMetadata(contract).safeParse(
contract.examples[0]?.input,
).success,
).toBe(true);
});
});
-11
View File
@@ -13,12 +13,6 @@ describe("compareCodePoints", () => {
expect(compareCodePoints(GRINNING, REPLACEMENT)).toBeGreaterThan(0);
});
it("reports equality only for equal strings", () => {
expect(compareCodePoints("", "")).toBe(0);
expect(compareCodePoints(GRINNING, GRINNING)).toBe(0);
expect(compareCodePoints("a", "a")).toBe(0);
});
it("keeps a prefix before its own extension", () => {
expect(compareCodePoints("ab", "abc")).toBe(-1);
expect(compareCodePoints("abc", "ab")).toBe(1);
@@ -39,9 +33,4 @@ describe("uniqueSorted", () => {
GRINNING,
]);
});
it("preserves the inferred literal type", () => {
const values: ReadonlyArray<"a" | "b"> = ["b", "a", "b"];
expect(uniqueSorted(values)).toEqual(["a", "b"]);
});
});
-8
View File
@@ -90,14 +90,6 @@ describe("jsonValueSchema depth bound", () => {
).toBe(false);
expect(jsonValueSchema.safeParse({ a: 1n }).success).toBe(false);
});
it("accepts ordinary nested JSON", () => {
expect(
jsonValueSchema.safeParse({
list: [1, "two", null, true, { deep: { further: [{}] } }],
}).success,
).toBe(true);
});
});
it("preserves prototype-named members without prototype mutation", () => {
@@ -82,14 +82,4 @@ describe("process observation vocabulary", () => {
expect(observations[3]?.captured_at_ms).toBeNull();
expect(observations[4]?.captured_at_ms).toBeNull();
});
it("returns no observation for a missing collection record", () => {
expect(
projectProcessObservation(capture, {
collection: "frames",
index: 1,
capture_order: 10,
}),
).toBeNull();
});
});
@@ -6,21 +6,12 @@ import {
type WindowsProcessTreeHost,
} from "./ProcessOwnership.js";
import {
createSystemProcessOwnershipHost,
observeOwnedProcessGroup,
observeOwnedProcessLineage,
} from "./ProcessOwnershipObservation.js";
import { host, ownership } from "./ProcessOwnership.fixture.js";
describe("owned process-group cleanup validation: ownership and lineage", () => {
it("builds a host seam from the injected platform and environment", async () => {
const host = createSystemProcessOwnershipHost("win32", {
PATH: "/injected/path",
});
expect(host.platform).toBe("win32");
await expect(host.listProcesses()).resolves.toEqual([]);
});
it("fails closed when a descendant in another process group lacks the token", async () => {
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
@@ -11,54 +11,61 @@ import { cliTest } from "../../support/cli/cliFixture.js";
const filter = "evidence_id,normalized_result.graph.nodes[0:1].node_id";
for (const command of ["analyze-javascript-application", "analyze"]) {
for (const format of ["json", "jsonl"]) {
for (const fullOutput of [false, true]) {
for (const filtered of [false, true]) {
cliTest(
`${command} preserves ${format}, full output ${String(fullOutput)}, filtering ${String(filtered)}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-output-");
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({
input_path: root,
});
if (!direct.ok) throw direct.error;
const output = await cli.run({
arguments: [
command,
root,
"--format",
format,
...(fullOutput ? ["--full-output"] : []),
...(filtered ? ["--filter-output", filter] : []),
],
});
expect(output.exitCode).toBe(0);
let data: unknown = output.json;
if (fullOutput) {
const envelope = z
.object({
ok: z.literal(true),
data: z.unknown(),
meta: z.object({
command: z.literal(command),
duration: z.string().regex(/^\d+ms$/u),
}),
})
.parse(output.json);
data = envelope.data;
}
expect(data).toEqual(
filtered
? Filter.apply(direct.value, Filter.parse(filter))
: direct.value,
);
},
);
for (const scenario of [
{
command: "analyze-javascript-application",
format: "json",
fullOutput: false,
filtered: true,
},
{
command: "analyze-javascript-application",
format: "jsonl",
fullOutput: true,
filtered: true,
},
{ command: "analyze", format: "json", fullOutput: true, filtered: false },
{ command: "analyze", format: "jsonl", fullOutput: false, filtered: false },
] as const) {
cliTest(
`${scenario.command} preserves representative ${scenario.format} output`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-json-output-");
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({ input_path: root });
if (!direct.ok) throw direct.error;
const output = await cli.run({
arguments: [
scenario.command,
root,
"--format",
scenario.format,
...(scenario.fullOutput ? ["--full-output"] : []),
...(scenario.filtered ? ["--filter-output", filter] : []),
],
});
expect(output.exitCode).toBe(0);
let data: unknown = output.json;
if (scenario.fullOutput) {
const envelope = z
.object({
ok: z.literal(true),
data: z.unknown(),
meta: z.object({
command: z.literal(scenario.command),
duration: z.string().regex(/^\d+ms$/u),
}),
})
.parse(output.json);
data = envelope.data;
}
}
}
expect(data).toEqual(
scenario.filtered
? Filter.apply(direct.value, Filter.parse(filter))
: direct.value,
);
},
);
}
cliTest(
@@ -21,114 +21,115 @@ const unsupportedHostOutput = {
};
describe("compiled Windows reference-source import", () => {
for (const fullOutput of [false, true]) {
for (const logging of [false, true]) {
cliTest.runIf(process.platform === "win32")(
`readable root, ${fullOutput ? "full-output" : "JSON"}, logging ${String(logging)}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-reference-host-");
const source = join(root, "source.js");
const bytes = "export const answer = 42;\n";
await writeFile(source, bytes);
const result = await cli.run({
arguments: [
"import-reference-source",
root,
"--json",
...(fullOutput ? ["--full-output"] : []),
],
cwd: root,
environment: {
USERPROFILE: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
...(logging ? { REA_LOG_LEVEL: "info" } : {}),
},
for (const scenario of [
{ fullOutput: false, logging: false },
{ fullOutput: true, logging: true },
]) {
cliTest.runIf(process.platform === "win32")(
`readable root, ${scenario.fullOutput ? "full-output" : "JSON"}, logging ${String(scenario.logging)}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-reference-host-");
const source = join(root, "source.js");
const bytes = "export const answer = 42;\n";
await writeFile(source, bytes);
const result = await cli.run({
arguments: [
"import-reference-source",
root,
"--json",
...(scenario.fullOutput ? ["--full-output"] : []),
],
cwd: root,
environment: {
USERPROFILE: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
...(scenario.logging ? { REA_LOG_LEVEL: "info" } : {}),
},
});
expect(result.json).toEqual(
scenario.fullOutput
? expect.objectContaining({
ok: true,
data: unsupportedHostOutput,
})
: unsupportedHostOutput,
);
expect.soft(result.exitCode).toBe(1);
expect(await readFile(source, "utf8")).toBe(bytes);
if (scenario.logging) {
expect(JSON.parse(result.stderr.trim())).toMatchObject({
command: "import-reference-source",
status: "error",
level: 50,
msg: "CLI command failed",
});
expect(result.json).toEqual(
fullOutput
? expect.objectContaining({
ok: true,
data: unsupportedHostOutput,
})
: unsupportedHostOutput,
);
expect.soft(result.exitCode).toBe(1);
expect(await readFile(source, "utf8")).toBe(bytes);
if (logging) {
expect(JSON.parse(result.stderr.trim())).toMatchObject({
command: "import-reference-source",
status: "error",
level: 50,
msg: "CLI command failed",
});
} else expect(result.stderr).toBe("");
},
);
}
} else expect(result.stderr).toBe("");
},
);
}
});
describe("compiled reference-source import preflight failures", () => {
for (const rootKind of ["missing", "regular-file"] as const) {
for (const fullOutput of [false, true]) {
for (const logging of [false, true]) {
cliTest(
`${rootKind} root, ${fullOutput ? "full-output" : "JSON"}, logging ${String(logging)}`,
async ({ cli }) => {
const directory = await createTestTempDirectory(
"rea-reference-cli-status-",
);
const root = join(directory, "input");
if (rootKind === "regular-file")
await writeFile(root, "inert input\n");
const result = await cli.run({
arguments: [
"import-reference-source",
root,
"--json",
...(fullOutput ? ["--full-output"] : []),
],
cwd: directory,
environment: {
HOME: directory,
USERPROFILE: directory,
XDG_CONFIG_HOME: directory,
XDG_CACHE_HOME: directory,
...(logging ? { REA_LOG_LEVEL: "info" } : {}),
},
});
if (fullOutput) {
// Incur's legacy wrapper remains unchanged; operation status is
// conveyed by the exit code and command log, not this `ok` field.
expect(result.json).toMatchObject({
ok: true,
data: invalidRootOutput,
});
expect(result.json).toHaveProperty("data", invalidRootOutput);
} else {
expect(result.json).toEqual(invalidRootOutput);
}
expect.soft(result.exitCode).toBe(1);
if (logging) {
const records: unknown[] = result.stderr
.trim()
.split("\n")
.map((line) => JSON.parse(line) as unknown);
expect(records).toEqual([
expect.objectContaining({
command: "import-reference-source",
status: "error",
level: 50,
msg: "CLI command failed",
}),
]);
} else {
expect(result.stderr).toBe("");
}
},
for (const scenario of [
{ rootKind: "missing", fullOutput: false, logging: false },
{ rootKind: "missing", fullOutput: true, logging: true },
{ rootKind: "regular-file", fullOutput: false, logging: true },
{ rootKind: "regular-file", fullOutput: true, logging: false },
] as const) {
cliTest(
`${scenario.rootKind} root, ${scenario.fullOutput ? "full-output" : "JSON"}, logging ${String(scenario.logging)}`,
async ({ cli }) => {
const directory = await createTestTempDirectory(
"rea-reference-cli-status-",
);
}
}
const root = join(directory, "input");
if (scenario.rootKind === "regular-file")
await writeFile(root, "inert input\n");
const result = await cli.run({
arguments: [
"import-reference-source",
root,
"--json",
...(scenario.fullOutput ? ["--full-output"] : []),
],
cwd: directory,
environment: {
HOME: directory,
USERPROFILE: directory,
XDG_CONFIG_HOME: directory,
XDG_CACHE_HOME: directory,
...(scenario.logging ? { REA_LOG_LEVEL: "info" } : {}),
},
});
if (scenario.fullOutput) {
// Incur's legacy wrapper remains unchanged; operation status is
// conveyed by the exit code and command log, not this `ok` field.
expect(result.json).toMatchObject({
ok: true,
data: invalidRootOutput,
});
} else {
expect(result.json).toEqual(invalidRootOutput);
}
expect.soft(result.exitCode).toBe(1);
if (scenario.logging) {
const records: unknown[] = result.stderr
.trim()
.split("\n")
.map((line) => JSON.parse(line) as unknown);
expect(records).toEqual([
expect.objectContaining({
command: "import-reference-source",
status: "error",
level: 50,
msg: "CLI command failed",
}),
]);
} else {
expect(result.stderr).toBe("");
}
},
);
}
});
@@ -29,48 +29,35 @@ const observe = async (path: string) => {
};
describe("artifact comparison summary", () => {
it.each([
{ removed: 1, added: 1 },
{ removed: 0, added: 1 },
{ removed: 0, added: 0 },
])(
"counts unchanged paths with $removed removals and $added additions",
async ({ removed, added }) => {
const root = await createTestTempDirectory("rea-artifact-summary-");
const leftPath = join(root, "left");
const rightPath = join(root, "right");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all(
[leftPath, rightPath].flatMap((path) =>
["same.txt", "duplicate.txt"].map((name) =>
writeFile(join(path, name), "unchanged content"),
),
it("counts unchanged paths alongside additions and removals", async () => {
const root = await createTestTempDirectory("rea-artifact-summary-");
const leftPath = join(root, "left");
const rightPath = join(root, "right");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all(
[leftPath, rightPath].flatMap((path) =>
["same.txt", "duplicate.txt"].map((name) =>
writeFile(join(path, name), "unchanged content"),
),
);
await Promise.all([
...Array.from({ length: removed }, (_, index) =>
writeFile(join(leftPath, `removed-${index}.txt`), "old content"),
),
...Array.from({ length: added }, (_, index) =>
writeFile(join(rightPath, `added-${index}.txt`), "new content"),
),
]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
const comparison = compareArtifacts(left, right);
const changed = removed + added > 0 ? 1 : 0;
expect(comparison.summary).toEqual({
unchanged: 3 - changed,
added,
removed,
changed,
unknown: 0,
contradiction: 0,
});
expect(comparison.changes).toHaveLength(removed + added + changed);
},
);
),
);
await Promise.all([
writeFile(join(leftPath, "removed.txt"), "old content"),
writeFile(join(rightPath, "added.txt"), "new content"),
]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
const comparison = compareArtifacts(left, right);
expect(comparison.summary).toEqual({
unchanged: 2,
added: 1,
removed: 1,
changed: 1,
unknown: 0,
contradiction: 0,
});
expect(comparison.changes).toHaveLength(3);
});
});
@@ -4,10 +4,8 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
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/artifacts/inventory/scanCanonical.js";
import { targetFormatSchema } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -31,11 +29,6 @@ describe("MZ artifact classification", () => {
expect(classifyArtifactContent("bad.exe", Buffer.from("MZbroken"))).toEqual(
{ kind: "unknown", format: "unknown" },
);
expect(classifyArtifactContent("NATIVE.EXE", peFixture(128))).toMatchObject(
{
format: "pe",
},
);
const distantPe = peFixture(ARTIFACT_CLASSIFICATION_PREFIX_BYTES + 64);
expect(
classifyArtifactContent(
@@ -56,7 +49,6 @@ describe("MZ artifact classification", () => {
distantRelocations.length,
).format,
).toBe("unknown");
expect(targetFormatSchema.parse("dos-mz")).toBe("dos-mz");
});
it("keeps standalone and embedded DOS identities through inventory", async () => {
@@ -65,8 +57,6 @@ describe("MZ artifact classification", () => {
const pePath = join(directory, "NATIVE.EXE");
await writeFile(dosPath, dosFixture());
await writeFile(pePath, peFixture(128));
expect(await classifyRoot(dosPath, false)).toBe("dos-mz");
expect(await classifyRoot(pePath, false)).toBe("pe");
const standalone = artifactInventoryResultSchema.parse(
await scanCanonicalArtifactInventory(dosPath),
);
@@ -14,6 +14,10 @@ import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import {
runUninstall,
systemUninstallHost,
} from "../../../src/application/Uninstall.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -114,3 +118,38 @@ it("rejects malformed BOM-prefixed JSON without writing or backing it up", async
expect(await readFile(configPath)).toEqual(Buffer.from(original));
expect(await readdir(home)).toEqual(["mcp.json"]);
});
it("restores original BOM-prefixed JSONC bytes after update and removal", async () => {
const home = await createTestTempDirectory("rea-client-config-bom-cycle-");
const client = supportedClients(home, "linux", {}).find(
(candidate) => candidate.name === "cursor",
);
if (client?.format !== "json") throw new Error("missing Cursor JSON config");
const serversKey = clientConfigurationServersKey(client.format);
const prefix = `\uFEFF{\r\n // Keep prefix \uFEFF comment.\r\n "label": "left\uFEFFright",\r\n "${serversKey}": {\r\n // Keep this unrelated registration.\r\n "other": {\r\n "command": "other\uFEFFtool"\r\n },\r\n`;
const suffix = ` },\r\n // Keep suffix comment.\r\n "theme": "dark"\r\n}\r\n`;
const original = `${prefix}${suffix}`;
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, original);
const firstCommand = [join(home, "bin", "rea"), "mcp"];
const updatedCommand = [join(home, "updated", "bin", "rea"), "mcp"];
expect(
await configureClientConfiguration(client, {}, firstCommand),
).toMatchObject({ status: "configured" });
expect(
await configureClientConfiguration(client, {}, updatedCommand),
).toMatchObject({ status: "configured" });
const updated = await readFile(client.configPath, "utf8");
expect(parseClientConfiguration(updated, client.format).servers).toEqual({
other: { command: "other\uFEFFtool" },
rea: clientRegistrationEntry(client.format, updatedCommand, {}),
});
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("complete");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "cursor", status: "removed" }),
);
expect(await readFile(client.configPath, "utf8")).toBe(original);
});
@@ -39,8 +39,6 @@ it("publishes valid SDK schemas and records the named module trace without a bin
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const args = { manifest_path: "/analysis/manifest.json", script_index: 0 };
expect(ajv.validate(inputSchema, args)).toBe(true);
const response = await client.callTool({
@@ -45,8 +45,6 @@ it("publishes valid SDK schemas and records the named module trace without a bin
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(ajv.validate(inputSchema, args)).toBe(true);
const response = await client.callTool({
name: "trace_web_source_location",
@@ -37,7 +37,6 @@ describe("development test selection", () => {
]),
);
expect(plan.needsBuild).toBe(true);
expect(plan.vitestArguments).not.toContain("--passWithNoTests");
expect(plan.vitestArguments).not.toContain("--changed");
});