Merge branch 'main' into codex/review-fixes-pr-1977

This commit is contained in:
morluto
2026-10-14 02:45:55 +08:00
committed by GitHub
259 changed files with 12710 additions and 1417 deletions
@@ -0,0 +1,130 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer } from "node:stream/consumers";
import { setImmediate } from "node:timers/promises";
import { expect, it } from "vitest";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { readAsarListing } from "../../../src/artifacts/AsarListing.js";
import {
asarHeaderBytes,
nestedAsarHeader,
} from "../../fixtures/asarHeader.js";
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const archiveWith = async (bytes: Buffer) => {
const root = await createTestTempDirectory("rea-asar-listing-");
const path = join(root, "app.asar");
await writeFile(path, bytes);
return path;
};
it("interrupts expanded listing admission between traversal batches", async () => {
const controller = new AbortController();
const header = {
files: Object.fromEntries(
Array.from({ length: 4000 }, (_, index) => [
`f${index}`,
{ size: 0, offset: "0" },
]),
),
};
const listing = readAsarListing(header, controller.signal);
await setImmediate();
controller.abort();
await expect(listing).rejects.toMatchObject({ reason: "cancelled" });
});
it("rejects path expansion before publishing any inventory, preserving the input", async () => {
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
expect(bytes.length).toBeLessThan(150_000);
const path = await archiveWith(bytes);
await expect(inventoryArtifact(path)).rejects.toMatchObject({
reason: "limit",
message: "ASAR expanded listing exceeds its 64 MiB representation budget",
});
expect(await readFile(path)).toEqual(bytes);
});
it("reads deeply nested packed metadata without recursive listing or member lookup", async () => {
const path = await archiveWith(nestedAsarHeader(3500, "d", 1));
const reader = new AsarArtifactReader(path);
try {
let count = 0;
for await (const entry of reader.entries()) {
count++;
if (entry.kind === "file") {
expect(entry.path).toBe(`${"d/".repeat(3500)}f0`);
expect(await buffer(await reader.open(entry))).toEqual(Buffer.alloc(0));
}
}
expect(count).toBe(3501);
} finally {
await reader.close();
}
});
it.each(["..", ".", "", "a/../b", "a/b", "a\0b"])(
"rejects raw ASAR component %j before host normalization can alias another entry",
async (component) => {
const json = JSON.stringify({
files: { [component]: { size: 0, offset: "0" } },
});
await expect(
inventoryArtifact(await archiveWith(asarHeaderBytes(json))),
).rejects.toMatchObject({ reason: "path" });
},
);
it("orders raw names portably and retains prototype-named entries and links", async () => {
const path = await archiveWith(
asarHeaderBytes(
'{"files":{"a0":{"size":0,"offset":"0"},"__proto__":{"size":0,"offset":"0"},"a":{"files":{"b":{"link":"a0"}}},"😀":{"size":0,"offset":"0"},"\uE000":{"size":0,"offset":"0"}}}',
),
);
const reader = new AsarArtifactReader(path);
try {
const entries = [];
for await (const entry of reader.entries())
entries.push([entry.path, entry.kind]);
expect(entries).toEqual([
["__proto__", "file"],
["a", "directory"],
["a/b", "symlink"],
["a0", "file"],
["\uE000", "file"],
["😀", "file"],
]);
} finally {
await reader.close();
}
});
it("preserves POSIX literal backslashes and rejects Windows component separators", async () => {
const path = await archiveWith(
asarHeaderBytes(
JSON.stringify({ files: { "a\\b": { size: 0, offset: "0" } } }),
),
);
const reader = new AsarArtifactReader(path);
try {
const list = async () => {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
return entries;
};
if (process.platform === "win32") {
await expect(list()).rejects.toMatchObject({ reason: "path" });
} else {
const entries = await list();
expect(entries).toHaveLength(1);
expect(entries[0]?.path).toBe("a\\b");
expect(await buffer(await reader.open(entries[0]!))).toEqual(
Buffer.alloc(0),
);
}
} finally {
await reader.close();
}
});
@@ -365,7 +365,9 @@ it("keeps fast feedback separate from complete qualification and release proof",
expect(ci.concurrency["cancel-in-progress"]).toBe(
"${{ github.event_name == 'pull_request' && inputs.source_sha == '' && !contains(github.event.pull_request.labels.*.name, 'ci:full') }}",
);
expect(ci.jobs.required?.if).toBe("${{ always() }}");
// Failed dependencies still reach the gate, but superseded PR runs must
// release their concurrency slot without waiting for another runner.
expect(ci.jobs.required?.if).toBe("${{ !cancelled() }}");
const shards = ci.jobs["test-shard"]?.steps ?? [];
const fast = shards.find((step) => step.run?.includes("npm run test:run"));
const full = shards.find((step) => step.run?.includes("test:ci:shard:run"));
@@ -45,23 +45,34 @@ const workflow = async () =>
),
).jobs;
it("collects failed-shard diagnostics before enforcing the shard result", async () => {
it("merges available failed-shard diagnostics and skips unavailable shard reports", async () => {
const steps = (await workflow()).test!.steps;
const download = steps.find(
(step) =>
step.uses?.includes("actions/download-artifact") &&
step.with?.pattern === "vitest-report-*",
);
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
const upload = steps.findIndex((step) => step.with?.name === "test-results");
const gate = steps.findIndex(
(step) => step.env?.SHARD_RESULT && step.run?.includes("test "),
);
expect(merge).toBeGreaterThan(0);
expect(download?.if).toContain("!cancelled()");
expect(download?.if).toContain("needs.test-shard.result == 'success'");
expect(download?.if).toContain("needs.test-shard.result == 'failure'");
expect(upload).toBeGreaterThan(merge);
expect(gate).toBeGreaterThan(upload);
expect(steps[merge]?.if).not.toContain("needs.test-shard.result");
const merges = steps.filter((step) => step.run?.includes("--reporter=json"));
expect(merges).toHaveLength(2);
for (const step of merges)
for (const step of merges) {
expect(step.run).toContain(
"--reporter=./scripts/ci/test-timing-reporter.mjs",
);
expect(step.if).toContain("!cancelled()");
expect(step.if).toContain("needs.test-shard.result == 'success'");
expect(step.if).toContain("needs.test-shard.result == 'failure'");
}
expect(steps[upload]?.with?.path).toContain("test-timings.json");
expect(steps[upload]?.with).toMatchObject({ "include-hidden-files": true });
expect(steps[upload]?.with?.path).toContain(
@@ -64,6 +64,7 @@ describe("client configuration filesystem lifecycle", () => {
"copilot_cli",
"commandcode",
"qwen_code",
"kimi",
"vscode",
"trae",
"grok_build",
@@ -1895,14 +1896,11 @@ describe("client configuration filesystem failure reporting", () => {
remove: () => Promise.reject(new Error("SECRET removal failure")),
}),
);
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining(
`Managed file could not be removed: ${join(skillRoot, "SKILL.md")}`,
),
}),
const skillItem = result.items.find(({ name }) => name === "skill");
expect(skillItem?.status).toBe("failed");
expect(skillItem?.detail).toContain(`shared (${skillRoot}): failed (`);
expect(skillItem?.detail).toContain(
`Managed file could not be removed: ${join(skillRoot, "SKILL.md")}`,
);
expect(JSON.stringify(result)).not.toContain("SECRET");
expect(await readFile(join(skillRoot, "SKILL.md"), "utf8")).toBe(
@@ -1944,6 +1942,42 @@ describe("client configuration filesystem failure reporting", () => {
});
});
describe("skill root client identifier labels", () => {
it("labels each retained or removed skill root by its client identifier", async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-labels-");
roots.push(home);
const customClaudeDirectory = join(home, "claude-config");
const sharedRoot = join(home, ".agents/skills/reverse-engineer-anything");
const claudeRoot = join(
customClaudeDirectory,
"skills/reverse-engineer-anything",
);
await mkdir(sharedRoot, { recursive: true });
await mkdir(claudeRoot, { recursive: true });
await writeFile(
join(sharedRoot, "SKILL.md"),
"---\nname: another-skill\n---\n# Not REA-owned\n",
);
await writeFile(join(claudeRoot, "SKILL.md"), ownedSkillManifest);
const skillItem = await systemUninstallHost(home, testFileSystem, {
CLAUDE_CONFIG_DIR: customClaudeDirectory,
}).removeSkill();
expect(skillItem.name).toBe("skill");
expect(skillItem.detail).toContain(`shared (${sharedRoot}): retained (`);
expect(skillItem.detail).toContain(
`claude_code (${claudeRoot}): removed (`,
);
await expect(
readFile(join(claudeRoot, "SKILL.md"), "utf8"),
).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(join(sharedRoot, "SKILL.md"), "utf8")).toContain(
"another-skill",
);
});
});
const testFileSystem: UninstallFileSystem = {
readText: (path) => readFile(path, "utf8"),
copy: (source, destination) =>
@@ -2195,3 +2195,135 @@ describe("DeepSeek Harness caller node metadata", () => {
},
);
});
describe("DeepSeek Harness uninstall of a shared operation", () => {
it("keeps a group patch's own fields and comment when its only row was REA's", async () => {
const { home, client } = await harnessClient();
const entry = canonicalEntry();
await writeFile(
client.configPath,
`- insert:
- id: user-a
name: plugin-a
# caller group patch
- id: tools
config:
sandbox: strict
insert:
- id: rea-mcp
name: "${entry.name}"
config:
serverName: rea
transport: stdio
command: ${entry.config.command}
args: ${JSON.stringify(entry.config.args)}
`,
);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const text = await readFile(client.configPath, "utf8");
expect(parseYaml(text)).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ id: "tools", config: { sandbox: "strict" } },
]);
expect(text).toContain("# caller group patch");
});
it("keeps an operation's own fields when setup removes a second REA row from it", async () => {
// Setup refuses a REA row in a group patch, so the setup path meets the
// keep rule only on an operation without a selector.
const { home, client } = await harnessClient();
const entry = canonicalEntry();
const row = (launcher: string) => ` - id: rea-mcp
name: "${entry.name}"
config:
serverName: rea
transport: stdio
command: ${launcher}
args: [mcp]
`;
await writeFile(
client.configPath,
`- insert:
${row("first-launcher")}# caller operation
- disabled: false
insert:
${row("second-launcher")}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("# caller operation");
expect(loadedInserts(text)).toHaveLength(1);
expect((parseYaml(text) as unknown[]).at(-1)).toEqual({ disabled: false });
expect(await dshStatus(home)).toMatchObject({ state: "aligned" });
});
it("drops an emptied operation that targets REA's own row", async () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{
id: "rea-mcp",
config: { serverName: "rea" },
insert: [canonicalEntry()],
},
]),
);
const host = systemUninstallHost(home);
expect((await host.removeClient(client)).status).toBe("removed");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
});
it.each([
{ selector: { id: "tools" } },
{ selector: { name: "tools" } },
{ selector: { id: "tools", name: "tools" } },
])(
"drops an emptied operation left with only its target selector $selector",
async ({ selector }) => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ ...selector, insert: [canonicalEntry()] },
]),
);
expect(
(await systemUninstallHost(home).removeClient(client)).status,
).toBe("removed");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
},
);
it("still drops an insert-only operation that REA's row emptied", async () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
stringifyYaml([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
{ insert: [canonicalEntry()] },
]),
);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
{ insert: [{ id: "user-a", name: "plugin-a" }] },
]);
});
});
+16 -21
View File
@@ -209,13 +209,7 @@ describe("installer TTY fallback", { timeout: 20_000 }, () => {
cwd: process.cwd(),
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...installerEnvironment(fixture),
TERM: "xterm-256color",
},
name: "xterm-256color",
@@ -581,6 +575,19 @@ const executable = async (path: string, source: string): Promise<void> => {
await chmod(path, 0o755);
};
/** Fixture-owned installer environment shared by the exec, pipe and PTY runs. */
const installerEnvironment = (
fixture: InstallerFixture,
): Record<string, string> => ({
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
});
const runInstaller = async (
fixture: InstallerFixture,
args: readonly string[] = [],
@@ -590,13 +597,7 @@ const runInstaller = async (
execFileAsync("/bin/bash", [script, ...args], {
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...installerEnvironment(fixture),
...overrides,
},
});
@@ -618,13 +619,7 @@ const runPipedInstaller = async (
new Promise((resolve, reject) => {
const child = spawn("/bin/bash", ["-s", "--", ...args], {
env: {
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...installerEnvironment(fixture),
...overrides,
},
stdio: ["pipe", "pipe", "pipe"],
@@ -405,12 +405,16 @@ describe("keyed archive hierarchy coverage", () => {
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",
]);
await compile(
"/usr/bin/xcrun",
[
"swift",
"tests/conformance/native/keyed-archive-hierarchy.swift",
archive,
"40",
],
{ timeout: 90_000 },
);
const analysis = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
@@ -431,6 +435,7 @@ describe("keyed archive hierarchy coverage", () => {
),
).toHaveLength(41);
},
120_000,
);
});
@@ -135,7 +135,6 @@ it("retains every source declared by every included local source map", async ()
it.each([
["a non-array sourcesContent value", { sourcesContent: "source" }],
["a non-string, non-null source entry", { sourcesContent: [42] }],
["a source-content array with the wrong length", { sourcesContent: [] }],
])(
"reports %s as an invalid local source map",
async (_description, content) => {
@@ -210,6 +209,51 @@ it("accepts omitted and explicitly null source-map source contents", async () =>
expect(result.graph.coverage.status).toBe("complete");
});
it.each([
["shorter", ["export const answer = 42;"]],
["longer", ["export const answer = 42;", null, "unused trailing content"]],
])(
"keeps every source declaration when sourcesContent is %s than sources",
async (length, sourcesContent) => {
const root = await createTestTempDirectory(
`rea-javascript-${length}-source-content-`,
);
await writeFile(
join(root, "bundle.js.map"),
JSON.stringify({
version: 3,
sources: ["a.ts", "b.ts"],
sourcesContent,
names: [],
mappings: "AAAA;ACAA",
}),
);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const originals = result.graph.nodes.filter(
({ identity }) => identity.strategy === "source-map-original",
);
expect(
originals
.map(({ identity, observations }) => ({
original_source:
"original_source" in identity ? identity.original_source : null,
source_index: observations[0]?.properties.source_index,
content_available: observations[0]?.properties.content_available,
}))
.sort(
(left, right) =>
Number(left.source_index) - Number(right.source_index),
),
).toEqual([
{ original_source: "a.ts", source_index: 0, content_available: true },
{ original_source: "b.ts", source_index: 1, content_available: false },
]);
expect(result.graph.coverage.status).toBe("complete");
},
);
it("retains unnamed source declarations without shifting later source evidence", async () => {
const root = await createTestTempDirectory("rea-javascript-unnamed-source-");
const text = JSON.stringify({
@@ -0,0 +1,384 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { setupRegistrationCommand } from "../../../src/application/SetupHost.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import {
clientSkillDirectories,
supportedClients,
} from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { MCP_STARTUP_POLICY } from "../../../src/mcpStartupPolicy.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
const command = NPX_REGISTRATION_COMMAND;
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const kimiPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2] = {},
) => supportedClients(home, platform, env).find(({ name }) => name === "kimi");
const exists = async (path: string): Promise<boolean> => {
try {
await access(path);
return true;
} catch {
return false;
}
};
const expectedRegistration = (launcher: readonly string[]) => ({
command: launcher[0],
args: launcher.slice(1),
startupTimeoutMs: MCP_STARTUP_POLICY.kimiStartupTimeoutMs,
toolTimeoutMs: MCP_STARTUP_POLICY.kimiToolTimeoutMs,
});
describe("Kimi Code configuration paths and skills", () => {
it.each([
[undefined, join("/home/a/.kimi-code")],
["", join("/home/a/.kimi-code")],
[join("/tmp", "isolated-kimi"), join("/tmp", "isolated-kimi")],
])("resolves KIMI_CODE_HOME for %j", (override, directory) => {
const client = kimiPath(
"/home/a",
"linux",
override === undefined ? {} : { KIMI_CODE_HOME: override },
);
expect(client).toEqual({
name: "kimi",
displayName: "Kimi Code",
configPath: join(directory, "mcp.json"),
markerPath: directory,
format: "kimi",
});
});
it("uses the existing shared skill destination without a separate skill root", () => {
expect(clientSkillDirectories("/home/a", ["kimi"])).toEqual([
{ client: "shared", directory: "/home/a/.agents/skills" },
]);
});
});
describe("Kimi Code registration lifecycle", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("preserves the caller's enabledTools selection during refresh", async () => {
const { client } = await kimiClient();
const enabledTools = ["binary_session", "analyze_javascript_application"];
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: { command: "old-rea", args: ["mcp"], enabledTools },
},
}),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual({
...expectedRegistration(command),
enabledTools,
});
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("unchanged");
});
it("registers without type, preserves unrelated settings, backs up, and is idempotent", async () => {
const { home, client } = await kimiClient();
const original = `{
"customSetting": { "enabled": true },
"mcpServers": {
"other": { "command": "other-server", "startupTimeoutMs": 5000 }
}
}
`;
await writeFile(client.configPath, original);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "configured",
backupPath: `${client.configPath}.rea.backup`,
});
const text = await readFile(client.configPath, "utf8");
expect(JSON.parse(text)).toEqual({
customSetting: { enabled: true },
mcpServers: {
other: { command: "other-server", startupTimeoutMs: 5000 },
rea: expectedRegistration(command),
},
});
expect(text).not.toContain('"type"');
expect(text).not.toContain('"transport"');
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await readFile(client.configPath, "utf8")).toBe(text);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual({
customSetting: { enabled: true },
mcpServers: {
other: { command: "other-server", startupTimeoutMs: 5000 },
},
});
});
});
describe("Kimi Code package launchers", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-launcher-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client } as const;
};
it.each([
["npx", "linux"],
["bunx", "linux"],
["npx", "win32"],
["bunx", "win32"],
] as const)(
"keeps the %s launcher aligned on %s",
async (runner, platform) => {
const { home, client } = await kimiClient();
const launcher = setupRegistrationCommand(platform, runner);
expect(
(await configureClientConfiguration(client, {}, launcher)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual(expectedRegistration(launcher));
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform,
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command: launcher });
expect(await configureClientConfiguration(client, {}, launcher)).toEqual({
status: "unchanged",
});
},
);
});
describe("Kimi Code transport validation", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-validation-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("creates a registration in a zero-byte file and accepts whitespace-only files", async () => {
const { home, client } = await kimiClient();
for (const original of ["", " \n\t"]) {
await writeFile(client.configPath, original);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(
JSON.parse(await readFile(client.configPath, "utf8")).mcpServers.rea,
).toEqual(expectedRegistration(command));
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(await systemUninstallHost(home).removeClient(client)).status,
).toBe("removed");
}
});
it.each([
'{"mcpServers": {',
'{/* comment */ "mcpServers": {}}',
'{"mcpServers": {},}',
'\uFEFF{"mcpServers": {}}',
])("rejects invalid strict JSON %j without writes", async (original) => {
const { client } = await kimiClient();
await writeFile(client.configPath, original);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
expect(await exists(`${client.configPath}.rea.backup`)).toBe(false);
});
it("accepts explicit stdio transport without causing repeated rewrites", async () => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
transport: "stdio",
...expectedRegistration(command),
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command });
});
it.each(["sse"])(
"rejects explicit transport %j instead of silently accepting another protocol",
async (transport) => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
transport,
...expectedRegistration(command),
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "invalid", command: [] });
},
);
});
describe("Kimi Code timeout validation", () => {
const kimiClient = async () => {
const home = await createTestTempDirectory("rea-kimi-timeout-");
const client = kimiPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Kimi Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client } as const;
};
it.each([
["startupTimeoutMs", 1],
["toolTimeoutMs", 1],
["startupTimeoutMs", undefined],
["toolTimeoutMs", undefined],
] as const)("reports stale when %s is %j", async (field, value) => {
const { home, client } = await kimiClient();
const registration = {
...expectedRegistration(command),
[field]: value,
};
await writeFile(
client.configPath,
JSON.stringify({ mcpServers: { rea: registration } }),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "stale" });
});
it("uses a direct installed REA command without requiring a package runner", async () => {
const { home, client } = await kimiClient();
const entry = join(home, "scripts", "rea.mjs");
const launcher = [process.execPath, entry, "mcp"];
expect(
(await configureClientConfiguration(client, {}, launcher)).status,
).toBe("configured");
expect(
(
await readClientRegistrationStatuses(home, entry, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "aligned", command: launcher });
});
it("leaves a foreign rea-key registration out of aligned state", async () => {
const { home, client } = await kimiClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
...expectedRegistration(command),
command: "another-package",
args: ["mcp"],
},
},
}),
);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "kimi"),
).toMatchObject({ state: "stale" });
});
});
@@ -54,6 +54,42 @@ const holdReadHandle = (path: string, reason: string) => {
};
};
/** Linux setup host with its VS Code client configuration directory prepared. */
const preparedVsCodeSetupHost = async (prefix: string) => {
const home = await createTestTempDirectory(prefix);
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home, XDG_CONFIG_HOME: join(home, "xdg") },
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
return { home, host, client };
};
/** Release the held read handle and show host cleanup reuses it as a third attempt. */
const expectCloseReclaimsHandle = async (
host: { close?: () => Promise<string | undefined> },
closeAttempts: readonly object[],
release: () => void,
) => {
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
};
/** Give up on the assertion path: release the handle and let cleanup close it. */
const cleanupHeldHandle = async (
host: { close?: () => Promise<string | undefined> },
release: () => void,
) => {
release();
await host.close?.();
};
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
const path = join(home, "client.json");
@@ -77,13 +113,9 @@ it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fa
});
expect(await readFile(path)).toEqual(original);
expect(closeAttempts).toHaveLength(2);
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
});
@@ -126,13 +158,9 @@ describe("ZCode fallback cleanup ownership", () => {
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
},
);
@@ -145,20 +173,9 @@ describe("setup client configuration cleanup ownership", () => {
] as const)(
"stops configuration and retains the %s read owner until host close",
async (encoding, original) => {
const home = await createTestTempDirectory("rea-setup-config-close-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-close-",
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, original);
const { closeAttempts, release } = holdReadHandle(
@@ -210,32 +227,17 @@ describe("setup client configuration cleanup ownership", () => {
expect(closeAttempts[0]).toBe(closeAttempts[1]);
expect(await readFile(client.configPath)).toEqual(original);
release();
expect(await host.close?.()).toBeUndefined();
expect(closeAttempts).toHaveLength(3);
expect(closeAttempts[2]).toBe(closeAttempts[0]);
await expectCloseReclaimsHandle(host, closeAttempts, release);
} finally {
release();
await host.close?.();
await cleanupHeldHandle(host, release);
}
},
);
it("waits for an admitted configuration read and rejects later admissions", async () => {
const home = await createTestTempDirectory("rea-setup-config-inflight-");
const environment = {
HOME: home,
XDG_CONFIG_HOME: join(home, "xdg"),
};
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
environment,
const { host, client } = await preparedVsCodeSetupHost(
"rea-setup-config-inflight-",
);
const client = (await host.supportedClients()).find(
({ name }) => name === "vscode",
);
if (client === undefined) throw new Error("VS Code setup client missing");
await mkdir(dirname(client.configPath), { recursive: true });
await writeFile(client.configPath, '{"servers": {}}\n');
let beginRead!: () => void;
@@ -70,7 +70,7 @@ const failFirstCloses = (path: string) => {
describe("skill regular-file cleanup ownership", () => {
it("retains a failed setup skill read until setup host disposal", async () => {
const home = await createTestTempDirectory("rea-setup-skill-close-");
const [destination] = skillDestinations(home, []);
const [destination] = skillDestinations(home, [], {}, "linux");
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
@@ -1,4 +1,4 @@
import { chmod, realpath, writeFile } from "node:fs/promises";
import { chmod, readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
@@ -78,7 +78,7 @@ describe("executable format refusal diagnostics", () => {
});
describe("target route diagnostics", () => {
it.each(["module.wasm", "module.bin", "misleading.js"])(
it.each(["module.wasm", "module.bin", "misleading.js", "misleading.hop"])(
"identifies a WASM v1 header in %s without suggesting native provider installation",
async (name) => {
const directory = await createTestTempDirectory("rea-wasm-target-");
@@ -346,3 +346,68 @@ describe("raw-binary load rejection diagnostics", () => {
});
});
});
describe("caller-selected and inferred target interpretation", () => {
it.each(["archive.hop", "archive.HOP"])(
"preserves inferred database routing for ZIP content named %s",
async (name) => {
const directory = await createTestTempDirectory("rea-zip-database-");
const bytes = Buffer.alloc(22);
bytes.writeUInt32LE(0x06054b50, 0);
const zipPath = join(directory, "archive.zip");
const databasePath = join(directory, name);
await writeFile(zipPath, bytes);
await writeFile(databasePath, bytes);
expect(await parseBinaryTarget(zipPath)).toMatchObject({
ok: true,
value: { kind: "archive", format: "zip" },
});
expect(await parseBinaryTarget(databasePath)).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
expect(await readFile(databasePath)).toEqual(bytes);
},
);
it("preserves explicit DOS COM interpretation for bytes with a WASM header", async () => {
const directory = await createTestTempDirectory("rea-wasm-explicit-com-");
const path = join(directory, "module.hop");
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
expect(
await parseBinaryTarget(path, { formatHint: "dos-com" }),
).toMatchObject({
ok: true,
value: { kind: "executable", format: "dos-com", architecture: "x86" },
});
});
it.each(["module.wasm", "misleading.hop"])(
"preserves explicitly selected database routing for %s",
async (name) => {
const directory = await createTestTempDirectory(
"rea-wasm-explicit-database-",
);
const path = join(directory, name);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
expect(
await parseBinaryTarget(path, { targetKind: "database" }),
).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
},
);
it.each(["ordinary.hop", "ordinary.HOP"])(
"retains automatic database routing for non-WASM %s",
async (name) => {
const directory = await createTestTempDirectory("rea-ordinary-database-");
const path = join(directory, name);
await writeFile(path, "existing database content");
expect(await parseBinaryTarget(path)).toMatchObject({
ok: true,
value: { kind: "database", format: "analysis-database" },
});
},
);
});