browser-assistant 2.9.8 → 2.9.10

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.
@@ -160,26 +160,87 @@
160
160
  const numberedPrompt = /^(\d+)[.)]\s+.{3,1000}\?$/;
161
161
  const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
162
162
  .map(match => Number(match[1]));
163
+ const readingText = (node, separateInline = false) => {
164
+ const copy = node.cloneNode(true);
165
+ copy.querySelectorAll('script,style,template,[hidden],[aria-hidden="true"]').forEach(child => child.remove());
166
+ copy.querySelectorAll(separateInline ? 'br,p,div,li,span,strong,b,em' : 'br,p,div,li').forEach(child => {
167
+ child.before('\n');
168
+ child.after('\n');
169
+ });
170
+ return (copy.textContent || '').trim();
171
+ };
172
+ const phraseKeywords = (context) => {
173
+ const keywords = new Map();
174
+ // Preserve rendered lines when available. Some portals join
175
+ // the end of one item directly to the next item number.
176
+ const items = [...context.matchAll(/(?:^|[^\w])([1-9]\d*)\s*[.)]\s*(?=[A-Za-z])/g)];
177
+ for (const [index, item] of items.entries()) {
178
+ const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
179
+ const standalone = [...pair.matchAll(/^\s*([A-Z]{2,})\s*$/gm)].map(match => match[1]);
180
+ const candidates = standalone.length ? standalone : pair.match(/\b[A-Z]{2,}\b/g) || [];
181
+ if ((pair.match(/_{2,}/g) || []).length !== 1 || candidates.length !== 1
182
+ || keywords.has(Number(item[1])))
183
+ return null;
184
+ keywords.set(Number(item[1]), candidates[0]);
185
+ }
186
+ return keywords;
187
+ };
163
188
  const pageText = doc.body.innerText || doc.body.textContent || '';
164
189
  const readingRange = /questions\s+(\d+)\s*[-–—]\s*(\d+)/i.exec(pageText);
165
- const phraseSet = /which phrase best completes/i.test(pageText) && /between two and five words/i.test(pageText);
190
+ const phraseSet = /which\s+phrase\s+best\s+completes/i.test(pageText)
191
+ && /(?:two\s+and\s+five|2\s*(?:and|to|[-–—])\s*5)\s+words/i.test(pageText);
166
192
  const gapSet = blankNumbers(pageText).length >= 2 && /which (?:word|sentence) (?:best )?fits/i.test(pageText);
