From 23d8fb14d8066fc7de49e160edc722ce6720dde8 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:45:01 -0500 Subject: [PATCH] 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. --- .../analysisView/environmentStateRules.ts | 33 ++---------------- .../analysisView/environmentStateView.test.ts | 19 ----------- src/domain/desktop/appTaskChecks.fixture.ts | 18 ++++++++++ src/domain/desktop/appTaskChecks.test.ts | 21 +++++++++++- src/domain/desktop/appTaskChecks.ts | 29 ++-------------- src/domain/desktop/appTaskDraftGuards.ts | 5 ++- src/domain/desktop/appTaskDraftJson.ts | 12 ++++--- src/domain/desktop/appTaskDraftScalars.ts | 6 ++-- src/domain/desktop/appTaskScreen.ts | 9 ++--- src/domain/jsonValue.test.ts | 18 ++++++++++ src/domain/jsonValue.ts | 34 +++++++++++++++++++ 11 files changed, 110 insertions(+), 94 deletions(-) diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index a717291da2..bffa21e56e 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -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 => { diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index 6b1a314119..c9b1a0bd95 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -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); -}); diff --git a/src/domain/desktop/appTaskChecks.fixture.ts b/src/domain/desktop/appTaskChecks.fixture.ts index 7313de8fe0..ddf03d94be 100644 --- a/src/domain/desktop/appTaskChecks.fixture.ts +++ b/src/domain/desktop/appTaskChecks.fixture.ts @@ -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, diff --git a/src/domain/desktop/appTaskChecks.test.ts b/src/domain/desktop/appTaskChecks.test.ts index c216d331f9..fb6b076d05 100644 --- a/src/domain/desktop/appTaskChecks.test.ts +++ b/src/domain/desktop/appTaskChecks.test.ts @@ -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(""); }); +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); diff --git a/src/domain/desktop/appTaskChecks.ts b/src/domain/desktop/appTaskChecks.ts index f15912ffb6..29844f89aa 100644 --- a/src/domain/desktop/appTaskChecks.ts +++ b/src/domain/desktop/appTaskChecks.ts @@ -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; diff --git a/src/domain/desktop/appTaskDraftGuards.ts b/src/domain/desktop/appTaskDraftGuards.ts index 8cce48aab7..a8c4e33d00 100644 --- a/src/domain/desktop/appTaskDraftGuards.ts +++ b/src/domain/desktop/appTaskDraftGuards.ts @@ -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) diff --git a/src/domain/desktop/appTaskDraftJson.ts b/src/domain/desktop/appTaskDraftJson.ts index 45d67029b9..5ec79b653e 100644 --- a/src/domain/desktop/appTaskDraftJson.ts +++ b/src/domain/desktop/appTaskDraftJson.ts @@ -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", ); diff --git a/src/domain/desktop/appTaskDraftScalars.ts b/src/domain/desktop/appTaskDraftScalars.ts index 550633362a..97e5177f39 100644 --- a/src/domain/desktop/appTaskDraftScalars.ts +++ b/src/domain/desktop/appTaskDraftScalars.ts @@ -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); }; /** diff --git a/src/domain/desktop/appTaskScreen.ts b/src/domain/desktop/appTaskScreen.ts index 0de0f836c3..ecf8dc9701 100644 --- a/src/domain/desktop/appTaskScreen.ts +++ b/src/domain/desktop/appTaskScreen.ts @@ -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(); diff --git a/src/domain/jsonValue.test.ts b/src/domain/jsonValue.test.ts index a23a8ee949..12d1a4d9c2 100644 --- a/src/domain/jsonValue.test.ts +++ b/src/domain/jsonValue.test.ts @@ -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); diff --git a/src/domain/jsonValue.ts b/src/domain/jsonValue.ts index e1dee213b1..ebed611acc 100644 --- a/src/domain/jsonValue.ts +++ b/src/domain/jsonValue.ts @@ -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(); /** Validate JSON meaning and nesting without cloning a trusted immutable value. */