Skip to content

Commit d831b27

Browse files
committed
fix(protocol): fail protocol:check when the published schema drifts
dist/protocol.schema.json is gitignored and never committed, so the trailing `git diff --exit-code` guard in protocol:check exited 0 unconditionally. The Swift and Kotlin halves work because those files are tracked; the JSON half read as verification while it could not fail, leaving schema drift to the slow QA-lab scenario. scripts/prepush-ci.sh carried the same dead guard: its before/after diff covered only the untracked artifact and a file that protocol:check:swift never writes. The artifact is a build output with no committed baseline, so it gets a contract check instead of a diff. scripts/lib/protocol-schema-document.mts owns the published document; protocol-gen builds through it, asserts required frame definitions, frame ordering, discriminator mapping, and a non-empty method catalog before writing through the shared generated-output helper. The QA-lab verifier drops its duplicate envelope copy and compares the packed tarball against that same owner. The generated artifact is byte-identical to before.
1 parent d567246 commit d831b27

8 files changed

Lines changed: 286 additions & 148 deletions

File tree

‎docs/concepts/typebox.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ The authoritative advertised **discovery** inventory lives in `src/gateway/serve
6161
- `pnpm protocol:gen:swift` generates the Swift gateway models.
6262
- `pnpm protocol:check:swift` verifies the committed Swift models without rewriting them.
6363
- `pnpm protocol:gen:kotlin` generates the Android protocol models and constants.
64-
- `pnpm protocol:check` checks the registry structure, runs all three generators, and verifies the committed Swift and Kotlin output (the JSON Schema output is a gitignored build artifact).
64+
- `pnpm protocol:check` checks the registry structure, runs all three generators, and verifies the committed Swift and Kotlin output. The JSON Schema output is a gitignored build artifact with no committed baseline to diff against, so `pnpm protocol:gen` instead asserts the published-document contract (required frame definitions, frame ordering, `type` discriminator mapping, non-empty method metadata) and fails the check when the generated schema drifts from it.
6565

6666
When a gateway schema affects native clients, run `pnpm protocol:gen:swift`, review the generated diff, then run `pnpm protocol:check:swift`. Commit the schema and `GatewayModels.swift` update together. Stable decoding behavior belongs in the focused `GatewayModelsCompatibilityTests.swift` regressions rather than in handwritten model copies.
6767

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1764,7 +1764,7 @@
17641764
"prompt:snapshots:check": "node --import ./scripts/tsx.mjs scripts/generate-prompt-snapshots.ts --check",
17651765
"prompt:snapshots:gen": "node --import ./scripts/tsx.mjs scripts/generate-prompt-snapshots.ts --write",
17661766
"prompt:snapshots:sync-codex-model": "node --import ./scripts/tsx.mjs scripts/sync-codex-model-prompt-fixture.ts",
1767-
"protocol:check": "pnpm protocol-registry:check && pnpm protocol:gen && pnpm protocol:check:swift && pnpm protocol:gen:kotlin && node --import ./scripts/tsx.mjs scripts/check-protocol-since.mts && git diff --exit-code -- dist/protocol.schema.json apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewayProtocol.kt apps/android/app/src/main/java/ai/openclaw/app/protocol/OpenClawProtocolConstants.kt",
1767+
"protocol:check": "pnpm protocol-registry:check && pnpm protocol:gen && pnpm protocol:check:swift && pnpm protocol:gen:kotlin && node --import ./scripts/tsx.mjs scripts/check-protocol-since.mts && git diff --exit-code -- apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewayProtocol.kt apps/android/app/src/main/java/ai/openclaw/app/protocol/OpenClawProtocolConstants.kt",
17681768
"protocol:check:kotlin": "pnpm protocol:gen:kotlin && git diff --exit-code -- apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewayProtocol.kt apps/android/app/src/main/java/ai/openclaw/app/protocol/OpenClawProtocolConstants.kt",
17691769
"protocol:check:swift": "node --import ./scripts/tsx.mjs scripts/protocol-gen-swift.ts --check",
17701770
"protocol:gen": "node --import ./scripts/tsx.mjs scripts/protocol-gen.ts",
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Canonical published Gateway protocol schema document. The generator that
2+
// writes protocol.schema.json and the verifier that inspects the packed tarball
3+
// both build the envelope here; a second copy is how the shipped machine-readable
4+
// contract drifts without any lane noticing.
5+
6+
export type ProtocolMethodMetadata = {
7+
name: string;
8+
scope: string;
9+
since?: string;
10+
};
11+
12+
export type ProtocolSchemaDocument = {
13+
$id: string;
14+
$schema: string;
15+
definitions: Record<string, unknown>;
16+
description: string;
17+
discriminator: {
18+
mapping: Record<string, string>;
19+
propertyName: string;
20+
};
21+
methods: Record<string, { scope: string; since?: string }>;
22+
oneOf: { $ref: string }[];
23+
title: string;
24+
};
25+
26+
/** Frame definitions every consumer of the published schema resolves by name. */
27+
export const REQUIRED_PROTOCOL_DEFINITIONS = [
28+
"ConnectParams",
29+
"RequestFrame",
30+
"ResponseFrame",
31+
"EventFrame",
32+
] as const;
33+
34+
// Frame order is part of the published contract: generated clients select the
35+
// oneOf branch positionally before reading the discriminator, so req/res/event
36+
// must stay in this order across regenerations.
37+
const FRAME_DEFINITIONS_BY_TYPE = [
38+
["req", "RequestFrame"],
39+
["res", "ResponseFrame"],
40+
["event", "EventFrame"],
41+
] as const;
42+
43+
const definitionRef = (definition: string) => `#/definitions/${definition}`;
44+
const FRAME_REFS = FRAME_DEFINITIONS_BY_TYPE.map(([, definition]) => definitionRef(definition));
45+
const FRAME_DISCRIMINATOR_MAPPING = Object.fromEntries(
46+
FRAME_DEFINITIONS_BY_TYPE.map(([frameType, definition]) => [
47+
frameType,
48+
definitionRef(definition),
49+
]),
50+
);
51+
52+
/** Builds the JSON document published as protocol.schema.json. */
53+
export function buildProtocolSchemaDocument(params: {
54+
methods: readonly ProtocolMethodMetadata[];
55+
schemas: Record<string, unknown>;
56+
}): ProtocolSchemaDocument {
57+
const document = {
58+
$schema: "http://json-schema.org/draft-07/schema#",
59+
$id: "https://openclaw.ai/protocol.schema.json",
60+
title: "OpenClaw Gateway Protocol",
61+
description: "Handshake, request/response, and event frames for the Gateway WebSocket.",
62+
oneOf: FRAME_REFS.map((ref) => ({ $ref: ref })),
63+
discriminator: {
64+
propertyName: "type",
65+
mapping: FRAME_DISCRIMINATOR_MAPPING,
66+
},
67+
methods: Object.fromEntries(
68+
// Omit an absent `since` instead of carrying undefined so the document
69+
// equals the JSON the artifact ships.
70+
params.methods.map(({ name, scope, since }) => [
71+
name,
72+
since === undefined ? { scope } : { since, scope },
73+
]),
74+
),
75+
definitions: params.schemas,
76+
};
77+
// TypeBox schemas carry symbol keys that never reach JSON; cloning them away
78+
// lets the producer and the published-artifact verifier compare one document.
79+
return structuredClone(document) as ProtocolSchemaDocument;
80+
}
81+
82+
/** Rejects a published document that lost the frame contract clients decode by. */
83+
export function assertProtocolSchemaDocument(document: ProtocolSchemaDocument): void {
84+
const problems = REQUIRED_PROTOCOL_DEFINITIONS.filter(
85+
(definition) => !Object.hasOwn(document.definitions, definition),
86+
).map((definition) => `definition ${definition} is missing`);
87+
if (JSON.stringify(document.oneOf.map((entry) => entry.$ref)) !== JSON.stringify(FRAME_REFS)) {
88+
problems.push(`frame oneOf must list ${FRAME_REFS.join(", ")}`);
89+
}
90+
if (
91+
JSON.stringify(document.discriminator.mapping) !== JSON.stringify(FRAME_DISCRIMINATOR_MAPPING)
92+
) {
93+
problems.push(`type discriminator must map ${JSON.stringify(FRAME_DISCRIMINATOR_MAPPING)}`);
94+
}
95+
if (Object.keys(document.methods).length === 0) {
96+
problems.push("method metadata is empty");
97+
}
98+
if (problems.length > 0) {
99+
throw new Error(`published protocol schema contract violated: ${problems.join("; ")}`);
100+
}
101+
}

