diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml new file mode 100644 index 000000000..b654a375c --- /dev/null +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -0,0 +1,159 @@ +name: R06 D2 structured runtime compatibility + +on: + push: + branches: + - r06-d2-structured-runtime-compat-0929-sol + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + pull_request: + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-d2-structured-runtime-compat-${{ github.ref }} + cancel-in-progress: true + +jobs: + compatibility: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + STRUCTURED_RUNTIME_BASE_SHA: 1d5638f574b697a984fef008e0e16a093f34220e + D2_AUTHORITY_SHA: 6ed0a9e8f390dea7c12c05fb9e991ed6328d1458 + D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 + PYTHONDONTWRITEBYTECODE: "1" + steps: + - name: Resolve expected head + id: head + shell: bash + env: + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EVENT_SHA: ${{ github.sha }} + run: | + set -euo pipefail + expected="${PR_HEAD_SHA:-$EVENT_SHA}" + test -n "$expected" + echo "sha=$expected" >> "$GITHUB_OUTPUT" + + - name: Checkout exact current-package candidate + uses: actions/checkout@v4 + with: + ref: ${{ steps.head.outputs.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Prove package lineage and exact checkout + shell: bash + env: + EXPECTED_HEAD: ${{ steps.head.outputs.sha }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + git merge-base --is-ancestor "$STRUCTURED_RUNTIME_BASE_SHA" HEAD + test "$(git merge-base "$STRUCTURED_RUNTIME_BASE_SHA" HEAD)" = "$STRUCTURED_RUNTIME_BASE_SHA" + test -z "$(git status --porcelain)" + echo "D2_STRUCTURED_RUNTIME_BASE=$STRUCTURED_RUNTIME_BASE_SHA" + echo "D2_RUNTIME_PREINTEGRATION_HEAD=$EXPECTED_HEAD" + + - name: Extract exact D2 authority read-only + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority" + rm -rf "$authority" + mkdir -p "$authority" + git fetch --no-tags origin "$D2_AUTHORITY_SHA" + test "$(git cat-file -t "$D2_AUTHORITY_SHA")" = "commit" + git archive "$D2_AUTHORITY_SHA" "$D2_AUTHORITY_REL" | tar -x -C "$authority" + root="$authority/$D2_AUTHORITY_REL" + test -f "$root/D2_CORRECTED_NODE_HASH_INDEX.json" + test -f "$root/D2_FULL_CORRECTED_AGGREGATION_MANIFEST.json" + test -f "$root/evidence_hash_index.json" + echo "D2_RUNTIME_PREINTEGRATION_AUTHORITY=$D2_AUTHORITY_SHA" + + - name: Run compatibility-tool regressions + shell: bash + run: | + set -euo pipefail + python - <<'PY' + from pathlib import Path + path = Path("tools/validate_dev2_corrected_runtime_compat.py") + compile(path.read_text(encoding="utf-8"), str(path), "exec") + PY + python -m unittest tools/test_validate_dev2_corrected_runtime_compat.py -v + + - name: Run exact D2 through current-package runtime + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority/$D2_AUTHORITY_REL" + pack="$RUNNER_TEMP/R06_D2_PREINTEGRATION_ONLY.zip" + report="$RUNNER_TEMP/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json" + python tools/validate_dev2_corrected_runtime_compat.py --authority-root "$authority" --pack-out "$pack" --report "$report" + python - "$report" <<'PY' + import json + import pathlib + import sys + report = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) + assert report["status"] == "COMPATIBILITY_PASS / PROMOTION_BLOCKED", report + assert report["authority"]["node_count"] == 386, report + assert report["authority"]["evidence_count"] == 184, report + assert report["authority"]["independent_audit"] == "PENDING", report + runtime = report["current_package_runtime"] + assert runtime["repository_nodes"] == 386, runtime + assert runtime["self_grade_correct"] == 386, runtime + assert runtime["runtime_load_pass"] == 386, runtime + assert runtime["structured_witness_count"] == 11, runtime + assert len(runtime["structured_witness_node_ids"]) == 11, runtime + assert runtime["runtime_fallback_count"] == 0, runtime + assert runtime["runtime_fallback_node_ids"] == [], runtime + pack = report["preintegration_content_pack"] + assert pack["node_count"] == 386, pack + assert pack["structured_witness_count"] == 11, pack + assert pack["structured_witness_node_ids"] == runtime["structured_witness_node_ids"], (pack, runtime) + assert pack["runtime_fallback_count"] == 0, pack + assert pack["runtime_fallback_node_ids"] == [], pack + assert report["promotion_allowed"] is False, report + print("D2_STRUCTURED_RUNTIME_COMPAT_PASS nodes=386 self_grade=386 runtime_load=386 structured=11 fallbacks=0") + PY + + - name: Prove worktree stayed immutable + shell: bash + run: | + set -euo pipefail + dirty="$(git status --porcelain)" + if [[ -n "$dirty" ]]; then + echo "D2_RUNTIME_PREINTEGRATION_WORKTREE_DIRTY" >&2 + printf '%s\n' "$dirty" >&2 + exit 1 + fi + echo "D2_RUNTIME_PREINTEGRATION_READ_ONLY_PASS" + + - name: Upload read-only compatibility evidence + uses: actions/upload-artifact@v4 + with: + name: r06-d2-structured-runtime-compat-${{ steps.head.outputs.sha }} + path: | + ${{ runner.temp }}/R06_D2_PREINTEGRATION_ONLY.zip + ${{ runner.temp }}/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/r06-dev02-accessibility-qualification.yml b/.github/workflows/r06-dev02-accessibility-qualification.yml index 0d1973e89..6dbaf3443 100644 --- a/.github/workflows/r06-dev02-accessibility-qualification.yml +++ b/.github/workflows/r06-dev02-accessibility-qualification.yml @@ -9,6 +9,7 @@ on: - 'lanes/dev1/repair_overlay/frontend/keymap-ui.js' - 'lanes/dev1/repair_overlay/frontend/renderers-base.js' - 'lanes/dev1/repair_overlay/frontend/renderers.js' + - 'lanes/dev1/repair_overlay/frontend/scripture-reader-ui.js' - 'lanes/dev1/repair_overlay/frontend/accessibility-inspector-ui.js' - 'lanes/dev1/repair_overlay/frontend/settings-ui.js' - 'lanes/dev1/repair_overlay/frontend/settings.css' @@ -24,6 +25,8 @@ on: - 'lanes/dev1/repair_overlay/tests/test_accessibility_settings_ui.py' - 'lanes/dev1/repair_overlay/tests/test_composite_accessibility.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_accessibility_inspector_surface.py' + - 'lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py' + - 'lanes/dev1/repair_overlay/tests/test_scripture_reader_request_state.py' - '.github/workflows/r06-dev02-accessibility-qualification.yml' workflow_dispatch: @@ -58,7 +61,7 @@ jobs: run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - name: Compile accessibility Python contracts working-directory: lanes/dev1/repair_overlay - run: python -m py_compile scripture_archive_platform/accessibility/semantics.py scripture_archive_platform/composite_accessibility.py tests/test_accessibility.py tests/test_accessibility_settings_ui.py tests/test_composite_accessibility.py tests/test_packaged_accessibility_inspector_surface.py + run: python -m py_compile scripture_archive_platform/accessibility/semantics.py scripture_archive_platform/composite_accessibility.py tests/test_accessibility.py tests/test_accessibility_settings_ui.py tests/test_composite_accessibility.py tests/test_packaged_accessibility_inspector_surface.py tests/test_scripture_reader_request_state.py - name: Check changed accessibility ES modules working-directory: lanes/dev1/repair_overlay shell: bash @@ -68,6 +71,7 @@ jobs: node --check frontend/keymap-ui.js node --check frontend/renderers-base.js node --check frontend/renderers.js + node --check frontend/scripture-reader-ui.js node --check frontend/accessibility-inspector-ui.js node --check frontend/settings-ui.js - name: Run exact accessibility regression @@ -83,6 +87,13 @@ jobs: - name: Run packaged Accessibility Inspector surface regression working-directory: lanes/dev1/repair_overlay run: python -m unittest discover -s tests -p "test_packaged_accessibility_inspector_surface.py" -v + - name: Run Scripture reader accessibility regression on composed platform + env: + LIBRARY_SOURCE_SHA: ${{ env.EXPECTED_HEAD }} + run: python tools/verify_library_search_overlay.py + - name: Run Scripture reader request-state regression + working-directory: lanes/dev1/repair_overlay + run: python -m unittest discover -s tests -p "test_scripture_reader_request_state.py" -v - name: Diff hygiene shell: bash run: git diff --check diff --git a/lanes/dev1/repair_overlay/frontend/renderers-base.js b/lanes/dev1/repair_overlay/frontend/renderers-base.js index f1e7066c6..2ec26defa 100644 --- a/lanes/dev1/repair_overlay/frontend/renderers-base.js +++ b/lanes/dev1/repair_overlay/frontend/renderers-base.js @@ -17,7 +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('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/frontend/scripture-reader-ui.js b/lanes/dev1/repair_overlay/frontend/scripture-reader-ui.js index 072b3a8d9..9c1d4ecdd 100644 --- a/lanes/dev1/repair_overlay/frontend/scripture-reader-ui.js +++ b/lanes/dev1/repair_overlay/frontend/scripture-reader-ui.js @@ -235,12 +235,16 @@ function renderVerses(data) { const host = byId('scripture-reader-verses'); host.replaceChildren(); const heading = element('h4', `${data.book} ${data.chapter}`); - const list = element('ol', '', {'aria-label': `${data.book} ${data.chapter}, World English Bible Updated`}); + const list = element('ol', '', {'aria-label': `WEBU, ${data.book} ${data.chapter}`}); for (const row of data.verses || []) { - const text = row.text_state === 'source_empty' - ? `Verse ${row.verse}. Not stated in the cited WEBU source row.` - : `Verse ${row.verse}. ${row.text}`; - list.append(element('li', text, {'data-reference': row.reference})); + const item = element('li', '', {'data-reference': row.reference}); + item.append(element('span', `Вірш ${row.verse}. `)); + if (row.text_state === 'source_empty') { + item.append(element('span', 'Текст відсутній у цьому рядку джерела WEBU.')); + } else { + item.append(element('span', row.text, {lang: 'en'})); + } + list.append(item); } host.append(heading, list); heading.tabIndex = -1; @@ -250,15 +254,22 @@ function renderVerses(data) { function renderSearch(data) { const host = byId('scripture-reader-search-results'); host.replaceChildren(); + const heading = element('h4', 'Результати пошуку', {id: 'scripture-reader-search-results-heading'}); + heading.tabIndex = -1; if (!data.results?.length) { - host.append(element('p', 'No matching text found in the bundled WEBU source.')); + host.append(heading, element('p', 'У вбудованому тексті WEBU збігів не знайдено.')); + heading.focus(); return; } - const list = element('ol'); + const list = element('ol', '', {'aria-labelledby': 'scripture-reader-search-results-heading'}); for (const row of data.results) { - list.append(element('li', `${row.reference} — ${row.text}`)); + const item = element('li'); + item.append(element('span', `${row.reference} — `)); + item.append(element('span', row.text, {lang: 'en'})); + list.append(item); } - host.append(list); + host.append(heading, list); + heading.focus(); } export async function installScriptureReaderSurface() { @@ -266,28 +277,31 @@ export async function installScriptureReaderSurface() { if (!library || byId('scripture-reader')) return; const section = element('section', '', {id: 'scripture-reader', 'aria-labelledby': 'scripture-reader-heading'}); - const heading = element('h3', 'Full Scripture text — WEBU', {id: 'scripture-reader-heading'}); - const source = element('p', 'Bundled offline World English Bible Updated (engwebu), source tier TX1, public-domain source. Empty source rows are reported as empty and are never filled from another witness.', {id: 'scripture-reader-source', role: 'note'}); + const heading = element('h3', 'Повний текст Писання — WEBU', {id: 'scripture-reader-heading'}); + const source = element('p', 'Вбудований офлайн-текст World English Bible Updated (engwebu), рівень джерела TX1, суспільне надбання. Порожні рядки джерела показуються порожніми й ніколи не заповнюються з іншого свідчення.', {id: 'scripture-reader-source', role: 'note'}); const readForm = element('form', '', {id: 'scripture-reader-form', 'aria-labelledby': 'scripture-reader-read-heading'}); - readForm.append(element('h4', 'Read a chapter', {id: 'scripture-reader-read-heading'})); - const bookLabel = element('label', 'Book code'); bookLabel.htmlFor = 'scripture-reader-book'; + readForm.append(element('h4', 'Читати розділ', {id: 'scripture-reader-read-heading'})); + const bookLabel = element('label', 'Код книги'); bookLabel.htmlFor = 'scripture-reader-book'; const book = element('select', '', {id: 'scripture-reader-book'}); - const chapterLabel = element('label', 'Chapter'); chapterLabel.htmlFor = 'scripture-reader-chapter'; + const chapterLabel = element('label', 'Розділ'); chapterLabel.htmlFor = 'scripture-reader-chapter'; const chapter = element('input', '', {id: 'scripture-reader-chapter', type: 'number', min: '1', max: '200', value: '1', inputmode: 'numeric'}); - const readButton = element('button', 'Read chapter', {type: 'submit'}); + const readButton = element('button', 'Читати розділ', {type: 'submit'}); readForm.append(bookLabel, book, chapterLabel, chapter, readButton); const searchForm = element('form', '', {id: 'scripture-reader-text-search', role: 'search', 'aria-labelledby': 'scripture-reader-search-heading'}); - searchForm.append(element('h4', 'Search full text', {id: 'scripture-reader-search-heading'})); - const queryLabel = element('label', 'Words in Scripture text'); queryLabel.htmlFor = 'scripture-reader-query'; - const query = element('input', '', {id: 'scripture-reader-query', type: 'search', maxlength: '128', autocomplete: 'off'}); - const searchButton = element('button', 'Search WEBU', {type: 'submit'}); + searchForm.append(element('h4', 'Пошук у повному тексті', {id: 'scripture-reader-search-heading'})); + const queryLabel = element('label', 'Слова в тексті Писання'); queryLabel.htmlFor = 'scripture-reader-query'; + const query = element('input', '', {id: 'scripture-reader-query', type: 'search', maxlength: '128', autocomplete: 'off', lang: 'en'}); + const searchButton = element('button', 'Шукати в WEBU', {type: 'submit'}); searchForm.append(queryLabel, query, searchButton); - const live = element('p', '', {id: 'scripture-reader-status', role: 'status', 'aria-live': 'polite'}); - const verses = element('div', '', {id: 'scripture-reader-verses', 'aria-live': 'polite'}); - const results = element('div', '', {id: 'scripture-reader-search-results', 'aria-live': 'polite'}); + const live = element('p', '', {id: 'scripture-reader-status', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'}); + // Keep only the compact status as a live region. Chapter/search results may contain + // dozens of source rows; announcing those containers live would duplicate or flood NVDA. + // User-triggered result changes use explicit heading focus instead. + const verses = element('div', '', {id: 'scripture-reader-verses'}); + const results = element('div', '', {id: 'scripture-reader-search-results'}); section.append(heading, source, readForm, searchForm, live, verses, results); library.append(section); @@ -303,32 +317,44 @@ export async function installScriptureReaderSurface() { && monitoring.status === 'SOURCE_REAUDIT_REQUIRED'; if (driftPending) { const changedRefs = monitoring.changed_references.join(', '); - source.textContent = `Bundled offline World English Bible Updated (engwebu), source tier TX1, public-domain source. This is an audited pinned snapshot. The official upstream has changed at ${monitoring.changed_reference_count || 0} known references and is pending source re-audit; known changed references: ${changedRefs}. This reader continues to use the audited bundled snapshot. Empty source rows are reported as empty and are never filled from another witness.`; + source.textContent = `Вбудований офлайн-текст World English Bible Updated (engwebu), рівень джерела TX1, суспільне надбання. Це перевірений закріплений знімок. В офіційному upstream змінено ${monitoring.changed_reference_count || 0} відомих посилань; потрібен повторний аудит джерела. Відомі змінені посилання: ${changedRefs}. Читач продовжує використовувати перевірений вбудований знімок. Порожні рядки джерела показуються порожніми й ніколи не заповнюються з іншого свідчення.`; } - status(`Offline WEBU ready: ${catalog.verse_rows} source rows across ${catalog.books?.length || 0} book codes.${driftPending ? ' Audited pinned snapshot; upstream source re-audit is pending.' : ''}`); + status(`Офлайн WEBU готовий: ${catalog.verse_rows} рядків джерела, ${catalog.books?.length || 0} кодів книг.${driftPending ? ' Використовується перевірений закріплений знімок; потрібен повторний аудит upstream-джерела.' : ''}`); } catch (error) { - status(`Full-text provider unavailable: ${error.message}`); + console.error('Scripture reader catalog initialization failed', error); + status('Постачальник повного тексту недоступний.'); readButton.disabled = true; searchButton.disabled = true; return; } readForm.addEventListener('submit', async event => { - event.preventDefault(); readButton.disabled = true; status('Loading chapter…'); + event.preventDefault(); + readButton.disabled = true; + verses.replaceChildren(); + status('Завантаження розділу…'); try { const data = validateChapter(await api('library.read_chapter', {book: book.value, chapter: Number(chapter.value)})); - renderVerses(data); status(`${data.book} ${data.chapter}: ${data.verses.length} source rows.`); - } catch (error) { status(`Cannot read chapter: ${error.message}`); } + renderVerses(data); status(`${data.book} ${data.chapter}: ${data.verses.length} рядків джерела.`); + } catch (error) { + console.error('Scripture reader chapter load failed', error); + status('Не вдалося прочитати цей розділ. Перевірте код книги й номер розділу.'); + } finally { readButton.disabled = false; } }); searchForm.addEventListener('submit', async event => { event.preventDefault(); const value = query.value.trim(); - if (!value) { status('Enter words to search in the bundled WEBU text.'); query.focus(); return; } - searchButton.disabled = true; status('Searching bundled WEBU text…'); + if (!value) { status('Введіть слова для пошуку у вбудованому тексті WEBU.'); query.focus(); return; } + searchButton.disabled = true; + results.replaceChildren(); + status('Пошук у вбудованому тексті WEBU…'); try { const data = validateTextSearch(await api('library.text_search', {query: value, limit: MAX_SEARCH_RESULTS})); - renderSearch(data); status(`${data.total} matching source rows; showing up to 50.`); - } catch (error) { status(`Cannot search Scripture text: ${error.message}`); } + renderSearch(data); status(`Знайдено ${data.total} рядків джерела; показано до 50.`); + } catch (error) { + console.error('Scripture reader text search failed', error); + status('Не вдалося виконати пошук у тексті Писання.'); + } finally { searchButton.disabled = false; } }); } diff --git a/lanes/dev1/repair_overlay/tests/test_accessibility.py b/lanes/dev1/repair_overlay/tests/test_accessibility.py index 765925e94..1a204e148 100644 --- a/lanes/dev1/repair_overlay/tests/test_accessibility.py +++ b/lanes/dev1/repair_overlay/tests/test_accessibility.py @@ -77,6 +77,8 @@ def test_parallel_witness_renderer_is_keyboard_linear_and_structured(self): "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) diff --git a/lanes/dev1/repair_overlay/tests/test_scripture_reader_request_state.py b/lanes/dev1/repair_overlay/tests/test_scripture_reader_request_state.py new file mode 100644 index 000000000..57bb4cb14 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_scripture_reader_request_state.py @@ -0,0 +1,117 @@ +import subprocess +import textwrap +import unittest +from pathlib import Path + + +class ScriptureReaderRequestStateTests(unittest.TestCase): + def test_failed_requests_clear_stale_results_and_empty_query_preserves_them(self): + overlay = Path(__file__).resolve().parents[1] + ui_path = overlay / 'frontend' / 'scripture-reader-ui.js' + script = textwrap.dedent( + r""" + import {readFileSync} from 'node:fs'; + + let source = readFileSync(process.argv[1], 'utf8'); + source = source.replace( + "import {chooseTransport, unwrap} from './transport.js';", + "const chooseTransport=()=>Promise.resolve({}); const unwrap=async(_transport,command,payload)=>globalThis.__api(command,payload);" + ); + source = source.replace( + "const catalog = validateTextCatalog(await api('library.text_catalog'));", + "const catalog={books:[],verse_rows:38058,source_snapshot_status:'AUDITED_PINNED_SNAPSHOT',upstream_monitoring:{status:'MATCH_PINNED_AUTHORITY'}};" + ); + + let focused = null; + const nodes = new Map(); + class FakeNode { + constructor(tag) { + this.tagName = String(tag).toUpperCase(); + this.children = []; + this.attributes = {}; + this.listeners = {}; + this.textContent = ''; + this.value = ''; + this.disabled = false; + this.isConnected = true; + } + setAttribute(name, value) { + const text = String(value); + this.attributes[name] = text; + if (name === 'id') { this.id = text; nodes.set(text, this); } + if (name === 'value') this.value = text; + } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { this.children = [...children]; } + addEventListener(name, handler) { this.listeners[name] = handler; } + focus() { focused = this; } + } + + const library = new FakeNode('main'); + library.id = 'library-view'; + nodes.set('library-view', library); + globalThis.document = { + createElement: tag => new FakeNode(tag), + getElementById: id => nodes.get(id) || null, + }; + + let apiCalls = []; + globalThis.__api = async(command, payload) => { + apiCalls.push([command, payload]); + if (command === 'library.read_chapter') { + const host = nodes.get('scripture-reader-verses'); + if (host.children.length !== 0) throw new Error('chapter stale content reached transport'); + throw new Error('simulated chapter transport failure'); + } + if (command === 'library.text_search') { + const host = nodes.get('scripture-reader-search-results'); + if (host.children.length !== 0) throw new Error('search stale content reached transport'); + throw new Error('simulated search transport failure'); + } + throw new Error(`unexpected command ${command}`); + }; + + const mod = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')); + await mod.installScriptureReaderSurface(); + + const readForm = nodes.get('scripture-reader-form'); + const searchForm = nodes.get('scripture-reader-text-search'); + const verses = nodes.get('scripture-reader-verses'); + const results = nodes.get('scripture-reader-search-results'); + const query = nodes.get('scripture-reader-query'); + const status = nodes.get('scripture-reader-status'); + if (!readForm?.listeners.submit || !searchForm?.listeners.submit) { + throw new Error('reader submit handlers were not installed'); + } + + verses.append(new FakeNode('p')); + await readForm.listeners.submit({preventDefault(){}}); + if (verses.children.length !== 0) throw new Error('failed chapter request left stale result content'); + if (!status.textContent.includes('Не вдалося прочитати')) throw new Error('chapter failure status was not bounded'); + + results.append(new FakeNode('ol')); + query.value = ''; + focused = null; + const callsBeforeEmpty = apiCalls.length; + await searchForm.listeners.submit({preventDefault(){}}); + if (apiCalls.length !== callsBeforeEmpty) throw new Error('empty search query dispatched transport'); + if (results.children.length !== 1) throw new Error('empty query erased the last valid search result'); + if (focused !== query) throw new Error('empty query did not return focus to the search input'); + + query.value = 'beginning'; + await searchForm.listeners.submit({preventDefault(){}}); + if (results.children.length !== 0) throw new Error('failed search request left stale result content'); + if (!status.textContent.includes('Не вдалося виконати пошук')) throw new Error('search failure status was not bounded'); + """ + ) + result = subprocess.run( + ['node', '--input-type=module', '-e', script, str(ui_path)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, result.returncode, result.stderr or result.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py b/lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py index fba0dd3a8..38d5c562d 100644 --- a/lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py +++ b/lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py @@ -441,6 +441,106 @@ def test_frontend_response_validation_is_executable_and_fail_closed(self): ) self.assertEqual(0, result.returncode, result.stderr or result.stdout) + def test_frontend_result_focus_is_executable_without_bulk_live_regions(self): + overlay = Path(__file__).resolve().parents[1] + ui_path = overlay / 'frontend' / 'scripture-reader-ui.js' + script = textwrap.dedent( + r""" + import {readFileSync} from 'node:fs'; + let source = readFileSync(process.argv[1], 'utf8'); + source = source.replace( + "import {chooseTransport, unwrap} from './transport.js';", + "const chooseTransport=()=>null; const unwrap=async()=>({});" + ); + source = source.replace('function renderVerses(data) {', 'export function renderVerses(data) {'); + source = source.replace('function renderSearch(data) {', 'export function renderSearch(data) {'); + + let focused = null; + class FakeNode { + constructor(tag) { + this.tagName = String(tag).toUpperCase(); + this.textContent = ''; + this.children = []; + this.attributes = {}; + this.tabIndex = 0; + } + setAttribute(name, value) { this.attributes[name] = String(value); } + append(...nodes) { this.children.push(...nodes); } + replaceChildren(...nodes) { this.children = [...nodes]; } + focus() { focused = this; } + } + const nodes = new Map([ + ['scripture-reader-verses', new FakeNode('div')], + ['scripture-reader-search-results', new FakeNode('div')], + ]); + globalThis.document = { + createElement: tag => new FakeNode(tag), + getElementById: id => nodes.get(id) || null, + }; + + const mod = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')); + const verse = { + book:'GEN', chapter:1, verse:1, reference:'GEN 1:1', + text:'In the beginning', text_state:'present', + translation_id:'engwebu', source_tier:'TX1' + }; + mod.renderVerses({ + schema:'scripture.library.chapter.v1', + translation_id:'engwebu', source_tier:'TX1', + book:'GEN', chapter:1, verses:[verse], source_empty_rows:0 + }); + if (!focused || focused.tagName !== 'H4' || focused.textContent !== 'GEN 1') { + throw new Error('chapter result heading did not receive focus'); + } + const chapterList = nodes.get('scripture-reader-verses').children[1]; + const chapterItem = chapterList?.children?.[0]; + if (!chapterItem || chapterItem.children?.[1]?.attributes?.lang !== 'en') { + throw new Error('chapter source text is not marked as English'); + } + + focused = null; + mod.renderSearch({ + schema:'scripture.library.text-search.v1', + translation_id:'engwebu', source_tier:'TX1', + query:'beginning', total:1, results:[verse] + }); + const resultsHost = nodes.get('scripture-reader-search-results'); + if (!focused || focused.tagName !== 'H4' || focused.textContent !== 'Результати пошуку') { + throw new Error('search result heading did not receive focus'); + } + if (focused.attributes.id !== 'scripture-reader-search-results-heading') { + throw new Error('search result heading identity is missing'); + } + const list = resultsHost.children[1]; + if (!list || list.attributes['aria-labelledby'] !== 'scripture-reader-search-results-heading') { + throw new Error('search result list is not labelled by its focused heading'); + } + if (list.children?.[0]?.children?.[1]?.attributes?.lang !== 'en') { + throw new Error('search source text is not marked as English'); + } + + focused = null; + mod.renderSearch({ + schema:'scripture.library.text-search.v1', + translation_id:'engwebu', source_tier:'TX1', + query:'absent', total:0, results:[] + }); + if (!focused || focused.textContent !== 'Результати пошуку') { + throw new Error('empty search result heading did not receive focus'); + } + if (!resultsHost.children[1] || !resultsHost.children[1].textContent.includes('збігів не знайдено')) { + throw new Error('empty search result message is missing'); + } + """ + ) + result = subprocess.run( + ['node', '--input-type=module', '-e', script, str(ui_path)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, result.returncode, result.stderr or result.stdout) + def test_packaging_and_frontend_bindings_are_explicit(self): overlay = Path(__file__).resolve().parents[1] build = (overlay / 'packaging' / 'build_windows.ps1').read_text(encoding='utf-8') @@ -457,10 +557,27 @@ def test_packaging_and_frontend_bindings_are_explicit(self): self.assertIn('textContent', frontend) self.assertNotIn('innerHTML', frontend) self.assertIn("role: 'status'", frontend) + self.assertEqual(1, frontend.count("'aria-live': 'polite'")) + self.assertIn("'aria-atomic': 'true'", frontend) + self.assertIn("lang: 'en'", frontend) + self.assertIn('Повний текст Писання — WEBU', frontend) + self.assertIn('Результати пошуку', frontend) + self.assertNotIn('Full Scripture text — WEBU', frontend) + self.assertNotIn('status(`Постачальник повного тексту недоступний: ${error.message}`)', frontend) + self.assertNotIn('status(`Не вдалося прочитати розділ: ${error.message}`)', frontend) + self.assertNotIn('status(`Не вдалося виконати пошук у тексті Писання: ${error.message}`)', frontend) + self.assertIn("console.error('Scripture reader catalog initialization failed', error)", frontend) + self.assertIn("console.error('Scripture reader chapter load failed', error)", frontend) + self.assertIn("console.error('Scripture reader text search failed', error)", frontend) + self.assertNotIn("id: 'scripture-reader-verses', 'aria-live'", frontend) + self.assertNotIn("id: 'scripture-reader-search-results', 'aria-live'", frontend) + self.assertIn("id: 'scripture-reader-search-results-heading'", frontend) + self.assertIn("'aria-labelledby': 'scripture-reader-search-results-heading'", frontend) + self.assertGreaterEqual(frontend.count('heading.focus()'), 2) self.assertIn('AUDITED_PINNED_SNAPSHOT', frontend) self.assertIn('SOURCE_REAUDIT_REQUIRED', frontend) - self.assertIn('upstream source re-audit is pending', frontend) - self.assertIn('known changed references:', frontend) + self.assertIn('потрібен повторний аудит upstream-джерела', frontend) + self.assertIn('Відомі змінені посилання:', frontend) for token in ( 'validateTextCatalog', 'validateChapter', @@ -491,6 +608,22 @@ def test_packaging_and_frontend_bindings_are_explicit(self): self.assertIn("'SOURCE_REAUDIT_REQUIRED'", workflow) self.assertNotIn('steps.source_audit.outputs.source_matches', workflow) + accessibility_workflow = ( + overlay.parents[2] + / '.github' + / 'workflows' + / 'r06-dev02-accessibility-qualification.yml' + ).read_text(encoding='utf-8') + self.assertIn("'lanes/dev1/repair_overlay/frontend/scripture-reader-ui.js'", accessibility_workflow) + self.assertIn("'lanes/dev1/repair_overlay/tests/test_scripture_text_provider.py'", accessibility_workflow) + self.assertIn('node --check frontend/scripture-reader-ui.js', accessibility_workflow) + self.assertIn( + 'python tools/verify_library_search_overlay.py', + accessibility_workflow, + ) + self.assertIn('LIBRARY_SOURCE_SHA:', accessibility_workflow) + self.assertIn('${{ env.EXPECTED_HEAD }}', accessibility_workflow) + completed = subprocess.run( ['node', '--check', str(overlay / 'frontend' / 'scripture-reader-ui.js')], capture_output=True, diff --git a/runtime_engine/scripture_archive_runtime/grading.py b/runtime_engine/scripture_archive_runtime/grading.py index e8004b3db..8cf6f4257 100644 --- a/runtime_engine/scripture_archive_runtime/grading.py +++ b/runtime_engine/scripture_archive_runtime/grading.py @@ -33,6 +33,22 @@ def _structured_text(value: Any) -> str: return str(value or "") +def _parallel_witness_set(values: Sequence[Any]) -> set[str]: + """Normalize authored witness blocks without changing canonical source bytes. + + Historical D2 authority stores some array[passage] values as one semicolon- + delimited string while the keyboard UI accepts one passage per line. Treat + those two encodings as equivalent at grading time and nowhere else. + """ + normalized: set[str] = set() + for value in values: + for part in str(value).split(";"): + item = normalize_text(part) + if item: + normalized.add(item) + return normalized + + def _feedback(task: TaskDefinition, correctness: Correctness) -> str: if correctness is Correctness.CORRECT: return task.success_feedback @@ -150,14 +166,14 @@ def grade_parallel_witness_compare(task: TaskDefinition, answer: Any) -> GradeRe 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)} + submitted_witnesses = _parallel_witness_set(witnesses) 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)} + expected_witnesses = _parallel_witness_set(canonical_witnesses) if not expected_witnesses: return _result(task, Correctness.INCORRECT, 0.0, details={"validation": "empty canonical parallel witnesses"}) diff --git a/runtime_engine/tests/test_grading.py b/runtime_engine/tests/test_grading.py index c82ae8954..cfeedb75f 100644 --- a/runtime_engine/tests/test_grading.py +++ b/runtime_engine/tests/test_grading.py @@ -34,9 +34,27 @@ def test_parallel_witness_compare_requires_synthesis_and_exact_witness_set(self) self.assertEqual(Correctness.CORRECT, exact.correctness) self.assertEqual(1.0, exact.score) + split_lines = self.registry.grade( + task, + {"synthesis": synthesis, "witnesses": ["Acts 9:10–19", "Acts 22:12–16"]}, + ) + self.assertEqual(Correctness.CORRECT, split_lines.correctness) + self.assertEqual(1.0, split_lines.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) + self.assertEqual(Correctness.PARTIAL, missing_witness.correctness) + self.assertEqual(0.5, missing_witness.score) + + extra_witness = self.registry.grade( + task, + { + "synthesis": synthesis, + "witnesses": ["Acts 9:10–19", "Acts 22:12–16", "Acts 26:12–18"], + }, + ) + self.assertEqual(Correctness.PARTIAL, extra_witness.correctness) + self.assertAlmostEqual(2 / 3, extra_witness.score) + self.assertIn("acts 26 12 18", extra_witness.details["witnesses"]["extras"]) weak_synthesis = self.registry.grade( task, diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py new file mode 100644 index 000000000..03c0e4b61 --- /dev/null +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import copy +import json +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +for entry in ( + REPO_ROOT / "runtime_engine", + REPO_ROOT / "runtime_engine" / "tests", + REPO_ROOT / "tools", +): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from fixtures import LN01_N03 +from scripture_archive_runtime.content_packs import ContentPackStore, inspect_content_pack +from validate_dev2_corrected_runtime_compat import ( + PACK_ID, + PACK_VERSION, + PARALLEL_WITNESS_FALLBACK_REASON, + CompatibilityError, + _project_nodes_for_current_runtime, + _runtime_compatibility, + write_preintegration_pack, +) + + +class D2CorrectedRuntimeCompatibilityTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_pack_writer_is_deterministic_and_installable(self) -> None: + node = copy.deepcopy(LN01_N03) + first = self.root / "first.zip" + second = self.root / "second.zip" + a = write_preintegration_pack([node], first, expected_node_count=1) + b = write_preintegration_pack([copy.deepcopy(node)], second, expected_node_count=1) + self.assertEqual(first.read_bytes(), second.read_bytes()) + self.assertEqual(a["archive_sha256"], b["archive_sha256"]) + inspected = inspect_content_pack(first) + self.assertEqual(PACK_ID, inspected.manifest.pack_id) + self.assertEqual(PACK_VERSION, inspected.manifest.version) + self.assertEqual(1, inspected.node_count) + + def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self) -> None: + node = copy.deepcopy(LN01_N03) + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["repository_nodes"]) + self.assertEqual(1, runtime["self_grade_correct"]) + self.assertEqual(1, runtime["runtime_load_pass"]) + + archive = self.root / "fixture.zip" + write_preintegration_pack([node], archive, expected_node_count=1) + store = ContentPackStore(self.root / "store") + inspected = store.install(archive) + self.assertEqual(1, inspected.node_count) + store.activate(PACK_ID, PACK_VERSION) + self.assertEqual({PACK_ID: PACK_VERSION}, store.active_versions()) + + def _parallel_witness_fixture(self): + node = copy.deepcopy(LN01_N03) + synthesis = "Witness-safe synthesis for current-runtime compatibility." + witnesses = ["Luke 22:8"] + node["task_type"] = "PARALLEL_WITNESS_COMPARE" + node["response_mode"] = "PARALLEL_WITNESS_COMPARE" + node["task_family"] = "parallel_witness_compare" + node["accepted_answer"] = {"synthesis": synthesis, "witnesses": witnesses} + node["accepted_variants"] = { + "synthesis_aliases": [synthesis], + "witnesses": witnesses, + } + node["grading"] = { + "accepted_propositions": [ + {"id": "P1", "required": True, "aliases": [synthesis]} + ], + "provenance_required": True, + "required_witnesses": witnesses, + } + node["response_contract"] = { + "kind": "witness_compare", + "answer_dto": { + "shape": "object", + "fields": {"synthesis": "string", "witnesses": "array[passage]"}, + }, + } + node["runtime_fallback"] = { + "task_type": "LONG_TEXT", + "accepted_answer": synthesis, + "reason": PARALLEL_WITNESS_FALLBACK_REASON, + } + return node + + def test_parallel_witness_structured_path_is_lossless_and_source_immutable(self) -> None: + node = self._parallel_witness_fixture() + original = copy.deepcopy(node) + projected, structured_ids = _project_nodes_for_current_runtime([node]) + self.assertEqual(original, node) + self.assertEqual([node["node_id"]], structured_ids) + self.assertEqual("PARALLEL_WITNESS_COMPARE", projected[0]["task_type"]) + self.assertEqual(node["accepted_answer"], projected[0]["accepted_answer"]) + + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["structured_witness_count"]) + self.assertEqual([node["node_id"]], runtime["structured_witness_node_ids"]) + self.assertEqual(0, runtime["runtime_fallback_count"]) + self.assertEqual([], runtime["runtime_fallback_node_ids"]) + + def test_parallel_witness_historical_fallback_metadata_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["runtime_fallback"]["accepted_answer"] = "Different synthesis" + with self.assertRaisesRegex(CompatibilityError, "historical runtime_fallback metadata changed"): + _project_nodes_for_current_runtime([node]) + + def test_parallel_witness_truth_binding_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["grading"]["required_witnesses"] = ["Acts 1:1"] + with self.assertRaisesRegex(CompatibilityError, "structured witness truth bindings changed"): + _project_nodes_for_current_runtime([node]) + + def test_conflicting_explicit_grading_truth_fails_closed(self) -> None: + node = copy.deepcopy(LN01_N03) + node["grading"] = {"accepted_choice": "CONTRADICTS CANONICAL ANSWER"} + with self.assertRaisesRegex( + CompatibilityError, + "provenance rejects corrected node", + ): + _runtime_compatibility([node], expected_node_count=1) + + def test_missing_nonvisual_equivalent_fails_before_runtime_promotion(self) -> None: + node = copy.deepcopy(LN01_N03) + node["functional_nonvisual_equivalent"] = "" + with self.assertRaisesRegex( + CompatibilityError, + "current runtime rejected corrected D2 corpus", + ): + _runtime_compatibility([node], expected_node_count=1) + + def test_workflow_requalifies_when_runtime_or_bound_package_changes(self) -> None: + workflow = ( + REPO_ROOT + / ".github" + / "workflows" + / "r06-d2-corrected-runtime-preintegration.yml" + ).read_text(encoding="utf-8") + required_trigger_surfaces = ( + "tools/validate_dev2_corrected_runtime_compat.py", + "tools/test_validate_dev2_corrected_runtime_compat.py", + "tools/validate_dev2_evidence_bundle.py", + "runtime_engine/scripture_archive_runtime/**", + "lanes/dev1/repair_overlay/scripture_archive_platform/**", + "lanes/dev1/repair_overlay/frontend/**", + "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**", + ) + for trigger in required_trigger_surfaces: + self.assertGreaterEqual( + workflow.count(f" - '{trigger}'"), + 2, + f"push and pull_request must both requalify on {trigger}", + ) + self.assertIn('PYTHONDONTWRITEBYTECODE: "1"', workflow) + self.assertIn( + "STRUCTURED_RUNTIME_BASE_SHA: 1d5638f574b697a984fef008e0e16a093f34220e", + workflow, + ) + self.assertNotIn("PACKAGE_BASE_SHA:", workflow) + self.assertNotIn("76176fc3dcd246284366ba88619947ba2626c7d7", workflow) + self.assertNotIn("python -m py_compile tools/validate_dev2_corrected_runtime_compat.py", workflow) + self.assertIn('dirty="$(git status --porcelain)"', workflow) + self.assertIn("D2_RUNTIME_PREINTEGRATION_WORKTREE_DIRTY", workflow) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py new file mode 100644 index 000000000..bd0135d37 --- /dev/null +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,591 @@ +#!/usr/bin/env python3 +"""Read-only compatibility gate for the corrected R06 D2 Paul/Acts authority. + +This gate never promotes the D2 corpus and never mutates the packaged-app content +surface. It consumes an exact external authority snapshot, proves its corrected +hash/index/evidence bindings, then runs all 386 nodes through the current-package +runtime and a deterministic preintegration content-pack round trip. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import stat +import sys +import tempfile +import zipfile +from collections import Counter +from pathlib import Path +from typing import Any, Iterable, Mapping + +REPO_ROOT = Path(__file__).resolve().parents[1] +RUNTIME_ROOT = REPO_ROOT / "runtime_engine" +TOOLS_ROOT = REPO_ROOT / "tools" +for entry in (RUNTIME_ROOT, TOOLS_ROOT): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from scripture_archive_runtime.application import RuntimeApplication +from scripture_archive_runtime.content import ContentRepository +from scripture_archive_runtime.content_packs import ( + CONTENT_PACK_SCHEMA, + CONTENT_SCHEMA_VERSION, + MANIFEST_NAME, + ContentPackStore, + inspect_content_pack, +) +from scripture_archive_runtime.grading import GraderRegistry +from scripture_archive_runtime.models import Correctness +from scripture_archive_runtime.provenance import canonical_answer_dto, classify_provenance +from scripture_archive_runtime.security import ValidationError +from validate_dev2_evidence_bundle import validate_bundle as validate_composed_evidence + +SCHEMA = "R06_D2_CORRECTED_RUNTIME_PREINTEGRATION_v1" +AUTHORITY_SCHEMA = "R06_D2_CORRECTED_NODE_HASH_INDEX_v1" +EXPECTED_NODE_COUNT = 386 +EXPECTED_EVIDENCE_COUNT = 184 +EXPECTED_NODE_AGGREGATE = "ef77ae5d822e105050dedfa9a460325259fe079701ca69f385693aabcad0e661" +EXPECTED_EVIDENCE_AGGREGATE = "88e197fd1c91b7787040e81bdd066d959d42b8ba64ac01acac667ffd8ad346ba" +EXPECTED_STAGING_ZIP = "b681ea26d985eb754bde02a77254d40ab0920061edb9226fae7921a6740a06c0" +EXPECTED_MISSION_COUNTS = { + "PA-03": 53, + "PA-04": 63, + "PA-05": 61, + "PA-06": 43, + "PA-07": 61, + "PA-08": 105, +} +EXPECTED_PARTS = tuple(f"nodes/part_{index:03d}.jsonl" for index in range(1, 27)) +PACKAGE_EVIDENCE_REL = ( + "evidence/part_001.jsonl", + "evidence/part_002.jsonl", + "evidence/part_003.jsonl", + "evidence_hash_index.json", + "mission_metadata.json", +) +PACK_ID = "r06-d2-paul-acts-preintegration" +PACK_VERSION = "0.6.0-d2pre.1" +EXPECTED_STRUCTURED_WITNESS_COUNT = 11 +PARALLEL_WITNESS_FALLBACK_REASON = ( + "DEV5 pre-integration runtime lacks PARALLEL_WITNESS_COMPARE grader; " + "preserve structured canonical comparison and use text fallback only for compatibility testing." +) + + +class CompatibilityError(ValueError): + pass + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _canonical_bytes(value: Any) -> bytes: + return json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + +def _load_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise CompatibilityError(f"cannot load JSON {path}: {exc}") from exc + + +def _require_regular(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_file(): + raise CompatibilityError(f"missing or unsafe regular file: {label}") + + +def _reject_symlinks(root: Path) -> None: + if root.is_symlink() or not root.is_dir(): + raise CompatibilityError(f"missing or unsafe authority root: {root}") + for path in root.rglob("*"): + if path.is_symlink(): + raise CompatibilityError( + f"symlink forbidden in authority snapshot: {path.relative_to(root)}" + ) + + +def _load_evidence_ids(authority_root: Path) -> set[str]: + index = _load_json(authority_root / "evidence_hash_index.json") + if not isinstance(index, Mapping): + raise CompatibilityError("evidence_hash_index.json must be an object") + if index.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence record_count changed") + if index.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("evidence aggregate changed") + records = index.get("records") + if not isinstance(records, list): + raise CompatibilityError("evidence index records must be a list") + ids: set[str] = set() + for row in records: + if not isinstance(row, Mapping): + raise CompatibilityError("evidence index row must be an object") + evidence_id = row.get("id") + digest = row.get("sha256") + if not isinstance(evidence_id, str) or not evidence_id: + raise CompatibilityError("invalid evidence id") + if evidence_id in ids: + raise CompatibilityError(f"duplicate evidence id: {evidence_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid evidence SHA256: {evidence_id}") + ids.add(evidence_id) + if len(ids) != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence ID cardinality changed") + return ids + + +def load_corrected_nodes(authority_root: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]: + _reject_symlinks(authority_root) + index = _load_json(authority_root / "D2_CORRECTED_NODE_HASH_INDEX.json") + if not isinstance(index, Mapping): + raise CompatibilityError("corrected node hash index must be an object") + if index.get("schema") != AUTHORITY_SCHEMA: + raise CompatibilityError("unexpected corrected node hash-index schema") + if index.get("record_count") != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected node record_count changed") + if index.get("aggregate_sha256") != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError("corrected node aggregate changed") + if index.get("historical_staging_zip_sha256") != EXPECTED_STAGING_ZIP: + raise CompatibilityError("historical staging provenance pin changed") + if index.get("source_truth_changed") is not False: + raise CompatibilityError("corrected authority claims source-truth mutation") + if "INDEPENDENT_AUDIT_PENDING" not in str(index.get("status", "")): + raise CompatibilityError("corrected authority improperly promotes audit status") + if index.get("mission_counts") != EXPECTED_MISSION_COUNTS: + raise CompatibilityError( + f"corrected authority mission_counts changed: {index.get('mission_counts')}" + ) + + rows = index.get("records") + if not isinstance(rows, list): + raise CompatibilityError("corrected index records must be a list") + + expected: dict[str, tuple[str, str]] = {} + indexed_parts: set[str] = set() + for row in rows: + if not isinstance(row, Mapping): + raise CompatibilityError("corrected index row must be an object") + node_id = row.get("id") + digest = row.get("sha256") + part = row.get("part") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError("corrected index row has invalid id") + if node_id in expected: + raise CompatibilityError(f"duplicate corrected index node: {node_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid corrected SHA256: {node_id}") + if part not in EXPECTED_PARTS: + raise CompatibilityError(f"unexpected corrected part for {node_id}: {part}") + expected[node_id] = (digest.casefold(), str(part)) + indexed_parts.add(str(part)) + + if len(expected) != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected index unique-node count changed") + if indexed_parts != set(EXPECTED_PARTS): + raise CompatibilityError("corrected index does not cover all 26 canonical parts") + + nodes: dict[str, dict[str, Any]] = {} + mission_counts: Counter[str] = Counter() + for part in EXPECTED_PARTS: + path = authority_root / part + _require_regular(path, part) + for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + try: + node = json.loads(line) + except json.JSONDecodeError as exc: + raise CompatibilityError(f"invalid node JSONL at {part}:{line_number}") from exc + if not isinstance(node, dict): + raise CompatibilityError(f"node at {part}:{line_number} must be an object") + node_id = node.get("node_id") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError(f"node at {part}:{line_number} has invalid node_id") + if node_id in nodes: + raise CompatibilityError(f"duplicate corrected node_id: {node_id}") + indexed = expected.get(node_id) + if indexed is None: + raise CompatibilityError(f"unindexed corrected node: {node_id}") + digest = _sha256_bytes(_canonical_bytes(node)) + if digest != indexed[0]: + raise CompatibilityError(f"corrected record SHA256 mismatch: {node_id}") + if indexed[1] != part: + raise CompatibilityError(f"corrected part mismatch: {node_id}") + mission_id = node.get("mission_id") + if mission_id not in EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"unexpected D2 mission_id: {mission_id}") + mission_counts[str(mission_id)] += 1 + nodes[node_id] = node + + if set(nodes) != set(expected): + missing = sorted(set(expected) - set(nodes)) + extra = sorted(set(nodes) - set(expected)) + raise CompatibilityError( + f"corrected node ID set mismatch missing={missing[:5]} extra={extra[:5]}" + ) + if dict(sorted(mission_counts.items())) != EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"mission node counts changed: {dict(mission_counts)}") + + aggregate = _sha256_bytes( + "".join( + f"{node_id}\t{_sha256_bytes(_canonical_bytes(nodes[node_id]))}\n" + for node_id in sorted(nodes) + ).encode("utf-8") + ) + if aggregate != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError(f"recomputed corrected aggregate mismatch: {aggregate}") + + return [nodes[node_id] for node_id in sorted(nodes)], dict(index) + + +def _verify_evidence_binding( + nodes: Iterable[Mapping[str, Any]], + *, + authority_root: Path, + repo_root: Path, +) -> tuple[int, dict[str, Any]]: + evidence_ids = _load_evidence_ids(authority_root) + missing: list[tuple[str, str]] = [] + for node in nodes: + required = node.get("required_evidence") + if not isinstance(required, list) or not all(isinstance(value, str) for value in required): + raise CompatibilityError(f"{node.get('node_id')}: invalid required_evidence") + for evidence_id in required: + if evidence_id not in evidence_ids: + missing.append((str(node.get("node_id")), evidence_id)) + if missing: + raise CompatibilityError(f"nodes reference unknown evidence IDs: {missing[:10]}") + + package_root = repo_root / "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05" + for rel in PACKAGE_EVIDENCE_REL: + authority_path = authority_root / rel + package_path = package_root / rel + _require_regular(authority_path, f"authority/{rel}") + _require_regular(package_path, f"package/{rel}") + if authority_path.read_bytes() != package_path.read_bytes(): + raise CompatibilityError(f"current-package evidence drift: {rel}") + + evidence_report = validate_composed_evidence(repo_root) + if evidence_report.get("status") != "PASS": + raise CompatibilityError("current-package D2 evidence validator did not PASS") + if evidence_report.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("current-package evidence count changed") + if evidence_report.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("current-package evidence aggregate changed") + if evidence_report.get("independent_audit") != "PENDING": + raise CompatibilityError("current-package evidence audit status was promoted") + return len(evidence_ids), evidence_report + + +def _project_nodes_for_current_runtime( + nodes: Iterable[Mapping[str, Any]], +) -> tuple[list[dict[str, Any]], list[str]]: + """Validate structured D2 truth and return an exact deep-copy runtime view. + + No compatibility downgrade is allowed here. Structured parallel-witness + nodes must remain structured so this gate exercises the actual current + runtime contract introduced by the package candidate. + """ + projected: list[dict[str, Any]] = [] + structured_node_ids: list[str] = [] + expected_fields = {"synthesis": "string", "witnesses": "array[passage]"} + allowed_contract_kinds = {"witness_compare", "parallel_witness_compare"} + + for source in nodes: + node = copy.deepcopy(dict(source)) + if str(node.get("task_type") or "") != "PARALLEL_WITNESS_COMPARE": + projected.append(node) + continue + + node_id = str(node.get("node_id") or "") + accepted = node.get("accepted_answer") + if not isinstance(accepted, Mapping) or set(accepted) != {"synthesis", "witnesses"}: + raise CompatibilityError( + f"{node_id}: PARALLEL_WITNESS_COMPARE requires structured synthesis+witnesses authority" + ) + synthesis = accepted.get("synthesis") + witnesses = accepted.get("witnesses") + if not isinstance(synthesis, str) or not synthesis.strip(): + raise CompatibilityError(f"{node_id}: structured synthesis must be non-empty string") + if ( + not isinstance(witnesses, list) + or not witnesses + or not all(isinstance(value, str) and value.strip() for value in witnesses) + ): + raise CompatibilityError(f"{node_id}: structured witnesses must be a non-empty string list") + + contract = node.get("response_contract") + dto = contract.get("answer_dto") if isinstance(contract, Mapping) else None + if ( + not isinstance(contract, Mapping) + or contract.get("kind") not in allowed_contract_kinds + or not isinstance(dto, Mapping) + or dto.get("shape") != "object" + or dto.get("fields") != expected_fields + ): + raise CompatibilityError(f"{node_id}: structured witness response_contract changed") + + variants = node.get("accepted_variants") + grading = node.get("grading") + if ( + not isinstance(variants, Mapping) + or variants.get("witnesses") != witnesses + or not isinstance(variants.get("synthesis_aliases"), list) + or synthesis not in variants.get("synthesis_aliases", []) + or not isinstance(grading, Mapping) + or grading.get("required_witnesses") != witnesses + ): + raise CompatibilityError(f"{node_id}: structured witness truth bindings changed") + + # The authority still carries historical fallback metadata as provenance + # of the pre-integration period. Verify it exactly, but do not execute it. + fallback = node.get("runtime_fallback") + if ( + not isinstance(fallback, Mapping) + or set(fallback) != {"accepted_answer", "reason", "task_type"} + or fallback.get("task_type") != "LONG_TEXT" + or fallback.get("accepted_answer") != synthesis + or fallback.get("reason") != PARALLEL_WITNESS_FALLBACK_REASON + ): + raise CompatibilityError(f"{node_id}: historical runtime_fallback metadata changed") + + projected.append(node) + structured_node_ids.append(node_id) + + return projected, sorted(structured_node_ids) + + +def _runtime_compatibility( + nodes: list[dict[str, Any]], + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: + runtime_nodes, structured_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(structured_node_ids) != EXPECTED_STRUCTURED_WITNESS_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_STRUCTURED_WITNESS_COUNT} structured parallel-witness nodes, got {len(structured_node_ids)}" + ) + try: + repository = ContentRepository(runtime_nodes, adapt_legacy=True, lane="D2") + except (ValidationError, ValueError, TypeError) as exc: + raise CompatibilityError(f"current runtime rejected corrected D2 corpus: {exc}") from exc + tasks = repository.all() + if len(tasks) != expected_node_count: + raise CompatibilityError("runtime repository did not retain expected nodes") + + grader = GraderRegistry() + app = RuntimeApplication(repository) + provenance_counts: Counter[str] = Counter() + self_grade_failures: list[str] = [] + runtime_load_failures: list[str] = [] + structured_runtime_ids: list[str] = [] + + for node_id in sorted(tasks): + task = tasks[node_id] + decision = classify_provenance(task.raw) + provenance_counts[decision.provenance_class] += 1 + if not decision.release_pass: + raise CompatibilityError( + f"{node_id}: current runtime provenance rejects corrected node: {decision.reason}" + ) + if node_id in structured_node_ids: + if task.task_type != "PARALLEL_WITNESS_SYNTHESIS": + raise CompatibilityError( + f"{node_id}: structured witness authority did not derive PARALLEL_WITNESS_SYNTHESIS" + ) + structured_runtime_ids.append(node_id) + try: + answer = canonical_answer_dto(task.raw) + result = grader.grade(task, answer) + except Exception as exc: + raise CompatibilityError(f"{node_id}: self-grade raised {type(exc).__name__}: {exc}") from exc + if result.correctness is not Correctness.CORRECT or result.score != 1.0: + self_grade_failures.append(node_id) + try: + response = app.load_task(node_id) + rendered = response.get("task", {}) + if rendered.get("node_id") != node_id: + runtime_load_failures.append(node_id) + if not str(rendered.get("functional_nonvisual_equivalent", "")).strip(): + runtime_load_failures.append(node_id) + except Exception as exc: + raise CompatibilityError(f"{node_id}: runtime load raised {type(exc).__name__}: {exc}") from exc + + if self_grade_failures: + raise CompatibilityError(f"runtime self-grade failed: {self_grade_failures[:10]}") + if runtime_load_failures: + raise CompatibilityError(f"runtime task render failed: {runtime_load_failures[:10]}") + if sorted(structured_runtime_ids) != structured_node_ids: + raise CompatibilityError("structured runtime node set drifted") + + return { + "repository_nodes": len(tasks), + "self_grade_correct": expected_node_count, + "runtime_load_pass": expected_node_count, + "provenance_classes": dict(sorted(provenance_counts.items())), + "structured_witness_node_ids": structured_node_ids, + "structured_witness_count": len(structured_node_ids), + "runtime_fallback_node_ids": [], + "runtime_fallback_count": 0, + } + + +def _json_bytes(value: Any) -> bytes: + return ( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + + +def write_preintegration_pack( + nodes: list[dict[str, Any]], + destination: Path, + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: + destination = destination.expanduser().resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + runtime_nodes, structured_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(structured_node_ids) != EXPECTED_STRUCTURED_WITNESS_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_STRUCTURED_WITNESS_COUNT} structured parallel-witness nodes, got {len(structured_node_ids)}" + ) + payload = _json_bytes({"nodes": runtime_nodes}) + payload_name = "content/nodes.json" + manifest = { + "schema": CONTENT_PACK_SCHEMA, + "pack_id": PACK_ID, + "version": PACK_VERSION, + "content_schema_version": CONTENT_SCHEMA_VERSION, + "entry_points": [payload_name], + "files": {payload_name: _sha256_bytes(payload)}, + } + manifest_bytes = _json_bytes(manifest) + with zipfile.ZipFile( + destination, + "w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=9, + ) as archive: + for name, data in ((MANIFEST_NAME, manifest_bytes), (payload_name, payload)): + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = (stat.S_IFREG | 0o644) << 16 + archive.writestr(info, data) + + inspection = inspect_content_pack(destination) + if inspection.node_count != expected_node_count: + raise CompatibilityError("content-pack inspector did not see expected nodes") + if inspection.manifest.pack_id != PACK_ID or inspection.manifest.version != PACK_VERSION: + raise CompatibilityError("content-pack identity drifted") + + with tempfile.TemporaryDirectory() as temp: + store = ContentPackStore(Path(temp) / "store") + installed = store.install(destination) + if installed.node_count != expected_node_count: + raise CompatibilityError("content-pack store install lost expected nodes") + store.activate(PACK_ID, PACK_VERSION) + if store.active_versions().get(PACK_ID) != PACK_VERSION: + raise CompatibilityError("content-pack activation did not select D2 preintegration pack") + installed_payload = ( + Path(temp) + / "store" + / "packs" + / PACK_ID + / PACK_VERSION + / payload_name + ) + roundtrip = ContentRepository.from_json_files( + [installed_payload], + adapt_legacy=True, + lane="D2", + ) + roundtrip_nodes = roundtrip.all() + if len(roundtrip_nodes) != expected_node_count: + raise CompatibilityError("installed content pack runtime reload lost expected nodes") + for node_id in structured_node_ids: + if roundtrip_nodes[node_id].task_type != "PARALLEL_WITNESS_SYNTHESIS": + raise CompatibilityError( + f"{node_id}: installed pack lost structured parallel-witness contract" + ) + + return { + "pack_id": PACK_ID, + "version": PACK_VERSION, + "archive_sha256": _sha256_bytes(destination.read_bytes()), + "payload_sha256": manifest["files"][payload_name], + "node_count": inspection.node_count, + "file_count": inspection.file_count, + "structured_witness_node_ids": structured_node_ids, + "structured_witness_count": len(structured_node_ids), + "runtime_fallback_node_ids": [], + "runtime_fallback_count": 0, + } + + +def run(authority_root: Path, pack_out: Path) -> dict[str, Any]: + authority_root = authority_root.expanduser().resolve() + nodes, index = load_corrected_nodes(authority_root) + evidence_count, evidence_report = _verify_evidence_binding( + nodes, + authority_root=authority_root, + repo_root=REPO_ROOT, + ) + runtime_report = _runtime_compatibility(nodes) + pack_report = write_preintegration_pack(nodes, pack_out) + return { + "schema": SCHEMA, + "status": "COMPATIBILITY_PASS / PROMOTION_BLOCKED", + "authority": { + "node_count": len(nodes), + "corrected_node_aggregate_sha256": index["aggregate_sha256"], + "evidence_count": evidence_count, + "evidence_aggregate_sha256": evidence_report["aggregate_sha256"], + "historical_staging_zip_sha256": EXPECTED_STAGING_ZIP, + "source_truth_changed": False, + "independent_audit": "PENDING", + }, + "current_package_runtime": runtime_report, + "preintegration_content_pack": pack_report, + "promotion_allowed": False, + "promotion_blockers": [ + "final-head D2 hosted qualification must be terminal green", + "independent D2 QA verdict must be recorded", + "current-package composition must occur on its canonical lineage after those gates", + ], + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--authority-root", type=Path, required=True) + parser.add_argument("--pack-out", type=Path, required=True) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + try: + report = run(args.authority_root, args.pack_out) + except (CompatibilityError, ValidationError) as exc: + failure = {"schema": SCHEMA, "status": "FAIL", "error": str(exc)} + payload = json.dumps(failure, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="", file=sys.stderr) + return 1 + payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 907b6b7bc..b3187e61d 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -20,7 +20,7 @@ CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" EXPECTED_LIBRARY_SEARCH_TESTS = 6 -EXPECTED_WEBU_PROVIDER_TESTS = 9 +EXPECTED_WEBU_PROVIDER_TESTS = 10 EXPECTED_D4_READ_ONLY_TESTS = 13 OVERLAY_FIDELITY_PATHS = ( Path("frontend/scripture-reader-ui.js"), @@ -172,6 +172,14 @@ def compose_real_platform(temp_root: Path) -> Path: if workflow_target.read_bytes() != source_authority_workflow.read_bytes(): raise AssertionError("Candidate WEBU source-authority workflow fidelity mismatch") + accessibility_workflow = ROOT / ".github" / "workflows" / "r06-dev02-accessibility-qualification.yml" + if accessibility_workflow.is_symlink() or not accessibility_workflow.is_file(): + raise AssertionError("Candidate DEV02 accessibility workflow is missing or unsafe") + accessibility_target = composed_repo_root / ".github" / "workflows" / "r06-dev02-accessibility-qualification.yml" + shutil.copy2(accessibility_workflow, accessibility_target) + if accessibility_target.read_bytes() != accessibility_workflow.read_bytes(): + raise AssertionError("Candidate DEV02 accessibility workflow fidelity mismatch") + shutil.copytree(OVERLAY, platform_root, dirs_exist_ok=True) for relative in OVERLAY_FIDELITY_PATHS: @@ -291,8 +299,8 @@ def main() -> None: print( "Library/Search qualification PASS: exact candidate checkout, pinned canonical " "FINALPREP02 DEV1 base hash/CRC, exact candidate repository-level .gitattributes " - "and WEBU source-authority workflow fidelity, overlay fidelity, six real " - "Library/Search regressions, nine real WEBU provider regressions, and thirteen " + "WEBU source-authority and DEV02 accessibility workflow fidelity, overlay fidelity, six real " + "Library/Search regressions, ten real WEBU provider regressions, and thirteen " "real qualified-D4 read-only/runtime-eligibility/hash/mission-authority regressions." )