Skip to content

Commit 49ff3e5

Browse files
authored
fix(validation): preserve wave 2 boundary compatibility (#125031)
1 parent bb5c27b commit 49ff3e5

11 files changed

Lines changed: 126 additions & 39 deletions

‎src/agents/sessions/session-manager-codec.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,39 @@ describe("session manager codec compatibility", () => {
4747
expect(isIndexedSessionEntry(entry)).toBe(false);
4848
});
4949

50+
it.each([
51+
{ name: "singleton", reason: ["reset"] },
52+
{ name: "nested singleton", reason: [["reset"]] },
53+
])("preserves a $name legacy reset reason", ({ reason }) => {
54+
const manager = SessionManager.fromEntries([
55+
{
56+
type: "session",
57+
version: CURRENT_SESSION_VERSION,
58+
id: "legacy-reset-session",
59+
timestamp: "2026-01-01T00:00:00.000Z",
60+
cwd: "/tmp",
61+
},
62+
{
63+
type: "message",
64+
id: "before-reset",
65+
parentId: null,
66+
message: { role: "user", content: "before" },
67+
},
68+
{ type: "reset", id: "legacy-reset", parentId: "before-reset", reason },
69+
{
70+
type: "message",
71+
id: "after-reset",
72+
parentId: "legacy-reset",
73+
message: { role: "user", content: "after" },
74+
},
75+
]);
76+
77+
expect(manager.getEntry("legacy-reset")).toBeDefined();
78+
const context = JSON.stringify(manager.buildSessionContext());
79+
expect(context).not.toContain("before");
80+
expect(context).toContain("after");
81+
});
82+
5083
it("parses opaque tree links without widening their variants", () => {
5184
expect(parseParentLinkedOpaqueEntry({ type: "future", id: "f1", parentId: null })).toEqual({
5285
id: "f1",

‎src/agents/sessions/session-manager-codec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ const indexedSessionEntrySchema = z.discriminatedUnion("type", [
8383
z.looseObject({
8484
...indexedSessionEntryBaseShape,
8585
type: z.literal("reset"),
86-
reason: z.enum(["new", "reset", "idle", "daily", "cron-stale"]),
86+
reason: z.coerce.string().pipe(z.enum(["new", "reset", "idle", "daily", "cron-stale"])),
8787
firstKeptEntryId: z.string().optional(),
8888
}),
8989
z.looseObject({

‎src/cron/task-run-detail.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ const optionalCronTokenCountSchema = z
4545
.optional()
4646
.transform((value) => asSafeIntegerInRange(value, { min: 0 }));
4747
const cronUsageSchema = z
48-
.looseObject({
48+
.object({
4949
input_tokens: optionalCronTokenCountSchema,
5050
output_tokens: optionalCronTokenCountSchema,
5151
total_tokens: optionalCronTokenCountSchema,

‎src/cron/task-run-history.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,13 +558,18 @@ describe("cron task run history", () => {
558558
usage: undefined,
559559
});
560560
expect(parseCronRunLogEntryObject({ ...base, usage: [] })?.usage).toBeUndefined();
561-
expect(parseCronRunLogEntryObject({ ...base, usage: { input_tokens: 0 } })?.usage).toEqual({
561+
expect(
562+
parseCronRunLogEntryObject({ ...base, usage: { input_tokens: 0, future_tokens: 1 } })?.usage,
563+
).toEqual({
562564
input_tokens: 0,
563565
output_tokens: undefined,
564566
total_tokens: undefined,
565567
cache_read_tokens: undefined,
566568
cache_write_tokens: undefined,
567569
});
570+
expect(
571+
parseCronRunLogEntryObject({ ...base, usage: { future_tokens: 1 } })?.usage,
572+
).toBeUndefined();
568573
expect(parseCronRunLogEntryObject({ ...base, ts: MAX_DATE_TIMESTAMP_MS })).not.toBeNull();
569574
expect(parseCronRunLogEntryObject({ ...base, ts: MAX_DATE_TIMESTAMP_MS + 1 })).toBeNull();
570575
});

‎src/infra/exec-approvals-config.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ describe("persisted exec approvals schema", () => {
179179
const parsed = tryParsePersistedExecApprovals(
180180
JSON.stringify({
181181
version: 1,
182-
agents: { main: { allowlist: ["ls", { pattern: "cat", source: "legacy" }] } },
182+
agents: { main: { allowlist: [" ls ", { pattern: "cat", source: "legacy" }] } },
183183
}),
184184
);
185185
expect(parsed?.agents?.main?.allowlist?.[0]).toMatchObject({ pattern: "ls" });

‎src/infra/exec-approvals-config.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Parses and normalizes the persisted exec approval policy.
22
import { randomBytes } from "node:crypto";
33
import path from "node:path";
4+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
45
import {
56
normalizeLowercaseStringOrEmpty,
67
normalizeOptionalString,
@@ -33,7 +34,7 @@ function normalizePersistedAllowlistSource(value: string): "allow-always" | unde
3334
}
3435
const persistedExecAllowlistEntrySchema = z
3536
.union([
36-
z.string().refine((value) => value.trim().length > 0),
37+
z.string().trim().min(1),
3738
z.looseObject({
3839
pattern: z.string().refine((value) => value.trim().length > 0),
3940
id: z.string().optional(),
@@ -51,6 +52,10 @@ const persistedExecAllowlistEntrySchema = z
5152
const persistedExecApprovalsAgentSchema = persistedExecApprovalPolicySchema.extend({
5253
allowlist: z.array(persistedExecAllowlistEntrySchema).optional(),
5354
});
55+
const persistedExecApprovalsAgentsSchema = z
56+
.unknown()
57+
.refine((value) => !isRecord(value) || !Object.hasOwn(value, "__proto__"))
58+
.pipe(z.record(z.string(), persistedExecApprovalsAgentSchema));
5459
const persistedExecApprovalsSchema = z.looseObject({
5560
version: z.literal(1),
5661
socket: z
@@ -60,7 +65,7 @@ const persistedExecApprovalsSchema = z.looseObject({
6065
})
6166
.optional(),
6267
defaults: persistedExecApprovalPolicySchema.optional(),
63-
agents: z.record(z.string(), persistedExecApprovalsAgentSchema).optional(),
68+
agents: persistedExecApprovalsAgentsSchema.optional(),
6469
});
6570

6671
export const DEFAULT_SECURITY: ExecSecurity = "full";

‎src/infra/exec-approvals-store.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,17 @@ describe("exec approvals SQLite store", () => {
223223
expect(row()).toMatchObject({ has_socket_token: 1, socket_path: first.socket?.path });
224224
});
225225

226-
it("fails closed and warns once for malformed raw_json", () => {
226+
it.each([
227+
{ name: "invalid JSON", raw: "{not-json" },
228+
{
229+
name: "an invalid own prototype-key policy",
230+
raw: '{"version":1,"agents":{"__proto__":{"security":42}}}',
231+
},
232+
])("fails closed and warns once for $name", ({ raw }) => {
227233
const { db } = openOpenClawStateDatabase();
228234
db.prepare(
229235
"INSERT INTO exec_approvals_config (config_key, raw_json, socket_path, has_socket_token, default_security, default_ask, default_ask_fallback, auto_allow_skills, agent_count, allowlist_count, updated_at_ms) VALUES (?, ?, NULL, 0, NULL, NULL, NULL, NULL, 0, 0, 1)",
230-
).run("current", "{not-json");
236+
).run("current", raw);
231237

232238
expect(loadExecApprovals().defaults).toMatchObject({ security: "deny", ask: "off" });
233239
expect(loadExecApprovals().defaults?.security).toBe("deny");

‎src/infra/state-migrations.acp-replay.test.ts‎

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -168,30 +168,44 @@ describe("legacy ACP replay doctor migration", () => {
168168
});
169169
});
170170

171-
it("retains malformed state without partially importing it", async () => {
172-
await withTestDir({ prefix: "openclaw-acp-replay-migration-" }, async (stateDir) => {
173-
const sourcePath = await writeLegacyStore(stateDir, {
174-
...legacyStore(),
175-
sessions: { broken: { sessionId: "broken" } },
176-
});
177-
const result = await migrateLegacyAcpReplayLedger({
178-
detected: detectLegacyAcpReplayLedger({
171+
it.each([
172+
{
173+
name: "an ordinary session",
174+
sessionId: "broken",
175+
sessions: { broken: { sessionId: "broken" } },
176+
},
177+
{
178+
name: "an own prototype-key session",
179+
sessionId: "__proto__",
180+
sessions: JSON.parse('{"__proto__":{"sessionId":"broken"}}') as Record<string, unknown>,
181+
},
182+
])(
183+
"retains malformed state from $name without partially importing it",
184+
async ({ sessionId, sessions }) => {
185+
await withTestDir({ prefix: "openclaw-acp-replay-migration-" }, async (stateDir) => {
186+
const sourcePath = await writeLegacyStore(stateDir, {
187+
...legacyStore(),
188+
sessions,
189+
});
190+
const result = await migrateLegacyAcpReplayLedger({
191+
detected: detectLegacyAcpReplayLedger({
192+
stateDir,
193+
doctorOnlyStateMigrations: true,
194+
}),
179195
stateDir,
180-
doctorOnlyStateMigrations: true,
181-
}),
182-
stateDir,
183-
});
196+
});
184197

185-
expect(result.changes).toEqual([]);
186-
expect(result.warnings[0]).toContain("legacy ACP replay session broken is invalid");
187-
await expect(fs.stat(sourcePath)).resolves.toBeDefined();
188-
await expect(
189-
createSqliteAcpEventLedger({
190-
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
191-
}).readReplayBySessionId({ sessionId: "broken" }),
192-
).resolves.toEqual({ complete: false, events: [] });
193-
});
194-
});
198+
expect(result.changes).toEqual([]);
199+
expect(result.warnings[0]).toContain(`legacy ACP replay session ${sessionId} is invalid`);
200+
await expect(fs.stat(sourcePath)).resolves.toBeDefined();
201+
await expect(
202+
createSqliteAcpEventLedger({
203+
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
204+
}).readReplayBySessionId({ sessionId }),
205+
).resolves.toEqual({ complete: false, events: [] });
206+
});
207+
},
208+
);
195209

196210
it("removes a retry source when its prior import already exists", async () => {
197211
await withTestDir({ prefix: "openclaw-acp-replay-migration-" }, async (stateDir) => {

‎src/infra/state-migrations.acp-replay.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import path from "node:path";
66
import type { DatabaseSync } from "node:sqlite";
77
import { isDeepStrictEqual } from "node:util";
88
import type { SessionUpdate } from "@agentclientprotocol/sdk";
9+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
910
import { z } from "zod";
1011
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
1112
import { runOpenClawStateWriteTransaction } from "../state/openclaw-state-db.js";
@@ -63,7 +64,10 @@ type AcpReplayMigrationDatabase = Pick<
6364
"acp_replay_events" | "acp_replay_sessions"
6465
>;
6566

66-
const legacyAcpReplayUpdateSchema = z.looseObject({ sessionUpdate: z.string() });
67+
const legacyAcpReplayRecordSchema = z.custom<Record<string, unknown>>(isRecord);
68+
const legacyAcpReplayUpdateSchema = legacyAcpReplayRecordSchema.refine(
69+
(update) => typeof update.sessionUpdate === "string",
70+
);
6771
const legacyAcpReplayEventSchema = z.looseObject({
6872
seq: z
6973
.number()
@@ -90,7 +94,7 @@ const legacyAcpReplaySessionSchema = z.looseObject({
9094
});
9195
const legacyAcpReplayLedgerSchema = z.looseObject({
9296
version: z.literal(LEGACY_LEDGER_VERSION),
93-
sessions: z.record(z.string(), z.unknown()),
97+
sessions: legacyAcpReplayRecordSchema,
9498
});
9599

96100
function resolveLegacyAcpReplayLedgerPath(stateDir: string): string {

‎src/skills/workshop/store-record.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,23 @@ describe("Skill Workshop persisted record validation", () => {
146146
},
147147
},
148148
},
149+
{
150+
name: "invalid own prototype-key metric",
151+
value: {
152+
...shippedProposal,
153+
evaluation: {
154+
...validEvaluation,
155+
outcomes: [
156+
{
157+
evaluatorId: "reviewer",
158+
pluginId: "review-plugin",
159+
status: "completed",
160+
result: { metrics: JSON.parse('{"__proto__":null}') as unknown },
161+
},
162+
],
163+
},
164+
},
165+
},
149166
])("rejects $name", ({ value }) => {
150167
expect(parseSkillProposalRecord(value)).toBeNull();
151168
});

0 commit comments

Comments
 (0)