@applitools/mcp 0.7.0 → 0.7.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
@@ -3228,8 +3228,7 @@ function parseApplitoolsUrl(url) {
3228
3228
  function parseSessionUrl(url) {
3229
3229
  const parsed = parseApplitoolsUrl(url);
3230
3230
  if (!parsed.sessionId) {
3231
- throw new Error('The input URL is a batch URL while a session URL is expected. ' +
3232
- 'Use the eyes_fetch_visual_results MCP tool to obtain URLs of sessions in this batch.');
3231
+ throw new Error('The input URL is a batch URL while a session URL is expected.');
3233
3232
  }
3234
3233
  return parsed;
3235
3234
  }
@@ -4439,7 +4438,7 @@ function gateRejectionCount() {
4439
4438
 
4440
4439
  var name = "@applitools/mcp";
4441
4440
  var mcpName = "io.github.applitools/applitools";
4442
- var version = "0.7.0";
4441
+ var version = "0.7.1";
4443
4442
  var description = "Applitools MCP server for AI coding assistants";
4444
4443
  var main = "./dist/index.js";
4445
4444
  var bin = "./dist/index.js";
@@ -4569,6 +4568,21 @@ var packageJson = {
4569
4568
  lavamoat: lavamoat
4570
4569
  };
4571
4570
 
4571
+ /** Elides every image block's base64 `data` — one evidence call carries megabytes of screenshot, and users attach these logs to support tickets. */
4572
+ function serializeResultForLog(result) {
4573
+ const content = Array.isArray(result.content)
4574
+ ? result.content.map(block => {
4575
+ var _a;
4576
+ return block.type === 'image'
4577
+ ? {
4578
+ ...block,
4579
+ data: `<${String((_a = block.data) !== null && _a !== void 0 ? _a : '').length} base64 chars elided>`,
4580
+ }
4581
+ : block;
4582
+ })
4583
+ : result.content;
4584
+ return JSON.stringify({ ...result, content }, null, 2);
4585
+ }
4572
4586
  /** Recursively truncate arrays to `maxItems` before serialisation to avoid megabyte payloads in telemetry. */
4573
4587
  function truncateForTelemetry(value, maxItems = 3) {
4574
4588
  if (Array.isArray(value)) {
@@ -4716,7 +4730,7 @@ const createToolHandler = (toolDef, logic) => {
4716
4730
  const validatedParams = toolDef.input.parse(enrichedParams || {});
4717
4731
  const result = await withToolTelemetry(telemetry, () => logic(validatedParams));
4718
4732
  if (isVerboseLogging)
4719
- log$2('info', `[MCP] 📤 Result:`, JSON.stringify(result, null, 2));
4733
+ log$2('info', `[MCP] 📤 Result:`, serializeResultForLog(result));
4720
4734
  const structuredContentWithoutMessage = { ...result.structuredContent };
4721
4735
  if (structuredContentWithoutMessage && 'message' in structuredContentWithoutMessage) {
4722
4736
  delete structuredContentWithoutMessage.message;
@@ -5582,7 +5596,7 @@ const eyesSetupUfgTool = {
5582
5596
  };
5583
5597
 
5584
5598
  const TOOL_NAME$3 = TOOL_NAMES.EYES_ADD_CHECKPOINTS;
5585
- const TOOL_DESCRIPTION$3 = 'Add visual checkpoints to existing Playwright tests following best practices';
5599
+ const TOOL_DESCRIPTION$3 = 'Setup step: add eyes.check() visual checkpoints to an existing Playwright test file. Edits source, not results.';
5586
5600
  const PlaywrightJsAddCheckpointsInputSchema = commonInputSchema.extend({
5587
5601
  filePath: zod.z
5588
5602
  .string()
@@ -7516,10 +7530,10 @@ async function fetchVisibleDomDiff(url, stepIndex, keys, area, taskId, signal, d
7516
7530
  const baselineDomId = (_a = imageForSide(rawSession, stepIndex, 'baseline')) === null || _a === void 0 ? void 0 : _a.domId;
7517
7531
  const checkpointDomId = (_b = imageForSide(rawSession, stepIndex, 'checkpoint')) === null || _b === void 0 ? void 0 : _b.domId;
7518
7532
  if (!baselineDomId) {
7519
- throw new Error('This step has no baseline DOM capture');
7533
+ return { status: 'no-baseline-dom', reason: 'This step has no baseline DOM capture' };
7520
7534
  }
7521
7535
  if (!checkpointDomId) {
7522
- throw new Error('This step has no checkpoint DOM capture');
7536
+ return { status: 'no-checkpoint-dom', reason: 'This step has no checkpoint DOM capture' };
7523
7537
  }
7524
7538
  try {
7525
7539
  // deps.awaitDomDiff (api, backend-computed) owns its own cache, keyed on the two domIds alone (already
@@ -7550,10 +7564,165 @@ async function fetchVisibleDomDiff(url, stepIndex, keys, area, taskId, signal, d
7550
7564
  if (/Unknown or expired task/.test(message)) {
7551
7565
  throw new Error('The DOM diff task has expired server-side. Call this tool again with the same sessionUrl/stepIndex but WITHOUT taskId to restart the computation.');
7552
7566
  }
7567
+ // Backend-owned and permanent for this step, so it's reported as structural rather than as a transient error.
7568
+ if (/No store found/i.test(message)) {
7569
+ return { status: 'no-dom-data', reason: `The server holds no DOM data for this step: ${message}` };
7570
+ }
7553
7571
  throw new Error(`Error computing DOM diff: ${message}`);
7554
7572
  }
7555
7573
  }
7556
7574
 
7575
+ const EVIDENCE_PAD = 10;
7576
+ /** Unclamped, an area touching `left: 0` reaches the crop endpoint as `.clip(-10;…)`; a zero width or height means the area falls outside the image entirely. */
7577
+ function padAndClamp(rect, size, pad = EVIDENCE_PAD) {
7578
+ const clamp = (value, max) => Math.max(0, max === undefined ? value : Math.min(value, max));
7579
+ const left = clamp(rect.left - pad, size === null || size === void 0 ? void 0 : size.width);
7580
+ const top = clamp(rect.top - pad, size === null || size === void 0 ? void 0 : size.height);
7581
+ const right = clamp(rect.left + rect.width + pad, size === null || size === void 0 ? void 0 : size.width);
7582
+ const bottom = clamp(rect.top + rect.height + pad, size === null || size === void 0 ? void 0 : size.height);
7583
+ return { left, top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) };
7584
+ }
7585
+ /** Which images this step can produce for this area — the two sides can differ in size, so an area can fall off one of them entirely. */
7586
+ function evidenceCandidates(step, areaRect) {
7587
+ var _a;
7588
+ const sides = [
7589
+ ['baseline', step.baseline],
7590
+ ['checkpoint', step.checkpoint],
7591
+ ];
7592
+ return [
7593
+ // The diff is the checkpoint screenshot with differences highlighted, so it lives in checkpoint space.
7594
+ { label: 'diff', size: (_a = step.checkpoint.size) !== null && _a !== void 0 ? _a : step.baseline.size, missing: false },
7595
+ ...sides.map(([label, info]) => {
7596
+ var _a;
7597
+ return ({
7598
+ label,
7599
+ imageId: (_a = info.id) !== null && _a !== void 0 ? _a : undefined,
7600
+ size: info.size,
7601
+ missing: info.id === null,
7602
+ });
7603
+ }),
7604
+ ].map(({ label, size, missing, ...rest }) => {
7605
+ const rect = padAndClamp(areaRect, size);
7606
+ const where = label === 'diff' ? 'the checkpoint image it is drawn on' : `the ${label} image`;
7607
+ return {
7608
+ label,
7609
+ ...rest,
7610
+ rect,
7611
+ unavailable: missing
7612
+ ? `this step has no ${label} image`
7613
+ : rect.width > 0 && rect.height > 0
7614
+ ? undefined
7615
+ : `this area falls outside ${where}`,
7616
+ };
7617
+ });
7618
+ }
7619
+ /** The single source of truth for which images an area can have — `verifyDiffReportHardGate` must only demand evidence this says is obtainable. */
7620
+ function plannedEvidence(step, areaRect) {
7621
+ return evidenceCandidates(step, areaRect).filter(candidate => candidate.unavailable === undefined);
7622
+ }
7623
+ const EVIDENCE_FETCH_CONCURRENCY = 10;
7624
+ async function fetchEvidence(sessionUrl, stepIndex, areaRects, keys) {
7625
+ var _a;
7626
+ const session = await fetchSteps(sessionUrl, keys);
7627
+ const step = (_a = session.steps) === null || _a === void 0 ? void 0 : _a[stepIndex];
7628
+ if (!step)
7629
+ throw new Error(`Step index ${stepIndex} is out of range for this session.`);
7630
+ const { baseUrl } = parseSessionUrl(sessionUrl);
7631
+ const areas = areaRects.map(areaRect => {
7632
+ const candidates = evidenceCandidates(step, areaRect);
7633
+ return {
7634
+ areaRect,
7635
+ planned: candidates.filter(candidate => candidate.unavailable === undefined),
7636
+ unavailable: candidates
7637
+ .filter(candidate => candidate.unavailable !== undefined)
7638
+ .map(({ label, unavailable: reason }) => ({ label, reason: reason })),
7639
+ };
7640
+ });
7641
+ const tasks = areas.flatMap((area, areaIndex) => area.planned.map((request, imageIndex) => ({ areaIndex, imageIndex, request })));
7642
+ const paths = areas.map(area => new Array(area.planned.length));
7643
+ let cursor = 0;
7644
+ async function fetchNext() {
7645
+ while (cursor < tasks.length) {
7646
+ const { areaIndex, imageIndex, request } = tasks[cursor++];
7647
+ paths[areaIndex][imageIndex] =
7648
+ request.imageId === undefined
7649
+ ? await fetchImageDiff(sessionUrl, stepIndex, keys, request.rect)
7650
+ : await fetchImage(baseUrl, request.imageId, keys, request.rect);
7651
+ }
7652
+ }
7653
+ await Promise.all(Array.from({ length: Math.min(EVIDENCE_FETCH_CONCURRENCY, tasks.length) }, fetchNext));
7654
+ return areas.map(({ areaRect, planned, unavailable }, areaIndex) => ({
7655
+ areaRect,
7656
+ images: planned.map((request, imageIndex) => ({ ...request, path: paths[areaIndex][imageIndex], inline: false })),
7657
+ ...(unavailable.length > 0 ? { unavailable } : {}),
7658
+ }));
7659
+ }
7660
+ /** Clients known to render an MCP `image` block; anything else gets paths only, since base64-as-text costs ~20k tokens per image and still shows nothing. */
7661
+ const IMAGE_RENDERING_CLIENTS = new Set(['Claude Code']);
7662
+ /** A count, not bytes: Claude Code prices an image block at a flat ~1600 tokens whatever the payload weighed. */
7663
+ const INLINE_IMAGE_BUDGET = 21;
7664
+ /** The most images one area can have (the diff plus both sides), so a batch sized against it inlines whole even in the worst case. */
7665
+ const MAX_IMAGES_PER_AREA = 3;
7666
+ /** The ceiling Claude Code re-encodes every image under, so raw bytes above it buy payload size for zero context. */
7667
+ const MAX_INLINE_IMAGE_BYTES = 512 * 1024;
7668
+ /** Whole areas, in area order: an area's images inline together or not at all, so no area is ever judged from a partial set. */
7669
+ function inlineGroups(evidence) {
7670
+ return evidence.map(area => area.images).filter(group => group.length > 0);
7671
+ }
7672
+ /** The paths are unconditional; the image blocks are the turn saving, and `inlining` reports what the budget actually did. */
7673
+ function buildEvidenceResult(evidence, budget = {}) {
7674
+ var _a, _b;
7675
+ const { images: budgetImages = INLINE_IMAGE_BUDGET, maxImageBytes = MAX_INLINE_IMAGE_BYTES } = budget;
7676
+ const rendersImages = IMAGE_RENDERING_CLIENTS.has((_b = (_a = getClientInfo()) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : '');
7677
+ const groups = inlineGroups(evidence);
7678
+ const loaded = new Map();
7679
+ const load = (image) => {
7680
+ if (!rendersImages)
7681
+ return 'client-cannot-render';
7682
+ if (loaded.size >= budgetImages)
7683
+ return 'budget-spent';
7684
+ try {
7685
+ if (fs__namespace.statSync(image.path).size > maxImageBytes)
7686
+ return 'over-per-image-cap';
7687
+ return fs__namespace.readFileSync(image.path);
7688
+ }
7689
+ catch (error) {
7690
+ try {
7691
+ fs__namespace.rmSync(image.path, { force: true });
7692
+ }
7693
+ catch { }
7694
+ const area = evidence.find(entry => entry.images.includes(image));
7695
+ throw new Error(`Error reading the cached ${image.label} image for area ${JSON.stringify(area === null || area === void 0 ? void 0 : area.areaRect)} at ${image.path}: ${error instanceof Error ? error.message : String(error)}`);
7696
+ }
7697
+ };
7698
+ for (const group of groups) {
7699
+ const spent = rendersImages && budgetImages - loaded.size < group.length;
7700
+ for (const image of group) {
7701
+ const outcome = spent ? 'budget-spent' : load(image);
7702
+ if (Buffer.isBuffer(outcome))
7703
+ loaded.set(image, outcome);
7704
+ Object.assign(image, {
7705
+ inline: Buffer.isBuffer(outcome),
7706
+ notInlined: Buffer.isBuffer(outcome) ? undefined : outcome,
7707
+ });
7708
+ }
7709
+ }
7710
+ // Reading order, not selection order: the JSON names inlined images only by their position in the evidence list.
7711
+ const imageBlocks = evidence
7712
+ .flatMap(area => area.images)
7713
+ .filter(image => loaded.has(image))
7714
+ .map(image => ({ type: 'image', data: loaded.get(image).toString('base64'), mimeType: 'image/png' }));
7715
+ const inlining = {
7716
+ inlined: loaded.size,
7717
+ images: groups.reduce((total, group) => total + group.length, 0),
7718
+ budgetImages,
7719
+ maxImageBytes,
7720
+ };
7721
+ return {
7722
+ content: [{ type: 'text', text: JSON.stringify({ evidence, inlining }, null, 2) }, ...imageBlocks],
7723
+ };
7724
+ }
7725
+
7557
7726
  const SEARCH_MULTIPLIER = 2;
7558
7727
  const SEARCH_CAP = 10;
7559
7728
  /**
@@ -7832,14 +8001,17 @@ function logDataToolCall(scopeId, toolName, args, deps) {
7832
8001
  recordChainSource(scopeId, deps);
7833
8002
  logInvocation(scopeId, toolName, args, deps);
7834
8003
  }
7835
- const RectShape = zod.z
7836
- .object({
8004
+ const RequiredRectShape = zod.z.object({
7837
8005
  left: zod.z.number(),
7838
8006
  top: zod.z.number(),
7839
8007
  width: zod.z.number(),
7840
8008
  height: zod.z.number(),
7841
- })
7842
- .optional();
8009
+ });
8010
+ const RectShape = RequiredRectShape.optional();
8011
+ /** Areas, not images. An area inlines whole-or-not, so areas past what the budget holds would come back as paths only — a cost that moves to the client rather than disappearing. */
8012
+ const MAX_EVIDENCE_BATCH = Math.floor(INLINE_IMAGE_BUDGET / MAX_IMAGES_PER_AREA);
8013
+ /** A client only parallelises a batch of tool calls when every one of them declares `readOnlyHint`. */
8014
+ const READ_ONLY = { readOnlyHint: true };
7843
8015
  /**
7844
8016
  * Every `eyes_inspect_*` tool's own name, in one place — `registerTool`/`logDataToolCall` below
7845
8017
  * read from here, and so does `verifyInvocation` in `../eyes-review/tools.ts`'s hard gates, so a
@@ -7854,6 +8026,7 @@ const EYES_INSPECT_TOOLS = {
7854
8026
  dom: 'eyes_inspect_dom',
7855
8027
  domSearch: 'eyes_inspect_dom_search',
7856
8028
  domDiff: 'eyes_inspect_dom_diff',
8029
+ evidence: 'eyes_inspect_evidence',
7857
8030
  regions: 'eyes_inspect_regions',
7858
8031
  history: 'eyes_inspect_history',
7859
8032
  };
@@ -7884,6 +8057,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7884
8057
  .describe('Narrow to sessions matching this state — "mismatching" keeps sessions with at least one step that\'s non-matching, missing a checkpoint, or new'),
7885
8058
  format: zod.z.enum(['full', 'stats', 'scenarios']).optional().describe('Shape of the response; defaults to "full"'),
7886
8059
  },
8060
+ annotations: READ_ONLY,
7887
8061
  }, async ({ batchUrl, filter, format }) => {
7888
8062
  const keys = readOnlyApiKeyProvider(batchUrl);
7889
8063
  const rawArgs = [filter, format].filter((v) => v !== undefined);
@@ -7896,6 +8070,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7896
8070
  inputSchema: {
7897
8071
  sessionUrl: zod.z.string().describe(SESSION_URL_DESC),
7898
8072
  },
8073
+ annotations: READ_ONLY,
7899
8074
  }, async ({ sessionUrl }) => {
7900
8075
  const keys = readOnlyApiKeyProvider(sessionUrl);
7901
8076
  const result = await fetchSteps(sessionUrl, keys);
@@ -7909,6 +8084,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7909
8084
  stepIndex: zod.z.number().int().nonnegative().describe(STEP_INDEX_DESC),
7910
8085
  rect: RectShape.describe(RECT_DESC),
7911
8086
  },
8087
+ annotations: READ_ONLY,
7912
8088
  }, async ({ sessionUrl, stepIndex, rect }) => {
7913
8089
  const keys = readOnlyApiKeyProvider(sessionUrl);
7914
8090
  const result = await fetchChangedAreas(sessionUrl, stepIndex, keys, rect);
@@ -7922,6 +8098,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7922
8098
  stepIndex: zod.z.number().int().nonnegative().describe(STEP_INDEX_DESC),
7923
8099
  rect: RectShape.describe(RECT_DESC),
7924
8100
  },
8101
+ annotations: READ_ONLY,
7925
8102
  }, async ({ sessionUrl, stepIndex, rect }) => {
7926
8103
  const keys = readOnlyApiKeyProvider(sessionUrl);
7927
8104
  const filePath = await fetchImageDiff(sessionUrl, stepIndex, keys, rect);
@@ -7935,6 +8112,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7935
8112
  imageId: zod.z.string().describe('Baseline or checkpoint image id from eyes_inspect_steps'),
7936
8113
  rect: RectShape.describe(RECT_DESC),
7937
8114
  },
8115
+ annotations: READ_ONLY,
7938
8116
  }, async ({ sessionUrl, imageId, rect }) => {
7939
8117
  const keys = readOnlyApiKeyProvider(sessionUrl);
7940
8118
  const { baseUrl } = parseSessionUrl(sessionUrl);
@@ -7942,6 +8120,30 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7942
8120
  logDataToolCall(sessionScopeId(sessionUrl), EYES_INSPECT_TOOLS.image, { imageId, rect }, phaseTrackerDeps);
7943
8121
  return textResult(filePath);
7944
8122
  });
8123
+ server.registerTool(EYES_INSPECT_TOOLS.evidence, {
8124
+ description: "Everything needed to review a step's changed areas, in one call: for each area, the image diff (checkpoint with differences highlighted in pink) plus the baseline and checkpoint screenshots, fetched together. Pass EVERY area you still have to review in a single call's `areaRects` — one call per area is exactly what this tool exists to avoid. Pass each rect exactly as eyes_review_progress gave it to you — do NOT pad it, the server pads it and clamps it to each image. Prefer this over calling eyes_inspect_image_diff and eyes_inspect_image separately; it is what eyes_review_diff_report's gate checks for. Returns `evidence`, one entry per area in the order asked for, each with a labelled file path per image, plus the images themselves for clients that render them — read each `path` only for an image whose `inline` is false, and `notInlined` says why it was not. Inlined images arrive as image blocks in the same order as the `inline: true` entries, reading `evidence` top to bottom; `inlining` reports how much of the budget the response spent. Each image carries the `rect` it was actually cropped at: the two sides of a step can differ in size, so the crops are near-identical but NOT guaranteed equal — compare by content, and check the rects before reading anything into a difference in position or extent. Any image this step cannot produce for an area is listed under that area's `unavailable` with the reason, which is a fact about the step, not a failure. Already reflects any match regions added during resolution; resolution can happen between calls, so never reuse an earlier result in this conversation — call it again.",
8125
+ inputSchema: {
8126
+ sessionUrl: zod.z.string().describe(SESSION_URL_DESC),
8127
+ stepIndex: zod.z.number().int().nonnegative().describe(STEP_INDEX_DESC),
8128
+ areaRects: zod.z
8129
+ .array(RequiredRectShape)
8130
+ .min(1)
8131
+ .max(MAX_EVIDENCE_BATCH)
8132
+ .describe(`Every changed area of this step you still need evidence for — from eyes_inspect_changed_areas or eyes_review_progress, verbatim and unpadded. Up to ${MAX_EVIDENCE_BATCH} per call; if a step has more, review these first and call again for the rest.`),
8133
+ },
8134
+ annotations: READ_ONLY,
8135
+ }, async ({ sessionUrl, stepIndex, areaRects }) => {
8136
+ const keys = readOnlyApiKeyProvider(sessionUrl);
8137
+ const scopeId = stepScopeId(sessionUrl, stepIndex);
8138
+ const evidence = await fetchEvidence(sessionUrl, stepIndex, areaRects, keys);
8139
+ const result = buildEvidenceResult(evidence);
8140
+ recordChainSource(scopeId, phaseTrackerDeps);
8141
+ // One record per area, not per call: eyes_review_diff_report's gate reads these area by area.
8142
+ for (const area of evidence) {
8143
+ logInvocation(scopeId, EYES_INSPECT_TOOLS.evidence, { areaRect: area.areaRect, images: area.images.map(image => image.label) }, phaseTrackerDeps);
8144
+ }
8145
+ return result;
8146
+ });
7945
8147
  server.registerTool(EYES_INSPECT_TOOLS.dom, {
7946
8148
  description: "Export a DOM capture as JSON, saved to a file. `domId` comes from eyes_inspect_steps (baseline.domId or checkpoint.domId per step). Use to inspect exact computed styles/structure, or to locate an element's rect/id for use elsewhere (e.g. as an eyes_inspect_history nodeId). Returns a file path — pass it directly to the Read tool, or search it with eyes_inspect_dom_search rather than writing an ad-hoc script.",
7947
8149
  inputSchema: {
@@ -7949,6 +8151,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7949
8151
  domId: zod.z.string().describe('Baseline or checkpoint domId from eyes_inspect_steps'),
7950
8152
  rect: RectShape.describe(`${RECT_DESC} Don't pad it.`),
7951
8153
  },
8154
+ annotations: READ_ONLY,
7952
8155
  }, async ({ sessionUrl, domId, rect }) => {
7953
8156
  const keys = readOnlyApiKeyProvider(sessionUrl);
7954
8157
  const domIdError = validateDomId(domId);
@@ -7969,6 +8172,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7969
8172
  .string()
7970
8173
  .describe("Boolean predicate, e.g. \"tagName = 'HEADER'\" or \"child-of (tagName = 'UL') and tagName = 'LI'\""),
7971
8174
  },
8175
+ annotations: READ_ONLY,
7972
8176
  }, async ({ filePath, predicate }) => {
7973
8177
  const result = searchDomFile(filePath, predicate);
7974
8178
  return textResult(result);
@@ -7984,6 +8188,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7984
8188
  .optional()
7985
8189
  .describe('ONLY a taskId from a prior {"status":"computing"} response of this exact tool for the same sessionUrl/stepIndex — resumes checking that computation instead of resubmitting. Never invent or reuse one across steps.'),
7986
8190
  },
8191
+ annotations: READ_ONLY,
7987
8192
  }, async ({ sessionUrl, stepIndex, rect, taskId }, extra) => {
7988
8193
  const keys = readOnlyApiKeyProvider(sessionUrl);
7989
8194
  const result = await fetchVisibleDomDiff(sessionUrl, stepIndex, keys, rect, taskId, extra === null || extra === void 0 ? void 0 : extra.signal);
@@ -7998,6 +8203,17 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
7998
8203
  'Do NOT guess, summarize, or reconstruct the diff from anything else — it is only available through that call.',
7999
8204
  }, null, 2));
8000
8205
  }
8206
+ if (result.status !== 'ready') {
8207
+ // Logged, unlike `computing`, so eyes_review_end's step-close gate stays satisfiable without a diff.
8208
+ logDataToolCall(stepScopeId(sessionUrl, stepIndex), EYES_INSPECT_TOOLS.domDiff, { rect, status: result.status }, phaseTrackerDeps);
8209
+ return textResult(JSON.stringify({
8210
+ status: result.status,
8211
+ reason: result.reason,
8212
+ next: 'No DOM diff exists for this step and none can be computed — this is terminal, not transient. ' +
8213
+ 'Do NOT call this tool again for this step. Review it from the images alone and record that ' +
8214
+ 'the structural comparison was not available, rather than that no structural change was found.',
8215
+ }, null, 2));
8216
+ }
8001
8217
  logDataToolCall(stepScopeId(sessionUrl, stepIndex), EYES_INSPECT_TOOLS.domDiff, { rect }, phaseTrackerDeps);
8002
8218
  return textResult(result.diff);
8003
8219
  });
@@ -8008,6 +8224,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
8008
8224
  stepIndex: zod.z.number().int().nonnegative().describe(STEP_INDEX_DESC),
8009
8225
  rect: RectShape.describe(RECT_DESC),
8010
8226
  },
8227
+ annotations: READ_ONLY,
8011
8228
  }, async ({ sessionUrl, stepIndex, rect }) => {
8012
8229
  const keys = readOnlyApiKeyProvider(sessionUrl);
8013
8230
  const result = await fetchRegions(sessionUrl, stepIndex, keys, rect);
@@ -8030,6 +8247,7 @@ function registerEyesInspectDataTools(server, phaseTrackerDeps = defaultPhaseTra
8030
8247
  .optional()
8031
8248
  .describe('Target number of non-empty diffs to collect per node; defaults to 3'),
8032
8249
  },
8250
+ annotations: READ_ONLY,
8033
8251
  }, async ({ sessionUrl, stepIndex, nodeIds, count }, extra) => {
8034
8252
  const keys = readOnlyApiKeyProvider(sessionUrl);
8035
8253
  const result = await runHistory(sessionUrl, stepIndex, nodeIds, count !== null && count !== void 0 ? count : 3, keys, undefined, extra === null || extra === void 0 ? void 0 : extra.signal);
@@ -8952,7 +9170,7 @@ function reviewEndCall(scope, args, rootScope, mode) {
8952
9170
  * scope id) — otherwise it returns the cached, still-incomplete queue untouched, with no network
8953
9171
  * call at all. On a fresh check, only genuinely new keys are appended (`queueChildKeys`'s own
8954
9172
  * dedup) — nothing is ever removed. Always returns the full cumulative queue (old + new, completed
8955
- * or not), so it drops straight into `runProgress`'s `computeCompleted`/`incompleteChildCalls` and
9173
+ * or not), so it drops straight into `runProgress`'s `computeCompleted`/descent resolution and
8956
9174
  * `runEnd`'s `ownChildren`/`getSiblings` exactly like a plain live-fetched list would.
8957
9175
  */
8958
9176
  async function resolveScopedChildren(scopeId, fetchLiveChildKeys, descriptorForKey, deps) {
@@ -8987,20 +9205,20 @@ function computeCompleted(scopeId, liveChildScopeIds, deps) {
8987
9205
  * by one of them being reviewed/revised afterward), the instruction to call `eyes_review_end` for
8988
9206
  * this same level (`scope`); once `completed` holds a fresh timestamp, nothing further — plus,
8989
9207
  * only while `level` hasn't already reached `rootScope`, a suggestion to move on to the parent's own
8990
- * `eyes_review_progress` call. Every incoming call (`incompleteChildCalls`, `endCall`,
9208
+ * `eyes_review_progress` call. Every incoming call (`descentCall`, `endCall`,
8991
9209
  * `parentProgressCall`) is expected to already carry the investigation's `rootScope` — built via
8992
9210
  * `nextCall()` at its construction site in `tools.ts` — so this function only ever selects among
8993
9211
  * them, never mutates or re-scopes one.
8994
9212
  */
8995
9213
  function buildProgressNext(params) {
8996
- const { level, rootScope, completed, incompleteChildCalls, endCall, parentProgressCall } = params;
9214
+ const { level, rootScope, completed, descentCall, endCall, parentProgressCall } = params;
8997
9215
  const label = LEVEL_LABELS[level];
8998
9216
  const childLabel = LEVEL_LABELS[childLevelOf(level)];
8999
9217
  if (completed === null) {
9000
- if (incompleteChildCalls.length > 0) {
9218
+ if (descentCall) {
9001
9219
  return {
9002
9220
  instruction: `Not every ${childLabel} of this ${label} was reviewed. Call this next, in this order — don't reorder or substitute your own priority:`,
9003
- calls: [incompleteChildCalls[0]],
9221
+ calls: [descentCall],
9004
9222
  };
9005
9223
  }
9006
9224
  return {
@@ -9026,20 +9244,32 @@ function buildProgressNext(params) {
9026
9244
  * `parentProgressCall` are expected to already carry `rootScope` from their `nextCall()` call site.
9027
9245
  */
9028
9246
  function buildEndNext(params) {
9029
- const { level, rootScope, siblingCall, parentProgressCall, doneMessage } = params;
9247
+ const { level, rootScope, siblingCall, parentClose, parentProgressCall, doneMessage } = params;
9030
9248
  const label = LEVEL_LABELS[level];
9031
9249
  if (hasReachedRootScope(level, rootScope)) {
9032
9250
  return { instruction: doneMessage };
9033
9251
  }
9034
9252
  if (siblingCall) {
9253
+ const target = LEVEL_LABELS[siblingCall.level];
9035
9254
  return {
9036
- instruction: `This ${label} was reviewed. Another ${label} still needs reviewing — call it next.`,
9037
- calls: [siblingCall],
9255
+ instruction: siblingCall.level === level
9256
+ ? `This ${label} was reviewed. Another ${label} still needs reviewing — call it next.`
9257
+ : `This ${label} was reviewed. Reviewing continues at the next unreviewed ${target} — call it next.`,
9258
+ calls: [siblingCall.call],
9259
+ };
9260
+ }
9261
+ if (parentClose) {
9262
+ const closeLabel = LEVEL_LABELS[parentClose.level];
9263
+ return {
9264
+ instruction: `This ${label} was reviewed, and so was every other ${label}, so the ${closeLabel} is now fully reviewed too. Call ${parentClose.endCall.tool} for the ${closeLabel} next, citing the indexed findings in next.nextLevel as its sources — do not re-check its progress first, this response already is that answer.`,
9265
+ calls: [parentClose.endCall],
9266
+ nextLevel: parentClose.nextLevel,
9038
9267
  };
9039
9268
  }
9040
9269
  if (parentProgressCall) {
9270
+ const parentLabelHere = LEVEL_LABELS[parentLevelOf(level)];
9041
9271
  return {
9042
- instruction: `This ${label} was reviewed, and so was every other ${label}. Move on to ${parentProgressCall.tool} for the ${LEVEL_LABELS[parentLevelOf(level)]}.`,
9272
+ instruction: `This ${label} was reviewed, and so was every other ${label}. Move on to ${parentProgressCall.tool} for the ${parentLabelHere}.`,
9043
9273
  calls: [parentProgressCall],
9044
9274
  };
9045
9275
  }
@@ -9180,81 +9410,176 @@ async function walkSubtree(level, ctx, visit, deps) {
9180
9410
  }
9181
9411
  await visit(level, ctx, scopeId);
9182
9412
  }
9413
+ /** The one place entry order is decided — validation, display and clustering all derive from it, and a reordering in only one would be silently accepted. */
9414
+ function orderedChildFindingEntries(scopeId, deps) {
9415
+ return Object.entries(getChildFindings(scopeId, deps));
9416
+ }
9183
9417
  /**
9184
- * Every child finding `scopeId`'s children have reported, flattened into one array in a stable
9185
- * order — each child's own findings sub-array in full before the next child's, in
9186
- * `getChildFindings`'s own key order. This is the exact list a submitted finding's `sources`
9187
- * indexes into, and the same order `attachFindingIndices` numbers for display.
9418
+ * Every child finding `scopeId`'s children have reported, flattened into one array — each child's
9419
+ * own findings sub-array in full before the next child's. This is the exact list a submitted
9420
+ * finding's `sources` indexes into; see `orderedChildFindingEntries` for what fixes the order.
9188
9421
  */
9189
9422
  function flattenChildFindings(scopeId, deps) {
9190
- return Object.values(getChildFindings(scopeId, deps)).flat();
9423
+ return orderedChildFindingEntries(scopeId, deps).flatMap(([, findings]) => findings);
9191
9424
  }
9192
9425
  /**
9193
9426
  * Attaches this same flat, global `index` to every finding across every child-key group, so
9194
9427
  * `_progress`'s displayed findings can be cited by a later `_end` call's `sources`. Takes/returns
9195
- * `Object.entries(getChildFindings(...))`'s own shape so each level's `buildFindings` can wrap its
9196
- * existing call with this and keep its own per-child key naming (`scenarioName`, `sessionUrl`, …)
9197
- * unchanged.
9428
+ * `orderedChildFindingEntries`' own shape — feed it from there and nothing else, or display and
9429
+ * validation stop agreeing — so each level's `buildFindings` keeps its own per-child key naming
9430
+ * (`scenarioName`, `sessionUrl`, …) unchanged.
9198
9431
  */
9199
9432
  function attachFindingIndices(entries) {
9200
9433
  let index = 0;
9201
9434
  return entries.map(([key, findings]) => [key, findings.map(finding => ({ ...finding, index: index++ }))]);
9202
9435
  }
9436
+ const CLUSTER_NOTE = 'These share the listed mechanical key. Whether they share a cause is your call.';
9437
+ /** `undefined` when the value is a DOM node id rather than a rect. */
9438
+ function asRect(value) {
9439
+ const rect = value;
9440
+ return rect && typeof rect === 'object' && typeof rect.left === 'number' && typeof rect.width === 'number'
9441
+ ? rect
9442
+ : undefined;
9443
+ }
9444
+ /** Levels disagree on the field name, hence both. */
9445
+ function findingRect(finding) {
9446
+ var _a;
9447
+ const located = finding;
9448
+ return (_a = asRect(located.areaRect)) !== null && _a !== void 0 ? _a : asRect(located.area);
9449
+ }
9450
+ /** Only facts derivable from the finding itself, so the key never depends on traversal order. */
9451
+ function mechanicalKey(childKey, finding) {
9452
+ var _a, _b;
9453
+ const known = finding;
9454
+ const ancestry = Object.entries((_a = known.origin) !== null && _a !== void 0 ? _a : {})
9455
+ .filter(([, value]) => value !== undefined)
9456
+ .sort(([a], [b]) => (a < b ? -1 : 1))
9457
+ .map(([name, value]) => `${name}:${value}`);
9458
+ return [
9459
+ `at:${childKey}`,
9460
+ ...ancestry,
9461
+ `verdict:${known.isBug != null ? 'bug' : '-'}/${known.isExpected != null ? 'expected' : '-'}`,
9462
+ ...(((_b = known.dynamic) === null || _b === void 0 ? void 0 : _b.justification) ? [`dynamic:${known.dynamic.justification}`] : []),
9463
+ ].join(' · ');
9464
+ }
9465
+ /** Union-find because overlap is not transitive. Membership is stable across runs; ids are not, since they inherit the entry numbering. */
9466
+ function buildSourceClusters(entries) {
9467
+ const flat = entries.flatMap(([childKey, findings]) => findings.map(finding => ({ key: mechanicalKey(childKey, finding), rect: findingRect(finding) })));
9468
+ const parent = flat.map((_, index) => index);
9469
+ const find = (index) => (parent[index] === index ? index : (parent[index] = find(parent[index])));
9470
+ const union = (a, b) => {
9471
+ const [x, y] = [find(a), find(b)];
9472
+ if (x < y)
9473
+ parent[y] = x;
9474
+ else if (y < x)
9475
+ parent[x] = y;
9476
+ };
9477
+ const byKey = new Map();
9478
+ flat.forEach((item, index) => { var _a; return byKey.set(item.key, [...((_a = byKey.get(item.key)) !== null && _a !== void 0 ? _a : []), index]); });
9479
+ for (const members of byKey.values()) {
9480
+ for (let i = 0; i < members.length; i++) {
9481
+ for (let j = i + 1; j < members.length; j++) {
9482
+ const [a, b] = [flat[members[i]], flat[members[j]]];
9483
+ // No rect on either side means no geometry to separate them, so the other keys decide.
9484
+ if (a.rect && b.rect ? rectsIntersect(a.rect, b.rect) : !a.rect && !b.rect)
9485
+ union(members[i], members[j]);
9486
+ }
9487
+ }
9488
+ }
9489
+ const byLabel = new Map();
9490
+ flat.forEach((_, index) => {
9491
+ var _a;
9492
+ const label = find(index);
9493
+ byLabel.set(label, [...((_a = byLabel.get(label)) !== null && _a !== void 0 ? _a : []), index]);
9494
+ });
9495
+ return [...byLabel.entries()]
9496
+ .sort(([a], [b]) => a - b)
9497
+ .map(([label, indices]) => ({ id: `g${label}`, key: flat[label].key, indices, note: CLUSTER_NOTE }));
9498
+ }
9499
+ /** Clusters are disjoint and cover the whole numbering, so expanding them can neither manufacture an overlap nor conceal a gap from `verifySourcedFindings`. */
9500
+ function expandSourceCitations(findings, clusters) {
9501
+ const byId = new Map(clusters.map(cluster => [cluster.id, cluster.indices]));
9502
+ return findings.map((finding, findingIndex) => {
9503
+ var _a;
9504
+ const cited = ((_a = finding.sourceClusters) !== null && _a !== void 0 ? _a : []).flatMap(id => {
9505
+ const indices = byId.get(id);
9506
+ if (!indices) {
9507
+ throw new Error(`Finding ${findingIndex}'s sourceClusters names "${id}", which is not one of the cluster ids this level's own findings were grouped into ` +
9508
+ `(${clusters.map(cluster => cluster.id).join(', ') || 'there are none'}). Call again citing only ids this call was shown, or plain sources indices.`);
9509
+ }
9510
+ return indices;
9511
+ });
9512
+ return { ...finding, sources: [...new Set([...finding.sources, ...cited])].sort((a, b) => a - b) };
9513
+ });
9514
+ }
9203
9515
  /**
9204
9516
  * Validates a submitted `_end` finding array's `sources` against `childFindings` — the exact flat,
9205
9517
  * ordered list `flattenChildFindings` produces for this same scope — then checks each finding's
9206
9518
  * own isBug/isExpected for consistency with the isBug/isExpected of just the child findings its
9207
9519
  * `sources` names: isBug non-null iff any of them is, isExpected non-null iff every one of them is.
9208
- * Throws with an instructive, retry-guiding message on the first violation found, checked in this
9209
- * order so the earliest structural problem surfaces before a later, harder-to-diagnose one: an
9210
- * out-of-range index, then sources claimed by more than one finding, then a child finding no
9211
- * finding accounts for, and only once `sources` are well-formed, the isBug/isExpected check.
9212
- * Resolves with no return value once every finding passes.
9520
+ * The checks run in this order, so the earliest structural problem surfaces before a later,
9521
+ * harder-to-diagnose one: an out-of-range index, then sources claimed by more than one finding,
9522
+ * then a child finding no finding accounts for, and only once `sources` are well-formed, the
9523
+ * isBug/isExpected check. The failing check reports every violation it found, not just the first —
9524
+ * one per rejection would cost a regenerated submission each.
9213
9525
  */
9214
9526
  function verifySourcedFindings(findings, childFindings) {
9215
9527
  const claimedBy = new Map();
9528
+ const outOfRange = [];
9529
+ const overlapping = [];
9216
9530
  findings.forEach((finding, findingIndex) => {
9217
9531
  for (const source of finding.sources) {
9218
9532
  if (!Number.isInteger(source) || source < 0 || source >= childFindings.length) {
9219
- const range = childFindings.length > 0 ? `0-${childFindings.length - 1}` : '(there are no child findings to source from)';
9220
- throw new Error(`Finding ${findingIndex}'s sources names index ${source}, which is not a valid child finding index for this call — ` +
9221
- `valid indices are ${range}. Call again with sources that only reference indices from the findings this level's own _progress call reported.`);
9533
+ outOfRange.push(`finding ${findingIndex}'s sources names index ${source}`);
9534
+ continue;
9222
9535
  }
9223
9536
  const claimant = claimedBy.get(source);
9224
9537
  if (claimant !== undefined && claimant !== findingIndex) {
9225
- throw new Error(`Child finding ${source} is named in both finding ${claimant}'s and finding ${findingIndex}'s sources — ` +
9226
- `each child finding must be consolidated into exactly one submitted finding. Call again with non-overlapping sources.`);
9538
+ overlapping.push(`Child finding ${source} is named in both finding ${claimant}'s and finding ${findingIndex}'s sources`);
9539
+ continue;
9227
9540
  }
9228
9541
  claimedBy.set(source, findingIndex);
9229
9542
  }
9230
9543
  });
9544
+ if (outOfRange.length > 0) {
9545
+ const range = childFindings.length > 0 ? `0-${childFindings.length - 1}` : '(there are no child findings to source from)';
9546
+ throw new Error(`Sources name an index that is not a valid child finding index for this call: ${outOfRange.join('; ')}. ` +
9547
+ `Valid indices are ${range}. Call again with sources that only reference indices from the findings this level's own _progress call reported.`);
9548
+ }
9549
+ if (overlapping.length > 0) {
9550
+ throw new Error(`${overlapping.join('; ')} — each child finding must be consolidated into exactly one submitted finding. ` +
9551
+ `Call again with non-overlapping sources.`);
9552
+ }
9231
9553
  const missing = childFindings.map((_, i) => i).filter(i => !claimedBy.has(i));
9232
9554
  if (missing.length > 0) {
9233
9555
  throw new Error(`Child finding${missing.length === 1 ? '' : 's'} ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not named in ` +
9234
9556
  `any submitted finding's sources. Every child finding must be accounted for — call again with a finding (existing or new) whose ` +
9235
9557
  `sources include ${missing.length === 1 ? 'it' : 'them'}.`);
9236
9558
  }
9559
+ const inconsistent = [];
9237
9560
  findings.forEach((finding, findingIndex) => {
9238
9561
  const referenced = finding.sources.map(i => childFindings[i]);
9239
9562
  const anyIsBug = referenced.some(c => c.isBug !== null);
9240
9563
  if (anyIsBug && finding.isBug === null) {
9241
- throw new Error(`Finding ${findingIndex} consolidates a child finding with isBug set, so it must have isBug set too — call again with isBug describing the bug.`);
9564
+ inconsistent.push(`Finding ${findingIndex} consolidates a child finding with isBug set, so it must have isBug set too — call again with isBug describing the bug.`);
9242
9565
  }
9243
9566
  if (!anyIsBug && finding.isBug !== null) {
9244
- throw new Error(`Finding ${findingIndex} has isBug set, but none of the child findings it consolidates (sources: ${JSON.stringify(finding.sources)}) do — call again with isBug: null, or correct its sources.`);
9567
+ inconsistent.push(`Finding ${findingIndex} has isBug set, but none of the child findings it consolidates (sources: ${JSON.stringify(finding.sources)}) do — call again with isBug: null, or correct its sources.`);
9245
9568
  }
9246
9569
  const allIsExpected = referenced.every(c => c.isExpected !== null);
9247
9570
  if (allIsExpected && finding.isExpected === null) {
9248
- throw new Error(`Finding ${findingIndex} consolidates only child findings with isExpected set, so it must have isExpected set too — call again with isExpected filled in.`);
9571
+ inconsistent.push(`Finding ${findingIndex} consolidates only child findings with isExpected set, so it must have isExpected set too — call again with isExpected filled in.`);
9249
9572
  }
9250
9573
  if (!allIsExpected && finding.isExpected !== null) {
9251
- throw new Error(`Finding ${findingIndex} has isExpected set, but at least one child finding it consolidates (sources: ${JSON.stringify(finding.sources)}) does not — call again with isExpected: null, or correct its sources.`);
9574
+ inconsistent.push(`Finding ${findingIndex} has isExpected set, but at least one child finding it consolidates (sources: ${JSON.stringify(finding.sources)}) does not — call again with isExpected: null, or correct its sources.`);
9252
9575
  }
9253
9576
  });
9577
+ if (inconsistent.length > 0)
9578
+ throw new Error(inconsistent.join(' '));
9254
9579
  }
9255
- /** Drops `sources` from every finding — the field only ever exists on an `_end` call's own input, never in what gets persisted or pushed up to a parent (see `verifySourcedFindings`'s own doc comment). */
9580
+ /** Citations exist only on an `_end` call's input — never in what is persisted or pushed up to a parent. */
9256
9581
  function stripSources(findings) {
9257
- return findings.map(({ sources: _sources, ...rest }) => rest);
9582
+ return findings.map(({ sources: _sources, sourceClusters: _sourceClusters, ...rest }) => rest);
9258
9583
  }
9259
9584
 
9260
9585
  // Every Zod shape the review tools share — the `scope` level argument and the entity-id
@@ -9287,7 +9612,10 @@ const EndScopeShape = zod.z
9287
9612
  'summary, omit any "(sameAs: ...)" note from the underlying descriptions — describe the change itself, not how it ' +
9288
9613
  'was verified. In mode "resolve" this call also decides the step: rejected if any finding is a bug or inconsistent ' +
9289
9614
  'with its surroundings, accepted if every finding is justified (expected, or evidenced dynamic content), and ' +
9290
- 'otherwise left unresolved for human review — including whenever a region could not be applied.');
9615
+ 'otherwise left unresolved for human review — including whenever a region could not be applied. The block this ' +
9616
+ 'call consolidates may hold either already-reduced summaries or raw per-changed-area findings, depending on how ' +
9617
+ 'far the walk skipped to reach here — consolidate and cite both the same way, and where a finding carries an ' +
9618
+ '`origin`, keep the session/step it names in the summary you write.');
9291
9619
  /**
9292
9620
  * The entity-id arguments `eyes_review_progress`/`eyes_review_end` share. All four are optional at
9293
9621
  * the schema level and required by `scope` at call time — the MCP tool schema is a flat field
@@ -9483,10 +9811,30 @@ const IS_EXPECTED_IS_BUG_SHAPE = {
9483
9811
  };
9484
9812
  const SOURCES_DESC = "Indexes into the flat, combined list of every child finding this level's own _progress call reported for this " +
9485
9813
  'node — each one numbered there via its own `index` field. Every child finding must be claimed by exactly one ' +
9486
- "entry's `sources` (no gaps, no overlap between entries), and at least one index is required here. This " +
9487
- "entry's isBug/isExpected must then be consistent with the child findings it names: isBug non-null iff any of " +
9488
- 'them has isBug non-null; isExpected non-null iff every one of them has isExpected non-null.';
9489
- const SourcesShape = zod.z.array(zod.z.number().int().nonnegative()).min(1).describe(SOURCES_DESC);
9814
+ 'entry (no gaps, no overlap between entries), counting `sourceClusters` too; between the two fields, at least ' +
9815
+ "one citation is required here. This entry's isBug/isExpected must then be consistent with the child findings " +
9816
+ 'it names: isBug non-null iff any of them has isBug non-null; isExpected non-null iff every one of them has ' +
9817
+ 'isExpected non-null.';
9818
+ const SourcesShape = zod.z.array(zod.z.number().int().nonnegative()).describe(SOURCES_DESC);
9819
+ const SOURCE_CLUSTERS_DESC = 'Ids from the `clusters` block that same _progress call reported — a shorthand for every index the named cluster ' +
9820
+ 'holds, so a large list can be claimed without transcribing it. Clusters were grouped by a mechanical key alone ' +
9821
+ '(where a finding came from, its isBug/isExpected pair, how a dynamic claim was justified, overlapping areas); ' +
9822
+ 'whether the findings in one share a cause is your judgment, so split a cluster across entries via plain ' +
9823
+ '`sources` whenever they do not. Mixing the two fields on one entry is fine.';
9824
+ const SourceClustersShape = zod.z.array(zod.z.string()).optional().describe(SOURCE_CLUSTERS_DESC);
9825
+ /** Every entry must claim something. Enforced here rather than by a `.min(1)` on `sources`, since either field alone is a complete citation. */
9826
+ function requireCitation(findings, ctx) {
9827
+ findings.forEach((finding, index) => {
9828
+ var _a, _b;
9829
+ if (finding.sources.length + ((_b = (_a = finding.sourceClusters) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0)
9830
+ return;
9831
+ ctx.addIssue({
9832
+ code: 'custom',
9833
+ message: 'each finding must cite at least one child finding, via sources indices or sourceClusters ids',
9834
+ path: [index, 'sources'],
9835
+ });
9836
+ });
9837
+ }
9490
9838
  const StepEndDynamicShape = makeDynamicShape("The mask actually applied for this changed area at diff-report time — matching that response's `regions`.");
9491
9839
  /**
9492
9840
  * One consolidated summary per changed area. Carries the same categorical fields as
@@ -9494,15 +9842,17 @@ const StepEndDynamicShape = makeDynamicShape("The mask actually applied for this
9494
9842
  * findings rather than trusting a restatement of it) — the step-level accept/reject decision in
9495
9843
  * `eyes_review_end` reads them directly instead of parsing `summary` prose.
9496
9844
  */
9497
- const StepEndFindingsShape = zod.z.array(zod.z.object({
9845
+ const StepEndFindingShape = zod.z.object({
9498
9846
  areaRect: AreaRectShape,
9499
9847
  summary: zod.z.string(),
9500
9848
  consistent: zod.z.boolean().describe('Whether every diff in this changed area is consistent with its surroundings'),
9501
9849
  dynamic: StepEndDynamicShape,
9502
9850
  ...IS_EXPECTED_IS_BUG_SHAPE,
9503
9851
  sources: SourcesShape,
9504
- }));
9505
- const SummaryExampleShape = zod.z.array(zod.z.object({
9852
+ sourceClusters: SourceClustersShape,
9853
+ });
9854
+ const StepEndFindingsShape = zod.z.array(StepEndFindingShape).superRefine(requireCitation);
9855
+ const SummaryExampleFindingShape = zod.z.object({
9506
9856
  summary: zod.z.string(),
9507
9857
  example: zod.z
9508
9858
  .string()
@@ -9511,7 +9861,9 @@ const SummaryExampleShape = zod.z.array(zod.z.object({
9511
9861
  "(stepIndex + 1) matching the dashboard's own URL convention."),
9512
9862
  ...IS_EXPECTED_IS_BUG_SHAPE,
9513
9863
  sources: SourcesShape,
9514
- }));
9864
+ sourceClusters: SourceClustersShape,
9865
+ });
9866
+ const SummaryExampleShape = zod.z.array(SummaryExampleFindingShape).superRefine(requireCitation);
9515
9867
  /**
9516
9868
  * `eyes_review_end`'s `findings`, which takes a different shape per `scope`. The handler
9517
9869
  * re-validates against the shape its own `scope` requires and says which one it wanted if they
@@ -9521,10 +9873,21 @@ const SummaryExampleShape = zod.z.array(zod.z.object({
9521
9873
  * reaches `commands.ts` is stripped to exactly one shape, as it was when each level had its own tool.
9522
9874
  */
9523
9875
  const ReviewEndFindingsShape = zod.z
9524
- .union([zod.z.array(StepEndFindingsShape.element.loose()), zod.z.array(SummaryExampleShape.element.loose())])
9876
+ .union([zod.z.array(StepEndFindingShape.loose()), zod.z.array(SummaryExampleFindingShape.loose())])
9525
9877
  .describe('Which shape this takes depends on scope: "step" takes one consolidated summary per changed area (areaRect, ' +
9526
9878
  'summary, consistent, dynamic, isExpected/isBug, sources); "batch"/"scenario"/"session" take one summary per ' +
9527
- "finding with its own example link (summary, example, isExpected/isBug, sources). See each field's own description.");
9879
+ "finding with its own example link (summary, example, isExpected/isBug, sources). See each field's own " +
9880
+ 'description. There is no cap on how many entries this array holds, and every entry for this scope must arrive ' +
9881
+ 'together in one call. If writing every entry out inline risks the response not finishing before its JSON ' +
9882
+ "closes, use this argument's other accepted form (a file path) instead of the inline array — see JsonFileArgShape's own description.");
9883
+ /** Lets a model-supplied array argument be handed off as a file path instead of inline JSON, for whichever caller finds the array too large to safely generate inline. */
9884
+ const JsonFileArgShape = zod.z
9885
+ .string()
9886
+ .describe('Absolute path to a UTF-8 JSON file whose entire contents are the same array this argument otherwise takes ' +
9887
+ 'inline — nothing but the JSON array itself. Use this instead of the inline array only when the array would be ' +
9888
+ 'large enough to risk the response not finishing before its JSON closes (e.g. many entries, or many that share ' +
9889
+ 'one repetitive cause such as one locale/theme change touching every changed area alike) — writing to a file has ' +
9890
+ 'no such limit. The tool reads and validates the file exactly as if its contents had been sent inline.');
9528
9891
 
9529
9892
  /**
9530
9893
  * Builds a batch or session URL from parsed components — the inverse of `api`'s
@@ -10288,7 +10651,6 @@ async function batchChildren(batchUrl, keys, rootScope, mode, deps) {
10288
10651
  }, scenarioName => ({
10289
10652
  key: scenarioChildKey(scenarioName),
10290
10653
  scopeId: scenarioScopeId(batchUrl, scenarioName),
10291
- nextCall: reviewProgressCall('scenario', { batchUrl, scenarioName }, rootScope, mode),
10292
10654
  }), deps);
10293
10655
  }
10294
10656
  /**
@@ -10326,17 +10688,16 @@ async function scenarioChildren(batchUrl, scenarioName, keys, rootScope, mode, d
10326
10688
  // sessionStepChildren, which would also try to mutate structural steps (needs write
10327
10689
  // access, and doesn't belong in a read-only discovery cascade). That mutation still runs,
10328
10690
  // idempotently, whenever this session is genuinely visited with write access.
10329
- const stepKeys = stepChildDescriptors(s.sessionUrl, session, rootScope, mode, structuralExcludedIndices(session, mode)).map(d => d.key);
10691
+ const stepKeys = stepChildDescriptors(s.sessionUrl, session, structuralExcludedIndices(session, mode)).map(d => d.key);
10330
10692
  queueChildKeys(sessionScopeId(s.sessionUrl), stepKeys, deps);
10331
10693
  }));
10332
10694
  return sessions.map(s => sessionChildKey(s.sessionUrl));
10333
10695
  }, sessionUrl => ({
10334
10696
  key: sessionChildKey(sessionUrl),
10335
10697
  scopeId: sessionScopeId(sessionUrl),
10336
- nextCall: reviewProgressCall('session', { sessionUrl }, rootScope, mode),
10337
10698
  }), deps);
10338
10699
  }
10339
- function stepChildDescriptors(sessionUrl, session, rootScope, mode, excluded) {
10700
+ function stepChildDescriptors(sessionUrl, session, excluded) {
10340
10701
  var _a;
10341
10702
  return ((_a = session.steps) !== null && _a !== void 0 ? _a : [])
10342
10703
  .map((step, stepIndex) => ({ step, stepIndex }))
@@ -10344,7 +10705,6 @@ function stepChildDescriptors(sessionUrl, session, rootScope, mode, excluded) {
10344
10705
  .map(({ stepIndex }) => ({
10345
10706
  key: stepChildKey(stepIndex),
10346
10707
  scopeId: stepScopeId(sessionUrl, stepIndex),
10347
- nextCall: reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode),
10348
10708
  }));
10349
10709
  }
10350
10710
  /**
@@ -10359,14 +10719,13 @@ function stepChildDescriptors(sessionUrl, session, rootScope, mode, excluded) {
10359
10719
  * fresh queue" would otherwise skip it entirely whenever the queue arrived pre-populated.
10360
10720
  */
10361
10721
  async function sessionStepChildren(params) {
10362
- const { sessionUrl, session, rootScope, mode, keys, deps } = params;
10722
+ const { sessionUrl, session, mode, keys, deps } = params;
10363
10723
  if (mode === 'resolve') {
10364
10724
  await preResolveStructuralSteps({ sessionUrl, session, keys, deps });
10365
10725
  }
10366
- return resolveScopedChildren(sessionScopeId(sessionUrl), async () => stepChildDescriptors(sessionUrl, session, rootScope, mode, structuralExcludedIndices(session, mode)).map(d => d.key), key => ({
10726
+ return resolveScopedChildren(sessionScopeId(sessionUrl), async () => stepChildDescriptors(sessionUrl, session, structuralExcludedIndices(session, mode)).map(d => d.key), key => ({
10367
10727
  key,
10368
10728
  scopeId: stepScopeId(sessionUrl, parseStepChildKey(key)),
10369
- nextCall: reviewProgressCall('step', { sessionUrl, stepIndex: parseStepChildKey(key) }, rootScope, mode),
10370
10729
  }), deps);
10371
10730
  }
10372
10731
  async function sessionChildren(params) {
@@ -10376,39 +10735,155 @@ async function sessionChildren(params) {
10376
10735
  function toRect(area) {
10377
10736
  return { left: area.left, top: area.top, width: area.width, height: area.height };
10378
10737
  }
10379
- async function stepChildren(sessionUrl, stepIndex, keys, rootScope, mode, deps) {
10738
+ async function stepChildren(sessionUrl, stepIndex, keys, deps) {
10380
10739
  return resolveScopedChildren(stepScopeId(sessionUrl, stepIndex), async () => {
10381
10740
  const { areas } = await fetchChangedAreas(sessionUrl, stepIndex, keys);
10382
10741
  return areas.map(area => diffChildKey(toRect(area)));
10383
- }, key => {
10384
- const rect = parseDiffChildKey(key);
10385
- return {
10386
- key,
10387
- scopeId: diffScopeId(sessionUrl, stepIndex, rect),
10388
- nextCall: nextCall(EYES_REVIEW_TOOLS.diffReport, { sessionUrl, stepIndex, areaRect: rect }, rootScope, mode),
10389
- };
10390
- }, deps);
10742
+ }, key => ({
10743
+ key,
10744
+ scopeId: diffScopeId(sessionUrl, stepIndex, parseDiffChildKey(key)),
10745
+ }), deps);
10746
+ }
10747
+ // Path compression — see the traversal gotcha in llm-docs/OVERVIEW.md.
10748
+ /** Only these two have no `verifyInvocation` gate and no mutating decision, so skipping one needs no synthetic invocation record. */
10749
+ const COMPRESSIBLE_LEVELS = new Set(['scenario', 'session']);
10750
+ /** Carries the full ancestry down (unlike `review-core`'s `childContextFor`), which the ascent needs to name a parent. */
10751
+ function childWalkNode(level, ctx, childKey, rootScope, mode) {
10752
+ switch (level) {
10753
+ case 'batch':
10754
+ return {
10755
+ level: 'scenario',
10756
+ scopeId: scenarioScopeId(ctx.batchUrl, childKey),
10757
+ ctx: { ...ctx, scenarioName: childKey },
10758
+ key: childKey,
10759
+ call: reviewProgressCall('scenario', { batchUrl: ctx.batchUrl, scenarioName: childKey }, rootScope, mode),
10760
+ };
10761
+ case 'scenario':
10762
+ return {
10763
+ level: 'session',
10764
+ scopeId: sessionScopeId(childKey),
10765
+ ctx: { ...ctx, sessionUrl: childKey },
10766
+ key: childKey,
10767
+ call: reviewProgressCall('session', { sessionUrl: childKey }, rootScope, mode),
10768
+ };
10769
+ case 'session': {
10770
+ const stepIndex = parseStepChildKey(childKey);
10771
+ return {
10772
+ level: 'step',
10773
+ scopeId: stepScopeId(ctx.sessionUrl, stepIndex),
10774
+ ctx: { ...ctx, stepIndex },
10775
+ key: childKey,
10776
+ call: reviewProgressCall('step', { sessionUrl: ctx.sessionUrl, stepIndex }, rootScope, mode),
10777
+ };
10778
+ }
10779
+ case 'step': {
10780
+ const areaRect = parseDiffChildKey(childKey);
10781
+ return {
10782
+ level: 'diff',
10783
+ scopeId: diffScopeId(ctx.sessionUrl, ctx.stepIndex, areaRect),
10784
+ ctx: { ...ctx, areaRect },
10785
+ key: childKey,
10786
+ call: nextCall(EYES_REVIEW_TOOLS.diffReport, { sessionUrl: ctx.sessionUrl, stepIndex: ctx.stepIndex, areaRect }, rootScope, mode),
10787
+ };
10788
+ }
10789
+ case 'diff':
10790
+ throw new Error('diff has no children'); // unreachable — no caller descends past the leaf
10791
+ }
10792
+ }
10793
+ function queuedChildNodes(node, rootScope, mode, deps) {
10794
+ return getQueuedChildKeys(node.scopeId, deps).map(key => childWalkNode(node.level, node.ctx, key, rootScope, mode));
10795
+ }
10796
+ /** The `recordScopeMode` write is load-bearing: `checkModeAgreesWithParent` reads an unrecorded mode as "nothing to disagree with", disarming the gate below. */
10797
+ function chainDown(child, rootScope, mode, deps) {
10798
+ let node = child;
10799
+ for (;;) {
10800
+ if (!COMPRESSIBLE_LEVELS.has(node.level))
10801
+ return node;
10802
+ const incomplete = queuedChildNodes(node, rootScope, mode, deps).filter(c => !isCompleted(c.scopeId, deps));
10803
+ if (incomplete.length !== 1)
10804
+ return node;
10805
+ recordScopeMode(node.scopeId, mode, deps);
10806
+ node = incomplete[0];
10807
+ }
10808
+ }
10809
+ function descentTarget(parentLevel, parentCtx, childKey, rootScope, mode, deps) {
10810
+ return chainDown(childWalkNode(parentLevel, parentCtx, childKey, rootScope, mode), rootScope, mode, deps);
10811
+ }
10812
+ /** Counts entries, not queued children: a step that was never queued still reports one (`preResolveStructuralSteps`), and would be compressed away. */
10813
+ function compressibleOnAscent(level, scopeId, deps) {
10814
+ if (!COMPRESSIBLE_LEVELS.has(level))
10815
+ return false;
10816
+ const entries = orderedChildFindingEntries(scopeId, deps);
10817
+ if (entries.length !== 1)
10818
+ return false;
10819
+ return level === 'scenario' || entries[0][1].length === 1;
10820
+ }
10821
+ /** An identity copy: `origin` accumulates rather than replaces, so a finding carried past both a session and a scenario still names the step it came from. */
10822
+ function forwardFindings(findings, origin) {
10823
+ return findings.map(finding => {
10824
+ const existing = finding.origin;
10825
+ return { ...finding, origin: { ...existing, ...origin } };
10826
+ });
10827
+ }
10828
+ function originContribution(level, childKey) {
10829
+ switch (level.level) {
10830
+ case 'session':
10831
+ return { sessionUrl: level.ctx.sessionUrl, stepIndex: parseStepChildKey(childKey) };
10832
+ case 'scenario':
10833
+ return { scenarioName: level.ctx.scenarioName, sessionUrl: childKey };
10834
+ default:
10835
+ throw new Error(`a ${level.level} is never compressed, so it never forwards findings`);
10836
+ }
10837
+ }
10838
+ /** Every write is keyed by child key and overwriting, so two siblings racing into the same ancestor is safe. */
10839
+ async function deriveClose(level, mode, deps) {
10840
+ const [childKey, childFindings] = orderedChildFindingEntries(level.scopeId, deps)[0];
10841
+ const { findings: forwarded, rollup } = consolidateRollup(level.scopeId, forwardFindings(childFindings, originContribution(level, childKey)), mode, deps);
10842
+ const parent = await level.up.parent();
10843
+ recordCompletion(level.scopeId, forwarded, deps);
10844
+ appendChildFinding(parent.scopeId, level.up.key, forwarded, deps);
10845
+ reportRollup(parent.scopeId, level.up.key, rollup, deps);
10846
+ recordScopeMode(level.scopeId, mode, deps);
10847
+ log(level.scopeId, 'derived-close', { input: { scopeId: level.scopeId } }, deps);
10848
+ return parent;
10849
+ }
10850
+ /** Stops at the first ancestor that consolidates — or sooner, at the first with an unreviewed branch, which it deep-links into rather than re-asking for its progress. */
10851
+ async function chainUp(parent, rootScope, mode, deps) {
10852
+ let level = parent;
10853
+ for (;;) {
10854
+ if (!level.up || !compressibleOnAscent(level.level, level.scopeId, deps))
10855
+ return { kind: 'end', level };
10856
+ const grandParent = await deriveClose(level, mode, deps);
10857
+ const unreviewed = queuedChildNodes(grandParent, rootScope, mode, deps).find(child => child.scopeId !== level.scopeId && !isCompleted(child.scopeId, deps));
10858
+ if (unreviewed) {
10859
+ const target = chainDown(unreviewed, rootScope, mode, deps);
10860
+ return { kind: 'call', call: target.call, level: target.level };
10861
+ }
10862
+ level = grandParent;
10863
+ }
10391
10864
  }
10392
10865
  async function runProgress(params) {
10393
- const { level, rootScope, mode, scopeId, children, endCall, parentProgressCall, buildFindings, deps } = params;
10866
+ const { level, rootScope, mode, scopeId, children, descend, endCall, parentProgressCall, buildFindings, deps } = params;
10394
10867
  const completed = computeCompleted(scopeId, children.map(c => c.scopeId), deps);
10395
- const incompleteChildCalls = children.filter(c => !isCompleted(c.scopeId, deps)).map(c => c.nextCall);
10396
- const next = buildProgressNext({ level, rootScope, completed, incompleteChildCalls, endCall, parentProgressCall });
10397
- const stillInvestigating = completed === null && incompleteChildCalls.length > 0;
10868
+ const nextChild = completed === null ? children.find(c => !isCompleted(c.scopeId, deps)) : undefined;
10869
+ const descentCall = nextChild && descend(nextChild);
10870
+ const next = buildProgressNext({ level, rootScope, completed, descentCall, endCall, parentProgressCall });
10871
+ const stillInvestigating = completed === null && descentCall !== undefined;
10398
10872
  // Each branch below builds its own complete literal, keys already in the order they must
10399
10873
  // serialize in — `next` last, however many of findings/resolution/regions precede it — rather
10400
10874
  // than mutating one object, so `next`'s position can never drift from a future edit here.
10401
10875
  if (stillInvestigating)
10402
10876
  return { completed, next };
10403
10877
  const findings = buildFindings();
10878
+ const clusters = sourceClustersFor(scopeId, deps);
10404
10879
  if (mode !== 'resolve')
10405
- return { completed, findings, next };
10880
+ return { completed, findings, clusters, next };
10406
10881
  const rollup = childRollupTotal(scopeId, deps);
10407
10882
  recordToolTelemetry({ resolve_decisions: rollup.resolution });
10408
- return { completed, findings, resolution: rollup.resolution, regions: rollup.regions, next };
10883
+ return { completed, findings, clusters, resolution: rollup.resolution, regions: rollup.regions, next };
10409
10884
  }
10410
10885
  async function runEnd(params) {
10411
- const { level, toolName, rootScope, scopeId, ownChildren, progressCall, pushUpTo, finalize, getSiblings, parentProgressCall, doneMessage, deps, } = params;
10886
+ const { level, toolName, rootScope, scopeId, ownChildren, progressCall, pushUpTo, finalize, getSiblings, descend, parentProgressCall, ascent, mode, doneMessage, deps, } = params;
10412
10887
  const stillIncomplete = ownChildren.some(c => !isCompleted(c.scopeId, deps));
10413
10888
  if (stillIncomplete) {
10414
10889
  const instruction = `Not every ${childLevelLabel(level)} of this ${level} was reviewed yet. This submission was discarded — call ${progressCall.tool} for this ${level} again to see what remains, then call this again once it reports being fully reviewed.`;
@@ -10429,10 +10904,30 @@ async function runEnd(params) {
10429
10904
  }
10430
10905
  const siblings = await getSiblings();
10431
10906
  const incompleteSibling = siblings.find(s => !isCompleted(s.scopeId, deps));
10907
+ // No incomplete sibling means the parent's `_progress` could only answer "call `_end`", which is already known here.
10908
+ let target;
10909
+ if (incompleteSibling) {
10910
+ if (descend)
10911
+ target = { kind: 'call', ...descend(incompleteSibling) };
10912
+ }
10913
+ else if (ascent && !hasReachedRootScope(level, rootScope)) {
10914
+ target = await chainUp(ascent(), rootScope, mode, deps);
10915
+ }
10432
10916
  const next = buildEndNext({
10433
10917
  level,
10434
10918
  rootScope,
10435
- siblingCall: incompleteSibling === null || incompleteSibling === void 0 ? void 0 : incompleteSibling.nextCall,
10919
+ siblingCall: (target === null || target === void 0 ? void 0 : target.kind) === 'call' ? { call: target.call, level: target.level } : undefined,
10920
+ parentClose: (target === null || target === void 0 ? void 0 : target.kind) === 'end'
10921
+ ? {
10922
+ level: target.level.level,
10923
+ endCall: target.level.endCall,
10924
+ nextLevel: {
10925
+ scope: target.level.scope,
10926
+ findings: target.level.findings(),
10927
+ clusters: target.level.clusters(),
10928
+ },
10929
+ }
10930
+ : undefined,
10436
10931
  parentProgressCall,
10437
10932
  doneMessage,
10438
10933
  });
@@ -10492,7 +10987,7 @@ function endResponse(result, mode, isRootScope) {
10492
10987
  function verifyAndConsolidate(scopeId, logScopeId, logInput, findings, mode, deps) {
10493
10988
  return async () => {
10494
10989
  const childFindings = flattenChildFindings(scopeId, deps);
10495
- await withGateLog(EYES_REVIEW_TOOLS.end, logScopeId, logInput, deps, () => verifySourcedFindings(findings, childFindings));
10990
+ await withGateLog(EYES_REVIEW_TOOLS.end, logScopeId, logInput, deps, () => verifySourcedFindings(expandSourceCitations(findings, sourceClustersFor(scopeId, deps)), childFindings));
10496
10991
  return consolidateRollup(scopeId, stripSources(findings), mode, deps);
10497
10992
  };
10498
10993
  }
@@ -10614,39 +11109,53 @@ async function verifySameAsEligibility(sessionUrl, stepIndex, areaRect, sameAs,
10614
11109
  `— only occurrences within the same scenario can be fast-tracked against each other.`);
10615
11110
  }
10616
11111
  }
11112
+ /** Whether the record is a diff the agent examined rather than a placeholder for a step that has none — tagged `unobtainable` by `stepProgress`, `status` by the tool handler. */
11113
+ function isExaminedDomDiff(args) {
11114
+ const record = args;
11115
+ return record.status === undefined && record.unobtainable === undefined;
11116
+ }
10617
11117
  async function verifyDiffReportHardGate(sessionUrl, stepIndex, areaRect, findings, sameAs, keys, deps) {
10618
11118
  var _a, _b;
10619
11119
  const stepScope = stepScopeId(sessionUrl, stepIndex);
10620
11120
  const rectMatches = (loggedRect) => loggedRect === undefined || rectsIntersect(loggedRect, areaRect);
11121
+ // Both the bundled call and the raw per-image calls are agent-initiated, so either satisfies the gate.
11122
+ const evidenceCovers = (label) => verifyInvocation(stepScope, EYES_INSPECT_TOOLS.evidence, args => { var _a; return rectMatches(args.areaRect) && ((_a = args.images) === null || _a === void 0 ? void 0 : _a.includes(label)) === true; }, deps);
10621
11123
  const session = await fetchSteps(sessionUrl, keys);
10622
11124
  const step = (_a = session.steps) === null || _a === void 0 ? void 0 : _a[stepIndex];
10623
11125
  if (!step)
10624
11126
  throw new Error(`Step index ${stepIndex} is out of range for this session.`);
10625
11127
  if (sameAs) {
10626
- if (!verifyInvocation(stepScope, EYES_INSPECT_TOOLS.domDiff, () => true, deps)) {
10627
- throw new Error('eyes_inspect_dom_diff has not been called for this step yet. A sameAs shortcut is only valid once ' +
11128
+ if (!verifyInvocation(stepScope, EYES_INSPECT_TOOLS.domDiff, isExaminedDomDiff, deps)) {
11129
+ throw new Error('No examined dom diff is on record for this step. A sameAs shortcut is only valid once ' +
10628
11130
  "you've actually examined this step's own dom diff and confirmed it shows the same structural " +
10629
- 'change — call eyes_inspect_dom_diff first.');
11131
+ 'change — call eyes_inspect_dom_diff first. A step that structurally has no dom diff cannot ' +
11132
+ 'use this shortcut at all: report it the full way, with its own image diff and both images.');
10630
11133
  }
10631
- if (step.checkpoint.id &&
10632
- !verifyInvocation(sessionScopeId(sessionUrl), EYES_INSPECT_TOOLS.image, args => args.imageId === step.checkpoint.id && rectMatches(args.rect), deps)) {
10633
- throw new Error(`eyes_inspect_image has not been called for this step's checkpoint image (padded to this areaRect) yet. ` +
10634
- `Even with sameAs, you must fetch and review the checkpoint image before calling eyes_review_diff_report.`);
11134
+ const checkpoint = plannedEvidence(step, areaRect).find(request => request.label === 'checkpoint');
11135
+ if (checkpoint &&
11136
+ !evidenceCovers('checkpoint') &&
11137
+ !verifyInvocation(sessionScopeId(sessionUrl), EYES_INSPECT_TOOLS.image, args => args.imageId === checkpoint.imageId && rectMatches(args.rect), deps)) {
11138
+ throw new Error(`This step's checkpoint image has not been fetched for this areaRect yet. Even with sameAs, you must ` +
11139
+ `fetch and review it before calling eyes_review_diff_report — call eyes_inspect_evidence with this areaRect in its areaRects.`);
10635
11140
  }
10636
11141
  await verifySameAsEligibility(sessionUrl, stepIndex, areaRect, sameAs, session.sessionName, keys, deps);
10637
11142
  return; // the per-finding gates below are not re-checked on this branch — see the reasoning above.
10638
11143
  }
10639
- if (!verifyInvocation(stepScope, EYES_INSPECT_TOOLS.imageDiff, args => rectMatches(args.rect), deps)) {
10640
- throw new Error(`eyes_inspect_image_diff has not been called for this areaRect yet. Fetch it (padded 10px on every side) before calling eyes_review_diff_report.`);
11144
+ // Exactly what `eyes_inspect_evidence` would gather and no more: demanding a side the bundle refuses to fetch would leave the step unclosable.
11145
+ const planned = plannedEvidence(step, areaRect);
11146
+ if (planned.length === 0) {
11147
+ // Otherwise the loop below would demand nothing and pass vacuously on an invented rect.
11148
+ throw new Error(`areaRect ${JSON.stringify(areaRect)} lies outside every image of this step, so there is no evidence to review it by. Report a changed area that eyes_inspect_changed_areas or eyes_review_progress actually named.`);
10641
11149
  }
10642
- for (const [side, imageId] of [
10643
- ['baseline', step.baseline.id],
10644
- ['checkpoint', step.checkpoint.id],
10645
- ]) {
10646
- if (!imageId)
10647
- continue; // a missing/new step legitimately has no image on one side
10648
- if (!verifyInvocation(sessionScopeId(sessionUrl), EYES_INSPECT_TOOLS.image, args => args.imageId === imageId && rectMatches(args.rect), deps)) {
10649
- throw new Error(`eyes_inspect_image has not been called for this step's ${side} image (padded to this areaRect) yet. Fetch it before calling eyes_review_diff_report.`);
11150
+ for (const request of planned) {
11151
+ if (evidenceCovers(request.label))
11152
+ continue;
11153
+ const fetchedRaw = request.label === 'diff'
11154
+ ? verifyInvocation(stepScope, EYES_INSPECT_TOOLS.imageDiff, args => rectMatches(args.rect), deps)
11155
+ : verifyInvocation(sessionScopeId(sessionUrl), EYES_INSPECT_TOOLS.image, args => args.imageId === request.imageId && rectMatches(args.rect), deps);
11156
+ if (!fetchedRaw) {
11157
+ const what = request.label === 'diff' ? 'The image diff' : `This step's ${request.label} image`;
11158
+ throw new Error(`${what} has not been fetched for this areaRect yet. Call eyes_inspect_evidence with this areaRect in its areaRects — batch every other unreviewed area of this step into the same call — before calling eyes_review_diff_report.`);
10650
11159
  }
10651
11160
  }
10652
11161
  for (const finding of findings) {
@@ -10725,6 +11234,82 @@ function finalDoneMessage(params) {
10725
11234
  // and calls exactly one of these per handler, after resolving `rootScope`/`mode`/`keys`, and
10726
11235
  // JSON-serializes whatever it returns.
10727
11236
  // ---------------------------------------------------------------------------
11237
+ /** Each level's indexed child findings — the block its `_end` validates `sources` against, read by its own `_progress` and by its last child's `_end`. */
11238
+ const findingsBlock = {
11239
+ batch: (scopeId, deps) => attachFindingIndices(orderedChildFindingEntries(scopeId, deps)).map(([scenarioName, findings]) => ({ scenarioName, findings })),
11240
+ scenario: (scopeId, deps) => attachFindingIndices(orderedChildFindingEntries(scopeId, deps)).map(([sessionUrl, findings]) => ({ sessionUrl, findings })),
11241
+ session: (scopeId, deps) => attachFindingIndices(orderedChildFindingEntries(scopeId, deps)).map(([stepKey, findings]) => ({
11242
+ stepIndex: parseStepChildKey(stepKey),
11243
+ findings,
11244
+ })),
11245
+ step: (scopeId, deps) => attachFindingIndices(orderedChildFindingEntries(scopeId, deps)).map(([rectKey, findings]) => ({
11246
+ areaRect: parseDiffChildKey(rectKey),
11247
+ findings,
11248
+ })),
11249
+ };
11250
+ /** Parent links are thunks so a walk that compresses nothing resolves nothing — at the step edge, naming the parent costs a fetch. */
11251
+ function batchAscent(batchUrl, rootScope, mode, deps) {
11252
+ const scopeId = batchScopeId(batchUrl);
11253
+ return {
11254
+ level: 'batch',
11255
+ scope: 'batch',
11256
+ scopeId,
11257
+ ctx: { batchUrl },
11258
+ endCall: reviewEndCall('batch', { batchUrl }, rootScope, mode),
11259
+ findings: () => findingsBlock.batch(scopeId, deps),
11260
+ clusters: () => sourceClustersFor(scopeId, deps),
11261
+ };
11262
+ }
11263
+ function scenarioAscent(batchUrl, scenarioName, rootScope, mode, deps) {
11264
+ const scopeId = scenarioScopeId(batchUrl, scenarioName);
11265
+ return {
11266
+ level: 'scenario',
11267
+ scope: 'scenario',
11268
+ scopeId,
11269
+ ctx: { batchUrl, scenarioName },
11270
+ endCall: reviewEndCall('scenario', { batchUrl, scenarioName }, rootScope, mode),
11271
+ findings: () => findingsBlock.scenario(scopeId, deps),
11272
+ clusters: () => sourceClustersFor(scopeId, deps),
11273
+ ...(hasReachedRootScope('scenario', rootScope)
11274
+ ? {}
11275
+ : {
11276
+ up: {
11277
+ key: scenarioChildKey(scenarioName),
11278
+ parent: async () => batchAscent(batchUrl, rootScope, mode, deps),
11279
+ },
11280
+ }),
11281
+ };
11282
+ }
11283
+ function sessionAscent(params) {
11284
+ const { sessionUrl, scenario, rootScope, mode, deps } = params;
11285
+ const scopeId = sessionScopeId(sessionUrl);
11286
+ return {
11287
+ level: 'session',
11288
+ scope: 'session',
11289
+ scopeId,
11290
+ ctx: { sessionUrl },
11291
+ endCall: reviewEndCall('session', { sessionUrl }, rootScope, mode),
11292
+ findings: () => findingsBlock.session(scopeId, deps),
11293
+ clusters: () => sourceClustersFor(scopeId, deps),
11294
+ ...(hasReachedRootScope('session', rootScope) ? {} : { up: { key: sessionChildKey(sessionUrl), parent: scenario } }),
11295
+ };
11296
+ }
11297
+ /** No `up` link on purpose: a step is never compressed, so the ascent stops here. */
11298
+ function stepAscent(sessionUrl, stepIndex, rootScope, mode, deps) {
11299
+ const scopeId = stepScopeId(sessionUrl, stepIndex);
11300
+ return {
11301
+ level: 'step',
11302
+ scope: 'step',
11303
+ scopeId,
11304
+ ctx: { sessionUrl, stepIndex },
11305
+ endCall: reviewEndCall('step', { sessionUrl, stepIndex }, rootScope, mode),
11306
+ findings: () => findingsBlock.step(scopeId, deps),
11307
+ clusters: () => sourceClustersFor(scopeId, deps),
11308
+ };
11309
+ }
11310
+ function sourceClustersFor(scopeId, deps) {
11311
+ return buildSourceClusters(orderedChildFindingEntries(scopeId, deps));
11312
+ }
10728
11313
  async function batchProgress(params) {
10729
11314
  const { batchUrl, keys, rootScope, mode, restart, deps } = params;
10730
11315
  const scopeId = batchScopeId(batchUrl);
@@ -10737,8 +11322,9 @@ async function batchProgress(params) {
10737
11322
  rootScope,
10738
11323
  mode,
10739
11324
  children,
11325
+ descend: child => descentTarget('batch', { batchUrl }, child.key, rootScope, mode, deps).call,
10740
11326
  endCall: reviewEndCall('batch', { batchUrl }, rootScope, mode),
10741
- buildFindings: () => attachFindingIndices(Object.entries(getChildFindings(scopeId, deps))).map(([scenarioName, findings]) => ({ scenarioName, findings })),
11327
+ buildFindings: () => findingsBlock.batch(scopeId, deps),
10742
11328
  deps,
10743
11329
  });
10744
11330
  }
@@ -10765,6 +11351,7 @@ async function batchEnd(params) {
10765
11351
  finalize: verifyAndConsolidate(scopeId, batchScopeId(batchUrl), { batchUrl, findings }, findings, mode, deps),
10766
11352
  progressCall: reviewProgressCall('batch', { batchUrl }, rootScope, mode),
10767
11353
  getSiblings: async () => [],
11354
+ mode,
10768
11355
  doneMessage,
10769
11356
  deps,
10770
11357
  });
@@ -10794,8 +11381,9 @@ async function scenarioProgress(params) {
10794
11381
  rootScope,
10795
11382
  mode,
10796
11383
  children,
11384
+ descend: child => descentTarget('scenario', { batchUrl, scenarioName }, child.key, rootScope, mode, deps).call,
10797
11385
  endCall: reviewEndCall('scenario', { batchUrl, scenarioName }, rootScope, mode),
10798
- buildFindings: () => attachFindingIndices(Object.entries(getChildFindings(scopeId, deps))).map(([sessionUrl, findings]) => ({ sessionUrl, findings })),
11386
+ buildFindings: () => findingsBlock.scenario(scopeId, deps),
10799
11387
  deps,
10800
11388
  });
10801
11389
  }
@@ -10837,7 +11425,10 @@ async function scenarioEnd(params) {
10837
11425
  ? undefined
10838
11426
  : { parentScopeId: batchScopeId(batchUrl), childKey: scenarioChildKey(scenarioName) },
10839
11427
  getSiblings: async () => (await batchChildren(batchUrl, keys, rootScope, mode, deps)).filter(s => s.scopeId !== scopeId),
11428
+ descend: sibling => descentTarget('batch', { batchUrl }, sibling.key, rootScope, mode, deps),
10840
11429
  parentProgressCall: reviewProgressCall('batch', { batchUrl }, rootScope, mode),
11430
+ ascent: () => batchAscent(batchUrl, rootScope, mode, deps),
11431
+ mode,
10841
11432
  doneMessage,
10842
11433
  deps,
10843
11434
  });
@@ -10895,15 +11486,16 @@ async function sessionProgress(params) {
10895
11486
  if (mismatch)
10896
11487
  return { completed: null, next: mismatch };
10897
11488
  await promoteAndRecordMode({ level: 'session', scopeId, ctx: { sessionUrl }, rootScope, mode, restart, keys, deps });
10898
- const children = await sessionStepChildren({ sessionUrl, session, rootScope, mode, keys, deps });
11489
+ const children = await sessionStepChildren({ sessionUrl, session, mode, keys, deps });
10899
11490
  return runProgress({
10900
11491
  level: 'session',
10901
11492
  scopeId,
10902
11493
  rootScope,
10903
11494
  mode,
10904
11495
  children,
11496
+ descend: child => descentTarget('session', { sessionUrl }, child.key, rootScope, mode, deps).call,
10905
11497
  endCall: reviewEndCall('session', { sessionUrl }, rootScope, mode),
10906
- buildFindings: () => attachFindingIndices(Object.entries(getChildFindings(scopeId, deps))).map(([stepKey, findings]) => ({ stepIndex: parseStepChildKey(stepKey), findings })),
11498
+ buildFindings: () => findingsBlock.session(scopeId, deps),
10907
11499
  deps,
10908
11500
  });
10909
11501
  }
@@ -10933,7 +11525,7 @@ async function sessionEnd(params) {
10933
11525
  if (mismatch)
10934
11526
  return { next: mismatch };
10935
11527
  await promoteAndRecordMode({ level: 'session', scopeId, ctx: { sessionUrl }, rootScope, mode, restart, keys, deps });
10936
- const children = await sessionStepChildren({ sessionUrl, session, rootScope, mode, keys, deps });
11528
+ const children = await sessionStepChildren({ sessionUrl, session, mode, keys, deps });
10937
11529
  const doneMessage = finalDoneMessage({
10938
11530
  level: 'This session',
10939
11531
  findingsCount: findings.length,
@@ -10956,12 +11548,26 @@ async function sessionEnd(params) {
10956
11548
  childKey: sessionChildKey(sessionUrl),
10957
11549
  },
10958
11550
  getSiblings: async () => (await scenarioChildren(batchUrl, session.sessionName, keys, rootScope, mode, deps)).filter(s => s.scopeId !== scopeId),
11551
+ descend: sibling => descentTarget('scenario', { batchUrl, scenarioName: session.sessionName }, sibling.key, rootScope, mode, deps),
10959
11552
  parentProgressCall: reviewProgressCall('scenario', { batchUrl, scenarioName: session.sessionName }, rootScope, mode),
11553
+ ascent: () => scenarioAscent(batchUrl, session.sessionName, rootScope, mode, deps),
11554
+ mode,
10960
11555
  doneMessage,
10961
11556
  deps,
10962
11557
  });
10963
11558
  return endResponse(result, mode, result.next.instruction === doneMessage);
10964
11559
  }
11560
+ const DOM_DIFF_OBTAINABLE_RECORD = 'stepProgress:domDiffObtainable';
11561
+ /** Why this step can never yield a DOM diff, decided from session data ahead of any call; `fetchVisibleDomDiff`'s third case, `no-dom-data`, is only knowable from the server. */
11562
+ function domDiffUnobtainableReason(step) {
11563
+ if (!step)
11564
+ return null;
11565
+ if (!step.baseline.domId)
11566
+ return 'it has no baseline DOM capture';
11567
+ if (!step.checkpoint.domId)
11568
+ return 'it has no checkpoint DOM capture';
11569
+ return null;
11570
+ }
10965
11571
  async function stepProgress(params) {
10966
11572
  var _a, _b;
10967
11573
  const { sessionUrl, stepIndex, keys, rootScope, mode, restart, deps } = params;
@@ -10980,27 +11586,92 @@ async function stepProgress(params) {
10980
11586
  keys,
10981
11587
  deps,
10982
11588
  });
10983
- const children = await stepChildren(sessionUrl, stepIndex, keys, rootScope, mode, deps);
11589
+ const children = await stepChildren(sessionUrl, stepIndex, keys, deps);
10984
11590
  const result = await runProgress({
10985
11591
  level: 'step',
10986
11592
  scopeId,
10987
11593
  rootScope,
10988
11594
  mode,
10989
11595
  children,
11596
+ descend: child => descentTarget('step', { sessionUrl, stepIndex }, child.key, rootScope, mode, deps).call,
10990
11597
  endCall: reviewEndCall('step', { sessionUrl, stepIndex }, rootScope, mode),
10991
- buildFindings: () => attachFindingIndices(Object.entries(getChildFindings(scopeId, deps))).map(([rectKey, findings]) => ({ areaRect: parseDiffChildKey(rectKey), findings })),
11598
+ buildFindings: () => findingsBlock.step(scopeId, deps),
10992
11599
  deps,
10993
11600
  });
10994
11601
  if (result.completed === null) {
10995
- result.next.instruction +=
10996
- ' Run eyes_inspect_dom_diff for this step first, regardless of how small or scattered the changed areas look — a visual crop comparison can miss small displacement that dom_diff catches directly.';
10997
- if (((_b = (_a = result.next.calls) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.tool) === EYES_REVIEW_TOOLS.diffReport) {
11602
+ let unobtainable = null;
11603
+ if (!verifyInvocation(scopeId, EYES_INSPECT_TOOLS.domDiff, isExaminedDomDiff, deps)) {
11604
+ const alreadyLogged = verifyInvocation(scopeId, EYES_INSPECT_TOOLS.domDiff, args => {
11605
+ const reason = args.unobtainable;
11606
+ if (typeof reason !== 'string')
11607
+ return false;
11608
+ unobtainable = reason;
11609
+ return true;
11610
+ }, deps);
11611
+ if (!alreadyLogged && !verifyInvocation(scopeId, DOM_DIFF_OBTAINABLE_RECORD, () => true, deps)) {
11612
+ unobtainable = domDiffUnobtainableReason((_a = (await fetchSteps(sessionUrl, keys)).steps) === null || _a === void 0 ? void 0 : _a[stepIndex]);
11613
+ if (unobtainable)
11614
+ logInvocation(scopeId, EYES_INSPECT_TOOLS.domDiff, { unobtainable }, deps);
11615
+ else
11616
+ logInvocation(scopeId, DOM_DIFF_OBTAINABLE_RECORD, {}, deps);
11617
+ }
11618
+ }
11619
+ if (unobtainable) {
11620
+ result.next.instruction += ` Do NOT call eyes_inspect_dom_diff for this step — ${unobtainable}, so no structural comparison is available. Review from the images alone, and record that the structural comparison was unavailable rather than that no structural change was found.`;
11621
+ }
11622
+ else {
11623
+ result.next.instruction +=
11624
+ ' Run eyes_inspect_dom_diff for this step first, regardless of how small or scattered the changed areas look — a visual crop comparison can miss small displacement that dom_diff catches directly.';
11625
+ }
11626
+ const calls = result.next.calls;
11627
+ if (((_b = calls === null || calls === void 0 ? void 0 : calls[0]) === null || _b === void 0 ? void 0 : _b.tool) === EYES_REVIEW_TOOLS.diffReport) {
11628
+ // Not a review tool, so it carries no rootScope/mode and is not built through `nextCall`.
11629
+ const unreviewed = incompleteAreaRects(children, deps);
11630
+ const evidence = evidenceRoundCall(sessionUrl, stepIndex, unreviewed);
11631
+ const batched = evidence.args.areaRects;
11632
+ calls.unshift(evidence);
11633
+ result.next.instruction += ` Call ${EYES_INSPECT_TOOLS.evidence} ONCE, with the ${batched.length} areaRects the first call in next.calls already carries — not once per area, and do NOT pad them yourself; it returns the image diff and both baseline/checkpoint images for every area together, already padded and cropped.`;
11634
+ if (unreviewed.length > batched.length) {
11635
+ 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.`;
11636
+ }
10998
11637
  result.next.instruction +=
10999
- " Pad this areaRect by 10px, fetch eyes_inspect_image_diff and both baseline/checkpoint eyes_inspect_image, and count the pink regions. If more than one, report each individually via eyes_review_diff_report with its own smaller rect, then always finish with one eyes_review_diff_report call on the changed area's own full areaRect — that's what marks it reviewed. Shortcut: if eyes_inspect_dom_diff already shows this exact structural change was recorded earlier in this scenario (another step of this session, or a sibling session in another browser/environment/viewport), skip the image_diff/baseline-image step — call eyes_review_diff_report with sameAs: {sessionUrl, stepIndex, areaRect} pointing at that prior call, fetch only this step's checkpoint image, and report from that.";
11638
+ " Then take the areas one at a time: count the pink regions in that area's image diff. If more than one, report each individually via eyes_review_diff_report with its own smaller rect, then always finish with one eyes_review_diff_report call on the changed area's own full areaRect — that's what marks it reviewed.";
11639
+ // sameAs buys its way past the image gates with an examined dom diff, so a step with none can't use it.
11640
+ if (!unobtainable) {
11641
+ result.next.instruction +=
11642
+ " Shortcut: if eyes_inspect_dom_diff already shows this exact structural change was recorded earlier in this scenario (another step of this session, or a sibling session in another browser/environment/viewport), call eyes_review_diff_report with sameAs: {sessionUrl, stepIndex, areaRect} pointing at that prior call and report from this step's own evidence without re-analysing the whole change.";
11643
+ }
11000
11644
  }
11001
11645
  }
11002
11646
  return result;
11003
11647
  }
11648
+ /** The changed areas of a step still unreviewed. */
11649
+ function incompleteAreaRects(children, deps) {
11650
+ return children.filter(child => !isCompleted(child.scopeId, deps)).map(child => parseDiffChildKey(child.key));
11651
+ }
11652
+ /** One evidence round: as many unreviewed areas as a single call can inline. A step with more is reviewed a round at a time, so no area is ever judged from paths alone. */
11653
+ function evidenceRoundCall(sessionUrl, stepIndex, unreviewed) {
11654
+ return {
11655
+ tool: EYES_INSPECT_TOOLS.evidence,
11656
+ args: { sessionUrl, stepIndex, areaRects: unreviewed.slice(0, MAX_EVIDENCE_BATCH) },
11657
+ };
11658
+ }
11659
+ function hasEvidence(sessionUrl, stepIndex, areaRect, deps) {
11660
+ return verifyInvocation(stepScopeId(sessionUrl, stepIndex), EYES_INSPECT_TOOLS.evidence, args => rectsIntersect(args.areaRect, areaRect), deps);
11661
+ }
11662
+ /** Opens the next round when the walk reaches an area the last round did not cover — without it the area's gate would reject and the step would stall. */
11663
+ async function prependEvidenceRound(next, params) {
11664
+ var _a;
11665
+ const { sessionUrl, stepIndex, keys, deps } = params;
11666
+ const target = (_a = next.calls) === null || _a === void 0 ? void 0 : _a[0];
11667
+ if ((target === null || target === void 0 ? void 0 : target.tool) !== EYES_REVIEW_TOOLS.diffReport)
11668
+ return;
11669
+ if (hasEvidence(sessionUrl, stepIndex, target.args.areaRect, deps))
11670
+ return;
11671
+ const unreviewed = incompleteAreaRects(await stepChildren(sessionUrl, stepIndex, keys, deps), deps);
11672
+ next.calls.unshift(evidenceRoundCall(sessionUrl, stepIndex, unreviewed));
11673
+ next.instruction += ` The areas left need their own evidence: call ${EYES_INSPECT_TOOLS.evidence} ONCE with the areaRects the first call in next.calls already carries.`;
11674
+ }
11004
11675
  async function stepEnd(params) {
11005
11676
  const { sessionUrl, stepIndex, findings, keys, rootScope, mode, restart, deps } = params;
11006
11677
  const scopeId = stepScopeId(sessionUrl, stepIndex);
@@ -11023,7 +11694,7 @@ async function stepEnd(params) {
11023
11694
  throw new Error('eyes_inspect_dom_diff has not been called for this session+step yet. Call it before eyes_review_end for this step — it may reveal the diff is caused by element displacement rather than independent content changes.');
11024
11695
  }
11025
11696
  });
11026
- const children = await stepChildren(sessionUrl, stepIndex, keys, rootScope, mode, deps);
11697
+ const children = await stepChildren(sessionUrl, stepIndex, keys, deps);
11027
11698
  // Whatever this call decides is captured here so the response can state the outcome plainly
11028
11699
  // — `finalize` only runs when the call genuinely persists, so on the discarded path these
11029
11700
  // stay untouched and nothing is resolved.
@@ -11044,7 +11715,7 @@ async function stepEnd(params) {
11044
11715
  ownChildren: children,
11045
11716
  finalize: async () => {
11046
11717
  const childFindings = flattenChildFindings(scopeId, deps);
11047
- await withGateLog(EYES_REVIEW_TOOLS.end, sessionScopeId(sessionUrl), { sessionUrl, stepIndex, findings, rootScope, mode }, deps, () => verifySourcedFindings(findings, childFindings));
11718
+ await withGateLog(EYES_REVIEW_TOOLS.end, sessionScopeId(sessionUrl), { sessionUrl, stepIndex, findings, rootScope, mode }, deps, () => verifySourcedFindings(expandSourceCitations(findings, sourceClustersFor(scopeId, deps)), childFindings));
11048
11719
  const cleanFindings = stripSources(findings);
11049
11720
  // Computed here rather than asked of the model (unlike the session/scenario/batch
11050
11721
  // levels' model-supplied `example`): sessionUrl/stepIndex are this call's own args and
@@ -11081,8 +11752,21 @@ async function stepEnd(params) {
11081
11752
  pushUpTo: hasReachedRootScope('step', rootScope)
11082
11753
  ? undefined
11083
11754
  : { parentScopeId: sessionScopeId(sessionUrl), childKey: stepChildKey(stepIndex) },
11084
- getSiblings: async () => (await sessionChildren({ sessionUrl, keys, rootScope, mode, deps })).filter(s => s.scopeId !== scopeId),
11755
+ getSiblings: async () => (await sessionChildren({ sessionUrl, keys, mode, deps })).filter(s => s.scopeId !== scopeId),
11756
+ descend: sibling => descentTarget('session', { sessionUrl }, sibling.key, rootScope, mode, deps),
11085
11757
  parentProgressCall: reviewProgressCall('session', { sessionUrl }, rootScope, mode),
11758
+ ascent: () => sessionAscent({
11759
+ sessionUrl,
11760
+ rootScope,
11761
+ mode,
11762
+ deps,
11763
+ scenario: async () => {
11764
+ const { sessionName } = await fetchSteps(sessionUrl, keys);
11765
+ const { baseUrl, batchId, accountId } = await parseSessionUrlVerified(sessionUrl, keys);
11766
+ return scenarioAscent(buildBatchUrl({ baseUrl, batchId, accountId }), sessionName, rootScope, mode, deps);
11767
+ },
11768
+ }),
11769
+ mode,
11086
11770
  doneMessage,
11087
11771
  deps,
11088
11772
  });
@@ -11151,11 +11835,15 @@ async function diffReport(params) {
11151
11835
  pushUpTo: hasReachedRootScope('diff', rootScope)
11152
11836
  ? undefined
11153
11837
  : { parentScopeId: stepScopeId(sessionUrl, stepIndex), childKey: diffChildKey(areaRect) },
11154
- getSiblings: async () => (await stepChildren(sessionUrl, stepIndex, keys, rootScope, mode, deps)).filter(s => s.scopeId !== scopeId),
11838
+ getSiblings: async () => (await stepChildren(sessionUrl, stepIndex, keys, deps)).filter(s => s.scopeId !== scopeId),
11839
+ descend: sibling => descentTarget('step', { sessionUrl, stepIndex }, sibling.key, rootScope, mode, deps),
11155
11840
  parentProgressCall: reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode),
11841
+ ascent: () => stepAscent(sessionUrl, stepIndex, rootScope, mode, deps),
11842
+ mode,
11156
11843
  doneMessage: 'This changed area is recorded.',
11157
11844
  deps,
11158
11845
  });
11846
+ await prependEvidenceRound(result.next, { sessionUrl, stepIndex, keys, deps });
11159
11847
  return { findings: result.findings, next: result.next };
11160
11848
  }
11161
11849
 
@@ -11227,6 +11915,24 @@ function findingsFor(shape, findings, scope) {
11227
11915
  }
11228
11916
  return parsed.data;
11229
11917
  }
11918
+ /** Resolves a JsonFileArgShape-eligible argument: reads and parses it if the model sent a file path instead of the array inline. */
11919
+ async function resolveJsonArg(raw, argName) {
11920
+ if (typeof raw !== 'string')
11921
+ return raw;
11922
+ let contents;
11923
+ try {
11924
+ contents = await promises.readFile(raw, 'utf-8');
11925
+ }
11926
+ catch (err) {
11927
+ throw new Error(`${argName} named a file path ("${raw}") that could not be read: ${err.message}`);
11928
+ }
11929
+ try {
11930
+ return JSON.parse(contents);
11931
+ }
11932
+ catch (err) {
11933
+ throw new Error(`${argName}'s file ("${raw}") is not valid JSON: ${err.message}`);
11934
+ }
11935
+ }
11230
11936
  function recordReviewCall(scopeType, mode) {
11231
11937
  recordToolTelemetry({ chain_source: 'review', scope_type: scopeType, mode });
11232
11938
  }
@@ -11285,15 +11991,16 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
11285
11991
  inputSchema: {
11286
11992
  scope: EndScopeShape,
11287
11993
  ...REVIEW_SCOPE_ID_SHAPES,
11288
- findings: ReviewEndFindingsShape,
11994
+ findings: zod.z.union([ReviewEndFindingsShape, JsonFileArgShape]),
11289
11995
  rootScope: RootScopeShape,
11290
11996
  mode: ModeShape,
11291
11997
  restart: RestartShape,
11292
11998
  },
11293
- }, async ({ scope, batchUrl, scenarioName, sessionUrl, stepIndex, findings: rawFindings, rootScope: rawRootScope, mode: rawMode, restart, }) => {
11999
+ }, async ({ scope, batchUrl, scenarioName, sessionUrl, stepIndex, findings: rawFindingsArg, rootScope: rawRootScope, mode: rawMode, restart, }) => {
11294
12000
  const rootScope = resolveRootScope(scope, rawRootScope);
11295
12001
  const mode = resolveMode(rawMode);
11296
12002
  recordReviewCall(scope, mode);
12003
+ const rawFindings = await resolveJsonArg(rawFindingsArg, 'findings');
11297
12004
  const summaryFindings = () => findingsFor(SummaryExampleShape, rawFindings, scope);
11298
12005
  const result = await (async () => {
11299
12006
  switch (scope) {
@@ -11380,7 +12087,11 @@ const EXPERIMENTAL_TOOL_SWAP = {
11380
12087
  // Hidden IN experimental mode: the legacy results tools the families replace. Runtime-hidden
11381
12088
  // rather than deleted (see `.team-lead/plan-remove-legacy-results-tools.md` for the eventual
11382
12089
  // removal) so the default server keeps its published tool set untouched.
11383
- replacedByExperimental: [TOOL_NAMES.EYES_GET_BATCH_URL, TOOL_NAMES.EYES_ANALYZE_BATCH],
12090
+ replacedByExperimental: [
12091
+ TOOL_NAMES.EYES_GET_BATCH_URL,
12092
+ TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS,
12093
+ TOOL_NAMES.EYES_ANALYZE_BATCH,
12094
+ ],
11384
12095
  };
11385
12096
  function skippedToolNames(experimental) {
11386
12097
  return new Set(experimental ? EXPERIMENTAL_TOOL_SWAP.replacedByExperimental : EXPERIMENTAL_TOOL_SWAP.experimentalOnly);