167
193
  if (gapSet || phraseSet || readingRange) {
168
- const promptPattern = gapSet ? blankPrompt : phraseSet ? phrasePrompt : numberedPrompt;
169
- const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,legend,[role="heading"]')]
194
+ const promptPattern = phraseSet ? phrasePrompt : gapSet ? blankPrompt : numberedPrompt;
195
+ const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
170
196
  .filter(node => visible(node) && !node.closest('#assistant-root,nav,aside'));
171
197
  const headings = blocks.filter(node => promptPattern.test((node.textContent || '').trim())
172
- && ![...node.children].some(child => promptPattern.test((child.textContent || '').trim())));
173
- let passage = gapSet && blocks.find(node => {
198
+ && ![...node.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
199
+ .some(child => promptPattern.test((child.textContent || '').trim())));
200
+ const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
201
+ let phraseContext;
202
+ let phrases;
203
+ let passage = !phraseSet && gapSet && blocks.find(node => {
174
204
  const text = node.textContent || '';
175
205
  return text.length <= 12000 && blankNumbers(text).length >= 2
176
206
  && !/which (?:word|sentence) (?:best )?fits/i.test(text) && !node.querySelector(radioSelector)
177
207
  && ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
178
208
  });
179
- if (!gapSet && headings.length) {
209
+ if (phraseSet && headings.length >= 2) {
210
+ // Some layouts place directions and the numbered source
211
+ // text in different wrappers. Find the source by its gaps,
212
+ // independent of where the directions are rendered.
213
+ const sources = blocks.filter(node => {
214
+ const raw = node.textContent || '';
215
+ return raw.length <= 12000 && (raw.match(/_{2,}/g) || []).length >= 2
216
+ && !node.querySelector(`${radioSelector},${readingFieldSelector}`);
217
+ });
218
+ const gapCount = node => (node.textContent.match(/_{2,}/g) || []).length;
219
+ const total = Math.max(0, ...sources.map(gapCount));
220
+ if (total !== headings.length)
221
+ return null;
222
+ for (const source of sources.reverse()) {
223
+ if (gapCount(source) !== total)
224
+ continue;
225
+ for (const context of [source.innerText?.trim(), readingText(source), readingText(source, true)]) {
226
+ if (!context)
227
+ continue;
228
+ const found = phraseKeywords(context);
229
+ if (found?.size !== total || !headingNumbers.every(number => found.has(number)))
230
+ continue;
231
+ passage = source;
232
+ phraseContext = context;
233
+ phrases = found;
234
+ break;
235
+ }
236
+ if (passage)
237
+ break;
238
+ }
239
+ }
240
+ else if (!gapSet && !phraseSet && headings.length) {
180
241
  // The passage occupies a separate column preceding the
181
242
  // shared answer column. Never use the timer or palette.
182
- const instruction = phraseSet ? /complete the second sentence/i : /read the (?:text|comments|passage)/i;
243
+ const instruction = /read the (?:text|comments|passage)/i;
183
244
  for (let column = headings[0].parentElement; column && column !== doc.body && !passage; column = column.parentElement) {
184
245
  if (!headings.every(heading => column.contains(heading)))
185
246
  continue;
@@ -194,23 +255,9 @@
194
255
  }
195
256
  }
196
257
  if (passage && headings.length) {
197
- const copy = passage.cloneNode(true);
198
- copy.querySelectorAll('br,p,div,li').forEach(node => { node.before('\n'); node.after('\n'); });
199
- const context = (copy.textContent || '').trim();
200
- const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
201
- const phrases = new Map();
202
- if (phraseSet) {
203
- const items = [...context.matchAll(/(?:^|\s)(\d+)\s*[.)]\s+/g)];
204
- for (const [index, item] of items.entries()) {
205
- const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
206
- const keywords = pair.match(/\b[A-Z]{2,}\b/g) || [];
207
- if (!/_{2,}/.test(pair) || keywords.length !== 1 || phrases.has(Number(item[1])))
208
- return null;
209
- phrases.set(Number(item[1]), keywords[0]);
210
- }
211
- }
258
+ const context = phraseContext || readingText(passage);
212
259
  const count = readingRange ? Number(readingRange[2]) - Number(readingRange[1]) + 1 : 0;
213
- const numbers = (gapSet ? blankNumbers(context) : phraseSet ? [...phrases.keys()]
260
+ const numbers = (phraseSet ? [...phrases.keys()] : gapSet ? blankNumbers(context)
214
261
  : count >= 2 && count <= 30 ? Array.from({ length: count }, (_, index) => Number(readingRange[1]) + index) : [])
215
262
  .sort((a, b) => a - b);
216
263
  // A partially rendered or unrecognized reading set must
@@ -248,7 +295,7 @@
248
295
  const next = headings[position + 1] || submit;
249
296
  const group = fields.filter(node => follows(heading, node) && follows(node, next));
250
297
  return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
251
- requiredWord: phrases.get(headingNumbers[position]), container: scope };
298
+ requiredWord: phrases?.get(headingNumbers[position]), container: scope };
252
299
  });
253
300
  if (questions.some(question => !question.input) || fields.length !== questions.length)
254
301
  return null;
@@ -334,6 +381,18 @@
334
381
  groups.get(key).push(control);
335
382
  }
336
383
  const radioCandidates = [];
