Files
rea/scripts/verify-opencode-client.mjs
GamerDubz 104c1c189e test(clients): verify native OpenCode integration against OpenCode V2 (#10178)
* test(clients): verify native OpenCode integration against OpenCode V2

The OpenCode client lane targeted OpenCode V1 (opencode-ai@1.18.35) and
could not pass against OpenCode V2. The V2 skill tool names its argument
`id`, so the lane's `{ name: ... }` call was rejected with "id: Missing
key" and the personal skill never loaded.

Bring the lane to OpenCode V2:

- Call the skill tool with `id` under V2 and keep `name` for V1.
- Register REA in the native `mcp.servers` table and read additional skill
  sources from the `skills` array; grant tool access with a `permissions`
  ruleset. The V1 dialect remains selectable with
  `REA_VERIFY_OPENCODE_DIALECT=v1`.
- OpenCode V2 groups MCP tools behind its Code Mode tool by default, so the
  lane sets the documented `codemode: false` server option to observe the
  forwarded catalog as direct function tools. REA's refresh preserves that
  client-owned option, which the lane now covers.
- Start a private server under V2. The shared background service keeps the
  environment it started with and would read the caller's own configuration
  instead of the lane's isolated one.
- Isolate the home for both platforms. The lane set only USERPROFILE, so a
  POSIX run resolved the caller's real home for the shared skill directory.
- Take the expected catalog from the runtime under test, so
  `REA_VERIFY_RUNTIME_ROOT` can point at an installed package whose catalog
  differs from this checkout.
- Record the dialect, plugin-isolation mechanism and tool surface in the
  receipt. OpenCode V2 dropped OPENCODE_PURE, so the V1 isolation claim no
  longer described what ran.

The lane no longer refuses Windows, so the OpenCode integration can be
verified on a native Windows host.

* fix(clients): isolate OpenCode verifier config and coverage claims

Clear inherited OPENCODE_CONFIG and OPENCODE_CONFIG_CONTENT so the lab
cannot load the caller's configuration layers. Record V2 as verified
only on native Windows and leave POSIX V2 explicitly unverified.

* fix(clients): pin OpenCode verifier to a full REA catalog

Clear inherited REA_MCP_TOOL_FAMILIES and set REA_MCP_TOOL_CATALOG_PROFILE=full so setup and the MCP child always advertise the complete catalog the fixture asserts.

* fix(ci): pin Native MCP OpenCode checks to @opencode/cli@2.2.7

The verifier defaults to the OpenCode V2 dialect, but the Native MCP
registration workflow still installed opencode-ai@1.19.6 without selecting
v1. Point the matrix at the published V2 CLI that supports the V2 config
and --standalone.

* fix(clients): harden OpenCode V2 verifier modes and launch seeds

Keep Code Mode enabled for scoped-chat and assert the paginated catalog
search, clear inherited REA MCP capacity/schema settings that can reject
fixture calls, and accept Aube-managed shim launchers alongside the
raw Node/script/mcp shape.

* fix(clients): only require Code Mode catalog search for OpenCode V2

* fix(clients): clear OpenCode verifier ambient budget and Windows env aliases

Unset inherited REA_AGENT_RESULT_BUDGET_BYTES so the fixture keeps complete
Evidence, and delete cleared OpenCode/REA launch seeds case-insensitively
before spawn so mixed-case Windows aliases cannot survive.

* fix(clients): require Windows packaged OpenCode runtime and isolate V2 ancestors

Document that Windows call verification needs REA_VERIFY_RUNTIME_ROOT with a
matching packaged runtime, and refuse OpenCode V2 lab runs when an ancestor
project configuration file would join the private server.

* fix(clients): qualify POSIX OpenCode V2 coverage and dialect Windows hint

Limit checked-in POSIX V2 claims to scoped-chat catalog search and point
Windows preflight recovery at the selected OpenCode package major.

* fix(clients): match OpenCode runtime contracts and clear registration seeds

Reject a REA_VERIFY_RUNTIME_ROOT whose package version or tool catalog
differs from this checkout, and clear every selected registration setting
from SetupRegistrationEnvironment instead of a hand-maintained MCP list.

* fix(verification): bind OpenCode fixtures to selected runtime

* fix(verification): refuse discovered OpenCode plugin sources

* test(verification): reject plugins before starting OpenCode

* test(ci): exercise packaged OpenCode on Windows

* fix(verification): type the selected-runtime fixture reader

* chore(ci): use pinned npm for Windows client proof

* docs(verification): distinguish Windows runner isolation

* test(verification): keep compiled fixtures in the built test lane

* test(verification): type catalog fixtures without generated output

* fix(ci): classify automated OpenCode verification
2026-12-02 13:39:47 +08:00

434 lines
16 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 { currentClientRegistrationCommand } from "../dist/application/ClientRegistrationIdentity.js";
import { registeredAubeShim } from "../dist/process/AubeBinShim.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";
import { matchingClientRuntimeContracts } from "./verify/clients/runtime-contracts.mjs";
import {
openCodeVerificationEnvironment,
assertIsolatedOpenCodeSources,
} from "./verify/clients/opencode-environment.mjs";
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";
const dialect = process.env.REA_VERIFY_OPENCODE_DIALECT ?? "v2";
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",
);
assert(
["v1", "v2"].includes(dialect),
"REA_VERIFY_OPENCODE_DIALECT must be v1 or v2",
);
const runtimeContracts = await matchingClientRuntimeContracts(
runtimeRoot,
repo,
);
const catalogFixture = clientCatalogFixture(
mode,
runtimeContracts.contractsForToolFamilies,
);
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 = openCodeVerificationEnvironment({
inherited: process.env,
account,
profile,
lab,
dialect,
runId: verifier.run_id,
});
await assertIsolatedOpenCodeSources(workspace, dialect, {
home: account,
env: environment,
platform: process.platform,
});
try {
clientVersion = await readClientVersion(commands, command, environment);
} catch (cause) {
// npm installs put only an opencode.cmd shim on PATH; cross-spawn runs
// that shim, and a desktop installation ships a real executable.
const windowsPackage = dialect === "v1" ? "opencode-ai" : "@opencode/cli";
const windowsHint =
process.platform === "win32"
? ` On Windows, select the opencode executable, for example the npm package's node_modules/${windowsPackage}/bin/opencode.exe.`
: "";
throw new Error(
`OpenCode preflight failed for ${command}; install OpenCode or set REA_VERIFY_OPENCODE_COMMAND.${windowsHint} ${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,
runtimeContracts.toolContract,
);
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;
// OpenCode V2 names the skill argument `id`; V1 accepted `name`.
return call(skill.name, {
[dialect === "v1" ? "name" : "id"]: "reverse-engineer-anything",
});
}
assert(
skillLoaded,
"OpenCode must load the installed personal REA skill",
);
return call(analysis.name, { input_path: target, format: "directory" });
},
});
// The registration REA's setup writes is the same launcher it selects for
// itself. Seeding it keeps the lane on REA's own refresh path and proves
// that a client-owned server option survives that refresh.
const reaLauncher = currentClientRegistrationCommand({
entrypointPath: join(runtimeRoot, "scripts/rea.mjs"),
environment,
platform: process.platform,
});
assert(
(reaLauncher.length === 3 && reaLauncher[2] === "mcp") ||
registeredAubeShim(reaLauncher) !== undefined,
"REA must resolve a runtime/script/mcp launcher or an Aube-managed shim",
);
// OpenCode V2 groups MCP tools behind its Code Mode tool by default.
// Call and chat observe the forwarded catalog as direct function tools
// through the documented `codemode: false` option. Scoped-chat keeps the
// default so it can exercise the paginated Code Mode search path.
const reaServer = {
type: "local",
command: [...reaLauncher],
...(dialect === "v2" && mode !== "scoped-chat"
? { codemode: false }
: {}),
};
const unrelatedServer = {
type: "local",
command: ["unrelated-server"],
...(dialect === "v2" ? { disabled: true } : { enabled: false }),
};
const original =
(configFormat === "jsonc" ? "// Keep caller configuration.\n" : "") +
JSON.stringify(
{
autoupdate: false,
// OpenCode V2 reads additional skill sources as an array.
skills:
dialect === "v1"
? { paths: [join(account, ".agents", "skills")] }
: [join(account, ".agents", "skills")],
// OpenCode V2 replaced the V1 permission map with ordered rules.
...(dialect === "v1"
? { permission: { "*": "allow" } }
: {
permissions: [{ action: "*", resource: "*", effect: "allow" }],
}),
// No external plugin package may join the verified run.
plugins: [],
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 },
},
},
},
},
// OpenCode V2 keeps server names under `mcp.servers`; the V1 table
// placed them directly under `mcp`.
mcp:
dialect === "v2"
? { servers: { other: unrelatedServer, rea: reaServer } }
: { other: unrelatedServer, rea: reaServer },
},
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",
// The shared background service keeps the environment it started
// with, so it would ignore this lane's isolated configuration
// directory. A private server reads the redirected one.
...(dialect === "v2" ? ["--standalone"] : []),
"--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);
if (dialect === "v2" && mode === "scoped-chat")
assert(
catalogSearchRequested,
"OpenCode scoped-chat must search the REA catalog through Code Mode",
);
}, [
() => commands.close(),
async () => {
await fixture?.close();
},
]);
passed = true;
}, [
async () => {
const lineage = await completeVerifierRun(verifier);
await publishReceipt({
client: "OpenCode",
clientVersion,
mode,
configFormat,
dialect,
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; other discovered skills and default OS home discovery unverified",
externalPlugins:
dialect === "v1"
? "disabled through native OPENCODE_PURE"
: "disabled through the OpenCode V2 plugins configuration, a redirected configuration directory without a plugin directory, and confirmed absence of foreign project/system configuration and auto-discovered plugin directories",
mcpToolSurface:
dialect === "v2"
? mode === "scoped-chat"
? "paginated Code Mode search through OpenCode V2's default execute tool"
: "direct function tools through the OpenCode V2 codemode:false server option"
: "direct function tools",
catalogSize,
schemasChecked,
evidenceSeen,
skillLoaded,
artifactDigest,
finalSeen,
requests: fixture?.requests,
probes: fixture?.probes,
fixtureFailure: fixture?.failure,
verifier: lineage,
});
},
]);