Files
reverse-engineering-anything/scripts/verify-opencode-client.mjs
T
morluto 8e18bdecef test(clients): check configured MCP catalogs in native harnesses (#15121)
* test(clients): check configured MCP catalogs in native harnesses

* test(opencode): resolve the native CLI in the isolated home

* ci(clients): identify native catalog discovery in the job log

* test(ci): isolate native clients and preserve registration failures
2026-11-29 18:03:55 +00:00

351 lines
12 KiB
JavaScript

import { clientCatalogFixture } from "./verify/clients/catalog.mjs";
import assert from "node:assert/strict";
import { verifyClientSetupAndReadSkillBody } from "./verify/clients/setup.mjs";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import Ajv2020 from "ajv/dist/2020.js";
import { isPathWithinRoot } from "../dist/domain/localPath.js";
import { createVerifierCommands } from "./lib/verify-commands.mjs";
import { saveVerifierCommandOutput } from "./lib/verifier-command-output.mjs";
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
import { readClientVersion } from "./verify/clients/version.mjs";
import { receiptContext, publishReceipt } from "./verify/clients/receipt.mjs";
import {
CLIENT_JAVASCRIPT_FIXTURE_SOURCE,
assertClientJavaScriptFixtureEvidence,
} from "./verify/clients/javascript-fixture.mjs";
import {
findClientResult,
isClientJavaScriptEvidence,
} from "./verify/clients/result-discovery.mjs";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
import {
createOpenAiModelFixture,
toolCallMessage,
} from "./verify/clients/model-fixture.mjs";
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
assert(
process.platform !== "win32",
"Native OpenCode verifier requires POSIX; Windows is unverified",
);
const repo = fileURLToPath(new URL("..", import.meta.url));
const runtimeRoot = process.env.REA_VERIFY_RUNTIME_ROOT ?? repo;
const command = process.env.REA_VERIFY_OPENCODE_COMMAND ?? "opencode";
const mode = process.argv[2] ?? "call";
const configFormat = process.env.REA_VERIFY_OPENCODE_CONFIG_FORMAT ?? "jsonc";
assert(
["chat", "scoped-chat", "call"].includes(mode),
"Usage: verify-opencode-client.mjs [chat|scoped-chat|call]",
);
const configFilename = new Map([
["json", "opencode.json"],
["jsonc", "opencode.jsonc"],
]).get(configFormat);
assert(
configFilename !== undefined,
"REA_VERIFY_OPENCODE_CONFIG_FORMAT must be json or jsonc",
);
const catalogFixture = clientCatalogFixture(mode);
const verifier = createVerifierRun();
const { path: lab } = await VerifierFixture.keepArtifacts({
prefix: "rea-opencode-client-",
});
const account = join(lab, "account");
const profile = join(lab, "selected profile");
const workspace = join(lab, "workspace");
const configPath = join(profile, configFilename);
const skillDirectory = join(
account,
".agents",
"skills",
"reverse-engineer-anything",
);
assert.equal(
isPathWithinRoot(skillDirectory, `${skillDirectory}-sibling/AGENTS.md`),
false,
);
assert.equal(
isPathWithinRoot(
skillDirectory,
join(skillDirectory, "..", "outside", "AGENTS.md"),
),
false,
);
let clientVersion = null;
let fixture;
let passed = false;
let skillRequested = false;
let skillLoaded = false;
let expectedSkillBody;
let evidenceSeen = false;
let finalSeen = false;
let catalogSize = null;
let catalogSearchRequested = false;
let schemasChecked = 0;
let artifactDigest;
const commands = await createVerifierCommands();
await withVerifierCleanup(async () => {
await withVerifierCleanup(async () => {
await Promise.all([mkdir(account), mkdir(profile), mkdir(workspace)]);
await commands.exec("git", ["init", "--quiet", workspace], {
timeout: 30_000,
stdin: "pipe",
});
const environment = {
HOME: account,
USERPROFILE: account,
PATH: process.env.PATH ?? "",
OPENCODE_CONFIG_DIR: profile,
XDG_CONFIG_HOME: join(lab, "config"),
XDG_CACHE_HOME: join(lab, "cache"),
XDG_DATA_HOME: join(lab, "data"),
XDG_STATE_HOME: join(lab, "state"),
OPENCODE_DISABLE_AUTOUPDATE: "true",
OPENCODE_DISABLE_MODELS_FETCH: "true",
// Use the native core without external account plugins.
OPENCODE_PURE: "true",
REA_PROCESS_RUN_ID: verifier.run_id,
};
try {
clientVersion = await readClientVersion(commands, command, environment);
} catch (cause) {
throw new Error(
`OpenCode preflight failed for ${command}; install OpenCode or set REA_VERIFY_OPENCODE_COMMAND. ${String(cause)}`,
{ cause },
);
}
const target = join(lab, "fixture α测试");
await mkdir(target);
await writeFile(join(target, "app.js"), CLIENT_JAVASCRIPT_FIXTURE_SOURCE);
const schemaValidator = new Ajv2020({
strict: false,
validateFormats: false,
});
fixture = await createOpenAiModelFixture({
directory: lab,
prefix: "opencode",
onRequest: async ({ body, tools, requestIndex }) => {
// Native session-title requests do not execute the analyst's workflow.
if (tools.length === 0)
return { role: "assistant", content: "REA fixture title" };
const analysis = tools.find((t) =>
t.name.endsWith("analyze_javascript_application"),
);
if (
!analysis &&
mode === "scoped-chat" &&
tools.some((tool) => tool.name === "execute")
) {
if (!catalogSearchRequested) {
catalogSearchRequested = true;
return toolCallMessage("call_rea_catalog", "execute", {
code: `const paths = []; let offset = 0;
do {
const page = await search({ namespace: "rea", offset });
paths.push(...page.items.map(item => item.path));
if (!page.next) break;
if (page.next.offset <= offset) throw Error("OpenCode catalog cursor did not advance");
offset = page.next.offset;
} while (true);
return { reaCatalogPaths: paths };`,
});
}
const result = findClientResult(
body.messages.filter((message) => message.role === "tool"),
(value) => Array.isArray(value.reaCatalogPaths),
);
assert(
result,
"OpenCode must return its native REA namespace search results",
);
catalogFixture.assertNames(result.reaCatalogPaths, "tools.rea.");
catalogSize = result.reaCatalogPaths.length;
finalSeen = true;
return { role: "assistant", content: "REA_CLIENT_COMPATIBILITY_OK" };
}
assert(analysis, "OpenCode must expose the REA analysis tool");
const prefix = analysis.name.slice(
0,
-"analyze_javascript_application".length,
);
const reaTools = catalogFixture.check(tools, prefix);
catalogSize = reaTools.length;
if (schemasChecked === 0) {
for (const tool of reaTools) {
assert(
tool.parameters,
`${tool.name}: missing advertised input schema`,
);
assert(
schemaValidator.validateSchema(tool.parameters),
`${tool.name}: invalid input schema: ${JSON.stringify(schemaValidator.errors)}`,
);
schemasChecked++;
}
}
const replies = body.messages.filter((m) => m.role === "tool");
skillLoaded ||= replies.some(
(m) =>
typeof m.content === "string" &&
expectedSkillBody !== undefined &&
m.content.includes(skillDirectory) &&
m.content.includes(expectedSkillBody),
);
const observed = findClientResult(replies, isClientJavaScriptEvidence);
if (observed) {
const { evidence } = await assertClientJavaScriptFixtureEvidence(
observed,
target,
);
const bytes = JSON.stringify(evidence);
artifactDigest = createHash("sha256").update(bytes).digest("hex");
await writeFile(join(lab, "opencode-evidence.json"), bytes);
evidenceSeen = true;
}
if (mode !== "call" || evidenceSeen) {
finalSeen = true;
return { role: "assistant", content: "REA_CLIENT_COMPATIBILITY_OK" };
}
assert(
requestIndex <= 8,
"Local model workflow exceeded its turn budget",
);
const call = (name, args) =>
toolCallMessage(`call_rea_fixture_${requestIndex}`, name, args);
if (!skillRequested) {
const skill = tools.find((t) => t.name === "skill");
assert(skill, "OpenCode must expose its native skill tool");
skillRequested = true;
return call(skill.name, { name: "reverse-engineer-anything" });
}
assert(
skillLoaded,
"OpenCode must load the installed personal REA skill",
);
return call(analysis.name, { input_path: target, format: "directory" });
},
});
const original =
(configFormat === "jsonc" ? "// Keep caller configuration.\n" : "") +
JSON.stringify(
{
autoupdate: false,
skills: { paths: [join(account, ".agents", "skills")] },
permission: { "*": "allow" },
provider: {
"rea-fixture": {
npm: "@ai-sdk/openai-compatible",
name: "REA local model fixture",
options: {
baseURL: fixture.baseUrl,
apiKey: "local-fixture-key",
},
models: {
"rea-client-fixture": {
name: "REA fixture",
tool_call: true,
limit: { context: 1_000_000, output: 4096 },
},
},
},
},
mcp: {
other: {
type: "local",
command: ["unrelated-server"],
enabled: false,
},
},
},
null,
2,
);
await writeFile(configPath, original);
expectedSkillBody = await verifyClientSetupAndReadSkillBody({
setupArguments: catalogFixture.setupArguments,
client: "opencode",
commands,
runtimeRoot,
environment,
workspace,
lab,
configPath,
original,
skillDirectory,
checkConfigured: (configured) => {
assert(configured.includes("unrelated-server"));
if (configFormat === "jsonc")
assert(configured.includes("// Keep caller configuration."));
},
});
const response = await saveVerifierCommandOutput(
() =>
commands.exec(
command,
[
"run",
"--format",
"json",
"--model",
"rea-fixture/rea-client-fixture",
mode !== "call"
? "Say hello briefly."
: `Use REA to analyze the JavaScript directory ${target}. Report the result.`,
],
{
env: environment,
cwd: workspace,
timeout: 120_000,
maxBuffer: 10 * 1024 * 1024,
stdin: "closed-pipe",
},
),
{
stdout: join(lab, `${mode}.stdout`),
stderr: join(lab, `${mode}.stderr`),
},
);
assert.equal(fixture.failure, undefined);
assert(
finalSeen && response.stdout.includes("REA_CLIENT_COMPATIBILITY_OK"),
);
if (mode === "call") assert(evidenceSeen && skillLoaded);
}, [
() => commands.close(),
async () => {
await fixture?.close();
},
]);
passed = true;
}, [
async () => {
const lineage = await completeVerifierRun(verifier);
await publishReceipt({
client: "OpenCode",
clientVersion,
mode,
configFormat,
passed,
...receiptContext(lab, runtimeRoot),
modelFixture:
"loopback custom OpenAI-compatible provider; one-million-token fixture capacity and synthetic usage; no live provider claim",
skillDiscovery:
"caller-configured isolated shared directory; default OS home discovery unverified",
externalPlugins: "disabled through native OPENCODE_PURE",
catalogSize,
schemasChecked,
evidenceSeen,
skillLoaded,
artifactDigest,
finalSeen,
requests: fixture?.requests,
probes: fixture?.probes,
fixtureFailure: fixture?.failure,
verifier: lineage,
});
},
]);