384
+ const choiceSelector = 'input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]';
385
+ const codeSelector = 'pre,code,.ace_editor,.CodeMirror,.monaco-editor';
386
+ const promptSelector = '#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]';
387
+ const readable = node => visible(node) && !node.closest('[hidden],[aria-hidden="true"],[inert],#assistant-root')
388
+ && doc.defaultView?.getComputedStyle?.(node)?.visibility !== 'hidden';
389
+ const proseText = node => {
390
+ if (!readable(node) || node.matches(codeSelector))
391
+ return '';
392
+ const clone = node.cloneNode(true);
393
+ clone.querySelectorAll(`${codeSelector},[hidden],[aria-hidden="true"],[inert]`).forEach(child => child.remove());
394
+ return textOf(clone);
395
+ };
337
396
  for (const group of groups.values()) {
338
397
  if (group.length < 2)
339
398
  continue;
@@ -362,27 +421,23 @@
362
421
  const fieldset = container.closest('fieldset') || group[0].closest('fieldset');
363
422
  const radioGroup = group[0].closest('[role="radiogroup"]');
364
423
  const optionScope = fieldset || radioGroup || group[0].parentElement?.parentElement || container;
365
- const heading = fieldset?.querySelector('legend')
366
- || radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]')
367
- || container.querySelector?.('h1,h2,h3,h4,[role="heading"]');
424
+ const heading = [fieldset?.querySelector('legend'), radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]'),
425
+ container.querySelector?.('h1,h2,h3,h4,[role="heading"]')].find(node => node && readable(node));
368
426
  const localPrompt = [...optionScope.querySelectorAll('p,h1,h2,h3,h4,[role="heading"],div,span')]
