refactor(json): share structural value equality (#12280)

Reuse the admitted JSON comparator for environment replay and desktop task checks. Keep the public missing-operand types and portable Python semantics intact.
This commit is contained in:
morluto authored and GitHub committed 2026-11-19 11:45:01 +00:00
1 parent fce336236e
commit 23d8fb14d8
11 files changed
+110 -94

No files matched your search

@@ -8,7 +8,7 @@ import type { OffsetDateTimeInstant } from "../offsetDateTime.js";
import type { StateRecordChronology } from "./StateRecordChronology.js";
import type { ListQuery } from "./environmentStateListQuery.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { JsonValue } from "../jsonValue.js";
import { equalJsonValues as same, type JsonValue } from "../jsonValue.js";
import type { StateWritePlan } from "./environmentStateWriteRules.js";
import {
respellClock,
@@ -349,36 +349,7 @@ export const setOwnMember = (
});
};
/** Equal admitted JSON values. Object member order carries no meaning. */
export const same = (
left: JsonValue | undefined,
right: JsonValue | undefined,
): boolean => {
if (left === right) return true;
if (
left === null ||
right === null ||
typeof left !== "object" ||
typeof right !== "object"
)
return false;
if (Array.isArray(left)) {
if (!Array.isArray(right) || left.length !== right.length) return false;
for (let index = 0; index < left.length; index++)
if (!same(left[index], right[index])) return false;
return true;
}
if (Array.isArray(right)) return false;
const keys = Object.keys(left);
if (keys.length !== Object.keys(right).length) return false;
for (const key of keys)
if (
!Object.prototype.propertyIsEnumerable.call(right, key) ||
!same(left[key], right[key])
)
return false;
return true;
};
export { same };
/** A path segment percent-decoded, or as written when it does not decode. */
export const decodedSegment = (segment: string): string => {
@@ -27,7 +27,6 @@ import {
identityCandidates,
replaceAt,
renderStateList,
same,
type JsonObject,
type StateRecordFacts,
} from "./environmentStateRules.js";
@@ -2187,21 +2186,3 @@ it.each([true, false])(
).toBe(false);
},
);
it("compares admitted state values by JSON meaning and preserves own keys", () => {
const left = ownedJsonObjectSchema.parse(
JSON.parse('{"__proto__":{"q":1},"value":[-0,"𐐷"],"nested":{"b":2,"a":1}}'),
);
const right = ownedJsonObjectSchema.parse(
JSON.parse('{"nested":{"a":1,"b":2},"value":[0,"𐐷"],"__proto__":{"q":1}}'),
);
expect(same(left, right)).toBe(true);
expect(same(left, { ...right, value: ["𐐷", 0] })).toBe(false);
expect(same({ value: null }, { other: null })).toBe(false);
const hidden = Object.defineProperty({ other: null }, "value", {
value: null,
});
expect(same({ value: null }, hidden)).toBe(false);
expect(same(undefined, null)).toBe(false);
expect(same({ constructor: 1 }, { constructor: 2 })).toBe(false);
});
@@ -2109,6 +2109,24 @@ export const CHECK_CASES: readonly (readonly [
},
false,
],
[
{
kind: "value_equals",
file: settings,
pointer: "/shaped",
value: { children: ["437.8"], attributes: {}, name: "Cell" },
},
true,
],
[
{
kind: "value_equals",
file: settings,
pointer: "/shaped",
value: { children: ["437.8"], attributes: [], name: "Cell" },
},
false,
],
[
{ kind: "value_equals", file: settings, pointer: "/tags/1", value: "b" },
true,
+20 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { ownedJsonObjectSchema, type JsonValue } from "../jsonValue.js";
import { parseDesktopTask } from "./appTask.js";
import {
evaluateTaskChecks,
@@ -36,6 +36,25 @@ it("redacts full check values before shortening descriptions without changing th
expect(result?.description).toContain("<secret:master>");
});
it("compares only recorded members of the actual task view", () => {
const actual = ownedJsonObjectSchema.parse(
Object.defineProperty({ other: null }, "value", { value: null }),
);
const outcome = evaluateTaskChecks(
[
{
id: "own-keys",
kind: "value_equals",
file: "data.json",
pointer: "/actual",
value: { value: null },
},
],
new Map([["data.json", { format: "json", view: { actual } }]]),
);
expect(outcome[0]?.passed).toBe(false);
});
/** A value as a description shows it: caller data and what the view holds, as JSON. */
const quoted = (value: unknown) => JSON.stringify(value);
+3 -26
View File
@@ -1,6 +1,6 @@
import { ellipsisExcerpt } from "../excerpt.js";
import { CHECK_VALUE_CHARS } from "./valueCuts.js";
import type { JsonValue } from "../jsonValue.js";
import { equalJsonValues, type JsonValue } from "../jsonValue.js";
import {
collapseWhitespace,
countComparison,
@@ -84,29 +84,6 @@ const undecided = (file: string): Verdict =>
const notFound = (description: string, cut: boolean): Verdict =>
cut ? unread(description) : fail(description);
/** JSON equality: numbers by value, objects by their keys, arrays in order. */
export const sameJson = (
actual: JsonValue | undefined,
expected: JsonValue,
): boolean => {
if (Array.isArray(expected))
return (
Array.isArray(actual) &&
actual.length === expected.length &&
expected.every((item, index) => sameJson(actual[index], item))
);
if (isRecord(expected))
return (
isRecord(actual) &&
Object.keys(actual).length === Object.keys(expected).length &&
Object.entries(expected).every(
([key, item]) =>
Object.hasOwn(actual, key) && sameJson(actual[key], item),
)
);
return actual === expected;
};
/** A decimal numeral as FreeCAD and other apps write numbers in text, such as `5.0000000000000000`. */
const NUMERAL = /^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/u;
@@ -339,7 +316,7 @@ const valueVerdict = (
shown,
);
}
return sameJson(located.value, check.value)
return equalJsonValues(located.value, check.value)
? pass(`${at} is ${shown(check.value)}`)
: fail(`${at} is ${shown(located.value)}, not ${shown(check.value)}`);
}
@@ -534,7 +511,7 @@ export const countTaskRows = (
for (const row of rows)
if (
conditions.every(
([index, value]) => index >= 0 && sameJson(row[index], value),
([index, value]) => index >= 0 && equalJsonValues(row[index], value),
)
)
count += 1;
+2 -3
View File
@@ -2,9 +2,8 @@ import {
escapeJsonPointerToken,
unescapeJsonPointerToken,
} from "../jsonPointer.js";
import type { JsonValue } from "../jsonValue.js";
import { equalJsonValues, type JsonValue } from "../jsonValue.js";
import { collapseWhitespace, type DesktopTaskCheckInput } from "./appTask.js";
import { sameJson } from "./appTaskChecks.js";
import { holdsSplitDate, isCoordinates, isStamp } from "./appTaskDraftNoise.js";
import { holdsNoisyText } from "./appTaskDraftText.js";
import { decimalOf, valueEqualsCheck } from "./appTaskDraftScalars.js";
@@ -115,7 +114,7 @@ const guardAt = (
: undefined;
}
return typeof before !== "object" &&
sameJson(before, after) &&
equalJsonValues(before, after) &&
!isStamp(before) &&
(typeof before !== "string" || before.length <= context.chars)
? valueEqualsCheck(file, pointer, before)
+7 -5
View File
@@ -3,10 +3,9 @@ import {
jsonPointerTokens,
unescapeJsonPointerToken,
} from "../jsonPointer.js";
import type { JsonValue } from "../jsonValue.js";
import { equalJsonValues, type JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import type { FileNote } from "./appTaskDraftFileNotes.js";
import { sameJson } from "./appTaskChecks.js";
import {
MAX_GUARDS,
MAX_GUARDS_PER_CHECK,
@@ -388,7 +387,7 @@ export const isLikeDefault = (
record.field !== "/" &&
record.likes.final.length > 0 &&
record.likes.final.every(({ item }) =>
sameJson(resolvePointer(item, record.field), value),
equalJsonValues(resolvePointer(item, record.field), value),
)
);
};
@@ -417,7 +416,7 @@ const recordGuard = (
return before !== undefined &&
after !== undefined &&
typeof before !== "object" &&
sameJson(after, before) &&
equalJsonValues(after, before) &&
!isStamp(before)
? valueEqualsCheck(file, pointer, before)
: undefined;
@@ -527,7 +526,10 @@ export const decisive = (
): Suggestion[] =>
suggestions.filter((check) =>
check.kind === "value_equals"
? !sameJson(resolvePointer(ends.baseline, check.pointer), check.value)
? !equalJsonValues(
resolvePointer(ends.baseline, check.pointer),
check.value,
)
: check.kind !== "value_absent" ||
locatePointer(ends.final, check.pointer).kind === "none",
);
+3 -3
View File
@@ -1,6 +1,6 @@
import type { JsonValue } from "../jsonValue.js";
import { equalJsonValues, type JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { numberOf, sameJson } from "./appTaskChecks.js";
import { numberOf } from "./appTaskChecks.js";
/** How far a decimal the app writes as text may drift, such as `437.80000000000001` for 437.8, and still match. */
export const DECIMAL_TOLERANCE = 0.001;
@@ -28,7 +28,7 @@ export const passesOn = (
const number = numberOf(value);
return check.tolerance !== undefined && typeof check.value === "number"
? number !== undefined && Math.abs(number - check.value) <= check.tolerance
: sameJson(value, check.value);
: equalJsonValues(value, check.value);
};
/**
+3 -6
View File
@@ -1,9 +1,6 @@
import { equalJsonValues } from "../jsonValue.js";
import type { DesktopTask, DesktopTaskCheck } from "./appTask.js";
import {
sameJson,
type TaskCheckOutcome,
type TaskFileView,
} from "./appTaskChecks.js";
import type { TaskCheckOutcome, TaskFileView } from "./appTaskChecks.js";
/** The model a bundle's screen judge asks when the runner's config names none for judges or by default. */
export const DEFAULT_JUDGE_MODEL = "anthropic/claude-sonnet-5-5";
@@ -56,7 +53,7 @@ export const readableChanges = (
readable(before) &&
readable(after) &&
((before === undefined) !== (after === undefined) ||
!sameJson(before?.view ?? null, after?.view ?? null))
!equalJsonValues(before?.view ?? null, after?.view ?? null))
);
})
.sort();
+18
View File
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
equalJsonValues,
jsonObjectSchema,
ownedJsonObjectSchema,
jsonValueSchema,
@@ -43,6 +44,23 @@ it("still parses only JSON values at runtime", () => {
expect(jsonValueSchema.safeParse(value).success).toBe(false);
});
it("compares admitted values by JSON meaning and distinguishes an absent root", () => {
const left = ownedJsonObjectSchema.parse(
JSON.parse('{"__proto__":{"q":1},"value":[-0,"𐐷"],"nested":{"b":2,"a":1}}'),
);
const right = ownedJsonObjectSchema.parse(
JSON.parse('{"nested":{"a":1,"b":2},"value":[0,"𐐷"],"__proto__":{"q":1}}'),
);
expect(equalJsonValues(left, right)).toBe(true);
expect(equalJsonValues(left, { ...right, value: ["𐐷", 0] })).toBe(false);
expect(equalJsonValues({ value: null }, { other: null })).toBe(false);
expect(equalJsonValues(undefined, undefined)).toBe(true);
expect(equalJsonValues(undefined, null)).toBe(false);
expect(equalJsonValues({ value: true }, { value: 1 })).toBe(false);
expect(equalJsonValues([0], { "0": 0 })).toBe(false);
expect(equalJsonValues({ constructor: 1 }, { constructor: 2 })).toBe(false);
});
it("retains owned object identity while caller objects remain isolated", () => {
const source = JSON.parse('{"__proto__":{"name":"recorded"},"items":[1]}');
const owned = ownedJsonObjectSchema.parse(source);
+34
View File
@@ -15,6 +15,40 @@ export type JsonValue =
| JsonValue[]
| { [key: string]: JsonValue };
/**
* Structural equality for admitted JSON. Object keys are unordered, array
* elements are ordered, and undefined is the sentinel for an absent root.
*/
export const equalJsonValues = (
left: JsonValue | undefined,
right: JsonValue | undefined,
): boolean => {
if (left === right) return true;
if (
left === null ||
right === null ||
typeof left !== "object" ||
typeof right !== "object"
)
return false;
if (Array.isArray(left)) {
if (!Array.isArray(right) || left.length !== right.length) return false;
for (let index = 0; index < left.length; index++)
if (!equalJsonValues(left[index], right[index])) return false;
return true;
}
if (Array.isArray(right)) return false;
const keys = Object.keys(left);
if (keys.length !== Object.keys(right).length) return false;
for (const key of keys)
if (
!Object.prototype.propertyIsEnumerable.call(right, key) ||
!equalJsonValues(left[key], right[key])
)
return false;
return true;
};
const immutableValidation = new WeakMap<object, string | undefined>();
/** Validate JSON meaning and nesting without cloning a trusted immutable value. */