diff --git a/lanes/dev1/repair_overlay/frontend/renderers-base.js b/lanes/dev1/repair_overlay/frontend/renderers-base.js index 6f06a94d9..f1e7066c6 100644 --- a/lanes/dev1/repair_overlay/frontend/renderers-base.js +++ b/lanes/dev1/repair_overlay/frontend/renderers-base.js @@ -17,6 +17,7 @@ register('EVIDENCE_SELECT',(task,host)=>{const c=choiceControl({...task,options: register('CLAIM_EVIDENCE',(task,host)=>{const l=document.createElement('label');l.htmlFor='claim-text';l.textContent='Твердження';const t=document.createElement('textarea');t.id='claim-text';t.rows=4;host.append(l,t);const c=choiceControl({...task,options:(task.evidence_options||[])},host,false,'Оберіть докази до твердження');return ()=>dto(task,{claim:t.value,evidence_ids:c.many()})}); register('SPEAKER_RECIPIENT',(task,host)=>{const fs=document.createElement('fieldset');fs.append(Object.assign(document.createElement('legend'),{textContent:'Визначте мовця й адресата'}));const a=labelledInput('speaker-value','Мовець');const b=labelledInput('recipient-value','Адресат');fs.append(a.wrap,b.wrap);host.append(fs);return ()=>dto(task,{speaker:a.input.value,recipient:b.input.value})}); register('PARALLEL_WITNESS_COMPARE',(task,host)=>{const c=choiceControl(task,host,true,'Оберіть коректне порівняння свідків без гармонізації');return ()=>dto(task,{choice:c.one()})}); +register('PARALLEL_WITNESS_SYNTHESIS',(task,host)=>{const fs=document.createElement('fieldset');const lg=document.createElement('legend');lg.textContent='Порівняйте свідчення без гармонізації';fs.append(lg);const synthesisLabel=document.createElement('label');synthesisLabel.htmlFor='parallel-synthesis';synthesisLabel.textContent='Синтез за джерелами';const synthesis=document.createElement('textarea');synthesis.id='parallel-synthesis';synthesis.rows=6;const witnessesLabel=document.createElement('label');witnessesLabel.htmlFor='parallel-witnesses';witnessesLabel.textContent='Свідки або джерельні блоки — по одному на рядок';const witnesses=document.createElement('textarea');witnesses.id='parallel-witnesses';witnesses.rows=4;witnesses.setAttribute('aria-describedby','parallel-witnesses-help');const help=document.createElement('p');help.id='parallel-witnesses-help';help.textContent='Вкажіть лише ті джерельні блоки, які підтримують ваш синтез. Не зливайте окремі свідчення в новий текст.';fs.append(synthesisLabel,synthesis,witnessesLabel,witnesses,help);host.append(fs);return ()=>dto(task,{synthesis:synthesis.value,witnesses:witnesses.value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean)})}); register('OT_NT_LINK',(task,host)=>{const fs=document.createElement('fieldset');fs.append(Object.assign(document.createElement('legend'),{textContent:'Опишіть OT↔NT зв’язок за структурованим контрактом'}));const ot=labelledInput('ot-ref','Уривок Старого Завіту');const nt=labelledInput('nt-ref','Уривок Нового Завіту');const relLabel=document.createElement('label');relLabel.htmlFor='relation-type';relLabel.textContent='Категорія зв’язку';const rel=document.createElement('select');rel.id='relation-type';rel.append(new Option('— оберіть —',''));(task.relation_types||[]).forEach(x=>rel.append(new Option(x.label||x.id,x.id)));if(!(task.relation_types||[]).length){['DIRECT_QUOTATION','EXPLICIT_FULFILMENT_CLAIM','TYPOLOGICAL_USE','THEMATIC_ECHO','LEXICAL_PARALLEL','NARRATIVE_PARALLEL','PROMISE_APPLICATION','DISPUTED_CONNECTION'].forEach(x=>rel.append(new Option(x,x)))}const confLabel=document.createElement('label');confLabel.htmlFor='link-confidence';confLabel.textContent='Confidence';const conf=document.createElement('select');conf.id='link-confidence';conf.append(new Option('— оберіть —',''));['T1','T2','C1','I1','D1'].forEach(x=>conf.append(new Option(x,x)));const ev=labelledInput('link-evidence','Evidence ID');fs.append(ot.wrap,nt.wrap,relLabel,rel,confLabel,conf,ev.wrap);host.append(fs);return ()=>dto(task,{ot_passage:ot.input.value,nt_passage:nt.input.value,relation_category:rel.value,confidence:conf.value,evidence_id:ev.input.value})}); function scopeIds(root,prefix){const ids=new Map();root.querySelectorAll('[id]').forEach(node=>{const old=node.id;const next=`${prefix}-${old}`;ids.set(old,next);node.id=next});for(const attr of ['for','aria-labelledby','aria-describedby','aria-controls','aria-owns']){root.querySelectorAll(`[${attr}]`).forEach(node=>{const value=node.getAttribute(attr)||'';node.setAttribute(attr,value.split(/\s+/).filter(Boolean).map(token=>ids.get(token)||token).join(' '))})}} register('COMPOSITE_MULTI_STEP',(task,host)=>{const fs=document.createElement('fieldset');fs.append(Object.assign(document.createElement('legend'),{textContent:'Багатокрокове завдання'}));const getters=[];(task.steps||[]).forEach((s,i)=>{const stepId=String(s?.step_id||i+1);const section=document.createElement('section');section.className='composite-step';const h=document.createElement('h4');h.id=`composite-step-${i}-heading`;h.textContent=`Крок ${i+1}: ${s?.label||stepId}`;section.setAttribute('aria-labelledby',h.id);section.append(h);if(s?.prompt){const p=document.createElement('p');p.textContent=s.prompt;section.append(p)}const childType=String(s?.task_type||'').trim();if(!childType){const error=document.createElement('p');error.setAttribute('role','alert');error.textContent='Цей крок не має семантичного типу відповіді й не може бути надісланий.';section.append(error);getters.push(()=>({step_id:stepId,answer:{}}));fs.append(section);return}const child={...s,node_id:`${task.node_id||'task'}#${stepId}`,mission_id:task.mission_id,task_type:childType};const childHost=document.createElement('div');childHost.className='composite-step-answer';section.append(childHost);let getChild;try{getChild=RendererRegistry.get(child.task_type).render(child,childHost)}catch(error){const failure=document.createElement('p');failure.setAttribute('role','alert');failure.textContent=`Непідтримуваний тип кроку: ${childType}`;section.replaceChildren(h,failure);getters.push(()=>({step_id:stepId,answer:{}}));fs.append(section);return}const safeNode=String(task.node_id||'task').replace(/[^A-Za-z0-9_-]/g,'-');scopeIds(childHost,`composite-${safeNode}-${i}`);getters.push(()=>({step_id:stepId,answer:getChild()}));fs.append(section)});host.append(fs);return ()=>dto(task,{steps:getters.map(g=>g())})}); diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/accessibility_inspector.py b/lanes/dev1/repair_overlay/scripture_archive_platform/accessibility_inspector.py index 4796736b2..6e089ca84 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/accessibility_inspector.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/accessibility_inspector.py @@ -24,6 +24,7 @@ "CLAIM_EVIDENCE", "SPEAKER_RECIPIENT", "PARALLEL_WITNESS_COMPARE", + "PARALLEL_WITNESS_SYNTHESIS", "OT_NT_LINK", "COMPOSITE_MULTI_STEP", } diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/loader.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/loader.py index fb045b3f1..d797eea27 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/loader.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/loader.py @@ -3,7 +3,7 @@ from pathlib import Path from typing import Any from scripture_archive_platform.domain.models import CONTENT_SCHEMA_VERSION -from scripture_archive_platform.transport.answer_contracts import canonical_task_type, answer_contract_descriptor +from scripture_archive_platform.transport.answer_contracts import canonical_node_task_type, canonical_task_type, answer_contract_descriptor from scripture_archive_platform.composite_accessibility import inspect_packaged_task class ContentLoadError(RuntimeError): pass @@ -72,7 +72,7 @@ class TaskPresentationMapper: ) def infer_task_type(self,node:dict[str,Any])->str: explicit=node.get('task_type') - if explicit:return canonical_task_type(str(explicit)) + if explicit:return canonical_node_task_type(node) mode=(str(node.get('response_mode',''))+' '+str(node.get('task_family',''))).lower() if 'speaker' in mode and 'recipient' in mode:return 'SPEAKER_RECIPIENT' if 'parallel' in mode and 'witness' in mode:return 'PARALLEL_WITNESS_COMPARE' @@ -201,10 +201,12 @@ def to_renderable(self,node:dict[str,Any],mission:dict[str,Any]|None=None)->dict 'source_references':self._source_refs(node,mission),'options':options,'items':items,'pairs':pairs, 'evidence_options':evidence_options,'steps':normalized_steps,'fields':list(ui.get('fields') or []), 'witnesses':list(ui.get('witnesses') or []),'relation_types':relation_types, - 'answer_contract':answer_contract,'legacy_answer_contract':legacy_answer_contract, + 'answer_contract':answer_contract, 'accessibility':{'nonvisual_equivalent':node.get('functional_nonvisual_equivalent',''),'announcements':'Result, evidence, confidence/TX1 and next action are textual.'}, 'visual':dict(node.get('visual_metadata') or {'state_badge':node.get('confidence_code'),'media_slot':None}), } + if legacy_answer_contract: + surface['legacy_answer_contract']=legacy_answer_contract inspection=inspect_packaged_task(surface) surface['accessibility']['inspection']=inspection.to_dict() surface['accessibility']['inspection_linear']=list(inspection.linear()) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/answer_contracts.py b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/answer_contracts.py index 115fb1ac6..4a283c393 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/answer_contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/answer_contracts.py @@ -6,6 +6,7 @@ from runtime_engine.scripture_archive_runtime.answer_contracts import ( ANSWER_CONTRACT_VERSION, answer_contract_descriptor, + canonical_node_task_type, canonical_task_type, validate_answer_dto, ) @@ -17,6 +18,6 @@ "SINGLE_CHOICE", "MULTI_SELECT", "SHORT_TEXT", "LONG_TEXT", "ARGUMENT", "COMBOBOX_SELECT", "ORDERING", "MATCHING", "EVIDENCE_SELECT", "CLAIM_EVIDENCE", "COMPOSITE_MULTI_STEP", "SPEAKER_RECIPIENT", - "PARALLEL_WITNESS_COMPARE", "OT_NT_LINK", + "PARALLEL_WITNESS_COMPARE", "PARALLEL_WITNESS_SYNTHESIS", "OT_NT_LINK", ) } diff --git a/lanes/dev1/repair_overlay/tests/test_accessibility.py b/lanes/dev1/repair_overlay/tests/test_accessibility.py index 8b2e7ed49..765925e94 100644 --- a/lanes/dev1/repair_overlay/tests/test_accessibility.py +++ b/lanes/dev1/repair_overlay/tests/test_accessibility.py @@ -67,6 +67,20 @@ def test_ordering_is_keyboard_operable_and_restores_focus_after_redraw(self): self.assertIn("button:not(:disabled)", self.renderers) self.assertIn("(preferred||fallback)?.focus()", self.renderers) + def test_parallel_witness_renderer_is_keyboard_linear_and_structured(self): + for marker in ( + "register('PARALLEL_WITNESS_COMPARE'", + "register('PARALLEL_WITNESS_SYNTHESIS'", + "document.createElement('fieldset')", + "document.createElement('legend')", + "synthesisLabel.htmlFor='parallel-synthesis'", + "witnessesLabel.htmlFor='parallel-witnesses'", + "synthesis: synthesis.value", + "witnesses:witnesses.value.split(/\\r?\\n/)", + ): + self.assertIn(marker.replace("synthesis: synthesis.value", "synthesis:synthesis.value"), self.renderers) + self.assertNotIn("dto(task,{choice:c.one()})});\nregister('OT_NT_LINK'", self.renderers) + def test_composite_renderer_dispatches_child_registry_and_scopes_ids(self): self.assertIn('RendererRegistry.get(child.task_type).render(child,childHost)', self.renderers) self.assertIn('scopeIds(childHost,', self.renderers) diff --git a/lanes/dev1/repair_overlay/tests/test_accessibility_inspector.py b/lanes/dev1/repair_overlay/tests/test_accessibility_inspector.py index ba825d285..0d00c390c 100644 --- a/lanes/dev1/repair_overlay/tests/test_accessibility_inspector.py +++ b/lanes/dev1/repair_overlay/tests/test_accessibility_inspector.py @@ -84,6 +84,40 @@ def test_ordering_without_numbered_keyboard_items_fails_closed(self) -> None: {item["code"] for item in inspection["findings"]}, ) + def test_parallel_witness_structured_text_surface_does_not_require_choice_options(self) -> None: + node = dict(self.node) + node.update( + { + "node_id": "PA03-N041", + "mission_id": "PA-03", + "task_type": "PARALLEL_WITNESS_COMPARE", + "response_mode": "PARALLEL_WITNESS_COMPARE", + "task_family": "parallel_witness_compare", + "player_prompt": "Порівняйте джерельні межі.", + "source_scope_visible_to_player": "Acts 9:10–19; Acts 22:12–16", + "accepted_answer": { + "synthesis": "Canonical private synthesis.", + "witnesses": ["Acts 9:10–19; Acts 22:12–16"], + }, + "ui_metadata": {}, + "functional_nonvisual_equivalent": ( + "Два підписані багаторядкові текстові поля: синтез і джерельні блоки." + ), + } + ) + task = self.mapper.to_renderable(node, self.mission) + + self.assertEqual([], task["options"]) + self.assertEqual( + {"synthesis": "string", "witnesses": "string[]"}, + task["answer_contract"]["fields"], + ) + self.assertTrue(task["accessibility"]["inspection"]["passed"]) + self.assertNotIn( + "A11Y_SEMANTIC_ITEMS_MISSING", + {item["code"] for item in task["accessibility"]["inspection"]["findings"]}, + ) + def test_media_requires_explicit_text_equivalent(self) -> None: node = dict(self.node) node["visual_metadata"] = {"media_slot": "map://case-1"} diff --git a/lanes/dev1/repair_overlay/tests/test_answer_dto.py b/lanes/dev1/repair_overlay/tests/test_answer_dto.py index e93582aba..b6fe8abf7 100644 --- a/lanes/dev1/repair_overlay/tests/test_answer_dto.py +++ b/lanes/dev1/repair_overlay/tests/test_answer_dto.py @@ -11,6 +11,18 @@ def test_exact_shared_descriptors(self): 'COMPOSITE_MULTI_STEP':{'steps':'{step_id:string,answer:object}[]'}, } for task_type,fields in expected.items(): self.assertEqual(fields,answer_contract_descriptor(task_type)['fields']) + def test_parallel_witness_contract_preserves_choice_and_adds_structured_synthesis(self): + legacy=validate_answer_dto('PARALLEL_WITNESS_COMPARE',{'choice':'Luke'}) + self.assertEqual('Luke',legacy['choice']) + dto=validate_answer_dto('PARALLEL_WITNESS_SYNTHESIS',{'synthesis':'Порівняння без гармонізації','witnesses':['Acts 9; Acts 22']}) + self.assertEqual('Порівняння без гармонізації',dto['synthesis']) + self.assertEqual(['Acts 9; Acts 22'],dto['witnesses']) + self.assertEqual( + {'synthesis':'string','witnesses':'string[]'}, + answer_contract_descriptor('PARALLEL_WITNESS_SYNTHESIS')['fields'], + ) + with self.assertRaises(AnswerContractError): validate_answer_dto('PARALLEL_WITNESS_SYNTHESIS',{'choice':'legacy'}) + def test_normalizes_matching_and_composite(self): m=validate_answer_dto('MATCHING',{'schema':'ANSWER_DTO_v1','task_type':'MATCHING','pairs':{'a':'b'}}) self.assertEqual([{'left':'a','right':'b'}],m['pairs']) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py b/lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py index e877ab54c..d285f9d55 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py @@ -10,7 +10,7 @@ class PackagedReviewTrainingSyntaxTest(unittest.TestCase): def test_review_frontend_javascript_parses_when_node_is_available(self): node = "node" - for name in ("review-queue-ui.js", "app.js"): + for name in ("review-queue-ui.js", "app.js", "renderers-base.js"): path = ROOT / "frontend" / name try: result = subprocess.run([node, "--check", str(path)], capture_output=True, text=True, check=False) diff --git a/lanes/dev1/repair_overlay/tests/test_player_task_truth_convergence.py b/lanes/dev1/repair_overlay/tests/test_player_task_truth_convergence.py index 2651c86af..f27d735cf 100644 --- a/lanes/dev1/repair_overlay/tests/test_player_task_truth_convergence.py +++ b/lanes/dev1/repair_overlay/tests/test_player_task_truth_convergence.py @@ -159,6 +159,41 @@ def test_matching_grading_pairs_are_not_player_presentation(self) -> None: self.assertNotIn("GRADING-SECRET-LEFT", serialized) self.assertNotIn("GRADING-SECRET-RIGHT", serialized) + def test_parallel_witness_public_surface_uses_structured_contract_without_truth_leak(self) -> None: + task = self.mapper.to_renderable( + { + "node_id": "PA03-N041", + "mission_id": "PA-03", + "task_type": "PARALLEL_WITNESS_COMPARE", + "task_family": "parallel_witness_compare", + "player_prompt": "Порівняйте джерельні межі.", + "source_scope_visible_to_player": "Acts 9:10–19; Acts 22:12–16", + "functional_nonvisual_equivalent": "Два підписані текстові поля.", + "accepted_answer": { + "synthesis": "GRADING-SECRET-SYNTHESIS", + "witnesses": ["GRADING-SECRET-WITNESS"], + }, + "grading": { + "accepted_propositions": [ + {"id": "P1", "required": True, "aliases": ["GRADING-SECRET-SYNTHESIS"]} + ], + "required_witnesses": ["GRADING-SECRET-WITNESS"], + }, + }, + self.loader.mission, + ) + + self.assertEqual("PARALLEL_WITNESS_SYNTHESIS", task["task_type"]) + self.assertEqual( + {"synthesis": "string", "witnesses": "string[]"}, + task["answer_contract"]["fields"], + ) + self.assertEqual([], task["witnesses"]) + self.assertNotIn("legacy_answer_contract", task) + serialized = json.dumps(task, ensure_ascii=False, sort_keys=True) + self.assertNotIn("GRADING-SECRET-SYNTHESIS", serialized) + self.assertNotIn("GRADING-SECRET-WITNESS", serialized) + def test_required_evidence_is_not_synthesized_into_answer_options_or_source_refs(self) -> None: task = self.mapper.to_renderable( { diff --git a/runtime_engine/scripture_archive_runtime/answer_contracts.py b/runtime_engine/scripture_archive_runtime/answer_contracts.py index b250993cc..a020aa141 100644 --- a/runtime_engine/scripture_archive_runtime/answer_contracts.py +++ b/runtime_engine/scripture_archive_runtime/answer_contracts.py @@ -34,7 +34,7 @@ def canonical_task_type(value: str) -> str: ANSWER_TASK_TYPES = frozenset({ "SINGLE_CHOICE", "MULTI_SELECT", "SHORT_TEXT", "LONG_TEXT", "COMBOBOX_SELECT", "ORDERING", "MATCHING", "EVIDENCE_SELECT", "CLAIM_EVIDENCE", "SPEAKER_RECIPIENT", - "PARALLEL_WITNESS_COMPARE", "OT_NT_LINK", "COMPOSITE_MULTI_STEP", "ARGUMENT", + "PARALLEL_WITNESS_COMPARE", "PARALLEL_WITNESS_SYNTHESIS", "OT_NT_LINK", "COMPOSITE_MULTI_STEP", "ARGUMENT", }) _LEGACY_LONG_TEXT_MARKERS = ( @@ -55,7 +55,16 @@ def canonical_node_task_type(node: Mapping[str, Any]) -> str: """ explicit = node.get("task_type") if explicit is not None and str(explicit).strip(): - return canonical_task_type(str(explicit)) + explicit_type = canonical_task_type(str(explicit)) + accepted = node.get("accepted_answer") + if ( + explicit_type == "PARALLEL_WITNESS_COMPARE" + and isinstance(accepted, Mapping) + and "synthesis" in accepted + and "witnesses" in accepted + ): + return "PARALLEL_WITNESS_SYNTHESIS" + return explicit_type response_mode = str(node.get("response_mode") or "").strip() task_family = str(node.get("task_family") or "").strip() @@ -132,6 +141,12 @@ def validate_answer_dto(task_type: str, value: Any) -> dict[str, Any]: if ctype in {"SINGLE_CHOICE", "COMBOBOX_SELECT", "PARALLEL_WITNESS_COMPARE"}: allowed = {"choice"} result = {"choice": _require_str(dto.get("choice"), "choice")} + elif ctype == "PARALLEL_WITNESS_SYNTHESIS": + allowed = {"synthesis", "witnesses"} + result = { + "synthesis": _require_str(dto.get("synthesis"), "synthesis"), + "witnesses": _require_str_list(dto.get("witnesses"), "witnesses"), + } elif ctype == "MULTI_SELECT": allowed = {"choices"} result = {"choices": _require_str_list(dto.get("choices"), "choices")} @@ -196,6 +211,7 @@ def answer_contract_descriptor(task_type: str) -> dict[str, Any]: "SINGLE_CHOICE": {"choice": "string"}, "COMBOBOX_SELECT": {"choice": "string"}, "PARALLEL_WITNESS_COMPARE": {"choice": "string"}, + "PARALLEL_WITNESS_SYNTHESIS": {"synthesis": "string", "witnesses": "string[]"}, "MULTI_SELECT": {"choices": "string[]"}, "SHORT_TEXT": {"text": "string"}, "LONG_TEXT": {"text": "string"}, diff --git a/runtime_engine/scripture_archive_runtime/grading.py b/runtime_engine/scripture_archive_runtime/grading.py index ce51f61da..e8004b3db 100644 --- a/runtime_engine/scripture_archive_runtime/grading.py +++ b/runtime_engine/scripture_archive_runtime/grading.py @@ -141,6 +141,65 @@ def grade_text(task: TaskDefinition, answer: Any) -> GradeResult: return _result(task, correctness, score, details=details) +def grade_parallel_witness_compare(task: TaskDefinition, answer: Any) -> GradeResult: + if not isinstance(answer, Mapping): + return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "parallel witness answer must be object"}) + synthesis = answer.get("synthesis") + witnesses = answer.get("witnesses") + if not isinstance(synthesis, str) or not synthesis.strip(): + return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "parallel witness synthesis must be non-empty"}) + if not isinstance(witnesses, Sequence) or isinstance(witnesses, (str, bytes)) or not witnesses: + return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "parallel witness list must be non-empty"}) + submitted_witnesses = {normalize_text(value) for value in witnesses if normalize_text(value)} + accepted = task.accepted_answer if isinstance(task.accepted_answer, Mapping) else {} + canonical_witnesses = task.grading.get("required_witnesses") + if canonical_witnesses is None: + canonical_witnesses = accepted.get("witnesses") + if not isinstance(canonical_witnesses, Sequence) or isinstance(canonical_witnesses, (str, bytes)) or not canonical_witnesses: + return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "missing canonical parallel witnesses"}) + expected_witnesses = {normalize_text(value) for value in canonical_witnesses if normalize_text(value)} + if not expected_witnesses: + return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "empty canonical parallel witnesses"}) + + variants = task.accepted_variants if isinstance(task.accepted_variants, Mapping) else {} + synthesis_task = replace( + task, + accepted_answer=accepted.get("synthesis", ""), + accepted_variants=variants.get("synthesis_aliases", []), + ) + synthesis_correctness, synthesis_score, synthesis_details = _proposition_score( + synthesis_task, + {"text": synthesis}, + ) + + witness_hits = submitted_witnesses & expected_witnesses + witness_missing = expected_witnesses - submitted_witnesses + witness_extras = submitted_witnesses - expected_witnesses + witness_score = len(witness_hits) / max(len(expected_witnesses), len(submitted_witnesses), 1) + score = min(synthesis_score, witness_score) + witnesses_exact = submitted_witnesses == expected_witnesses + if synthesis_correctness is Correctness.CORRECT and witnesses_exact: + correctness = Correctness.CORRECT + elif score > 0: + correctness = Correctness.PARTIAL + else: + correctness = Correctness.INCORRECT + return _result( + task, + correctness, + score, + accepted={"synthesis": accepted.get("synthesis"), "witnesses": sorted(expected_witnesses)}, + details={ + "synthesis": synthesis_details, + "witnesses": { + "matched": sorted(witness_hits), + "missing": sorted(witness_missing), + "extras": sorted(witness_extras), + }, + }, + ) + + def grade_ordering(task: TaskDefinition, answer: Any) -> GradeResult: raw = answer.get("items") if isinstance(answer, Mapping) and "items" in answer else answer submitted = [normalize_text(x) for x in _listify(raw)] @@ -307,6 +366,7 @@ def __init__(self) -> None: self._graders = {} for name in ("SINGLE_CHOICE", "COMBOBOX_SELECT", "PARALLEL_WITNESS_COMPARE", "radio", "select", "classification"): self.register(name, grade_single_choice) + self.register("PARALLEL_WITNESS_SYNTHESIS", grade_parallel_witness_compare) for name in ("MULTI_SELECT", "checkboxes", "citation selection"): self.register(name, grade_multi_select) for name in ("SHORT_TEXT", "LONG_TEXT", "ARGUMENT", "free response", "free response + citation", "free response / comparison", "witness comparison"): diff --git a/runtime_engine/scripture_archive_runtime/package_adapters.py b/runtime_engine/scripture_archive_runtime/package_adapters.py index 6015c1c87..b99233955 100644 --- a/runtime_engine/scripture_archive_runtime/package_adapters.py +++ b/runtime_engine/scripture_archive_runtime/package_adapters.py @@ -169,6 +169,10 @@ def adapt_node_for_runtime(node: Mapping[str, Any], *, lane: str = "unknown") -> if ctype in {"SINGLE_CHOICE", "COMBOBOX_SELECT", "PARALLEL_WITNESS_COMPARE"}: grading.setdefault("accepted_choice", adapted["answer_dto"]["choice"]) grading.setdefault("options", contract.get("options") or payload.get("options") or []) + elif ctype == "PARALLEL_WITNESS_SYNTHESIS": + # Preserve authored synthesis/proposition truth. Only mirror the canonical + # witness list when no explicit grading witness set exists. + grading.setdefault("required_witnesses", list(adapted["answer_dto"]["witnesses"])) elif ctype == "MULTI_SELECT": grading.setdefault("accepted_set", adapted["answer_dto"]["choices"]) grading.setdefault("options", contract.get("options") or payload.get("options") or []) diff --git a/runtime_engine/scripture_archive_runtime/provenance.py b/runtime_engine/scripture_archive_runtime/provenance.py index 9f36351a5..2863b55bb 100644 --- a/runtime_engine/scripture_archive_runtime/provenance.py +++ b/runtime_engine/scripture_archive_runtime/provenance.py @@ -32,6 +32,8 @@ class ProvenanceClass(str, Enum): "ORDERING", "MATCHING", "EVIDENCE_SELECT", "CLAIM_EVIDENCE", "SPEAKER_RECIPIENT", "PARALLEL_WITNESS_COMPARE", "OT_NT_LINK", "COMPOSITE_MULTI_STEP", "ARGUMENT", ) +DERIVED_RUNTIME_TASK_TYPES = ("PARALLEL_WITNESS_SYNTHESIS",) +SUPPORTED_RUNTIME_TASK_TYPES = CANONICAL_TASK_TYPES + DERIVED_RUNTIME_TASK_TYPES _PAYLOAD_TRUTH_KEYS = { "correct", "correct_evidence", "ordered_items", "pairs", "answer", "answer_index", "correct_index", "correct_option", "expected", "expected_answer", "speaker", "recipient", @@ -100,6 +102,14 @@ def _value_dto(t: str, value: Any, required: Sequence[str] = ()) -> dict[str, An if t in {"SINGLE_CHOICE", "COMBOBOX_SELECT", "PARALLEL_WITNESS_COMPARE"}: if not isinstance(value, str) or not value.strip(): raise ValidationError(f"{t} requires canonical string accepted_answer") body = {"choice": value.strip()} + elif t == "PARALLEL_WITNESS_SYNTHESIS": + if not isinstance(value, Mapping): + raise ValidationError("PARALLEL_WITNESS_SYNTHESIS requires canonical synthesis+witnesses object") + synthesis = value.get("synthesis") + witnesses = value.get("witnesses") + if not _nonempty(synthesis): + raise ValidationError("PARALLEL_WITNESS_SYNTHESIS lacks canonical synthesis") + body = {"synthesis": str(synthesis), "witnesses": _seq(witnesses, "accepted_answer.witnesses")} elif t == "MULTI_SELECT": body = {"choices": _seq(value, "accepted_answer")} elif t in {"SHORT_TEXT", "LONG_TEXT", "ARGUMENT"}: text = "; ".join(f"{k}: {value[k]}" for k in sorted(value) if str(value[k]).strip()) if isinstance(value, Mapping) else str(value).strip() if isinstance(value, str) else "" @@ -189,10 +199,30 @@ def _explicit(n: Mapping[str, Any], dto: Mapping[str, Any]) -> tuple[str | None, aliases = g.get("accepted_aliases") if aliases is not None: aliases = [aliases] if isinstance(aliases, str) else aliases - canon = {_norm(n.get("accepted_answer"))} | {_norm(x) for x in (n.get("accepted_variants") or [])} + variants = n.get("accepted_variants") or [] + variants = variants if isinstance(variants, Sequence) and not isinstance(variants, (str, bytes, Mapping)) else [] + canon = {_norm(n.get("accepted_answer"))} | {_norm(x) for x in variants} if not isinstance(aliases, Sequence) or any(_norm(x) not in canon for x in aliases if _nonempty(x)): return mismatch("grading.accepted_aliases", "aliases conflict with canonical accepted_answer/accepted_variants") if _nonempty(g.get("accepted_choice")): return direct("grading.accepted_choice") if _norm(g["accepted_choice"]) == _norm(dto["choice"]) else mismatch("grading.accepted_choice", "choice conflict") if _nonempty(g.get("accepted_value")): return legacy("grading.accepted_value") if _norm(g["accepted_value"]) == _norm(dto["choice"]) else mismatch("grading.accepted_value", "legacy choice conflict") + elif t == "PARALLEL_WITNESS_SYNTHESIS": + propositions = g.get("accepted_propositions") + required_witnesses = g.get("required_witnesses") + has_propositions = _nonempty(propositions) + has_witnesses = _nonempty(required_witnesses) + if has_propositions and not _props_accept(g, dto["synthesis"]): + return mismatch("grading.accepted_propositions", "parallel synthesis propositions reject canonical synthesis") + if has_witnesses: + if not isinstance(required_witnesses, Sequence) or isinstance(required_witnesses, (str, bytes)): + return mismatch("grading.required_witnesses", "parallel required_witnesses must be a canonical list") + if {_norm(x) for x in required_witnesses} != {_norm(x) for x in dto["witnesses"]}: + return mismatch("grading.required_witnesses", "grading.required_witnesses conflicts with canonical witnesses") + if has_propositions and has_witnesses: + return direct("grading.accepted_propositions+required_witnesses") + if has_propositions: + return direct("grading.accepted_propositions") + if has_witnesses: + return direct("grading.required_witnesses") elif t == "MULTI_SELECT" and _nonempty(g.get("accepted_set")): v = g["accepted_set"]; return direct("grading.accepted_set") if isinstance(v, Sequence) and not isinstance(v, (str, bytes)) and {_norm(x) for x in v} == {_norm(x) for x in dto["choices"]} else mismatch("grading.accepted_set", "set conflict") elif t in {"SHORT_TEXT", "LONG_TEXT", "ARGUMENT"}: @@ -242,7 +272,7 @@ def _explicit(n: Mapping[str, Any], dto: Mapping[str, Any]) -> tuple[str | None, def classify_provenance(n: Mapping[str, Any]) -> ProvenanceDecision: t = _type(n) - if t not in CANONICAL_TASK_TYPES: return ProvenanceDecision(ProvenanceClass.AMBIGUOUS_FAIL.value, False, f"unsupported task type {t}", None) + if t not in SUPPORTED_RUNTIME_TASK_TYPES: return ProvenanceDecision(ProvenanceClass.AMBIGUOUS_FAIL.value, False, f"unsupported task type {t}", None) try: dto = canonical_answer_dto(n) except Exception as exc: c = ProvenanceClass.ADAPTER_INFERENCE_FAIL if _payload_truth(n) else ProvenanceClass.AMBIGUOUS_FAIL @@ -260,6 +290,7 @@ def provenance_contract_descriptor() -> dict[str, Any]: "failure_classes": [ProvenanceClass.ADAPTER_INFERENCE_FAIL.value, ProvenanceClass.MISMATCH_FAIL.value, ProvenanceClass.AMBIGUOUS_FAIL.value], "presentation_fields_never_truth": ["task_payload.correct", "task_payload.correct_evidence", "task_payload.ordered_items", "task_payload.pairs", "option position/order", "UI labels"], "task_types": {t: "canonical accepted_answer/required_evidence -> ANSWER_DTO_v1; explicit grading must be equivalent" for t in CANONICAL_TASK_TYPES}, + "derived_runtime_task_types": {t: "deterministic node-context projection of authored canonical truth -> ANSWER_DTO_v1" for t in DERIVED_RUNTIME_TASK_TYPES}, "invariant": "canonical and explicit task-specific truth must be equivalent or MISMATCH_FAIL", "fail_closed": "ambiguous projection or presentation-field inference never passes release", } diff --git a/runtime_engine/scripture_archive_runtime/transport_contract.py b/runtime_engine/scripture_archive_runtime/transport_contract.py index c9dff444b..0215ec2b4 100644 --- a/runtime_engine/scripture_archive_runtime/transport_contract.py +++ b/runtime_engine/scripture_archive_runtime/transport_contract.py @@ -13,6 +13,7 @@ "CLAIM_EVIDENCE", "SPEAKER_RECIPIENT", "PARALLEL_WITNESS_COMPARE", "OT_NT_LINK", "COMPOSITE_MULTI_STEP", "ARGUMENT", ) +DERIVED_RUNTIME_TASK_TYPES = ("PARALLEL_WITNESS_SYNTHESIS",) def transport_contract_descriptor() -> dict[str, Any]: @@ -21,6 +22,7 @@ def transport_contract_descriptor() -> dict[str, Any]: "answer_contract": ANSWER_CONTRACT_VERSION, "commands": sorted(ALLOWED_COMMANDS), "task_types": {name: answer_contract_descriptor(name) for name in CANONICAL_TASK_TYPES}, + "derived_runtime_task_types": {name: answer_contract_descriptor(name) for name in DERIVED_RUNTIME_TASK_TYPES}, "provenance": provenance_contract_descriptor(), "platform_rule": "domain/runtime contains no pywebview, win32 or desktop-only imports", } diff --git a/runtime_engine/tests/test_answer_contracts.py b/runtime_engine/tests/test_answer_contracts.py index 94934738b..ef47b7cf7 100644 --- a/runtime_engine/tests/test_answer_contracts.py +++ b/runtime_engine/tests/test_answer_contracts.py @@ -7,7 +7,7 @@ validate_answer_dto, ) from scripture_archive_runtime.package_adapters import adapt_node_for_runtime -from scripture_archive_runtime.provenance import canonical_answer_dto +from scripture_archive_runtime.provenance import canonical_answer_dto, classify_provenance from scripture_archive_runtime.security import ValidationError @@ -35,6 +35,74 @@ def test_task_type_mismatch_fails_closed(self): def test_descriptor_is_versioned(self): self.assertEqual(answer_contract_descriptor("OT_NT_LINK")["schema"], "ANSWER_DTO_v1") + def test_parallel_witness_compare_preserves_legacy_choice_and_derives_structured_synthesis(self): + self.assertEqual( + {"choice": "string"}, + answer_contract_descriptor("PARALLEL_WITNESS_COMPARE")["fields"], + ) + legacy = validate_answer_dto("PARALLEL_WITNESS_COMPARE", {"choice": "Luke"}) + self.assertEqual("Luke", legacy["choice"]) + + accepted = { + "synthesis": "Acts 9 narrates Ananias while Acts 22 retells the encounter in Paul's speech.", + "witnesses": ["Acts 9:10–19; Acts 22:12–16"], + } + node = { + "node_id": "PA03-N041", + "mission_id": "PA-03", + "task_type": "PARALLEL_WITNESS_COMPARE", + "response_mode": "PARALLEL_WITNESS_COMPARE", + "accepted_answer": accepted, + "accepted_variants": {"synthesis_aliases": [accepted["synthesis"]], "witnesses": list(accepted["witnesses"])}, + "required_evidence": ["EVR-R06-D2-0001"], + "grading": { + "accepted_propositions": [{"id": "P1", "required": True, "aliases": [accepted["synthesis"]]}], + "required_witnesses": list(accepted["witnesses"]), + "provenance_required": True, + }, + } + self.assertEqual("PARALLEL_WITNESS_SYNTHESIS", canonical_node_task_type(node)) + dto = validate_answer_dto( + "PARALLEL_WITNESS_SYNTHESIS", + {"synthesis": accepted["synthesis"], "witnesses": list(accepted["witnesses"])}, + ) + self.assertEqual( + {"synthesis": "string", "witnesses": "string[]"}, + answer_contract_descriptor("PARALLEL_WITNESS_SYNTHESIS")["fields"], + ) + with self.assertRaises(ValidationError): + validate_answer_dto("PARALLEL_WITNESS_SYNTHESIS", {"choice": "legacy-choice"}) + with self.assertRaises(ValidationError): + validate_answer_dto("PARALLEL_WITNESS_SYNTHESIS", {"synthesis": accepted["synthesis"], "witnesses": []}) + + projected = canonical_answer_dto(node) + self.assertEqual(dto, projected) + decision = classify_provenance(node) + self.assertTrue(decision.release_pass, decision) + adapted = adapt_node_for_runtime(node, lane="D2") + self.assertEqual("PARALLEL_WITNESS_SYNTHESIS", adapted["task_type"]) + self.assertEqual(projected, adapted["answer_dto"]) + self.assertNotIn("accepted_choice", adapted["grading"]) + self.assertEqual(accepted["witnesses"], adapted["grading"]["required_witnesses"]) + + legacy_node = { + "node_id": "GW01-N19", + "mission_id": "GW-01", + "task_type": "PARALLEL_WITNESS_COMPARE", + "accepted_answer": "Luke", + "accepted_variants": [], + "required_evidence": ["GW-EV-19"], + "task_contract": {"options": ["Matthew", "Mark", "Luke", "John"]}, + } + self.assertEqual("PARALLEL_WITNESS_COMPARE", canonical_node_task_type(legacy_node)) + self.assertEqual("Luke", canonical_answer_dto(legacy_node)["choice"]) + + conflicting = dict(node) + conflicting["grading"] = dict(node["grading"], required_witnesses=["Acts 26:12–18"]) + conflict = classify_provenance(conflicting) + self.assertFalse(conflict.release_pass) + self.assertIn("required_witnesses", conflict.reason) + def test_short_free_response_uses_existing_short_text_contract_and_grader(self): self.assertEqual(canonical_task_type("short free response"), "SHORT_TEXT") dto = validate_answer_dto( diff --git a/runtime_engine/tests/test_cross_lane_contracts.py b/runtime_engine/tests/test_cross_lane_contracts.py index 6ff735774..1e958596f 100644 --- a/runtime_engine/tests/test_cross_lane_contracts.py +++ b/runtime_engine/tests/test_cross_lane_contracts.py @@ -38,6 +38,31 @@ def test_parallel_witness_compare_real_shape(self): n=node("GW01-N19","GW-01","PARALLEL_WITNESS_COMPARE","Luke",["GW-EV-19"],task_contract={"answer_shape":"witness_name","options":["Matthew","Mark","Luke","John"]}) a=adapt_node_for_runtime(n,lane="D3"); self.assertEqual(GraderRegistry().grade(TaskDefinition.from_canonical(a),derive_answer_dto(a)).correctness, Correctness.CORRECT) + def test_d2_parallel_witness_structured_shape_derives_synthesis_contract(self): + synthesis="Acts 9 narrates Ananias while Acts 22 preserves Paul's later retelling." + witnesses=["Acts 9:10–19; Acts 22:12–16"] + n=node( + "PA03-N041", + "PA-03", + "PARALLEL_WITNESS_COMPARE", + {"synthesis":synthesis,"witnesses":witnesses}, + ["EVR-R06-D2-0001"], + accepted_variants={"synthesis_aliases":[synthesis],"witnesses":witnesses}, + grading={ + "accepted_propositions":[{"id":"P1","required":True,"aliases":[synthesis]}], + "required_witnesses":witnesses, + "provenance_required":True, + }, + ) + a=adapt_node_for_runtime(n,lane="D2") + self.assertEqual("PARALLEL_WITNESS_SYNTHESIS",a["task_type"]) + dto=derive_answer_dto(a) + self.assertEqual(synthesis,dto["synthesis"]) + self.assertEqual(witnesses,dto["witnesses"]) + result=GraderRegistry().grade(TaskDefinition.from_canonical(a),dto) + self.assertEqual(result.correctness,Correctness.CORRECT) + self.assertEqual(result.score,1.0) + def test_ot_nt_link_requires_canonical_structured_truth(self): payload={"ot_passage":"2 Samuel 7:14","nt_passage":"Hebrews 1:5","relation_category":"DIRECT_QUOTATION","confidence":"T2","evidence_id":"EV-OT-1","correct":"presentation-only"} n=node("OTNTROYAL01-N019","OTNT-ROYAL-01","OT_NT_LINK","2 Samuel 7:14 ↔ Hebrews 1:5 | DIRECT_QUOTATION | T2 | EV-OT-1.","EV-OT-1",task_payload=payload) diff --git a/runtime_engine/tests/test_finalprep_strict.py b/runtime_engine/tests/test_finalprep_strict.py index 48f31fd88..b9e879804 100644 --- a/runtime_engine/tests/test_finalprep_strict.py +++ b/runtime_engine/tests/test_finalprep_strict.py @@ -125,12 +125,18 @@ def test_provenance_contract_marks_payload_as_nontruth(self): c=provenance_contract_descriptor() self.assertIn('task_payload.correct', c['presentation_fields_never_truth']) self.assertEqual(c['schema'], 'GROUND_TRUTH_PROVENANCE_v1') + self.assertEqual(set(c['derived_runtime_task_types']), {'PARALLEL_WITNESS_SYNTHESIS'}) + self.assertNotIn('PARALLEL_WITNESS_SYNTHESIS', c['task_types']) class TransportTests(unittest.TestCase): def test_all_14_task_types(self): self.assertEqual(len(CANONICAL_TASK_TYPES), 14) def test_contract_schema(self): self.assertEqual(transport_contract_descriptor()['answer_contract'], 'ANSWER_DTO_v1') def test_contract_has_all_types(self): self.assertEqual(set(transport_contract_descriptor()['task_types']), set(CANONICAL_TASK_TYPES)) + def test_derived_runtime_contract_is_separate_from_authored_taxonomy(self): + c=transport_contract_descriptor() + self.assertEqual(set(c['derived_runtime_task_types']), {'PARALLEL_WITNESS_SYNTHESIS'}) + self.assertNotIn('PARALLEL_WITNESS_SYNTHESIS', c['task_types']) def test_transport_exposes_provenance_contract(self): self.assertEqual(transport_contract_descriptor()['provenance']['schema'], 'GROUND_TRUTH_PROVENANCE_v1') diff --git a/runtime_engine/tests/test_grading.py b/runtime_engine/tests/test_grading.py index 51a6191f7..c82ae8954 100644 --- a/runtime_engine/tests/test_grading.py +++ b/runtime_engine/tests/test_grading.py @@ -16,6 +16,35 @@ def test_real_pa_fixture_is_proposition_graded_without_harmonizing(self): def test_translation_neutral_explicit_proposition_aliases(self): task=self.task(response_mode="short text",task_type="SHORT_TEXT",accepted_answer="Luke names Peter and John",grading={"accepted_propositions":[{"id":"witness","required":True,"aliases":["Luke","Лука"]},{"id":"names","required":True,"aliases":["Peter and John","Петро та Іван","Петра й Івана"]}]}) ua=self.registry.grade(task,"Лука прямо називає Петра й Івана"); self.assertEqual(ua.correctness,Correctness.CORRECT); self.assertEqual(ua.details["mode"],"proposition-groups") + def test_parallel_witness_compare_requires_synthesis_and_exact_witness_set(self): + synthesis = "Acts 9 narrates Ananias while Acts 22 preserves Paul's later retelling." + witnesses = ["Acts 9:10–19; Acts 22:12–16"] + task = self.task( + task_type="PARALLEL_WITNESS_SYNTHESIS", + response_mode="PARALLEL_WITNESS_COMPARE", + accepted_answer={"synthesis": synthesis, "witnesses": witnesses}, + accepted_variants={"synthesis_aliases": [synthesis], "witnesses": witnesses}, + grading={ + "accepted_propositions": [{"id": "P1", "required": True, "aliases": [synthesis]}], + "required_witnesses": witnesses, + "provenance_required": True, + }, + ) + exact = self.registry.grade(task, {"synthesis": synthesis, "witnesses": witnesses}) + self.assertEqual(Correctness.CORRECT, exact.correctness) + self.assertEqual(1.0, exact.score) + + missing_witness = self.registry.grade(task, {"synthesis": synthesis, "witnesses": ["Acts 9:10–19"]}) + self.assertEqual(Correctness.INCORRECT, missing_witness.correctness) + self.assertEqual(0.0, missing_witness.score) + + weak_synthesis = self.registry.grade( + task, + {"synthesis": "Acts 9 narrates Ananias.", "witnesses": witnesses}, + ) + self.assertNotEqual(Correctness.CORRECT, weak_synthesis.correctness) + self.assertLess(weak_synthesis.score, 1.0) + def test_multiselect_partial_and_exact(self): task=self.task(task_type="MULTI_SELECT",response_mode="multi-select",accepted_answer=["Acts 9","Acts 22","Acts 26"],grading={"accepted_set":["Acts 9","Acts 22","Acts 26"]}) self.assertEqual(self.registry.grade(task,["Acts 9","Acts 22"]).correctness,Correctness.PARTIAL); self.assertEqual(self.registry.grade(task,["Acts 26","Acts 9","Acts 22"]).correctness,Correctness.CORRECT)