369
- .find(node => !node.querySelector('input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]')
427
+ .find(node => readable(node) && !node.matches(choiceSelector) && !node.querySelector(choiceSelector)
428
+ && !options.some(option => option.node.contains(node))
370
429
  && textOf(node).length >= 12 && textOf(node).length <= 1200);
371
430
  let nearbyPrompt = '';
372
- let branch = optionScope;
373
- for (let ancestor = optionScope; ancestor && ancestor !== doc.body && !nearbyPrompt; ancestor = ancestor.parentElement) {
431
+ for (let branch = optionScope; branch && branch !== doc.body && !nearbyPrompt; branch = branch.parentElement) {
374
432
  for (let sibling = branch.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
375
- const prose = sibling.cloneNode(true);
376
- prose.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor').forEach(node => node.remove());
377
- const candidate = sibling.matches('pre,code,.ace_editor,.CodeMirror,.monaco-editor') ? '' : textOf(prose);
378
- if (candidate.length >= 20 && candidate.length <= 1200 && !sibling.querySelector('input[type="radio"],[role="radio"]')) {
433
+ const candidate = proseText(sibling);
434
+ if (candidate.length >= 20 && candidate.length <= 1200
435
+ && !sibling.matches(choiceSelector) && !sibling.querySelector(choiceSelector)
436
+ && !options.some(option => option.node === sibling || option.node.contains(sibling))) {
379
437
  nearbyPrompt = candidate;
380
438
  break;
381
439
  }
382
440
  }
383
- branch = ancestor;
384
- if (ancestor === doc.body)
385
- break;
386
441
  }
387
442
  const text = textOf(heading) || textOf(localPrompt) || labelledText(radioGroup) || labelledText(container)
388
443
  || radioGroup?.getAttribute('aria-label') || container.getAttribute('aria-label') || nearbyPrompt;
@@ -390,12 +445,18 @@
390
445
  continue;
391
446
  // Coding MCQs often render the code separately from the prose
392
447
  // question. Preserve that visible context before asking the AI.
393
- const questionRegion = optionScope.closest('[data-question],article,section,main') || optionScope.parentElement;
394
- const promptRegion = questionRegion?.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]')
395
- || doc.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id');
448
+ const questionRegion = optionScope.closest('[data-question],#generic-question-container,#exam-question-container,article,section,main')
449
+ || optionScope.parentElement;
450
+ const promptRegion = [...(questionRegion?.querySelectorAll(promptSelector) || [])].find(node => {
451
+ if (node.querySelector(choiceSelector))
452
+ return false;
453
+ const prose = proseText(node);
454
+ return prose.length >= 12 && (prose.includes(text.trim()) || text.includes(prose));
455
+ });
396
456
  const sourceRegion = promptRegion || questionRegion;
397
- const snippets = [...(sourceRegion?.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor') || [])]
398
- .filter(node => visible(node) && !node.parentElement?.closest('pre,code,.ace_editor,.CodeMirror,.monaco-editor'));
457
+ const snippets = [...(sourceRegion?.querySelectorAll(codeSelector) || [])]
458
+ .filter(node => readable(node) && !node.parentElement?.closest(codeSelector)
459
+ && (!node.closest(promptSelector) || node.closest(promptSelector) === promptRegion));
399
460
  const codeText = node => {
400
461
  const lines = [...node.querySelectorAll('.ace_line,.view-line,.CodeMirror-line')];
401
462
  if (lines.length)
@@ -405,7 +466,7 @@
405
466
  return (clone.textContent || '').trim();
406
467
  };
407
468
  let questionText;
408
- if (promptRegion && !promptRegion.querySelector('input[type="radio"],[role="radio"]')) {
469
+ if (promptRegion) {
409
470
  // Preserve filenames, prose and ALL snippets together; the
410
471
  // last code block alone is not the question's full context.
411
472
  const clone = promptRegion.cloneNode(true);
@@ -531,6 +531,11 @@ function mountJournalCountdown(signal) {
531
531
  if (!answer)
532
532
  return [];
533
533
  const normalize = value => value.trim().replace(/\r\n/g, '\n').replace(/(\d) +%/g, '$1%');
534
+ const complexityKey = (value) => {
535
+ const expression = value.trim().replace(/^\x60([^\x60\r\n]+)\x60$/, '$1').trim();
536
+ return /^O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)$/.test(expression)
537
+ ? expression.replace(/[ \t]+/g, ' ').replace(/ *([()+*/^.-]) */g, '$1') : '';
538
+ };
534
539
  const matrixSyntax = /\\begin\{(?:[bpBvV]?matrix|smallmatrix)\}/;
535
540
  const matrixQuestion = matrixSyntax.test(question.text ?? '') || question.options.some(option => matrixSyntax.test(option.text));
536
541
  const matrixKey = (value) => {
@@ -547,6 +552,9 @@ function mountJournalCountdown(signal) {
547
552
  const matchesOption = (option, candidate) => {
548
553
  if (normalize(option) === normalize(candidate))
549
554
  return true;
555
+ const complexity = complexityKey(option);
556
+ if (complexity && complexity === complexityKey(candidate))
557
+ return true;
550
558
  const matrix = matrixQuestion && matrixKey(option);
551
559
  return Boolean(matrix && matrix === matrixKey(candidate));
552
560
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.8",
4
+ "version": "2.9.10",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.8",
3
+ "version": "2.9.10",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
package/server/main.py CHANGED
@@ -28,7 +28,8 @@ from local_security import install_local_guards, redact, sanitize_data
28
28
  from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
29
29
  cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
30
30
  answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
31
- reading_response_constraints, VisionRateLimitError, VisionUnconfirmedError)
31
+ ordering_question, solve_sorted_list_merge_order, reading_response_constraints,
32
+ VisionRateLimitError, VisionUnconfirmedError)
32
33
 
33
34
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
34
35
  logger = logging.getLogger("browser-assistant")
@@ -191,7 +192,7 @@ async def lifespan(_app: FastAPI):
191
192
  client.close()
192
193
 
193
194
 
194
- app = FastAPI(title="Browser Assistant API", version="2.9.8", lifespan=lifespan)
195
+ app = FastAPI(title="Browser Assistant API", version="2.9.10", lifespan=lifespan)
195
196
  install_local_guards(app)
196
197
 
197
198
  @app.exception_handler(HTTPException)
@@ -1278,8 +1279,15 @@ async def solve_questions(content: PageContent):
1278
1279
  except ValueError as exc:
1279
1280
  raise HTTPException(status_code=422, detail=str(exc)) from exc
1280
1281
  system_prompt = build_system_prompt(content.practice_type, language)
1282
+ ordering = ordering_question(trimmed_text)
1281
1283
  reading_constraints = reading_response_constraints(trimmed_text) if content.require_answer_agreement else None
1282
- if reading_constraints:
1284
+ if ordering:
1285
+ system_prompt = (
1286
+ 'Arrange all steps in the order required by the problem. Check prerequisites and use each displayed '
1287
+ 'step number once. Return exactly one JSON array item with type "mcq", the question, a brief '
1288
+ 'reasoning string, and an answer array of the original step numbers in their new order.'
1289
+ )
1290
+ elif reading_constraints:
1283
1291
  _, _, keyword = reading_constraints
1284
1292
  rule = (f'Use two to five words including the unchanged word {keyword}. Preserve the meaning of the original sentence. '
1285
1293
  if keyword else 'Use exactly one word. ')
@@ -1317,6 +1325,11 @@ REPAIR MODE:
1317
1325
  )
1318
1326
  strict_code_review = require_code and (content.review_before_submit or not FAST_CODE_MODE or STRICT_REPAIR_REVIEW)
1319
1327
  verify_answers = not require_code and (content.verify_answer or content.require_answer_agreement or not FAST_SCAN_MODE)
1328
+ if ordering and not require_code:
1329
+ item = solve_sorted_list_merge_order(ordering)
1330
+ if item is not None:
1331
+ return {"results": json.dumps([item], ensure_ascii=False), "provider": "local merge-step check [verified]",
1332
+ "language": language, "answer_verified": True, "code_reviewed": False}
1320
1333
  if not require_code and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
1321
1334
  local_result = local_choice_result(trimmed_text, language)
1322
1335
  if local_result is not None:
@@ -167,6 +167,55 @@ def answer_permutation(value):
167
167
  and sorted(value) == list(range(1, len(value) + 1)))
168
168
 
169
169
 
170
+ def ordering_question(text):
171
+ prompt, separator, block = text.strip().rpartition('\nReorder ALL items.')
172
+ if not separator or not prompt:
173
+ return None
174
+ rows = block.splitlines()[1:]
175
+ if not 2 <= len(rows) <= 30:
176
+ return None
177
+ options = []
178
+ for index, line in enumerate(rows, 1):
179
+ match = re.fullmatch(rf'{index}\.\s+(\S.*)', line.strip())
180
+ if not match:
181
+ return None
182
+ options.append(match[1])
183
+ return prompt, options
184
+
185
+
186
+ def solve_sorted_list_merge_order(ordering):
187
+ if not ordering:
188
+ return None
189
+ prompt, options = ordering
190
+ if prompt.strip().rstrip(':').lower() != 'rearrange the steps to merge two sorted linked lists':
191
+ return None
192
+ steps = (
193
+ 'initialize pointers for the first and second list',
194
+ 'create a dummy node to serve as the head of the merged list',
195
+ 'traverse both lists simultaneously',
196
+ 'compare elements of both lists and link the smaller node to the merged list',
197
+ 'append remaining nodes of either list to the merged list',
198
+ 'return the merged list starting from the next of the dummy node',
199
+ )
200
+ normalized = [' '.join(option.split()).lower().rstrip('.') for option in options]
201
+ if len(normalized) != len(steps) or set(normalized) != set(steps):
202
+ return None
203
+ return {
204
+ 'type': 'mcq', 'question': prompt, 'answer': [normalized.index(step) + 1 for step in steps],
205
+ 'reasoning': 'Initialize both pointers and the dummy head before traversal. Compare and link nodes while both '
206
+ 'lists have items, append the remaining tail, then return the node after the dummy head.',
207
+ }
208
+
209
+
210
+ def ordering_key(value, size):
211
+ if isinstance(value, str):
212
+ try:
213
+ value = json.loads(value)
214
+ except ValueError:
215
+ return None
216
+ return tuple(value) if answer_permutation(value) and len(value) == size else None
217
+
218
+
170
219
  MATRIX_SYNTAX = re.compile(r'\\begin\{(?:[bpBvV]?matrix|smallmatrix)\}')
171
220
 
172
221
 
@@ -336,15 +385,16 @@ def normalize_checked_answer(value, *, matrix_math=False):
336
385
  value = re.sub(r'(^|;[ \t]*)(?:option[ \t]+)?([a-z])[ \t]*[:.)][ \t]*',
337
386
  lambda match: ('; ' if match[1] else '') + f'Option {match[2].upper()}: ',
338
387
  value, flags=re.I)
339
- if not matrix_math:
340
- return value
341
388
  choices = re.split(r'; (?=Option [A-Z]: )', value)
342
389
  normalized = []
343
390
  for choice in choices:
344
391
  label = re.match(r'Option [A-Z]: ', choice)
345
392
  prefix = label[0] if label else ''
346
393
  body = choice[len(prefix):]
347
- normalized.append(prefix + (numeric_matrix_key(body) or body))
394
+ expression = re.sub(r'^\x60([^\x60\r\n]+)\x60$', r'\1', body.strip()).strip()
395
+ if re.fullmatch(r'O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)', expression):
396
+ body = re.sub(r' *([()+*/^.-]) *', r'\1', re.sub(r'[ \t]+', ' ', expression))
397
+ normalized.append(prefix + ((numeric_matrix_key(body) if matrix_math else None) or body))
348
398
  return '; '.join(normalized)
349
399
 
350
400
 
@@ -448,11 +498,21 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
448
498
  )
449
499
  check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
450
500
  matrix_math = matrix_question(messages)
501
+ ordering = ordering_question(question_text)
502
+ if ordering and len(items) != 1:
503
+ raise VisionUnconfirmedError('Expected one answer containing all numbered steps.')
504
+ step_count = len(ordering[1]) if ordering else 0
451
505
  choices = displayed_single_choices(question_text) if len(items) == 1 else {}
452
506
  constraints = reading_response_constraints(question_text) if require_agreement and len(items) == 1 else None
453
- if require_agreement and not (choices or constraints):
507
+ if require_agreement and not (choices or constraints or step_count):
454
508
  raise VisionUnconfirmedError('Expected one linked answer with displayed options or a reading response format.')
455
- if constraints:
509
+ if step_count:
510
+ check_messages[0]['content'] = (
511
+ 'Independently order the displayed steps. Use every original item number once, check all prerequisite '
512
+ f'relationships, and return only JSON with readable=true and one answers entry with id=1. '
513
+ f'The answer value must be a JSON array of all {step_count} original item numbers in the correct order.'
514
+ )
515
+ elif constraints:
456
516
  _, _, keyword = constraints
457
517
  rule = (f'Use two to five words, including the unchanged word {keyword}. Preserve the meaning of the original sentence.'
458
518
  if keyword else 'Return exactly one word.')
@@ -460,6 +520,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
460
520
  check_messages[0]['content'] = instruction
461
521
 
462
522
  def answer_key(entries):
523
+ if step_count:
524
+ return ordering_key(entries[0].get('answer'), step_count)
463
525
  if choices:
464
526
  return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
465
527
  if constraints:
@@ -485,6 +547,11 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
485
547
  except ValueError:
486
548
  current = None
487
549
  if current is not None and (current == first or current == previous):
550
+ if step_count:
551
+ if current != first:
552
+ items[0].pop('reasoning', None)
553
+ items[0]['answer'] = list(current)
554
+ return json.dumps(items, ensure_ascii=False)
488
555
  if choices:
489
556
  if current != first:
490
557
  items[0].pop('reasoning', None)
@@ -496,7 +563,7 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
496
563
  items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
497
564
  return json.dumps(items, ensure_ascii=False)
498
565
  return results
499
- if not (choices or constraints) and current is not None:
566
+ if not (choices or constraints or step_count) and current is not None:
500
567
  break
501
568
  if not attempt:
502
569
  previous = current
@@ -508,16 +575,18 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
508
575
  # primary answer over blocking the automation entirely. The primary solve was
509
576
  # validated and the verification provider returned unusable JSON — a parsing
510
577
  # failure, not a disagreement — so a hard 422 is disproportionate.
511
- if not require_agreement and current is None and previous is None:
578
+ if not require_agreement and not step_count and current is None and previous is None:
512
579
  return results
513
580
  # For multi-answer questions (fill-in-the-blank), accept the primary answers
514
581
  # when the majority of individual answers agree with any independent solve.
515
- if not require_agreement and not choices and first is not None and len(first) > 1:
582
+ if not require_agreement and not choices and not step_count and first is not None and len(first) > 1:
516
583
  best = current or previous
517
584
  if best is not None:
518
585
  agreed = sum(a == b for a, b in zip(first, best))
519
586
  if agreed > len(first) // 2:
520
587
  return results
588
+ if step_count:
589
+ raise VisionUnconfirmedError('The independent checks could not confirm a complete order for the displayed steps.')
521
590
  raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
522
591
  else 'The independent solves could not agree on the displayed answer.')
523
592