‎scripts/prepush-ci.sh‎

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,6 @@ run_step() {
1414
"$@"
1515
}
1616

17-
run_protocol_ci_mirror() {
18-
local targets=(
19-
"dist/protocol.schema.json"
20-
"apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift"
21-
)
22-
local before after
23-
before="$(git diff --no-ext-diff -- "${targets[@]}" || true)"
24-
25-
run_step pnpm protocol:gen
26-
run_step pnpm protocol:check:swift
27-
28-
after="$(git diff --no-ext-diff -- "${targets[@]}" || true)"
29-
if [[ "$before" != "$after" ]]; then
30-
echo "Protocol generation changed tracked outputs beyond the pre-run worktree." >&2
31-
echo "Refresh generated protocol files and include the updated outputs before pushing." >&2
32-
git --no-pager diff -- "${targets[@]}"
33-
return 1
34-
fi
35-
}
36-
3717
has_native_swift_changes() {
3818
local native_paths=(
3919
apps/macos
@@ -71,7 +51,8 @@ run_linux_ci_mirror() {
7151
run_step pnpm check
7252
run_step pnpm build:strict-smoke
7353
run_step pnpm lint:ui:no-raw-window-open
74-
run_protocol_ci_mirror
54+
run_step pnpm protocol:gen
55+
run_step pnpm protocol:check:swift
7556
run_step pnpm plugins:assets:build
7657
run_step node scripts/run-vitest.mjs run --config test/vitest/vitest.extensions.config.ts --maxWorkers=1
7758
run_step env CI=true node scripts/run-vitest.mjs run --config test/vitest/vitest.unit.config.ts --maxWorkers=1

‎scripts/protocol-gen.ts‎

Lines changed: 29 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
// Protocol Gen script supports OpenClaw repository automation.
2-
import { promises as fs } from "node:fs";
32
import path from "node:path";
43
import { fileURLToPath } from "node:url";
54
import { ProtocolSchemas } from "../packages/gateway-protocol/src/schema/protocol-schemas.js";
65
import { listCoreGatewayMethodMetadata } from "../src/gateway/methods/core-descriptors.js";
6+
import { writeGeneratedOutput } from "./lib/generated-output-utils.mts";
7+
import {
8+
assertProtocolSchemaDocument,
9+
buildProtocolSchemaDocument,
10+
} from "./lib/protocol-schema-document.mts";
711

812
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
913
const repoRoot = path.resolve(scriptDir, "..");
@@ -31,48 +35,32 @@ function resolveOutputPath(args: string[]): string {
3135
return outputPath;
3236
}
3337

34-
async function writeJsonSchema(jsonSchemaPath: string) {
35-
const definitions: Record<string, unknown> = {};
36-
for (const [name, schema] of Object.entries(ProtocolSchemas)) {
37-
definitions[name] = schema;
38-
}
39-
const methods = Object.fromEntries(
40-
listCoreGatewayMethodMetadata().map(({ name, scope, since }) => [name, { since, scope }]),
38+
function main() {
39+
const document = buildProtocolSchemaDocument({
40+
methods: listCoreGatewayMethodMetadata(),
41+
schemas: ProtocolSchemas,
42+
});
43+
// The artifact is a build output with no committed baseline, so this contract
44+
// check is the only guard between a degraded registry and the published
45+
// schema; a regenerate-then-diff guard on it can never fail.
46+
assertProtocolSchemaDocument(document);
47+
const result = writeGeneratedOutput({
48+
check: false,
49+
next: JSON.stringify(document, null, 2),
50+
outputPath: resolveOutputPath(process.argv.slice(2)),
51+
repoRoot,
52+
});
53+
const displayPath = path.relative(repoRoot, result.outputPath);
54+
console.log(
55+
result.wrote
56+
? `[protocol-gen] wrote ${displayPath}`
57+
: `[protocol-gen] unchanged ${displayPath}`,
4158
);
42-
43-
const rootSchema = {
44-
$schema: "http://json-schema.org/draft-07/schema#",
45-
$id: "https://openclaw.ai/protocol.schema.json",
46-
title: "OpenClaw Gateway Protocol",
47-
description: "Handshake, request/response, and event frames for the Gateway WebSocket.",
48-
oneOf: [
49-
{ $ref: "#/definitions/RequestFrame" },
50-
{ $ref: "#/definitions/ResponseFrame" },
51-
{ $ref: "#/definitions/EventFrame" },
52-
],
53-
discriminator: {
54-
propertyName: "type",
55-
mapping: {
56-
req: "#/definitions/RequestFrame",
57-
res: "#/definitions/ResponseFrame",
58-
event: "#/definitions/EventFrame",
59-
},
60-
},
61-
methods,
62-
definitions,
63-
};
64-
65-
await fs.mkdir(path.dirname(jsonSchemaPath), { recursive: true });
66-
await fs.writeFile(jsonSchemaPath, JSON.stringify(rootSchema, null, 2));
67-
console.log(`wrote ${jsonSchemaPath}`);
68-
return { jsonSchemaPath, schemaString: JSON.stringify(rootSchema) };
6959
}
7060

71-
async function main() {
72-
await writeJsonSchema(resolveOutputPath(process.argv.slice(2)));
73-
}
74-
75-
main().catch((err: unknown) => {
61+
try {
62+
main();
63+
} catch (err: unknown) {
7664
console.error(err);
7765
process.exit(1);
78-
});
66+
}

‎test/e2e/qa-lab/runtime/gateway-protocol-artifacts.test.ts‎

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, expect, it } from "vitest";
2+
import { buildProtocolSchemaDocument } from "../../../../scripts/lib/protocol-schema-document.mts";
23
import {
34
assertPublishedProtocolSchema,
4-
buildCanonicalProtocolSchema,
55
buildInstalledProtocolInspectionScript,
66
buildPortableSwiftAnyCodableSource,
77
buildSwiftProtocolCompatibilityHarness,
@@ -22,31 +22,17 @@ describe("Gateway protocol artifact producer", () => {
2222
).toThrow("--artifact-base was provided more than once");
2323
});
2424

25-
it("builds the same schema envelope as the protocol generator", () => {
26-
const request = { type: "object", properties: { type: { const: "req" } } };
27-
const canonical = buildCanonicalProtocolSchema(
28-
{
29-
ConnectParams: { type: "object" },
30-
EventFrame: { type: "object" },
31-
RequestFrame: request,
32-
ResponseFrame: { type: "object" },
33-
},
34-
[{ name: "health", scope: "operator.read", since: "2026.7" }],
35-
);
36-
37-
expect(canonical.definitions.RequestFrame).toEqual(request);
38-
expect(canonical.methods.health).toEqual({ scope: "operator.read", since: "2026.7" });
39-
expect(canonical.discriminator.mapping.req).toBe("#/definitions/RequestFrame");
40-
});
41-
4225
it("requires the published schema and built registry to match canonical definitions", () => {
4326
const definitions = {
4427
ConnectParams: { type: "object" },
4528
EventFrame: { type: "object" },
4629
RequestFrame: { type: "object" },
4730
ResponseFrame: { type: "object" },
4831
};
49-
const canonical = buildCanonicalProtocolSchema(definitions, []);
32+
const canonical = buildProtocolSchemaDocument({
33+
methods: [{ name: "health", scope: "operator.read", since: "2026.7" }],
34+
schemas: definitions,
35+
});
5036

5137
expect(() =>
5238
assertPublishedProtocolSchema({

0 commit comments

Comments
 (0)