Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(environment): scope fidelity ID normalization

morlutofe0325c6d1c8
diff --git a/docs/agent-environments.md b/docs/agent-environments.md
index b4b8b5750..a5350caae 100644
--- a/docs/agent-environments.md
+++ b/docs/agent-environments.md
@@ -758,6 +758,12 @@ or `page`. Each call is checked against the served tool's input schema first, as
time-named fields), and two different values each side generated on its own compare equal: both UUIDs, or one length of
eight or more with the same character classes and a digit. The report counts each kind of normalised value.
+Comparison keeps response representations distinct: JSON values compare structurally, text compares as text, and a
+retained base64 body compares by bytes (including with UTF-8 text carrying those same bytes), never by its base64
+spelling. ID mappings apply at identifier fields, `ids`/`uuids`/`guids` lists, an entity's own identity within its
+collection, and a string field learning confirmed as a state-held ID. ID mappings leave other numeric and string values unchanged. A
+global conflict involving an equal pair is not used to normalize either pair; the report counts it as an ID conflict.
+
A step agrees when the statuses and the normalised bodies are equal. The report gives agreement overall, per probe and
per tool, `agreement_ignoring_order` for steps that differ only in item order, and each step's differences, at most 20,
with a JSON pointer and both values cut short:
diff --git a/docs/specs/agent-environments/fidelity-compare/spec.md b/docs/specs/agent-environments/fidelity-compare/spec.md
index 9b76998a4..58ccc279b 100644
--- a/docs/specs/agent-environments/fidelity-compare/spec.md
+++ b/docs/specs/agent-environments/fidelity-compare/spec.md
@@ -44,8 +44,11 @@ credentials and resets it between sequences.
`guid` of the answer's own entities (at the read view's entity or list location, a write's response location, or
else the root) also maps within the collection the call names, since two collections can reuse a live id for
different entities. An equal pair is kept in that collection, so another collection's mapping of the same live id
- does not replace it. A collection's map is a bijection: the first pairing of either side wins. Outside identifier
- fields, a string maps when the environment's state holds it as an id, and the keys of two objects keyed by ids map
+ does not replace it. Global mappings are one-to-one and first-pair-wins; equal global pairs also reserve both ids.
+ If an equal pair conflicts with another pairing, its contested live or environment id is not used to normalize
+ either pair, in either observation order. Only non-identity, unconflicted mappings count as mapped ids. Outside
+ identifier fields, a string maps only at a field where learning found it held as an id in environment state. The
+ keys of two objects keyed by ids map
when their values pair (keys that partly overlap only when they are digits, UUIDs or their entries' identities, and
every value pairs);
- ids are learned only from an answer the environment gave this call, from its state or from a recording of exactly
@@ -65,7 +68,8 @@ credentials and resets it between sequences.
- Answers compare after normalisation: empty response text and JSON `null` equal no body (a JSON empty string stays one);
decoded JSON values compare structurally, plain text compares as text, and retained base64 bodies compare as bytes
(including against UTF-8 text with the same bytes), without treating a base64 spelling as text. Mapped ids compare
- equal, in scalar sets as well, an entity's own identity within the call's collection and any other id by the
+ equal in identifier fields, in `ids`/`uuids`/`guids` scalar lists, and for an entity's own identity within the call's
+ collection; other numeric fields stay literal. Any other id compares by the
probe's mapping, and an entity's own identity both sides hold verbatim differs when its collection's mapping gives it
another environment value (a reference keeps raw equality, as the probe's mapping cannot tell which collection it
names); an object's members compare under the environment's mapped keys only when it is keyed by learned ids as
diff --git a/src/application/environment/environmentCompareDiff.test.ts b/src/application/environment/environmentCompareDiff.test.ts
index 7a33c970e..74d3365c3 100644
--- a/src/application/environment/environmentCompareDiff.test.ts
+++ b/src/application/environment/environmentCompareDiff.test.ts
@@ -121,6 +121,25 @@ describe("compareAnswers", () => {
]);
});
+ it("normalizes known string references but leaves ordinary numeric and string values literal", () => {
+ const map = new IdMap();
+ map.learn(101, 1);
+ learnIds({ ref: "live-ref" }, { ref: "env-ref" }, map, {
+ heldIds: new Set(["env-ref"]),
+ });
+ expect(
+ compare(
+ { ref: "live-ref", price: 101, label: "live-ref" },
+ { ref: "env-ref", price: 1, label: "env-ref" },
+ map,
+ ).differences.map((difference) => difference.pointer),
+ ).toEqual(["/price", "/label"]);
+ map.learn("live-key", "env-key");
+ expect(
+ compare({ ids: ["live-key"] }, { ids: ["env-key"] }, map).differences,
+ ).toEqual([]);
+ });
+
it("still compares an object keyed by ids under the environment's keys when some ids are the same on both sides", () => {
const map = new IdMap();
map.learn("101", "2");
diff --git a/src/application/environment/environmentCompareDiff.ts b/src/application/environment/environmentCompareDiff.ts
index feb38c981..32cc0e268 100644
--- a/src/application/environment/environmentCompareDiff.ts
+++ b/src/application/environment/environmentCompareDiff.ts
@@ -7,6 +7,7 @@ import {
import type { JsonValue } from "../../domain/jsonValue.js";
import type { ReplayedBody } from "./environmentSource.js";
import {
+ ID_FIELD,
IDENTITY_FIELD,
keyedByLearnedIds,
pairElements,
@@ -52,6 +53,7 @@ export interface Normalised {
export const STEP_DIFFERENCE_LIMIT = 20;
const VALUE_CHARS = 120;
const TIME_FIELD = /(at|time|date|timestamp|created|updated|modified)$/iu;
+const ID_LIST_FIELD = /^(ids|uuids|guids)$/u;
const isObject = (value: JsonValue | undefined): value is JsonObject =>
typeof value === "object" && value !== null && !Array.isArray(value);
@@ -169,10 +171,18 @@ class Differ {
(typeof live === "string" || typeof live === "number") &&
(typeof env === "string" || typeof env === "number")
) {
- const mapped = this.map.env(
- live,
- this.#inCollection(pointer, at) ? this.entity.scope : undefined,
- );
+ const mapsAsId =
+ (key !== undefined && ID_FIELD.test(key)) ||
+ this.#inCollection(pointer, at) ||
+ (typeof live === "string" &&
+ key !== undefined &&
+ this.map.isStateReference(live, key));
+ const mapped = mapsAsId
+ ? this.map.env(
+ live,
+ this.#inCollection(pointer, at) ? this.entity.scope : undefined,
+ )
+ : undefined;
if (mapped !== undefined && String(mapped) === String(env)) {
this.normalised.ids += 1;
return;
@@ -237,8 +247,17 @@ class Differ {
item === null || typeof item !== "object";
if (live.length !== env.length || !live.every(scalar) || !env.every(scalar))
return false;
- // Live ids compare in the environment's terms, as scalar values do.
- const mapped = live.map((item) => translateValue(item, this.map));
+ // Only identifier lists or known string identifiers are translated; numeric measurements stay literal.
+ const field = pointer.slice(pointer.lastIndexOf("/") + 1);
+ const mapped = live.map((item) => {
+ if (
+ (typeof item === "string" && this.map.isStateReference(item, field)) ||
+ ((typeof item === "number" || typeof item === "string") &&
+ ID_LIST_FIELD.test(field))
+ )
+ return translateValue(item, this.map);
+ return item;
+ });
const key = (items: JsonValue[]): string =>
JSON.stringify(items.map((item) => JSON.stringify(item)).sort());
if (key(mapped) !== key(env)) return false;
@@ -260,7 +279,9 @@ class Differ {
// An object keyed by ids compares each member under the environment's key; any other compares field by field.
const keyed = keyedByLearnedIds(live, env, this.map);
const envKey = (key: string): string => {
- const mapped = keyed ? this.map.env(key) : undefined;
+ const mapped = keyed
+ ? this.map.env(key, self ? this.entity.scope : undefined)
+ : undefined;
return mapped !== undefined && Object.hasOwn(env, String(mapped))
? String(mapped)
: key;
@@ -277,7 +298,11 @@ class Differ {
});
else {
matched.add(other);
- this.value(value, env[other]!, child, { key, own: self });
+ this.value(value, env[other]!, child, {
+ key,
+ own: self,
+ keyed: self && keyed,
+ });
}
}
for (const [key, value] of Object.entries(env))
@@ -294,12 +319,21 @@ class Differ {
live: JsonValue,
env: JsonValue,
pointer: string,
- at: { readonly key?: string; readonly own?: boolean } = {},
+ at: {
+ readonly key?: string;
+ readonly own?: boolean;
+ readonly keyed?: boolean;
+ } = {},
): void {
if (Array.isArray(live) && Array.isArray(env))
this.array(live, env, pointer);
else if (isObject(live) && isObject(env))
- this.object(live, env, pointer, at.own === true && at.key === undefined);
+ this.object(
+ live,
+ env,
+ pointer,
+ at.own === true && (at.key === undefined || at.keyed === true),
+ );
else if (
Array.isArray(live) ||
Array.isArray(env) ||
diff --git a/src/application/environment/environmentCompareIds.test.ts b/src/application/environment/environmentCompareIds.test.ts
index 68564e1aa..92363ebb5 100644
--- a/src/application/environment/environmentCompareIds.test.ts
+++ b/src/application/environment/environmentCompareIds.test.ts
@@ -28,6 +28,42 @@ describe("IdMap", () => {
expect(map.size).toBe(0);
});
+ it("reserves equal pairs and withholds a target that represents two live IDs", () => {
+ for (const pairs of [
+ [
+ [1, 1],
+ [2, 1],
+ ],
+ [
+ [2, 1],
+ [1, 1],
+ ],
+ ] as const) {
+ const map = new IdMap();
+ for (const [live, env] of pairs) map.learn(live, env);
+ expect(map.env(1)).toBeUndefined();
+ expect(map.env(2)).toBeUndefined();
+ expect(map.size).toBe(0);
+ expect(map.conflicts).toBe(1);
+ }
+ });
+
+ it("withholds a mapping when its live ID later also pairs equally", () => {
+ const map = new IdMap();
+ map.learn(2, 1);
+ map.learn(2, 2);
+ expect(map.env(2)).toBeUndefined();
+ expect(map.size).toBe(0);
+ });
+
+ it("withholds an environment ID reserved by a conflicting equal pair", () => {
+ const map = new IdMap();
+ map.learn(1, 2);
+ map.learn(1, 1);
+ expect(map.env(1)).toBeUndefined();
+ expect(map.size).toBe(0);
+ });
+
it("keeps an equal id in its collection and rejects a second live id for one environment id there", () => {
const map = new IdMap();
map.learn(101, 1, "/api/books");
diff --git a/src/application/environment/environmentCompareIds.ts b/src/application/environment/environmentCompareIds.ts
index 5b46336ac..8bc8c057d 100644
--- a/src/application/environment/environmentCompareIds.ts
+++ b/src/application/environment/environmentCompareIds.ts
@@ -26,30 +26,48 @@ export class IdMap {
readonly #toLive = new Map<string, string | number>();
readonly #scoped = new Map<string, Map<string, string | number>>();
readonly #envValues = new Set<string>();
+ readonly #stateReferenceFields = new Map<string, Set<string>>();
+ // Equal-pair collisions can make either side unsafe: raw equality on the second pair would hide its conflict.
+ readonly #ambiguousEnvValues = new Set<string>();
#conflicts = 0;
/**
- * Pair a live value with an environment value. The first pairing of either side wins. A collection keeps its own
- * first pairing, including a pair of equal values, and one environment value stands for one live value there.
+ * Pair a live value with an environment value. The first pairing of either side wins; if a conflict includes an equal
+ * pair, the accepted global destination is withheld from translation so raw equality cannot hide that conflict. A
+ * collection keeps its own first pairing, including equal values. `size` counts usable non-identity translations.
*/
- learn(live: string | number, env: string | number, scope?: string): void {
+ learn(
+ live: string | number,
+ env: string | number,
+ scope?: string,
+ stateReferenceField?: string,
+ ): void {
const liveKey = String(live);
const envKey = String(env);
if (scope !== undefined && !this.#pairScoped(scope, liveKey, env, envKey))
return;
- if (liveKey === envKey) return;
+ if (scope !== undefined && liveKey === envKey) return;
const known = this.#toEnv.get(liveKey);
if (known !== undefined) {
- if (String(known) !== envKey) this.#conflicts += 1;
+ if (String(known) !== envKey) {
+ this.#conflicts += 1;
+ if (liveKey === envKey) this.#ambiguousEnvValues.add(String(known));
+ } else if (stateReferenceField !== undefined)
+ this.#noteStateReference(liveKey, stateReferenceField);
return;
}
- if (this.#toLive.has(envKey)) {
+ const knownLive = this.#toLive.get(envKey);
+ if (knownLive !== undefined) {
this.#conflicts += 1;
+ if (String(knownLive) === envKey || liveKey === envKey)
+ this.#ambiguousEnvValues.add(envKey);
return;
}
this.#toEnv.set(liveKey, env);
this.#toLive.set(envKey, live);
this.#envValues.add(envKey);
+ if (stateReferenceField !== undefined)
+ this.#noteStateReference(liveKey, stateReferenceField);
}
/** Store one collection's pairing. False when it conflicts with a pairing that collection already kept. */
@@ -81,11 +99,13 @@ export class IdMap {
/** The environment's value for a live one: the collection's own when a scope is given and it knows one, else the probe's. */
env(live: string | number, scope?: string): string | number | undefined {
const liveKey = String(live);
- return (
- (scope === undefined
- ? undefined
- : this.#scoped.get(scope)?.get(liveKey)) ?? this.#toEnv.get(liveKey)
- );
+ const scoped =
+ scope === undefined ? undefined : this.#scoped.get(scope)?.get(liveKey);
+ if (scoped !== undefined) return scoped;
+ const global = this.#toEnv.get(liveKey);
+ return global !== undefined && !this.#ambiguousEnvValues.has(String(global))
+ ? global
+ : undefined;
}
hasLive(value: string | number): boolean {
@@ -100,8 +120,22 @@ export class IdMap {
return this.#envValues.has(String(value));
}
+ #noteStateReference(value: string, field: string): void {
+ const fields = this.#stateReferenceFields.get(value) ?? new Set<string>();
+ fields.add(field);
+ this.#stateReferenceFields.set(value, fields);
+ }
+
+ /** A non-identifier string field that learning proved is an id in environment state. */
+ isStateReference(value: string, field: string): boolean {
+ return this.#stateReferenceFields.get(String(value))?.has(field) ?? false;
+ }
+
get size(): number {
- return this.#toEnv.size;
+ return [...this.#toEnv].filter(
+ ([live, env]) =>
+ live !== String(env) && !this.#ambiguousEnvValues.has(String(env)),
+ ).length;
}
get conflicts(): number {
@@ -211,8 +245,9 @@ export const keyedByLearnedIds = (
const learnKeyedEntries = (
live: JsonObject,
env: JsonObject,
- map: IdMap,
- heldIds: ReadonlySet<string>,
+ context: LearnContext,
+ own: boolean,
+ at: string,
): boolean => {
const liveEntries = Object.entries(live);
const envEntries = Object.entries(env);
@@ -242,8 +277,11 @@ const learnKeyedEntries = (
for (const [left, right] of paired.pairs) {
const [liveKey, liveValue] = liveEntries[left]!;
const [envKey, envValue] = envEntries[right]!;
- map.learn(liveKey, envKey);
- learnIds(liveValue, envValue, map, { heldIds });
+ context.map.learn(liveKey, envKey, own ? context.scope : undefined);
+ learnAt(liveValue, envValue, context, {
+ at: childPointer(at, liveKey),
+ own,
+ });
}
return true;
};
@@ -310,18 +348,24 @@ const learnAt = (
context.map.learn(live, env, context.scope);
return;
}
- if (learnKeyedEntries(live, env, context.map, context.heldIds)) return;
const own = place.own || place.at === context.entityAt;
+ if (learnKeyedEntries(live, env, context, own, place.at)) return;
for (const [key, value] of Object.entries(live)) {
if (!Object.hasOwn(env, key)) continue;
const other = env[key];
const pair = idPair(key, value, other, context.heldIds);
- if (pair !== undefined)
+ if (pair !== undefined) {
+ const stateReferenceField =
+ !ID_FIELD.test(key) &&
+ typeof value === "string" &&
+ typeof other === "string" &&
+ context.heldIds.has(other);
context.map.learn(
...pair,
own && IDENTITY_FIELD.test(key) ? context.scope : undefined,
+ stateReferenceField ? key : undefined,
);
- else
+ } else
learnAt(value, other, context, {
at: childPointer(place.at, key),
own: false,
diff --git a/src/application/environment/environmentCompareIdsIntegration.test.ts b/src/application/environment/environmentCompareIdsIntegration.test.ts
new file mode 100644
index 000000000..390478706
--- /dev/null
+++ b/src/application/environment/environmentCompareIdsIntegration.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ environmentStateServeFixture,
+ environmentServeSource,
+} from "../../../tests/fixtures/environmentServe.js";
+import {
+ timedCaptureEvidence,
+ type TimedCaptureRow,
+} from "../../../tests/fixtures/analysisView.js";
+import { compareEnvironment } from "./environmentCompare.js";
+
+const compareRows = (
+ recorded: readonly TimedCaptureRow[],
+ probe: readonly TimedCaptureRow[],
+) => {
+ const capture = timedCaptureEvidence(recorded);
+ const fixture = environmentStateServeFixture(capture);
+ const report = compareEnvironment({
+ source: environmentServeSource(fixture),
+ captureValue: capture,
+ probes: [{ label: "probe", value: timedCaptureEvidence(probe) }],
+ operation: "environment-compare",
+ });
+ if (!report.ok) throw report.error;
+ return report.value.probes[0]!;
+};
+
+describe("environment comparison identifier semantics", () => {
+ it("does not normalize measurements after learning an unrelated numeric ID", () => {
+ const probe = compareRows(
+ [
+ ["GET", "/api/items", [{ id: 1, name: "A" }]],
+ ["GET", "/api/stats", { size: 1, workers: 1, price: 1 }],
+ ],
+ [
+ ["GET", "/api/items", [{ id: 101, name: "A" }]],
+ ["GET", "/api/stats", { size: 101, workers: 101, price: 101 }],
+ ],
+ );
+ expect(probe.results.map((step) => step.equal)).toEqual([true, false]);
+ expect(
+ probe.results[1]?.differences.map((difference) => difference.pointer),
+ ).toEqual(["/size", "/workers", "/price"]);
+ expect(probe.normalised.ids).toBe(1);
+ });
+
+ it("does not collapse distinct references when one field is equal", () => {
+ const cases: readonly [
+ { owner_id: number; reviewer_id: number },
+ { owner_id: number; reviewer_id: number },
+ ][] = [
+ [
+ { owner_id: 1, reviewer_id: 1 },
+ { owner_id: 1, reviewer_id: 2 },
+ ],
+ [
+ { owner_id: 1, reviewer_id: 1 },
+ { owner_id: 2, reviewer_id: 1 },
+ ],
+ [
+ { owner_id: 2, reviewer_id: 1 },
+ { owner_id: 1, reviewer_id: 1 },
+ ],
+ ];
+ for (const [recorded, live] of cases) {
+ const probe = compareRows(
+ [["GET", "/api/review", recorded]],
+ [["GET", "/api/review", live]],
+ );
+ expect(probe.results[0]?.equal).toBe(false);
+ expect(probe.results[0]?.differences).not.toHaveLength(0);
+ expect(probe.id_conflicts).toBeGreaterThan(0);
+ }
+ const identical = compareRows(
+ [["GET", "/api/review", { owner_id: 1, reviewer_id: 1 }]],
+ [["GET", "/api/review", { owner_id: 1, reviewer_id: 1 }]],
+ );
+ expect(identical.results[0]?.equal).toBe(true);
+ expect(identical.normalised.ids).toBe(0);
+ });
+
+ it("maps keyed identities in the collection that owns them", () => {
+ const book = (id: number) => ({ id, name: "Book", slug: "book" });
+ const things = (id: number) => ({ [String(id)]: { id, name: "Thing" } });
+ const probe = compareRows(
+ [
+ ["GET", "/api/books", [book(1)]],
+ ["GET", "/api/books/1", book(1)],
+ ["GET", "/api/things", things(102)],
+ ],
+ [
+ ["GET", "/api/books", [book(101)]],
+ ["GET", "/api/things", things(101)],
+ ],
+ );
+ expect(probe.results.map((step) => step.equal)).toEqual([true, true]);
+ expect(probe.results.flatMap((step) => step.differences)).toEqual([]);
+ });
+});