Skip to content

Commit a858924

Browse files
author
Peter Steinberger
committed
fix(plugins): compare authoring metadata by canonical JSON semantics
1 parent 71a5951 commit a858924

2 files changed

Lines changed: 234 additions & 4 deletions

File tree

‎src/cli/plugins-authoring-command.test.ts‎

Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
5+
import { expectDefined } from "@openclaw/normalization-core";
56
import { Type } from "typebox";
67
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
78
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
@@ -14,6 +15,7 @@ import {
1415
loadToolPlugin,
1516
runPluginsBuildCommand,
1617
runPluginsInitCommand,
18+
runPluginsValidateCommand,
1719
validateToolPluginProject,
1820
} from "./plugins-authoring-command.js";
1921

@@ -272,6 +274,230 @@ describe("plugin authoring commands", () => {
272274
).toEqual([]);
273275
});
274276

277+
it.each(["validate", "build --check"] as const)(
278+
"accepts reordered JSON object keys without rewriting files in %s",
279+
async (command) => {
280+
const tmpDir = tempDirs.make("openclaw-plugin-reordered-json-");
281+
const entryPath = writeSourceToolPluginProject({
282+
tmpDir,
283+
packageName: "openclaw-plugin-reordered-json",
284+
pluginId: "reordered-json",
285+
toolName: "reordered_json_echo",
286+
});
287+
await runPluginsBuildCommand({ root: tmpDir, entry: entryPath });
288+
289+
const manifestPath = path.join(tmpDir, "openclaw.plugin.json");
290+
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as Record<string, unknown>;
291+
const configSchema = manifest.configSchema as Record<string, unknown>;
292+
fs.writeFileSync(
293+
manifestPath,
294+
JSON.stringify(
295+
{
296+
...manifest,
297+
configSchema: {
298+
properties: configSchema.properties,
299+
additionalProperties: configSchema.additionalProperties,
300+
type: configSchema.type,
301+
},
302+
},
303+
null,
304+
2,
305+
),
306+
);
307+
const packagePath = path.join(tmpDir, "package.json");
308+
const manifestBefore = fs.readFileSync(manifestPath, "utf8");
309+
const packageBefore = fs.readFileSync(packagePath, "utf8");
310+
const exit = vi.spyOn(defaultRuntime, "exit").mockImplementation((code) => {
311+
throw new Error(`unexpected runtime exit ${code}`);
312+
});
313+
const log = vi.spyOn(defaultRuntime, "log").mockImplementation(() => {});
314+
const error = vi.spyOn(defaultRuntime, "error").mockImplementation(() => {});
315+
316+
try {
317+
if (command === "validate") {
318+
await runPluginsValidateCommand({ root: tmpDir, entry: entryPath });
319+
expect(log).toHaveBeenCalledWith("Plugin reordered-json is valid.");
320+
} else {
321+
await runPluginsBuildCommand({ root: tmpDir, entry: entryPath, check: true });
322+
expect(log).toHaveBeenCalledWith("Plugin metadata is up to date.");
323+
}
324+
expect(exit).not.toHaveBeenCalled();
325+
expect(error).not.toHaveBeenCalled();
326+
expect(fs.readFileSync(manifestPath, "utf8")).toBe(manifestBefore);
327+
expect(fs.readFileSync(packagePath, "utf8")).toBe(packageBefore);
328+
} finally {
329+
exit.mockRestore();
330+
log.mockRestore();
331+
error.mockRestore();
332+
}
333+
},
334+
);
335+
336+
it("keeps generated contract arrays ordered", () => {
337+
const metadata = createDemoMetadata();
338+
const extraTool = {
339+
...expectDefined(metadata.tools[0], "demo tool metadata"),
340+
name: "demo_extra",
341+
};
342+
const metadataWithTools = { ...metadata, tools: [...metadata.tools, extraTool] };
343+
const packageManifest = { version: "1.2.3", openclaw: { extensions: ["./src/index.ts"] } };
344+
const generated = buildToolPluginManifest({ metadata: metadataWithTools, packageManifest });
345+
const manifest = {
346+
...generated,
347+
contracts: { tools: ["demo_extra", "demo_echo"] },
348+
};
349+
350+
expect(
351+
validateToolPluginProject({
352+
metadata: metadataWithTools,
353+
entry: "./src/index.ts",
354+
manifest,
355+
packageManifest,
356+
}),
357+
).toEqual(["openclaw.plugin.json generated metadata is stale. Run openclaw plugins build."]);
358+
});
359+
360+
it("projects undefined TypeBox options into the persisted manifest shape", () => {
361+
const entry = defineToolPlugin({
362+
id: "undefined-schema-options",
363+
name: "Undefined Schema Options",
364+
description: "Plugin with optional TypeBox schema metadata.",
365+
configSchema: Type.Object(
366+
{ value: Type.Optional(Type.String({ description: undefined })) },
367+
{ description: undefined },
368+
),
369+
tools: (tool) => [
370+
tool({
371+
name: "undefined_schema_echo",
372+
description: "Echo input.",
373+
parameters: Type.Object({ input: Type.String() }),
374+
execute: ({ input }) => ({ input }),
375+
}),
376+
],
377+
});
378+
const metadata = getToolPluginMetadata(entry);
379+
if (!metadata) {
380+
throw new Error("missing metadata");
381+
}
382+
const runtimeSchema = metadata.configSchema;
383+
const runtimeProperties = runtimeSchema.properties as Record<string, unknown>;
384+
expect(Object.hasOwn(runtimeSchema, "description")).toBe(true);
385+
expect(Object.hasOwn(runtimeProperties.value as object, "description")).toBe(true);
386+
387+
const packageManifest = { version: "1.2.3", openclaw: { extensions: ["./src/index.ts"] } };
388+
const manifest = buildToolPluginManifest({ metadata, packageManifest });
389+
const persistedSchema = manifest.configSchema as Record<string, unknown>;
390+
const persistedProperties = persistedSchema.properties as Record<string, unknown>;
391+
expect(Object.hasOwn(persistedSchema, "description")).toBe(false);
392+
expect(Object.hasOwn(persistedProperties.value as object, "description")).toBe(false);
393+
expect(
394+
validateToolPluginProject({
395+
metadata,
396+
entry: "./src/index.ts",
397+
manifest,
398+
packageManifest,
399+
}),
400+
).toEqual([]);
401+
});
402+
403+
it.each([
404+
{
405+
label: "own prototype key versus different own key",
406+
expected: '{"__proto__":{}}',
407+
actual: '{"safe":{}}',
408+
stale: true,
409+
},
410+
{
411+
label: "different own key versus own prototype key",
412+
expected: '{"safe":{}}',
413+
actual: '{"__proto__":{}}',
414+
stale: true,
415+
},
416+
{
417+
label: "matching own prototype keys",
418+
expected: '{"__proto__":{}}',
419+
actual: '{"__proto__":{}}',
420+
stale: false,
421+
},
422+
])("compares $label in generated schemas", ({ expected, actual, stale }) => {
423+
const metadata = createDemoMetadata();
424+
const packageManifest = { version: "1.2.3", openclaw: { extensions: ["./src/index.ts"] } };
425+
const metadataWithSchema = {
426+
...metadata,
427+
configSchema: { type: "object", properties: JSON.parse(expected) as Record<string, unknown> },
428+
};
429+
const generated = buildToolPluginManifest({ metadata: metadataWithSchema, packageManifest });
430+
const manifest = {
431+
...generated,
432+
configSchema: { type: "object", properties: JSON.parse(actual) as Record<string, unknown> },
433+
};
434+
435+
expect(
436+
validateToolPluginProject({
437+
metadata: metadataWithSchema,
438+
entry: "./src/index.ts",
439+
manifest,
440+
packageManifest,
441+
}),
442+
).toEqual(
443+
stale
444+
? ["openclaw.plugin.json generated metadata is stale. Run openclaw plugins build."]
445+
: [],
446+
);
447+
});
448+
449+
it("still rejects a changed generated config schema", () => {
450+
const metadata = createDemoMetadata();
451+
const packageManifest = { version: "1.2.3", openclaw: { extensions: ["./src/index.ts"] } };
452+
const generated = buildToolPluginManifest({ metadata, packageManifest });
453+
const manifest = {
454+
...generated,
455+
configSchema: {
456+
...(generated.configSchema as Record<string, unknown>),
457+
additionalProperties: true,
458+
},
459+
};
460+
461+
expect(
462+
validateToolPluginProject({
463+
metadata,
464+
entry: "./src/index.ts",
465+
manifest,
466+
packageManifest,
467+
}),
468+
).toEqual(["openclaw.plugin.json generated metadata is stale. Run openclaw plugins build."]);
469+
});
470+
471+
it("rejects a missing generated manifest without changing package metadata", async () => {
472+
const tmpDir = tempDirs.make("openclaw-plugin-missing-generated-manifest-");
473+
const entryPath = writeSourceToolPluginProject({
474+
tmpDir,
475+
packageName: "openclaw-plugin-missing-generated-manifest",
476+
pluginId: "missing-generated-manifest",
477+
toolName: "missing_generated_manifest_echo",
478+
});
479+
const packagePath = path.join(tmpDir, "package.json");
480+
const packageBefore = fs.readFileSync(packagePath, "utf8");
481+
const exit = vi.spyOn(defaultRuntime, "exit").mockImplementation((code) => {
482+
throw new Error(`runtime exit ${code}`);
483+
});
484+
const error = vi.spyOn(defaultRuntime, "error").mockImplementation(() => {});
485+
486+
try {
487+
await expect(
488+
runPluginsBuildCommand({ root: tmpDir, entry: entryPath, check: true }),
489+
).rejects.toThrow("runtime exit 1");
490+
expect(error).toHaveBeenCalledWith(
491+
"Generated plugin metadata is out of date. Run openclaw plugins build.",
492+
);
493+
expect(fs.readFileSync(packagePath, "utf8")).toBe(packageBefore);
494+
expect(fs.existsSync(path.join(tmpDir, "openclaw.plugin.json"))).toBe(false);
495+
} finally {
496+
exit.mockRestore();
497+
error.mockRestore();
498+
}
499+
});
500+
275501
it("reports stale manifest contracts", () => {
276502
const metadata = createDemoMetadata();
277503

‎src/cli/plugins-authoring-command.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Plugin authoring commands for init/build/validate manifest generation.
22
import fs from "node:fs";
33
import path from "node:path";
4+
import { jsonSchemaValuesEqual } from "@openclaw/normalization-core/json-schema";
45
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
56
import { formatCwdRelativePathOrAbsolute as formatOutputPath } from "../infra/safe-cwd.js";
67
import { getToolPluginMetadata, type ToolPluginMetadata } from "../plugin-sdk/tool-plugin.js";
@@ -164,7 +165,7 @@ export function buildToolPluginManifest(params: {
164165
toolMetadata: _existingToolMetadata,
165166
...existingManifestFields
166167
} = params.existingManifest ?? {};
167-
return {
168+
const manifest: JsonObject = {
168169
...existingManifestFields,
169170
id: params.metadata.id,
170171
name: params.metadata.name,
@@ -179,6 +180,9 @@ export function buildToolPluginManifest(params: {
179180
},
180181
...(toolMetadata ? { toolMetadata } : {}),
181182
};
183+
// Runtime schema options can contain undefined fields that the manifest writer drops.
184+
const serializedManifest = JSON.stringify(manifest);
185+
return JSON.parse(serializedManifest) as JsonObject;
182186
}
183187

184188
function buildToolPluginToolMetadata(
@@ -238,7 +242,7 @@ export function validateToolPluginProject(params: {
238242
packageManifest: params.packageManifest,
239243
existingManifest: params.manifest,
240244
});
241-
if (JSON.stringify(params.manifest) !== JSON.stringify(expectedManifest)) {
245+
if (!jsonSchemaValuesEqual(params.manifest, expectedManifest)) {
242246
errors.push("openclaw.plugin.json generated metadata is stale. Run openclaw plugins build.");
243247
}
244248
if (params.manifest.id !== params.metadata.id) {
@@ -301,8 +305,8 @@ export async function runPluginsBuildCommand(opts: PluginsBuildOptions): Promise
301305
if (opts.check) {
302306
const currentPackage = readJsonFile(packagePath);
303307
if (
304-
JSON.stringify(currentManifest) !== JSON.stringify(manifest) ||
305-
JSON.stringify(currentPackage) !== JSON.stringify(nextPackageManifest)
308+
!jsonSchemaValuesEqual(currentManifest, manifest) ||
309+
!jsonSchemaValuesEqual(currentPackage, nextPackageManifest)
306310
) {
307311
defaultRuntime.error("Generated plugin metadata is out of date. Run openclaw plugins build.");
308312
return defaultRuntime.exit(1);

0 commit comments

Comments
 (0)