Files
rea/scripts/verify-deepseek-client.mjs
T
d9d2a17381 feat(setup): register DeepSeek Harness through setup, doctor and uninstall (#1929)
* feat(setup): register DeepSeek Harness through setup, doctor and uninstall

DeepSeek Harness registers MCP clients through a Cordis YAML patch
sequence in the home patch rather than a server table, so setup could
not configure it and users had to append the documented entry by hand.

Add a dsh client: the home patch $DSH_HOME/cordis.patch.yml
(~/.dsh/cordis.patch.yml when unset) is parsed as a patch list, the REA
entry owns the stable rea-mcp id, and setup appends or replaces exactly
that entry while preserving unrelated patches and comments in place.
Doctor reports the registration through the same entry, and uninstall
removes it, dropping insert operations it emptied. Skill destinations
follow ~/.agents/skills ($DSH_AGENTS_HOME/skills when configured), the
home the rest of the client machinery already uses.

Fixes #1839

* fix(setup): carry environment and identity validation into DSH registrations

Address review: the DSH entry discarded discovered provider overrides;
config.env is now emitted and retained like the other dialects. An entry
carrying the rea-mcp id under a wrong or missing package name, or
duplicated entries, reads back as absent so setup rewrites exactly one
canonical entry instead of reporting unchanged. Doctor now requires
serverName rea and stdio transport before calling a DSH registration
aligned, and the Harness skill identifier in the docs matches the
installed reverse-engineer-anything skill.

* fix(setup): apply Cordis patch order and collapse DSH registrations

Address review: a later direct { id, config } operation replaces the
row's config under the native patch DSL, so the registration view now
applies patches in order instead of only reading insert operations;
doctor reports the effective command rather than the inserted one.
Setup rewrites exactly one canonical entry: duplicate id-matching rows
collapse to the first, direct patches to the entry are dropped from the
document and from the edited YAML, and uninstall removes them with the
entry. The client-location test fixture now clears DSH_HOME and
DSH_AGENTS_HOME so a developer environment cannot point the suite at
real Harness homes.

* fix(setup): repair direct-only registrations and preserve Cordis entry state

Serialize now edits the first insertion carrying rea-mcp in place, so a
grouped entry keeps its scope, neighbors, and comments instead of moving
to a fresh root-level insertion, and later carrying insertions and direct
patches collapse away. Entry-level disabled state projects into the
registration the doctor and setup compare, so a disabled row reads as
stale and the repair re-enables it. A direct-only registration no longer
suppresses the canonical insert append, and an update retains the
registration environment. Duplicate entries collapse across operations,
not only within one.

* fix(setup): preserve Harness row state through identity and refresh repairs

A wrong-package row still reads back as a server record carrying its
environment and caller fields, projected with a package marker the
alignment path treats as stale, instead of vanishing and dropping
config.env from the repair. A direct Cordis patch without a preceding
insertion configures nothing, so a direct-only registration reads as
absent even when its config matches and the repair appends the insert.
Caller-owned config fields beyond the REA-owned keys, such as the cwd
the native verifier sets, survive a refresh instead of being silently
dropped.

* fix(setup): preserve Cordis tags and collapse aligned Harness rows

A refresh rebuilt Harness config from parsed values, so a caller !!js
expression was written back as a literal. Owned keys are now overlaid on
the winning config node and other nodes stay in place. Two already-aligned
rea-mcp insertions read as stale, so setup collapses them to one row, and
the bundled skill lists dsh with the other clients.

* fix(setup): drop the unused DSH configuration type

Knip reports DshConfigurationFormat as an unused export. The format union
does not depend on that alias.

* fix(setup): keep Harness env tags and comment-only patches

A refresh replaced the whole env map, so a caller !!js value was written
back as a literal. Environment entries now stay in place unless the value
changed. A comment-only cordis.patch.yml parses as an empty patch list and
keeps those comments when the registration is appended. Docs describe
plain rea uninstall, which scans supported clients and has no --client flag.

* fix(setup): own Harness rows by entry id and expression state

Uninstall removes a rea-mcp row even when the launcher is stale or the
patch never established a server record. A non-boolean disabled value,
including a Cordis expression, reads as stale. Expression text on a known
environment setting is not validated as a literal path, so a refresh can
keep the tag.

* fix(setup): collapse aliased Harness insertions

An anchored insert followed by an alias parses as two rea-mcp rows, but
the YAML edit kept the alias, so readback stayed duplicated and setup
restored the file. Aliases that resolve to the owned entry are now
dropped, including an alias of the entry inside one insert. Aliases of
other patches stay.

* fix(setup): resolve aliased Harness lists and config maps

An insert value that aliases another entry list still loaded a second
rea-mcp row after the operation-level alias collapse. That alias is now
dropped once the anchored list is rewritten. A config: *cfg map is
resolved and cloned before the refresh, so a caller !!js field on the
aliased map is not rewritten as a plain literal.

* fix(setup): follow Harness aliases for ids, lists, and env tags

An insert alias whose anchor is not another insert is copied so
unrelated rows stay while the owned row is rewritten. An aliased
entry id is resolved before ownership checks, and an environment alias
of an unchanged !!js scalar is left in place.

* fix(setup): keep aliased Harness env maps through uninstall

An env alias is cloned before a refresh so tagged values are not rebuilt
as literals, and expression-key scans follow aliases before path checks.
Insert aliases that carry REA are recorded before uninstall empties their
anchor, so the later alias is dropped instead of dangling.

* fix(setup): follow root Harness aliases and mark dsh as main-only

Winning-config walks resolve a root alias before patch order, so a replayed direct config's !!js env is not validated as a literal path. Root aliases that own rea-mcp are recorded before uninstall empties their anchor. An insert whose only owned member is an external alias is cloned so Cordis tags survive. Docs state dsh is not in npm 6.4.0.

* fix(setup): keep rows behind inert Harness aliases

A root alias whose anchor is not a loaded operation is copied and only the owned row is edited, so unrelated rows stay active. Entry id aliases become a scalar before their anchor patch is dropped. Root-alias ownership follows insert-list aliases, so a replay is removed instead of dangling after uninstall.

* refactor(setup): centralize Cordis source ownership

* fix(javascript): share Electron mutation proof with wrapped calls

* test(mcp): align graph and catalog checks with current contracts

* fix(setup): separate Cordis ownership from editability

* docs: clarify ownership and interpretation boundaries

* fix(setup): preserve Cordis applicability and caller metadata

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 11:06:26 +08:00

409 lines
13 KiB
JavaScript

import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { Ajv2020 } from "ajv/dist/2020.js";
import { parse as parseYaml } from "yaml";
import {
TOOL_CONTRACTS,
toolContract,
} from "../dist/contracts/toolContracts.js";
import { exec, pathExists } from "./lib/verify-package-core.mjs";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
import { createOpenAiModelFixture } from "./verify/clients/model-fixture.mjs";
const mode = process.argv[2] ?? "call";
assert(["chat", "call"].includes(mode), "Select chat or call.");
assert(process.platform !== "win32", "Native Windows coverage 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_DEEPSEEK_COMMAND ?? "dsh";
const lab = await mkdtemp(join(tmpdir(), "rea-deepseek-client-"));
const account = join(lab, "account");
const profile = join(lab, "selected profile");
const workspace = join(lab, "workspace");
const target = join(workspace, "fixture α测试");
const skillPath = join(
account,
".agents",
"skills",
"reverse-engineer-anything",
"SKILL.md",
);
const cli = join(runtimeRoot, "scripts", "rea.mjs");
const configPath = join(profile, "cordis.patch.yml");
const verifier = createVerifierRun();
await Promise.all([
mkdir(account),
mkdir(profile),
mkdir(target, { recursive: true }),
]);
const environment = {
PATH: process.env.PATH ?? "",
HOME: account,
USERPROFILE: account,
DSH_HOME: profile,
OPENAI_API_KEY: "local-fixture-key",
REA_PROCESS_RUN_ID: verifier.run_id,
};
// A temporary directory under the checkout must not inherit its project skills or AGENTS.md.
await exec(
"git",
["-c", "init.defaultBranch=main", "init", "--quiet", workspace],
{
env: environment,
timeout: 30_000,
},
);
await writeFile(
join(target, "app.js"),
'export function result() { return { clientCompatibility: "REA_CLIENT_FIXTURE", count: 7 }; }\n',
);
const clientVersion = (
await exec(command, ["--version"], {
env: environment,
cwd: workspace,
timeout: 30_000,
})
).stdout.trim();
const lifecycle = [];
const runRea = async (args, artifact) => {
const result = await exec(process.execPath, [cli, ...args, "--json"], {
env: environment,
cwd: workspace,
timeout: 60_000,
});
await writeFile(join(lab, `${artifact}.json`), result.stdout);
return JSON.parse(result.stdout);
};
const patches = (text) =>
parseYaml(text, {
customTags: [
{
tag: "tag:yaml.org,2002:js",
resolve: (source) => ({ __jsExpr: source }),
},
],
});
const withoutRea = (text) =>
patches(text).flatMap((op) => {
if (op.id === "rea-mcp") return [];
if (!Array.isArray(op.insert)) return [op];
const insert = op.insert.filter((entry) => entry.id !== "rea-mcp");
return insert.length === 0 ? [] : [{ ...op, insert }];
});
let catalog;
let patternCount = 0;
let skillRequested = false;
let skillLoaded = false;
let evidenceSeen = false;
let finalSeen = false;
let artifactDigest;
let mainRequests = 0;
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const patterns = new Set();
const validatePatterns = (value) => {
if (!value || typeof value !== "object") return;
for (const [key, child] of Object.entries(value)) {
if (key === "pattern" && typeof child === "string") {
// Check the representation the native client actually forwards to its model adapter.
for (const flags of ["", "u", "v"]) new RegExp(child, flags);
patterns.add(child);
patternCount++;
} else validatePatterns(child);
}
};
const extractEvidence = (value) => {
if (typeof value === "string") {
try {
return extractEvidence(JSON.parse(value));
} catch {
return undefined;
}
}
if (value && typeof value === "object") {
if (
typeof value.evidence_id === "string" &&
value.normalized_result?.graph?.nodes
)
return value;
for (const child of Object.values(value)) {
const found = extractEvidence(child);
if (found) return found;
}
}
};
const fixture = await createOpenAiModelFixture({
directory: lab,
prefix: `deepseek-${mode}`,
onRequest: async ({ body, tools, requestIndex }) => {
// Harness generates a session title in a separate, tool-free model request.
if (tools.length === 0)
return { role: "assistant", content: "REA validation" };
assert(
++mainRequests <= 4,
"Harness did not complete the bounded fixture workflow.",
);
const rea = tools.filter((tool) => tool.name.startsWith("mcp__rea__"));
const observedCatalog = rea
.map((tool) => tool.name.slice("mcp__rea__".length))
.sort();
assert.deepEqual(
observedCatalog,
TOOL_CONTRACTS.map((tool) => tool.name).sort(),
);
if (catalog === undefined) {
catalog = observedCatalog;
for (const tool of rea) {
assert(
ajv.validateSchema(tool.parameters),
`${tool.name}: ${ajv.errorsText(ajv.errors)}`,
);
validatePatterns(tool.parameters);
}
assert(
patternCount > 0,
"The advertised regex constraints must reach the model.",
);
}
const toolMessages = (body.messages ?? []).filter(
(message) => message.role === "tool",
);
const serialized = JSON.stringify(toolMessages);
skillLoaded ||=
serialized.includes(
'<skill_content name=\\"reverse-engineer-anything\\">',
) && serialized.includes(dirname(skillPath));
for (const message of toolMessages) {
const found = extractEvidence(message.content);
if (found === undefined) continue;
const evidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(found);
assert.equal(evidence.subject.local_path, target);
const shape = evidence.normalized_result.graph.nodes
.flatMap((node) => node.observations)
.map((observation) => observation.properties)
.find(
(properties) =>
properties.semantic_role === "export-return-shapes" &&
properties.exported_name === "result",
);
assert(shape?.return_shape_coverage?.projection_complete);
const fields = shape.static_return_shapes.flatMap(
(entry) => entry.fields,
);
assert(
fields.some(
(field) =>
field.path === "/clientCompatibility" &&
field.state === "literal" &&
field.value === "REA_CLIENT_FIXTURE",
),
);
assert(
fields.some(
(field) =>
field.path === "/count" &&
field.state === "literal" &&
field.value === 7,
),
);
const text = JSON.stringify(evidence);
await writeFile(join(lab, "evidence.json"), text);
artifactDigest = createHash("sha256").update(text).digest("hex");
evidenceSeen = true;
}
if (mode === "chat" || evidenceSeen) {
finalSeen = true;
return { role: "assistant", content: "REA_CLIENT_COMPATIBILITY_OK" };
}
const call = (name, args) => ({
role: "assistant",
content: null,
tool_calls: [
{
id: `call_rea_${requestIndex}`,
type: "function",
function: { name, arguments: JSON.stringify(args) },
},
],
});
if (!skillRequested) {
assert(tools.some((tool) => tool.name === "skill"));
skillRequested = true;
return call("skill", { name: "reverse-engineer-anything" });
}
assert(
skillLoaded,
"Harness must load the installed skill before analysis.",
);
return call("mcp__rea__analyze_javascript_application", {
input_path: target,
format: "directory",
});
},
});
let failure;
try {
// Seed model settings and a stale registration; the public setup workflow
// must produce the registration this native client actually boots.
const original = `
- id: llm-pi-ai
config:
providers:
rea-fixture:
apiKeyEnv: OPENAI_API_KEY
api: openai-completions
baseURL: ${fixture.baseUrl}
defaultMaxTokens: 4096
retryPolicy:
mode: normal
maxRetries: 0
models:
- id: rea-client-fixture
contextWindow: 1000000
- id: agent-default-model
config:
provider: rea-fixture
model: rea-client-fixture
- insert:
- id: rea-mcp
name: '@deepseek-ai/dsh-mcp-client'
config:
serverName: rea
transport: stdio
command: stale-launcher
args: [mcp]
cwd: !!js process.cwd()
env:
REA_PROCESS_RUN_ID: ${JSON.stringify(verifier.run_id)}
`;
await writeFile(configPath, original);
const planned = await runRea(
["setup", "--client", "dsh", "--dry-run"],
"setup-plan",
);
assert.equal(planned.status, "planned");
assert(planned.plannedActions.some((action) => action.target === configPath));
assert(
planned.plannedActions.some(
(action) => action.target === dirname(skillPath),
),
);
assert(
planned.plannedActions.every(
(action) =>
action.target === configPath || action.target === dirname(skillPath),
),
);
assert.equal(await readFile(configPath, "utf8"), original);
assert.equal(await pathExists(`${configPath}.rea.backup`), false);
lifecycle.push("dry-run");
const setup = await runRea(["setup", "--client", "dsh", "--yes"], "setup");
assert.equal(setup.status, "ready");
assert.equal(await readFile(`${configPath}.rea.backup`, "utf8"), original);
const configured = await readFile(configPath, "utf8");
assert.deepEqual(withoutRea(configured), withoutRea(original));
assert(configured.includes("!!js process.cwd()"));
assert(
(await readFile(skillPath, "utf8")).includes(
"name: reverse-engineer-anything",
),
);
lifecycle.push("setup");
const repeated = await runRea(
["setup", "--client", "dsh", "--yes"],
"setup-repeat",
);
assert.deepEqual(repeated.appliedActions, []);
assert.equal(await readFile(configPath, "utf8"), configured);
assert.equal(await readFile(`${configPath}.rea.backup`, "utf8"), original);
lifecycle.push("idempotent-setup");
const doctor = await runRea(
["doctor", "--client", "dsh", "--skill"],
"doctor",
);
assert.equal(doctor.healthy, true);
lifecycle.push("doctor");
const execution = exec(
command,
[
"--profile",
"headless",
"--json",
mode === "chat" ? "Say hello briefly." : `Use REA to analyze ${target}.`,
],
{
env: environment,
cwd: workspace,
timeout: 120_000,
maxBuffer: 10 * 1024 * 1024,
},
);
execution.child.stdin.end();
const result = await execution;
await writeFile(join(lab, "client.stdout"), result.stdout);
await writeFile(join(lab, "client.stderr"), result.stderr);
assert.equal(fixture.failure, undefined);
assert(finalSeen && result.stdout.includes("REA_CLIENT_COMPATIBILITY_OK"));
if (mode === "call") assert(evidenceSeen && skillLoaded);
lifecycle.push(mode === "call" ? "native-tool-invocation" : "native-chat");
const uninstall = await runRea(["uninstall"], "uninstall");
assert.equal(uninstall.status, "complete");
assert(
uninstall.items.some(
(item) => item.name === "dsh" && item.status === "removed",
),
);
assert.deepEqual(
patches(await readFile(configPath, "utf8")),
withoutRea(original),
);
assert.equal(await pathExists(skillPath), false);
lifecycle.push("uninstall");
} catch (cause) {
failure = cause;
if (typeof cause?.stdout === "string")
await writeFile(join(lab, "client.stdout"), cause.stdout);
if (typeof cause?.stderr === "string")
await writeFile(join(lab, "client.stderr"), cause.stderr);
} finally {
await fixture.close();
const receipt = {
client: "deepseek-harness",
clientVersion,
mode,
lifecycle,
passed: failure === undefined,
artifacts: lab,
runtimeRoot,
host: {
platform: process.platform,
architecture: process.arch,
node: process.versions.node,
},
modelFixture:
"loopback custom OpenAI-compatible adapter; no live DeepSeek provider claim",
modelContextWindow: 1000000,
skillDiscovery:
"native HOME shared personal directory; isolated project root",
catalogSize: catalog?.length,
patternCount,
uniquePatterns: patterns.size,
skillLoaded,
evidenceSeen,
artifactDigest,
finalSeen,
requests: fixture.requests,
fixtureFailure: fixture.failure,
verifier: await completeVerifierRun(verifier),
};
await writeFile(join(lab, "receipt.json"), JSON.stringify(receipt, null, 2));
console.log(JSON.stringify(receipt));
}
if (failure !== undefined) throw failure;