@applitools/mcp 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -696,6 +696,11 @@ function rectContains(outer, inner) {
696
696
  function rectsIntersect(a, b) {
697
697
  return a.left < b.left + b.width && a.left + a.width > b.left && a.top < b.top + b.height && a.top + a.height > b.top;
698
698
  }
699
+ function intersectionArea(a, b) {
700
+ const w = Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left);
701
+ const h = Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top);
702
+ return w > 0 && h > 0 ? w * h : 0;
703
+ }
699
704
  function boundingRect(a, b) {
700
705
  const left = Math.min(a.left, b.left);
701
706
  const top = Math.min(a.top, b.top);
@@ -703,6 +708,41 @@ function boundingRect(a, b) {
703
708
  const bottom = Math.max(a.top + a.height, b.top + b.height);
704
709
  return { left, top, width: right - left, height: bottom - top };
705
710
  }
711
+ /** A region under this covers a diff artefact, not content, and as a search source it matches almost everywhere. */
712
+ const MIN_REGION_AREA_PX = 16;
713
+ function isTooSmallRegion(rect) {
714
+ return rect.width * rect.height < MIN_REGION_AREA_PX;
715
+ }
716
+ function sameRect(a, b) {
717
+ return a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
718
+ }
719
+ /** Intersection area as a fraction of the smaller rect's area — IoU would punish a thin rect for a few px of drift. */
720
+ function overlapCoverage(a, b) {
721
+ const smaller = Math.min(a.width * a.height, b.width * b.height);
722
+ // A rect with no area covers nothing, and would divide by zero.
723
+ if (smaller === 0)
724
+ return 0;
725
+ return intersectionArea(a, b) / smaller;
726
+ }
727
+ /** Below this, two rects merely graze each other at the edges and are treated as unrelated. */
728
+ const SIGNIFICANT_OVERLAP_MIN_FRACTION = 0.1;
729
+ /** Below this on either axis the two rects are different shapes, however much they overlap. */
730
+ const SIMILAR_SIZE_MIN_RATIO = 0.85;
731
+ const SIMILAR_COVERAGE_MIN_FRACTION = 0.7;
732
+ function isSignificantOverlap(a, b) {
733
+ return rectsIntersect(a, b) && overlapCoverage(a, b) > SIGNIFICANT_OVERLAP_MIN_FRACTION;
734
+ }
735
+ /**
736
+ * Similar size on both axes and mostly overlapping: one rect is the other after a drift of a few px.
737
+ * A rect that moved a whole row away shares no area with where it was, so it is not nearly the same.
738
+ */
739
+ function isNearlySameRect(a, b) {
740
+ if (!isSignificantOverlap(a, b))
741
+ return false;
742
+ const ratio = (x, y) => Math.min(x, y) / Math.max(x, y);
743
+ const sizeRatio = Math.min(ratio(a.width, b.width), ratio(a.height, b.height));
744
+ return sizeRatio >= SIMILAR_SIZE_MIN_RATIO && overlapCoverage(a, b) >= SIMILAR_COVERAGE_MIN_FRACTION;
745
+ }
706
746
 
707
747
  /** Shapes a raw batch entity's fields (see `BatchInfo` — fetched via `api`'s `fetchBatchInfo`) into `BatchStats`. */
708
748
  function toBatchStats(raw) {
@@ -1251,17 +1291,15 @@ function resolveNodeIdsToNodes(root, nodeIds) {
1251
1291
  return result;
1252
1292
  }
1253
1293
  /**
1254
- * Finds the element node in `root` whose rect most closely matches `targetRect` — within
1255
- * `tolerancePx` on all four of left/top/width/height — returning the same {domSelector,
1256
- * rect} shape as `findNodeById`. Lets a caller upgrade a raw pixel rect (e.g. one eyeballed off
1257
- * a screenshot) into a domSelector-backed region when a matching element actually exists,
1258
- * so the region tracks that element rather than a fixed set of pixels. Returns `null` if no
1259
- * node is within tolerance. When multiple nodes qualify (e.g. a wrapper and its one child
1260
- * share nearly the same rect), the one with the smallest total deviation wins.
1294
+ * The element `targetRect` denotes: a match within `tolerancePx` on every edge, else the element
1295
+ * whose box is nearly the same rect — a changed-area rect bounds the differing pixels, which rarely
1296
+ * lands within a few px of the element's own box. Within a tier the smallest total deviation wins.
1261
1297
  */
1262
1298
  function findNodeByRect(root, targetRect, tolerancePx = 5) {
1263
- let best = null;
1264
- let bestDelta = Infinity;
1299
+ let exact = null;
1300
+ let exactDelta = Infinity;
1301
+ let shifted = null;
1302
+ let shiftedDelta = Infinity;
1265
1303
  for (const { node } of flattenTree(root)) {
1266
1304
  const r = nodeRect(node);
1267
1305
  if (!r)
@@ -1270,15 +1308,20 @@ function findNodeByRect(root, targetRect, tolerancePx = 5) {
1270
1308
  const dTop = Math.abs(r.top - targetRect.top);
1271
1309
  const dWidth = Math.abs(r.width - targetRect.width);
1272
1310
  const dHeight = Math.abs(r.height - targetRect.height);
1273
- if (dLeft > tolerancePx || dTop > tolerancePx || dWidth > tolerancePx || dHeight > tolerancePx)
1274
- continue;
1275
1311
  const delta = dLeft + dTop + dWidth + dHeight;
1276
- if (delta < bestDelta) {
1277
- bestDelta = delta;
1278
- best = node;
1312
+ if (dLeft <= tolerancePx && dTop <= tolerancePx && dWidth <= tolerancePx && dHeight <= tolerancePx) {
1313
+ if (delta < exactDelta) {
1314
+ exactDelta = delta;
1315
+ exact = node;
1316
+ }
1317
+ }
1318
+ else if (isNearlySameRect(r, targetRect) && delta < shiftedDelta) {
1319
+ shiftedDelta = delta;
1320
+ shifted = node;
1279
1321
  }
1280
1322
  }
1281
- return best ? findNodeById(root, best.id) : null;
1323
+ const found = exact ?? shifted;
1324
+ return found ? findNodeById(root, found.id) : null;
1282
1325
  }
1283
1326
  // ---------------------------------------------------------------------------
1284
1327
  // Reading-order sort
@@ -2764,7 +2807,9 @@ function pickCategories(bucket) {
2764
2807
  * `appOutputResolution[stepIndex].annotations` if a resolution exists, else
2765
2808
  * `expectedAppOutput[stepIndex].annotations` (the baseline's own regions) — since
2766
2809
  * `imageMatchSettings`'s own arrays only reflect what was true when the test last ran, not any
2767
- * region a reviewer added since.
2810
+ * region a reviewer added since. The coded regions among them (`regionId`) stay in those arrays
2811
+ * ahead of the annotations: the compare endpoint applies the arrays and not `identifiedRegions`,
2812
+ * so leaving them out reports diffs inside regions the real match never checks.
2768
2813
  *
2769
2814
  * No baseline/checkpoint side-picking or healing happens here: the raw session already resolves
2770
2815
  * which side a region describes (see `regions.ts`'s `getEffectiveRegions`, used instead for a
@@ -2774,12 +2819,33 @@ function pickCategories(bucket) {
2774
2819
  function getEffectiveMatchSettings(rawSession, stepIndex) {
2775
2820
  const imageMatchSettings = rawSession?.actualAppOutput?.[stepIndex]?.imageMatchSettings ?? {};
2776
2821
  const annotations = rawSession?.appOutputResolution?.[stepIndex]?.annotations ?? rawSession?.expectedAppOutput?.[stepIndex]?.annotations;
2777
- return {
2778
- ...imageMatchSettings,
2779
- ...pickCategories(annotations),
2780
- identifiedRegions: pickCategories(imageMatchSettings),
2781
- };
2822
+ const coded = pickCategories(imageMatchSettings);
2823
+ const annotated = pickCategories(annotations);
2824
+ const regions = {};
2825
+ for (const category of MATCH_SETTINGS_CATEGORIES) {
2826
+ regions[category] = [...coded[category].filter(isCodedRegion), ...annotated[category]];
2827
+ }
2828
+ return { ...imageMatchSettings, ...regions, identifiedRegions: coded };
2782
2829
  }
2830
+ function isCodedRegion(region) {
2831
+ return typeof region.regionId === 'string' && region.regionId !== '';
2832
+ }
2833
+ /**
2834
+ * The five match levels a match region can name — a subset of `MATCH_SETTINGS_CATEGORIES`, ordered
2835
+ * as the `regionOp` wire syntax and the MCP tool schemas list them.
2836
+ */
2837
+ const REGION_TYPES = ['ignore', 'strict', 'ignorecolors', 'dynamic', 'layout'];
2838
+ /**
2839
+ * Higher masks less: `strict` checks almost everything, `ignore` checks nothing. Read to refuse a
2840
+ * replacement that would leave a region weaker than it was.
2841
+ */
2842
+ const REGION_TYPE_STRENGTH = {
2843
+ ignore: 0,
2844
+ layout: 1,
2845
+ dynamic: 2,
2846
+ ignorecolors: 3,
2847
+ strict: 4,
2848
+ };
2783
2849
 
2784
2850
  const ANNOTATION_CATEGORIES = [
2785
2851
  'content',
@@ -4438,7 +4504,7 @@ function gateRejectionCount() {
4438
4504
 
4439
4505
  var name = "@applitools/mcp";
4440
4506
  var mcpName = "io.github.applitools/applitools";
4441
- var version = "0.8.0";
4507
+ var version = "0.8.1";
4442
4508
  var description = "Applitools MCP server for AI coding assistants";
4443
4509
  var main = "./dist/index.js";
4444
4510
  var bin = "./dist/index.js";
@@ -8323,7 +8389,6 @@ function registerEyesInspectResources(server) {
8323
8389
  }));
8324
8390
  }
8325
8391
 
8326
- const SUPPORTED_REGION_TYPES = ['ignore', 'strict', 'ignorecolors', 'dynamic', 'layout'];
8327
8392
  /** A clear op — `-*` (every category) or `-<category>-*`/`-<category>*` (one category) — drops every matching existing region instead of resolving a single id/rect target. */
8328
8393
  function isClearOp(op) {
8329
8394
  return op.targetRaw === '*';
@@ -8349,8 +8414,8 @@ function parseRegionOp(arg) {
8349
8414
  return { action: 'remove', regionType: 'all', targetRaw: '*' };
8350
8415
  }
8351
8416
  const regionType = rest.replace(/-?\*$/, '');
8352
- if (!SUPPORTED_REGION_TYPES.includes(regionType)) {
8353
- throw new Error(`Unknown match level "${regionType}" in regionOp "${arg}". Supported: ${SUPPORTED_REGION_TYPES.join(', ')}`);
8417
+ if (!REGION_TYPES.includes(regionType)) {
8418
+ throw new Error(`Unknown match level "${regionType}" in regionOp "${arg}". Supported: ${REGION_TYPES.join(', ')}`);
8354
8419
  }
8355
8420
  return { action: 'remove', regionType: regionType, targetRaw: '*' };
8356
8421
  }
@@ -8363,8 +8428,11 @@ function parseRegionOp(arg) {
8363
8428
  if (!targetRaw) {
8364
8429
  throw new Error(`regionOp is missing a target: "${arg}"`);
8365
8430
  }
8366
- if (!SUPPORTED_REGION_TYPES.includes(regionType)) {
8367
- throw new Error(`Unknown match level "${regionType}" in regionOp "${arg}". Supported: ${SUPPORTED_REGION_TYPES.join(', ')}`);
8431
+ if (!REGION_TYPES.includes(regionType)) {
8432
+ throw new Error(`Unknown match level "${regionType}" in regionOp "${arg}". Supported: ${REGION_TYPES.join(', ')}`);
8433
+ }
8434
+ if (sign === '+' && regionType === 'dynamic') {
8435
+ throw new Error(`regionOp "${arg}" adds a dynamic region, but dynamic is Eyes' default match level and masks nothing on its own. Add a layout region instead.`);
8368
8436
  }
8369
8437
  return { action: sign === '+' ? 'add' : 'remove', regionType: regionType, targetRaw };
8370
8438
  }
@@ -8776,8 +8844,8 @@ async function updateRegions(url, stepIndex, action, rawRegionOps, keys, propaga
8776
8844
  ];
8777
8845
  if (propagate) {
8778
8846
  // Every add/remove op is propagate-eligible, plus every synthetic remove op a clear op
8779
- // expanded into above.
8780
- const propagatableOps = [...regionOps.filter(op => !isClearOp(op)), ...clearSynthesizedOps];
8847
+ // expanded into above — except a speck, which images/find matches almost everywhere.
8848
+ const propagatableOps = [...regionOps.filter(op => !isClearOp(op)), ...clearSynthesizedOps].filter(op => !isTooSmallRegion(resolvedOnRefBeforeConversion.get(op.targetRaw)));
8781
8849
  if (propagatableOps.length > 0) {
8782
8850
  const sourceImage = imageForSide(rawSession, stepIndex, refSide);
8783
8851
  const candidateSteps = await findPropagationCandidateSteps(rawSession, stepIndex, sessionId, baseUrl, batchId, accountId, keys, propagate, false, deps);
@@ -9031,9 +9099,9 @@ const PROPAGATE_DESC = 'Which other steps also get this exact change, applied to
9031
9099
  'session\'s scenario name, e.g. "Login|Checkout" — sessions matching are included in the candidate pool on top ' +
9032
9100
  'of the same-scenario default.';
9033
9101
  const REGION_OP_DESC = 'A compact match-region change: (+|-)<matchLevel>-(<rect>|<id>). matchLevel, strictest to loosest: strict (near pixel-perfect), ignorecolors ' +
9034
- "(color-only drift tolerated), dynamic (Eyes' own dynamic-content matching), layout (content may change but structure must still hold — a " +
9102
+ '(color-only drift tolerated), layout (content may change but structure must still hold — a ' +
9035
9103
  'vanished/overlapping/resized element is still flagged), ignore (nothing in the region is ever checked). Always pick the strictest level ' +
9036
- 'that still accommodates the diff: prefer dynamic over layout over ignore. Target is a raw rect "left,top,width,height" or a bare DOM node ' +
9104
+ 'that still accommodates the diff: prefer layout over ignore. A dynamic add is refused — dynamic is the default match level — so add layout instead. Target is a raw rect "left,top,width,height" or a bare DOM node ' +
9037
9105
  'id from eyes_inspect_dom/eyes_inspect_dom_diff. A removal target may also be a glob: "-*" removes every region, "-<matchLevel>-*" removes ' +
9038
9106
  'every region of that one category. Examples: "+layout-14", "-ignore-100,200,50,80", "-layout-*".';
9039
9107
  function registerEyesResolveTools(server, deps = defaultCommandsDeps) {
@@ -9733,17 +9801,25 @@ const IS_EXPECTED_DESC = 'Non-null means this diff is a real, permanent, intenti
9733
9801
  'the field for a one-off change someone made on purpose; if instead the content itself is expected to vary or recur on every run (a rotating ' +
9734
9802
  "banner, a timestamp), that's `dynamic`'s job instead, not this one — a finding is either a permanent change (this field) or recurring/" +
9735
9803
  'varying content (`dynamic`), never justified as both from the same evidence.';
9736
- const MATCH_LEVEL_DESC = 'Strictest to loosest: "strict" (near pixel-perfect — tightens, not a masking choice), "ignorecolors" (color-only drift tolerated, ' +
9737
- 'structure and text still checked), "dynamic" (Eyes\' own dynamic-content matching), "layout" (content may change but structure must still ' +
9738
- 'hold — a vanished/overlapping/resized element is still flagged), "ignore" (nothing in the region is ever checked, content or structure). ' +
9739
- 'Always pick the strictest level that still accommodates the diff: prefer dynamic over layout over ignore.';
9740
- /** The five match levels a `regionOp` can express — the same set `eyes-resolve/region-op.ts`'s `RegionType` names. */
9741
- const RegionTypeShape = zod.z.enum(['ignore', 'strict', 'ignorecolors', 'dynamic', 'layout']).describe(MATCH_LEVEL_DESC);
9742
- /** One region: where it is (a DOM node id or a checkpoint-image rect) and which match level it applies. */
9804
+ /** The two levels a mask can be added at, strictest first. */
9805
+ const MASK_LEVELS = ['layout', 'ignore'];
9806
+ /** Also appended to the step's `next.instruction` in resolve mode, so it reaches the model as a result and not only as schema text. */
9807
+ const MASK_LEVEL_RULE = 'If the dynamic area follows a clear consistent symmetry such that text segments are replaced with (possibly longer or shorter) text of ' +
9808
+ 'similar font and font size, and images are replaced with other images of similar size but overall all elements retain their relative ' +
9809
+ 'alignment and margins, you should mask the dynamic area with a Layout region. In all other cases use an Ignore region. Do not use any ' +
9810
+ 'other match level for masking.';
9811
+ /** Every level an existing region can carry — `before` names one of those, dynamic included. */
9812
+ const ExistingRegionTypeShape = zod.z.enum(REGION_TYPES).describe('The match level the existing region currently has');
9813
+ const RegionTypeShape = zod.z.enum(MASK_LEVELS).describe(MASK_LEVEL_RULE);
9814
+ const AREA_DESC = 'A DOM node id (string) from eyes_inspect_dom/eyes_inspect_dom_diff, or a checkpoint-image rect';
9815
+ /** An existing region: where it is and the level it currently has. */
9816
+ const ExistingRegionSpecShape = zod.z.object({
9817
+ area: zod.z.union([zod.z.string(), AreaRectShape]).describe(AREA_DESC),
9818
+ matchLevel: ExistingRegionTypeShape,
9819
+ });
9820
+ /** A region to add: where it is and which level it applies. */
9743
9821
  const RegionSpecShape = zod.z.object({
9744
- area: zod.z
9745
- .union([zod.z.string(), AreaRectShape])
9746
- .describe('A DOM node id (string) from eyes_inspect_dom/eyes_inspect_dom_diff, or a checkpoint-image rect'),
9822
+ area: zod.z.union([zod.z.string(), AreaRectShape]).describe(AREA_DESC),
9747
9823
  matchLevel: RegionTypeShape,
9748
9824
  });
9749
9825
  /**
@@ -9754,7 +9830,7 @@ const RegionSpecShape = zod.z.object({
9754
9830
  * opposite of this field's purpose.
9755
9831
  */
9756
9832
  zod.z.object({
9757
- before: RegionSpecShape.nullable().describe('The stale region being replaced, if one existed — null for a from-scratch mask over content that was never masked at all'),
9833
+ before: ExistingRegionSpecShape.nullable().describe('The stale region being replaced, if one existed — null for a from-scratch mask over content that was never masked at all'),
9758
9834
  after: RegionSpecShape.describe('The corrected/fresh region that should mask this content — always required'),
9759
9835
  description: zod.z.string().describe('Human-readable description of the proposed change'),
9760
9836
  });
@@ -9764,7 +9840,7 @@ zod.z.object({
9764
9840
  * supply the one judgment call this schema can't make for it: `after.matchLevel`.
9765
9841
  */
9766
9842
  const MaskProposalShape = zod.z.object({
9767
- before: RegionSpecShape.nullable().describe('The stale region being replaced, if one existed — null for a from-scratch mask over content that was never masked at all'),
9843
+ before: ExistingRegionSpecShape.nullable().describe('The stale region being replaced, if one existed — null for a from-scratch mask over content that was never masked at all'),
9768
9844
  after: zod.z
9769
9845
  .object({
9770
9846
  area: zod.z
@@ -9785,8 +9861,8 @@ const DYNAMIC_JUSTIFICATION_DESC = 'How it was established that this diff is dyn
9785
9861
  "finding's node.";
9786
9862
  const DYNAMIC_EVIDENCE_DESC = "The concrete evidence for `justification` — the actual pattern observed, what the history call showed, the user's own words, or the code path.";
9787
9863
  const DYNAMIC_MASK_DESC = 'The region to add or change to mask this diff — required whenever `dynamic` is non-null, so a masking decision always names an actual fix, ' +
9788
- 'not just a category. `matchLevel` is always required — see its own description for what each level tolerates and prefer the strictest one ' +
9789
- "that still accommodates the diff. `area` may be null or omitted, in which case the tool uses this finding's own `area`. `before` is null " +
9864
+ 'not just a category. `matchLevel` is always required, `layout` or `ignore` — see its own description for which. ' +
9865
+ "`area` may be null or omitted, in which case the tool uses this finding's own `area`. `before` is null " +
9790
9866
  'for a from-scratch mask; naming a stale region being replaced — one that stopped tracking its element as the page drifted — requires ' +
9791
9867
  'calling eyes_inspect_regions for this step first to identify it.';
9792
9868
  const DYNAMIC_DESC = 'Non-null means this diff is dynamic/recurring content — expected to vary or reappear differently on every run — rather than a one-off ' +
@@ -10019,12 +10095,11 @@ function buildDiffUrl(parts) {
10019
10095
  */
10020
10096
  const MAX_REGION_AREA_FRACTION = 0.5;
10021
10097
  /**
10022
- * The step's current regions, as the guard rails see them: the checkpoint side's rect (the side
10023
- * `DiffFindingShape.area` is always expressed in), and the `matchLevel` a regionOp would name.
10024
- * A region in a category no regionOp can express (`floating`/`accessibility`/…) is left out — the
10025
- * guard rails only reason about regions this flow could actually add or remove, which is also why
10026
- * only `fetchRegions`' `regions` are considered and never its `codedRegions`: those come from the
10027
- * test code itself and no region op can touch them.
10098
+ * Regions as the guard rails see them: the checkpoint side's rect (the side `DiffFindingShape.area`
10099
+ * is always expressed in), and the `matchLevel` a regionOp would name. A region in a category no
10100
+ * regionOp can express (`floating`/`accessibility`/…) is left out. Applied to `fetchRegions`'
10101
+ * `regions` for what this flow may remove or replace, and to its `codedRegions` for what it must
10102
+ * only avoid — those come from the test code and no region op can touch them.
10028
10103
  */
10029
10104
  function toExistingRegionEntries(regions) {
10030
10105
  var _a;
@@ -10056,9 +10131,6 @@ function proposedRegionChange(finding) {
10056
10131
  description: mask.description,
10057
10132
  };
10058
10133
  }
10059
- function sameRect(a, b) {
10060
- return a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
10061
- }
10062
10134
  /**
10063
10135
  * Whether a proposal's resolved `after` already exists, verbatim (same rect, same `matchLevel`),
10064
10136
  * among the step's current regions — e.g. because propagation from a sibling step (or an earlier
@@ -10070,42 +10142,121 @@ function sameRect(a, b) {
10070
10142
  function regionAlreadyInEffect(existing, rect, matchLevel) {
10071
10143
  return rect !== null && existing.some(e => e.matchLevel === matchLevel && sameRect(e.rect, rect));
10072
10144
  }
10145
+ function matchExistingRegion(existing, rect, matchLevel) {
10146
+ var _a;
10147
+ const exact = existing.find(entry => entry.matchLevel === matchLevel && sameRect(entry.rect, rect));
10148
+ if (exact)
10149
+ return exact;
10150
+ const shifted = existing.filter(entry => entry.matchLevel === matchLevel && isNearlySameRect(entry.rect, rect));
10151
+ if (shifted.length > 1)
10152
+ return 'ambiguous';
10153
+ return (_a = shifted[0]) !== null && _a !== void 0 ? _a : null;
10154
+ }
10073
10155
  /**
10074
- * §4 step 2's two guard rails, checked before anything is sent:
10156
+ * §4 step 2's guard rails, checked before anything is sent:
10075
10157
  *
10076
10158
  * - **No nesting, regardless of matchLevel.** A proposal falling entirely inside an existing
10077
10159
  * region is already covered, so it's refused. A proposal entirely containing existing ones is
10078
10160
  * fine — those get removed first, and come back as `contained`.
10161
+ * - **No touching a coded region.** `coded` regions come from the test code, so a proposal inside
10162
+ * one is refused as covered and one overlapping it is refused outright — it can be neither
10163
+ * replaced nor removed here.
10079
10164
  * - **No oversized regions.** A proposal covering more than `MAX_REGION_AREA_FRACTION` of the
10080
10165
  * checkpoint image is refused.
10166
+ * - **No specks.** A proposal under `MIN_REGION_AREA_PX` is refused: it masks a diff artefact, not
10167
+ * content, and propagation would find it everywhere.
10168
+ * - **No stacking on top of a region it partly covers.** A proposal that is nearly the same rect as
10169
+ * an existing region replaces it (`superseded`); one that straddles a different region, or is
10170
+ * equally close to two of them, is refused. A replacement may never weaken the match level.
10081
10171
  *
10082
10172
  * `proposedRect` is `null` when the proposal's `area` is a node id whose geometry couldn't be
10083
- * resolved; both rails are geometric, so there's nothing to check and the proposal passes.
10084
- * `excludeRect` is the proposal's own `before` region, which must not count as either a
10085
- * containing neighbour or a nested one — it's the thing being replaced.
10173
+ * resolved; every rail then has nothing to check and the proposal passes.
10174
+ * `excludeRect` is the proposal's own `before` region, which must not count as a containing
10175
+ * neighbour, a nested one, or an overlap — it's the thing being replaced.
10086
10176
  */
10087
10177
  function checkGuardRails(params) {
10088
- const { proposedRect, existing, imageSize, excludeRect, matchLevel } = params;
10178
+ var _a;
10179
+ const { proposedRect, existing, coded = [], imageSize, excludeRect, matchLevel } = params;
10089
10180
  if (!proposedRect)
10090
- return { ok: true, contained: [] };
10181
+ return { ok: true, contained: [], superseded: null };
10182
+ if (isTooSmallRegion(proposedRect)) {
10183
+ return {
10184
+ ok: false,
10185
+ kind: 'too-small',
10186
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} is ${proposedRect.width}x${proposedRect.height}px, under the ${MIN_REGION_AREA_PX}px² floor — a mask this small covers a diff artefact, not content`,
10187
+ };
10188
+ }
10091
10189
  const relevant = existing.filter(e => !excludeRect || !sameRect(e.rect, excludeRect));
10092
10190
  const container = relevant.find(e => rectContains(e.rect, proposedRect));
10093
10191
  if (container) {
10094
10192
  return {
10095
10193
  ok: false,
10194
+ kind: 'nested',
10096
10195
  reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} falls entirely inside an existing ${container.matchLevel} region ${formatRect(container.rect)}, so the area is already covered`,
10097
10196
  };
10098
10197
  }
10198
+ const codedContainer = coded.find(e => rectContains(e.rect, proposedRect));
10199
+ if (codedContainer) {
10200
+ return {
10201
+ ok: false,
10202
+ kind: 'nested',
10203
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} falls entirely inside an existing ${codedContainer.matchLevel} region ${formatRect(codedContainer.rect)} from the test code, so the area is already covered`,
10204
+ };
10205
+ }
10206
+ const codedOverlap = coded.find(e => isSignificantOverlap(e.rect, proposedRect));
10207
+ if (codedOverlap) {
10208
+ const percent = Math.round(overlapCoverage(codedOverlap.rect, proposedRect) * 100);
10209
+ return {
10210
+ ok: false,
10211
+ kind: 'overlaps',
10212
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} overlaps an existing ${codedOverlap.matchLevel} region ${formatRect(codedOverlap.rect)} from the test code by ${percent}% of the smaller region, ` +
10213
+ 'and a region from the test code can be neither replaced nor removed here',
10214
+ };
10215
+ }
10099
10216
  if (imageSize && imageSize.width > 0 && imageSize.height > 0) {
10100
10217
  const fraction = (proposedRect.width * proposedRect.height) / (imageSize.width * imageSize.height);
10101
10218
  if (fraction > MAX_REGION_AREA_FRACTION) {
10102
10219
  return {
10103
10220
  ok: false,
10221
+ kind: 'oversized',
10104
10222
  reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} covers ${Math.round(fraction * 100)}% of the checkpoint image, which would nullify the purpose of the check`,
10105
10223
  };
10106
10224
  }
10107
10225
  }
10108
- return { ok: true, contained: relevant.filter(e => rectContains(proposedRect, e.rect)) };
10226
+ const contained = relevant.filter(e => rectContains(proposedRect, e.rect));
10227
+ const neighbours = relevant.filter(e => !contained.includes(e));
10228
+ const shifted = neighbours.filter(e => isNearlySameRect(e.rect, proposedRect));
10229
+ const straddled = neighbours.find(e => !shifted.includes(e) && isSignificantOverlap(e.rect, proposedRect));
10230
+ if (straddled) {
10231
+ const percent = Math.round(overlapCoverage(straddled.rect, proposedRect) * 100);
10232
+ return {
10233
+ ok: false,
10234
+ kind: 'overlaps',
10235
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} overlaps an existing ${straddled.matchLevel} region ${formatRect(straddled.rect)} by ${percent}% of the smaller region ` +
10236
+ 'without being nearly the same rect (their sizes or positions differ too much)',
10237
+ };
10238
+ }
10239
+ if (shifted.length > 1) {
10240
+ const named = shifted.map(e => `${e.matchLevel} ${formatRect(e.rect)}`).join(' and ');
10241
+ return {
10242
+ ok: false,
10243
+ kind: 'ambiguous-overlap',
10244
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} overlaps ${shifted.length} existing regions closely enough that which one it replaces is ambiguous (${named})`,
10245
+ };
10246
+ }
10247
+ const superseded = (_a = shifted[0]) !== null && _a !== void 0 ? _a : null;
10248
+ // A dynamic region only restates Eyes' default match level, so superseding it weakens nothing.
10249
+ if (superseded &&
10250
+ superseded.matchLevel !== 'dynamic' &&
10251
+ REGION_TYPE_STRENGTH[matchLevel] < REGION_TYPE_STRENGTH[superseded.matchLevel]) {
10252
+ return {
10253
+ ok: false,
10254
+ kind: 'overlaps',
10255
+ reason: `the proposed ${matchLevel} region ${formatRect(proposedRect)} is nearly the same rect as an existing ${superseded.matchLevel} region ${formatRect(superseded.rect)}, ` +
10256
+ `but replacing a ${superseded.matchLevel} region with a ${matchLevel} region would remove protection this flow cannot restore`,
10257
+ };
10258
+ }
10259
+ return { ok: true, contained, superseded };
10109
10260
  }
10110
10261
  function regionOpTarget(area) {
10111
10262
  return typeof area === 'string' ? area : formatRect(area);
@@ -10119,19 +10270,34 @@ function removeOp(matchLevel, target) {
10119
10270
  /**
10120
10271
  * §4 step 3's plan: every region already contained by the proposal is removed first, then the
10121
10272
  * proposal itself is applied — as a plain add when nothing preceded it, or as a remove-then-add
10122
- * pair when it replaces a stale region. The pair counts as one `(before, after)` transition rather
10273
+ * pair when it replaces a stale region, whether the model named that region as its `before` or the
10274
+ * guard rails found it (`superseded`). The pair counts as one `(before, after)` transition rather
10123
10275
  * than two independent ops, since that's what actually happened to the region.
10124
10276
  */
10125
- function planRegionActions(change, contained) {
10277
+ function planRegionActions(change, contained, superseded = null) {
10126
10278
  const plans = [];
10127
10279
  for (const entry of contained) {
10128
10280
  const op = removeOp(entry.matchLevel, formatRect(entry.rect));
10129
10281
  plans.push({ ops: [op], countOp: op, before: entry.matchLevel, after: null });
10130
10282
  }
10131
10283
  const add = addOp(change.after);
10284
+ const removeSuperseded = superseded ? [removeOp(superseded.matchLevel, formatRect(superseded.rect))] : [];
10132
10285
  if (change.before) {
10133
10286
  const remove = removeOp(change.before.matchLevel, regionOpTarget(change.before.area));
10134
- plans.push({ ops: [remove, add], countOp: add, before: change.before.matchLevel, after: change.after.matchLevel });
10287
+ plans.push({
10288
+ ops: [...removeSuperseded, remove, add],
10289
+ countOp: add,
10290
+ before: change.before.matchLevel,
10291
+ after: change.after.matchLevel,
10292
+ });
10293
+ }
10294
+ else if (superseded) {
10295
+ plans.push({
10296
+ ops: [...removeSuperseded, add],
10297
+ countOp: add,
10298
+ before: superseded.matchLevel,
10299
+ after: change.after.matchLevel,
10300
+ });
10135
10301
  }
10136
10302
  else {
10137
10303
  plans.push({ ops: [add], countOp: add, before: null, after: change.after.matchLevel });
@@ -10165,25 +10331,48 @@ function countAppliedRegions(plans, results) {
10165
10331
  function describeRegionOutcome(regions, failureReasons) {
10166
10332
  const sentences = [];
10167
10333
  const added = regions.filter(r => r.before === null && r.after !== null);
10168
- const adjusted = regions.filter(r => r.before !== null);
10334
+ const moved = regions.filter(r => r.before !== null && r.before === r.after);
10335
+ const adjusted = regions.filter(r => r.before !== null && r.before !== r.after);
10169
10336
  const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
10170
10337
  const addedText = added.map(r => plural(r.count, `${r.after} region`)).join(', ');
10338
+ const movedText = moved.map(r => plural(r.count, `${r.after} region`)).join(', ');
10171
10339
  const adjustedText = adjusted
10172
10340
  .map(r => r.after === null
10173
10341
  ? plural(r.count, `nested ${r.before} region`) + ' away'
10174
10342
  : plural(r.count, 'region') + ` from ${r.before} to ${r.after}`)
10175
10343
  .join(', ');
10176
- if (addedText && adjustedText)
10177
- sentences.push(`Added ${addedText} and adjusted ${adjustedText} to mask this diff.`);
10178
- else if (addedText)
10179
- sentences.push(`Added ${addedText} to mask this diff.`);
10180
- else if (adjustedText)
10181
- sentences.push(`Adjusted ${adjustedText} to mask this diff.`);
10344
+ const clauses = [
10345
+ addedText && `added ${addedText}`,
10346
+ adjustedText && `adjusted ${adjustedText}`,
10347
+ movedText && `moved ${movedText}`,
10348
+ ].filter((clause) => clause !== '');
10349
+ if (clauses.length > 0) {
10350
+ const joined = clauses.length > 1 ? `${clauses.slice(0, -1).join(', ')} and ${clauses[clauses.length - 1]}` : clauses[0];
10351
+ sentences.push(`${joined[0].toUpperCase()}${joined.slice(1)} to mask this diff.`);
10352
+ }
10182
10353
  for (const reason of failureReasons) {
10183
10354
  sentences.push(`The diff could not be masked because ${reason}.`);
10184
10355
  }
10185
10356
  return sentences.join(' ');
10186
10357
  }
10358
+ function resolveStaleRegion(existing, proposal, rectOf) {
10359
+ if (!proposal.before)
10360
+ return null;
10361
+ const rect = rectOf(proposal.before.area);
10362
+ if (!rect)
10363
+ return null;
10364
+ const resolved = matchExistingRegion(existing, rect, proposal.before.matchLevel);
10365
+ return resolved === 'ambiguous' ? null : resolved;
10366
+ }
10367
+ function foldAppliedProposal(existing, removed, added) {
10368
+ for (const gone of removed) {
10369
+ const at = gone ? existing.indexOf(gone) : -1;
10370
+ if (at !== -1)
10371
+ existing.splice(at, 1);
10372
+ }
10373
+ if (added)
10374
+ existing.push(added);
10375
+ }
10187
10376
  /**
10188
10377
  * Runs §4 over every finding of one `diff_report` call, in order, and returns the findings with
10189
10378
  * their `regions` filled in and their `description` extended. Region changes are applied against
@@ -10202,17 +10391,18 @@ function describeRegionOutcome(regions, failureReasons) {
10202
10391
  * `mode: 'resolve'` — never read back by this flow, and never part of what the model sees.
10203
10392
  */
10204
10393
  async function applyRegionMasking(params) {
10205
- var _a, _b, _c;
10394
+ var _a, _b, _c, _d;
10206
10395
  const { sessionUrl, stepIndex, findings, keys, deps = defaultPhaseTrackerDeps } = params;
10207
10396
  const proposals = findings.map(proposedRegionChange);
10208
10397
  if (proposals.every(p => p === null)) {
10209
10398
  return findings.map(finding => ({ ...finding, regions: [] }));
10210
10399
  }
10211
- const [{ regions: rawRegions }, session] = await Promise.all([
10400
+ const [{ regions: rawRegions, codedRegions: rawCoded }, session] = await Promise.all([
10212
10401
  fetchRegions(sessionUrl, stepIndex, keys),
10213
10402
  fetchSteps(sessionUrl, keys),
10214
10403
  ]);
10215
10404
  const existing = toExistingRegionEntries(rawRegions);
10405
+ const coded = toExistingRegionEntries(rawCoded);
10216
10406
  const imageSize = (_c = (_b = (_a = session.steps) === null || _a === void 0 ? void 0 : _a[stepIndex]) === null || _b === void 0 ? void 0 : _b.checkpoint.size) !== null && _c !== void 0 ? _c : null;
10217
10407
  // Every node id any proposal names, resolved to its checkpoint-side geometry in one pass — the
10218
10408
  // guard rails are geometric, and a proposal is free to name an element rather than a rect.
@@ -10239,11 +10429,16 @@ async function applyRegionMasking(params) {
10239
10429
  reported.push({ ...finding, regions: [] });
10240
10430
  continue;
10241
10431
  }
10432
+ const stale = resolveStaleRegion(existing, proposal, rectOf);
10433
+ const change = stale
10434
+ ? { ...proposal, before: { area: stale.rect, matchLevel: stale.matchLevel } }
10435
+ : { ...proposal, before: null };
10242
10436
  const guard = checkGuardRails({
10243
10437
  proposedRect,
10244
10438
  existing,
10439
+ coded,
10245
10440
  imageSize,
10246
- excludeRect: proposal.before ? rectOf(proposal.before.area) : null,
10441
+ excludeRect: (_d = stale === null || stale === void 0 ? void 0 : stale.rect) !== null && _d !== void 0 ? _d : null,
10247
10442
  matchLevel: proposal.after.matchLevel,
10248
10443
  });
10249
10444
  if (!guard.ok) {
@@ -10255,7 +10450,7 @@ async function applyRegionMasking(params) {
10255
10450
  });
10256
10451
  continue;
10257
10452
  }
10258
- const plans = planRegionActions(proposal, guard.contained);
10453
+ const plans = planRegionActions(change, guard.contained, guard.superseded);
10259
10454
  const ops = plans.flatMap(plan => plan.ops);
10260
10455
  const updateRegionsInput = {
10261
10456
  sessionUrl,
@@ -10288,17 +10483,8 @@ async function applyRegionMasking(params) {
10288
10483
  description: sentence ? `${finding.description} ${sentence}` : finding.description,
10289
10484
  });
10290
10485
  // What just happened is now part of "what's already there" for the remaining findings of this
10291
- // same call, so two findings can't end up nested inside each other either — the regions this
10292
- // proposal cleared out (its nested neighbours, and the stale one it replaced) are gone, and the
10293
- // one it added is now in effect.
10294
- const staleRect = proposal.before ? rectOf(proposal.before.area) : null;
10295
- for (const gone of [...guard.contained, ...(staleRect ? existing.filter(e => sameRect(e.rect, staleRect)) : [])]) {
10296
- const at = existing.indexOf(gone);
10297
- if (at !== -1)
10298
- existing.splice(at, 1);
10299
- }
10300
- if (proposedRect)
10301
- existing.push({ matchLevel: proposal.after.matchLevel, rect: proposedRect });
10486
+ // same call, so two findings can't end up nested inside — or overlapping — each other either.
10487
+ foldAppliedProposal(existing, [...guard.contained, guard.superseded, stale], proposedRect ? { matchLevel: proposal.after.matchLevel, rect: proposedRect } : null);
10302
10488
  }
10303
10489
  return reported;
10304
10490
  }
@@ -10345,12 +10531,19 @@ async function verifyMasksAgainstRegions(params) {
10345
10531
  reason: `its mask's \`before\` (${regionOpTarget(mask.before.area)}) could not be resolved to a rect, so it can't be confirmed as an existing region`,
10346
10532
  };
10347
10533
  }
10348
- if (!existing.some(e => e.matchLevel === mask.before.matchLevel && sameRect(e.rect, beforeRect))) {
10534
+ const resolved = matchExistingRegion(existing, beforeRect, mask.before.matchLevel);
10535
+ if (resolved === null) {
10349
10536
  return {
10350
10537
  findingIndex: index,
10351
10538
  reason: `its mask's \`before\` (a ${mask.before.matchLevel} region at ${formatRect(beforeRect)}) does not match any region currently in effect on this step`,
10352
10539
  };
10353
10540
  }
10541
+ if (resolved === 'ambiguous') {
10542
+ return {
10543
+ findingIndex: index,
10544
+ reason: `its mask's \`before\` (a ${mask.before.matchLevel} region at ${formatRect(beforeRect)}) is equally close to more than one region currently in effect on this step, so which one it replaces is ambiguous`,
10545
+ };
10546
+ }
10354
10547
  }
10355
10548
  const afterRect = rectOf(mask.after.area);
10356
10549
  const findingRect = rectOf(finding.area);
@@ -11715,6 +11908,9 @@ async function stepProgress(params) {
11715
11908
  result.next.instruction += ` This step has ${unreviewed.length} unreviewed areas, more than one call can carry: review these ${batched.length} first, then call ${EYES_INSPECT_TOOLS.evidence} again for the rest.`;
11716
11909
  }
11717
11910
  result.next.instruction += ` Then report all ${batched.length} in ONE ${EYES_REVIEW_TOOLS.diffReport} call, not one call per area — the last call in next.calls already carries a \`reports\` entry per area, so fill in each entry's own findings. Per area: count the pink regions in its image diff, and if there is more than one, add an entry for each with its own smaller rect BEFORE that area's own full-areaRect entry — at most ${ENTRIES_PER_AREA - 1} such sub-rect entries per area, with any further pink regions reported as extra findings (each with its own \`area\`) inside the full-areaRect entry, which is what marks the area reviewed. Kept to that, a full round always fits one call; if a call would still pass ${MAX_DIFF_REPORT_BATCH} entries, split it at a full-areaRect boundary — every sub-rect entry stays in the same call as, and before, its own full-areaRect entry; areas deferred this way come back in the next response's \`reports\` on their own.`;
11911
+ // Masks are applied here, so the level rule has to arrive as a result the model reads now, not only as schema text.
11912
+ if (mode === 'resolve')
11913
+ result.next.instruction += ` ${MASK_LEVEL_RULE}`;
11718
11914
  // sameAs buys its way past the image gates with an examined dom diff, so a step with none can't use it.
11719
11915
  if (!unobtainable) {
11720
11916
  result.next.instruction +=