Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(setup): preserve Cordis ownership across uncertain patch structure

morluto21eff3bae10f
diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts
index 588b0f9af..dc246d5e6 100644
--- a/src/application/ClientRegistrationStatus.ts
+++ b/src/application/ClientRegistrationStatus.ts
@@ -154,6 +154,20 @@ export const readClientRegistrationStatuses = async (
const policyBlock = policy.value;
const raw = effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
if (raw === undefined) {
+ const editabilityError =
+ parsed.dialect === "dsh"
+ ? dshDocument(parsed.document).editabilityError
+ : undefined;
+ if (editabilityError !== undefined) {
+ statuses.push({
+ client: client.name,
+ config_path: client.configPath,
+ command: [],
+ state: "invalid",
+ remediation: editabilityError.message,
+ });
+ continue;
+ }
statuses.push(
unavailableStatus(client.name, client.configPath, "missing"),
);
diff --git a/src/application/DshCordisPatch.ts b/src/application/DshCordisPatch.ts
index 81f7428fb..5e0fc10ec 100644
--- a/src/application/DshCordisPatch.ts
+++ b/src/application/DshCordisPatch.ts
@@ -19,6 +19,7 @@ interface PatchOperation {
readonly map: YAMLMap<unknown, unknown>;
readonly ownedRows: readonly number[];
readonly direct: boolean;
+ readonly unknownApplicability: boolean;
}
/** One interpretation of identity, ordered patch applicability and source nodes. */
@@ -29,6 +30,8 @@ export class DshCordisDocument {
#entryNode: YAMLMap<unknown, unknown> | undefined;
readonly #insertions: number;
#unknownSelector = false;
+ #unknownStructure = false;
+ readonly #editabilityError: ConfigurationError | undefined;
readonly config: Record<string, unknown> | undefined;
constructor(text: string) {
@@ -38,22 +41,39 @@ export class DshCordisDocument {
throw new ConfigurationError("Cordis patches must be a list");
const operations: PatchOperation[] = [];
let insertions = 0;
+ let malformedStructure = false;
for (const source of root.items) {
const map = this.#map(source);
- if (map === undefined) continue;
+ if (map === undefined) {
+ if (this.#yaml.value(source) instanceof CordisExpression)
+ this.#unknownStructure = true;
+ else malformedStructure = true;
+ continue;
+ }
const inserted = this.#yaml.resolve(this.#yaml.field(map, "insert"));
const targetId = this.#id(map);
+ const unknownApplicability = targetId !== undefined;
+ const insertedValue = this.#yaml.value(inserted);
+ const invalidEntries = isSeq(inserted)
+ ? inserted.items.filter((entry) => this.#map(entry) === undefined)
+ : [];
+ if (
+ insertedValue instanceof CordisExpression ||
+ invalidEntries.some(
+ (entry) => this.#yaml.value(entry) instanceof CordisExpression,
+ )
+ )
+ this.#unknownStructure = true;
+ else if (insertedValue != null && !isSeq(inserted))
+ malformedStructure = true;
+ else if (invalidEntries.length > 0) malformedStructure = true;
const ownedRows = isSeq(inserted)
? inserted.items.flatMap((entry, index) =>
this.#id(entry) === DSH_ENTRY_ID ? [index] : [],
)
: [];
const direct = !isSeq(inserted) && targetId === DSH_ENTRY_ID;
- if (ownedRows.length > 0 && targetId)
- throw new ConfigurationError(
- "Cannot establish the target group for a Cordis REA insertion from the home patch alone",
- );
- operations.push({ source, map, ownedRows, direct });
+ operations.push({ source, map, ownedRows, direct, unknownApplicability });
if (isSeq(inserted)) {
for (const index of ownedRows) {
const entry = this.#map(inserted.items[index]);
@@ -81,6 +101,33 @@ export class DshCordisDocument {
}
this.#operations = operations;
this.#insertions = insertions;
+ this.#editabilityError = this.#unknownStructure
+ ? new ConfigurationError(
+ "Expression-backed Cordis patches have unknown structure; use literal patches before setup",
+ )
+ : malformedStructure
+ ? new ConfigurationError(
+ "Malformed Cordis patches cannot be edited safely; use mapping entries and insert lists before setup",
+ )
+ : operations.some(
+ (op) => op.unknownApplicability && op.ownedRows.length > 0,
+ )
+ ? new ConfigurationError(
+ "Cordis REA insertion targets a group with unknown activity; use a direct insertion before setup",
+ )
+ : this.#unknownSelector
+ ? new ConfigurationError(
+ "Expression-backed Cordis name selectors have unknown applicability; use literal selectors before setup",
+ {
+ settings: [
+ {
+ setting: "name",
+ constraint: "Use literal selectors before setup",
+ },
+ ],
+ },
+ )
+ : undefined;
const config = this.#field("config");
// Ownership survives malformed config so uninstall can remove the source row.
this.config = insertions === 0 ? undefined : isRecord(config) ? config : {};
@@ -114,11 +161,17 @@ export class DshCordisDocument {
get carriesEntry(): boolean {
return this.#operations.some((op) => op.direct || op.ownedRows.length > 0);
}
+ get hasUnknownStructure(): boolean {
+ return this.#unknownStructure;
+ }
+ get editabilityError(): ConfigurationError | undefined {
+ return this.#editabilityError;
+ }
get ready(): boolean {
const disabled = this.#field("disabled");
return (
this.#insertions === 1 &&
- !this.#unknownSelector &&
+ this.#editabilityError === undefined &&
this.#field("name") === DSH_CLIENT_PACKAGE &&
(disabled === undefined || disabled === false)
);
@@ -128,20 +181,6 @@ export class DshCordisDocument {
environment(
overrides: Readonly<Record<string, string>> = {},
): Result<Readonly<Record<string, string>>, ConfigurationError> {
- if (this.#unknownSelector)
- return err(
- new ConfigurationError(
- "Expression-backed Cordis name selectors have unknown applicability; use literal selectors before setup",
- {
- settings: [
- {
- setting: "name",
- constraint: "Use literal selectors before setup",
- },
- ],
- },
- ),
- );
const config = this.#field("config");
if (config instanceof CordisExpression)
return err(
@@ -200,6 +239,8 @@ export class DshCordisDocument {
command: readonly string[],
overrides: Readonly<Record<string, string>>,
): Result<Record<string, unknown>, ConfigurationError> {
+ if (this.#editabilityError !== undefined)
+ return err(this.#editabilityError);
const environment = this.environment(overrides);
if (!environment.ok) return environment;
const env = {
@@ -214,6 +255,11 @@ export class DshCordisDocument {
/** Plan every replacement from source snapshots before changing an output tree. */
serialize(desired?: Record<string, unknown>): string {
+ if (
+ this.#editabilityError !== undefined &&
+ (this.#unknownStructure || desired !== undefined)
+ )
+ throw this.#editabilityError;
const root = this.#yaml.document.contents;
if (!isSeq(root))
throw new ConfigurationError("Cordis patches must be a list");
diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts
index ac493282a..a4f4e837e 100644
--- a/src/application/SetupClientConfiguration.ts
+++ b/src/application/SetupClientConfiguration.ts
@@ -59,6 +59,13 @@ const configureClientDocument = async (
throwCleanupFailure(files.error);
return { status: "failed", reason: "readback" };
}
+ const existing = files.value.at(-1);
+ const editabilityError =
+ existing?.dialect === "dsh"
+ ? dshDocument(existing.document).editabilityError
+ : undefined;
+ if (editabilityError !== undefined)
+ return { status: "failed", reason: "readback" };
const policy = await readClientPolicyBlock(
client,
undefined,
@@ -284,15 +291,20 @@ export const inspectClientConfiguration = async (
remediation: files.error.detail,
};
}
+ const existing = files.value.at(-1);
+ const editabilityError =
+ existing?.dialect === "dsh"
+ ? dshDocument(existing.document).editabilityError
+ : undefined;
+ if (editabilityError !== undefined)
+ return {
+ status: "invalid",
+ remediation: editabilityError.message,
+ };
const policy = await readClientPolicyBlock(
client,
undefined,
- clientConfigurationDesired(
- client,
- providerEnvironment,
- command,
- files.value.at(-1),
- ),
+ clientConfigurationDesired(client, providerEnvironment, command, existing),
);
if (!policy.ok) {
throwCleanupFailure(policy.error);
diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts
index d474419a8..9880c8cb9 100644
--- a/src/application/Uninstall.ts
+++ b/src/application/Uninstall.ts
@@ -310,6 +310,15 @@ const removeClient = async (
// still belongs to that id, and so does a direct patch that projects no row.
const carriesDshEntry =
parsed.dialect === "dsh" && dshDocument(parsed.document).carriesEntry;
+ if (
+ parsed.dialect === "dsh" &&
+ dshDocument(parsed.document).hasUnknownStructure
+ )
+ return item(
+ client.name,
+ "retained",
+ "A Cordis expression may produce registration rows, so the patch was retained without changes.",
+ );
if (!hasNative && legacyPath === undefined && !carriesDshEntry)
return item(client.name, "skipped", "REA registration is absent.");
const removeNative =
diff --git a/tests/acceptance/setup/dshClientSetup.test.ts b/tests/acceptance/setup/dshClientSetup.test.ts
index 1ee935da6..4010369cd 100644
--- a/tests/acceptance/setup/dshClientSetup.test.ts
+++ b/tests/acceptance/setup/dshClientSetup.test.ts
@@ -230,3 +230,70 @@ cliTest.for(["null", "caller-value", "[caller-value]"])(
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(initial);
},
);
+
+cliTest.for([
+ {
+ label: "group-owned rows",
+ patch: `- id: tools
+ insert:
+ - id: other
+ name: caller-plugin
+ - id: rea-mcp
+ name: '@deepseek-ai/dsh-mcp-client'
+ config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
+`,
+ remediation: "group with unknown activity",
+ removal: "removed",
+ },
+ {
+ label: "expression-backed inserts",
+ patch: "- insert: !!js process.env.DSH_ROWS\n",
+ remediation: "unknown structure",
+ removal: "retained",
+ },
+])(
+ "DSH CLI rejects setup and preserves ownership for $label",
+ async ({ patch, remediation, removal }, { cli }) => {
+ const home = await createTestTempDirectory("rea-dsh-ownership-");
+ const profile = join(home, ".dsh");
+ const config = join(profile, "cordis.patch.yml");
+ await mkdir(profile);
+ await writeFile(config, patch);
+ const run = (args: readonly string[]) =>
+ cli.run({
+ arguments: [...args, "--json"],
+ cwd: home,
+ environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
+ });
+ const setup = await run(["setup", "--client", "dsh", "--yes"]);
+ expect(setup.exitCode).not.toBe(0);
+ expect(setup.json).toMatchObject({
+ status: "needs_human",
+ appliedActions: [],
+ remediation: expect.stringContaining(remediation),
+ });
+ expect(await readFile(config, "utf8")).toBe(patch);
+ await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ const uninstall = await run(["uninstall"]);
+ expect(uninstall.exitCode).toBe(0);
+ expect(uninstall.json).toMatchObject({
+ status: "complete",
+ items: expect.arrayContaining([
+ expect.objectContaining({ name: "dsh", status: removal }),
+ ]),
+ });
+ if (removal === "removed") {
+ expect(parse(await readFile(config, "utf8"))).toEqual([
+ { id: "tools", insert: [{ id: "other", name: "caller-plugin" }] },
+ ]);
+ expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(patch);
+ } else {
+ expect(await readFile(config, "utf8")).toBe(patch);
+ await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ }
+ },
+);
diff --git a/tests/boundary/filesystem/dshClientConfiguration.test.ts b/tests/boundary/filesystem/dshClientConfiguration.test.ts
index c33354b40..72dbded9e 100644
--- a/tests/boundary/filesystem/dshClientConfiguration.test.ts
+++ b/tests/boundary/filesystem/dshClientConfiguration.test.ts
@@ -12,7 +12,10 @@ import {
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
-import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
+import {
+ configureClientConfiguration,
+ inspectClientConfiguration,
+} from "../../../src/application/SetupClientConfiguration.js";
import {
clientSkillDirectories,
supportedClients,
@@ -398,18 +401,134 @@ describe("DeepSeek Harness repair boundaries", () => {
]);
});
- it("refuses a group-targeted insertion whose applicability is unknown", async () => {
+ it("keeps group-targeted ownership for uninstall while setup rejects unknown activity", async () => {
+ const { home, client } = await harnessClient();
+ const initial = stringifyYaml([
+ {
+ id: "tools",
+ insert: [
+ canonicalEntry(),
+ { id: "foreign-peer", name: "caller-plugin", config: { keep: true } },
+ ],
+ },
+ ]);
+ await writeFile(client.configPath, initial);
+ expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
+ {
+ status: "invalid",
+ remediation: expect.stringContaining("targets a group"),
+ },
+ );
+ expect(
+ (await configureClientConfiguration(client, {}, command)).status,
+ ).toBe("failed");
+ expect(await dshStatus(home)).toMatchObject({
+ state: "stale",
+ command: [...command],
+ });
+ expect(await readFile(client.configPath, "utf8")).toBe(initial);
+ const host = systemUninstallHost(home);
+ expect(await host.inspectClient(client)).toBeUndefined();
+ expect((await host.removeClient(client)).status).toBe("removed");
+ expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
+ {
+ id: "tools",
+ insert: [
+ { id: "foreign-peer", name: "caller-plugin", config: { keep: true } },
+ ],
+ },
+ ]);
+ expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
+ initial,
+ );
+ });
+
+ it("blocks malformed literal patches but still uninstalls a known owned sibling", async () => {
const { home, client } = await harnessClient();
const initial = stringifyYaml([
- { id: "missing-group", insert: [canonicalEntry()] },
+ { insert: [canonicalEntry()] },
+ "foreign-invalid-row",
]);
await writeFile(client.configPath, initial);
+
+ expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
+ {
+ status: "invalid",
+ remediation: expect.stringContaining("Malformed Cordis patches"),
+ },
+ );
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("failed");
- expect(await dshStatus(home)).not.toMatchObject({ state: "aligned" });
expect(await readFile(client.configPath, "utf8")).toBe(initial);
+
+ const host = systemUninstallHost(home);
+ expect(await host.inspectClient(client)).toBeUndefined();
+ expect((await host.removeClient(client)).status).toBe("removed");
+ expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual([
+ "foreign-invalid-row",
+ ]);
});
+
+ it.each(["{ id: rea-mcp }", "7", "false", "''", "[null]"])(
+ "blocks a non-list literal insert value %s before setup edits the file",
+ async (insert) => {
+ const { client } = await harnessClient();
+ const initial = `- insert: ${insert}\n`;
+ await writeFile(client.configPath, initial);
+
+ expect(
+ await inspectClientConfiguration(client, {}, command),
+ ).toMatchObject({
+ status: "invalid",
+ remediation: expect.stringContaining("Malformed Cordis patches"),
+ });
+ expect(
+ (await configureClientConfiguration(client, {}, command)).status,
+ ).toBe("failed");
+ expect(await readFile(client.configPath, "utf8")).toBe(initial);
+ },
+ );
+
+ it("keeps Harness's null insert no-op editable", async () => {
+ const { client } = await harnessClient();
+ await writeFile(client.configPath, "- insert: null\n");
+
+ expect(
+ (await configureClientConfiguration(client, {}, command)).status,
+ ).toBe("configured");
+ });
+});
+
+describe("DeepSeek Harness expression-backed structure", () => {
+ it.each([
+ `- !!js process.env.DSH_PATCH\n`,
+ `- insert: !!js process.env.DSH_ROWS\n`,
+ `- insert: [!!js process.env.DSH_ROW]\n`,
+ ])(
+ "retains dynamic insertion structure without appending or removing rows: %s",
+ async (initial) => {
+ const { home, client } = await harnessClient();
+ await writeFile(client.configPath, initial);
+ expect(await dshStatus(home)).toMatchObject({ state: "invalid" });
+ expect(
+ await inspectClientConfiguration(client, {}, command),
+ ).toMatchObject({
+ status: "invalid",
+ remediation: expect.stringContaining("unknown structure"),
+ });
+ expect(
+ (await configureClientConfiguration(client, {}, command)).status,
+ ).toBe("failed");
+ expect(await readFile(client.configPath, "utf8")).toBe(initial);
+ const host = systemUninstallHost(home);
+ expect((await host.removeClient(client)).status).toBe("retained");
+ expect(await readFile(client.configPath, "utf8")).toBe(initial);
+ await expect(
+ readFile(`${client.configPath}.rea.backup`, "utf8"),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ },
+ );
});
describe("DeepSeek Harness registration state", () => {
@@ -993,7 +1112,7 @@ describe("DeepSeek Harness alias targets", () => {
const { client } = await harnessClient();
await writeFile(
client.configPath,
- `- insert: &rows
+ `- holder: &rows
- id: other-tool
name: other
config:
@@ -1015,7 +1134,7 @@ describe("DeepSeek Harness alias targets", () => {
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("other-tool");
expect(text).not.toContain("*rows");
- expect(text).not.toContain("stale-launcher");
+ expect(text).toContain("stale-launcher");
const patches = parseYaml(text) as { insert?: { id?: string }[] }[];
expect(
patches.flatMap(({ insert }) =>
@@ -1063,11 +1182,11 @@ describe("DeepSeek Harness alias targets", () => {
});
describe("DeepSeek Harness alias identity", () => {
- it("keeps unrelated rows when the insert list is anchored outside an operation", async () => {
+ it("keeps unrelated rows when a valid insertion list is aliased", async () => {
const { client } = await harnessClient();
await writeFile(
client.configPath,
- `- &rows
+ `- holder: &rows
- id: other-tool
name: other
config:
@@ -1107,7 +1226,8 @@ describe("DeepSeek Harness alias identity", () => {
const { client } = await harnessClient();
await writeFile(
client.configPath,
- `- &expr !!js process.env.TOKEN
+ `- insert: []
+ callerExpression: &expr !!js process.env.TOKEN
- insert:
- id: rea-mcp
name: "@deepseek-ai/dsh-mcp-client"
@@ -1137,7 +1257,8 @@ describe("DeepSeek Harness alias identity", () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
- `- &entryId rea-mcp
+ `- insert: []
+ holder: &entryId rea-mcp
- insert:
- id: *entryId
name: "@deepseek-ai/dsh-mcp-client"
@@ -1201,7 +1322,8 @@ describe("DeepSeek Harness alias cleanup", () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
- `- &expr !!js process.env.GHIDRA_INSTALL_DIR
+ `- insert: []
+ callerExpression: &expr !!js process.env.GHIDRA_INSTALL_DIR
- insert:
- id: rea-mcp
name: "@deepseek-ai/dsh-mcp-client"
@@ -1475,46 +1597,11 @@ describe("DeepSeek Harness alias anchors", () => {
).toBe("unchanged");
});
- it("edits a root alias whose insert list is itself an alias", async () => {
- const { client } = await harnessClient();
- await writeFile(
- client.configPath,
- `- &rows
- - id: other-tool
- name: other
- config:
- command: keep-me
- - id: rea-mcp
- name: "@deepseek-ai/dsh-mcp-client"
- config:
- serverName: rea
- transport: stdio
- command: stale-launcher
- args: [mcp]
-- holder: &op
- insert: *rows
-- *op
-`,
- );
-
- expect(
- (await configureClientConfiguration(client, {}, command)).status,
- ).toBe("configured");
- const inserted = loadedInserts(await readFile(client.configPath, "utf8"));
- expect(inserted.filter((entry) => entry.id === "other-tool")).toHaveLength(
- 1,
- );
- expect(inserted.filter((entry) => entry.id === "rea-mcp")).toHaveLength(1);
- expect(
- (await configureClientConfiguration(client, {}, command)).status,
- ).toBe("unchanged");
- });
-
it("drops a replayed root alias after its insert alias is emptied", async () => {
const { home, client } = await harnessClient();
await writeFile(
client.configPath,
- `- &rows
+ `- holder: &rows
- id: rea-mcp
name: "@deepseek-ai/dsh-mcp-client"
config:
@@ -1866,7 +1953,7 @@ describe("DeepSeek Harness ownership and editability", () => {
);
const initial = yaml.toString();
await writeFile(client.configPath, initial);
- expect(await dshStatus(home)).toMatchObject({ state: "invalid" });
+ expect(await dshStatus(home)).toMatchObject({ state: "stale" });
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("failed");