diff --git a/.github/workflows/r06-constructor-v2-direct-qualification.yml b/.github/workflows/r06-constructor-v2-direct-qualification.yml new file mode 100644 index 000000000..7c43eed85 --- /dev/null +++ b/.github/workflows/r06-constructor-v2-direct-qualification.yml @@ -0,0 +1,129 @@ +name: R06 Constructor V2 Direct Qualification + +on: + pull_request: + paths: + - 'lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js' + - 'lanes/dev1/repair_overlay/frontend/transport.js' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/authoring/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' + - 'lanes/dev1/repair_overlay/tests/test_authoring_transport.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py' + - '.github/workflows/r06-constructor-v2-direct-qualification.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-constructor-v2-direct-${{ github.ref }} + cancel-in-progress: true + +jobs: + constructor-v2-direct-overlay: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + pathsep: ':' + - os: windows-latest + pathsep: ';' + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + PYTHONPATH: "${{ github.workspace }}/r06_platform${{ matrix.pathsep }}${{ github.workspace }}" + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Reconstruct verified Constructor dependency substrate and apply overlay + shell: bash + run: | + python - <<'PY' + import base64, hashlib, shutil, zipfile + from pathlib import Path, PurePosixPath + + parts = sorted(Path('lanes/dev1/source_parts').glob('part-*.b64')) + if not parts: + raise SystemExit('missing DEV1 source parts') + encoded = ''.join(path.read_text(encoding='ascii') for path in parts) + archive_bytes = base64.b64decode(encoded) + archive = Path('DEV1_R06_PLATFORM_SOURCE_CONSTRUCTOR_SUBSTRATE.zip') + archive.write_bytes(archive_bytes) + print('exact-head source-parts sha256=', hashlib.sha256(archive_bytes).hexdigest()) + + # Shared DEV1 release qualification owns whole-archive fidelity (#146). + # Constructor qualification needs the Python platform dependency subtree + # plus the canonical test fixture used by the transport regression. + # CRC-verify every extracted dependency and fail closed on corruption in + # those dependencies; unrelated corrupt members are not evidence for or + # against this bounded Constructor qualification and remain #146-owned. + platform_prefix = PurePosixPath('r06_platform/scripture_archive_platform') + exact_dependencies = {PurePosixPath('r06_platform/tests/_fixture.py')} + extracted = 0 + with zipfile.ZipFile(archive) as zf: + for info in zf.infolist(): + member = PurePosixPath(info.filename) + wanted = ( + member == platform_prefix + or platform_prefix in member.parents + or member in exact_dependencies + ) + if not wanted: + continue + try: + zf.extract(info, '.') + except (zipfile.BadZipFile, OSError) as exc: + raise SystemExit(f'corrupt Constructor dependency member {info.filename}: {exc}') from exc + extracted += 1 + if extracted == 0: + raise SystemExit('DEV1 source parts contain no Constructor dependency subtree') + + root = Path('r06_platform') + required = [ + root / 'scripture_archive_platform' / 'persistence' / 'store.py', + root / 'scripture_archive_platform' / 'content' / 'loader.py', + root / 'scripture_archive_platform' / 'domain' / 'registries.py', + root / 'tests' / '_fixture.py', + ] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise SystemExit('Constructor dependency substrate missing: ' + ', '.join(missing)) + shutil.copytree('lanes/dev1/repair_overlay', root, dirs_exist_ok=True) + PY + - name: Compile composed Constructor V2 surface + run: >- + python -m compileall -q + r06_platform/scripture_archive_platform/authoring + r06_platform/scripture_archive_platform/application/service.py + r06_platform/scripture_archive_platform/transport/contracts.py + r06_platform/tests/test_constructor_v2_lifecycle.py + r06_platform/tests/test_constructor_v2_recovery_atomicity.py + r06_platform/tests/test_authoring_transport.py + - name: Run Constructor V2 lifecycle regression + run: python r06_platform/tests/test_constructor_v2_lifecycle.py + - name: Run Constructor V2 crash-recovery regression + run: python r06_platform/tests/test_constructor_v2_recovery_atomicity.py + - name: Run Constructor V2 allowlist and source-isolation regression + run: python r06_platform/tests/test_authoring_transport.py + - name: Run Constructor V2 semantic frontend regression + run: python r06_platform/tests/test_constructor_v2_frontend.py + - name: Verify Constructor V2 frontend module syntax + run: node --check r06_platform/frontend/constructor-v2-ui.js + - name: Diff hygiene + shell: bash + run: git diff --check diff --git a/.github/workflows/r06-content-pack-atomic-install-qualification.yml b/.github/workflows/r06-content-pack-atomic-install-qualification.yml new file mode 100644 index 000000000..1afd3677c --- /dev/null +++ b/.github/workflows/r06-content-pack-atomic-install-qualification.yml @@ -0,0 +1,37 @@ +name: R06 Content Pack Atomic Install Qualification + +on: + pull_request: + paths: + - "runtime_engine/scripture_archive_runtime/content_pack_store.py" + - "runtime_engine/tests/test_content_pack_store.py" + - ".github/workflows/r06-content-pack-atomic-install-qualification.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-content-pack-atomic-${{ github.ref }} + cancel-in-progress: true + +jobs: + content-pack-atomic-install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + defaults: + run: + working-directory: runtime_engine + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Compile content-pack runtime and tests + run: python -m compileall -q scripture_archive_runtime tests/test_content_packs.py tests/test_content_pack_store.py + - name: Run content-pack atomic install regressions + run: python -m unittest discover -s tests -p "test_content_pack_store.py" -v diff --git a/.github/workflows/r06-packaged-library-current-shell.yml b/.github/workflows/r06-packaged-library-current-shell.yml index bb4cb3239..95be4186c 100644 --- a/.github/workflows/r06-packaged-library-current-shell.yml +++ b/.github/workflows/r06-packaged-library-current-shell.yml @@ -7,21 +7,30 @@ on: - 'lanes/dev1/repair_overlay/frontend/transport.js' - 'lanes/dev1/repair_overlay/frontend/library-ui.js' - 'lanes/dev1/repair_overlay/frontend/library-shell-compat.js' + - 'lanes/dev1/repair_overlay/frontend/library-research-persistence.js' - 'lanes/dev1/repair_overlay/frontend/daily-case-ui.js' - 'lanes/dev1/repair_overlay/frontend/chronology-lab-ui.js' - 'lanes/dev1/repair_overlay/frontend/content-pack-manager.js' - 'lanes/dev1/repair_overlay/frontend/evidence-graph-ui.js' - 'lanes/dev1/repair_overlay/frontend/witness-matrix-ui.js' + - 'lanes/dev1/repair_overlay/frontend/review-queue-ui.js' - 'lanes/dev1/repair_overlay/frontend/research-export.js' - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/runtime_gateway.py' - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py' - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/runtime_compat.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_library_research_persistence.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_chronology_lab.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_transport_composition.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_witness_matrix_contract.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_witness_matrix_lifecycle.py' - 'lanes/dev1/repair_overlay/tests/test_research_export_current_shell.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_review_queue_ui.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_review_training_contract.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_review_training_player_ui.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_review_training_transport.py' - '.github/workflows/r06-packaged-library-current-shell.yml' workflow_dispatch: @@ -37,6 +46,7 @@ jobs: runs-on: ${{ matrix.os }} env: EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + PYTHONPATH: ${{ github.workspace }} steps: - uses: actions/checkout@v4 with: @@ -52,6 +62,8 @@ jobs: run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - name: Run packaged Library current-shell regression run: python lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py + - name: Run packaged Library bookmarks/notes regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_library_research_persistence.py - name: Run packaged Chronology Lab regression run: python lanes/dev1/repair_overlay/tests/test_packaged_chronology_lab.py - name: Run packaged transport composition regression @@ -60,6 +72,16 @@ jobs: run: python lanes/dev1/repair_overlay/tests/test_packaged_witness_matrix_lifecycle.py - name: Run packaged Research Export current-shell regression run: python lanes/dev1/repair_overlay/tests/test_research_export_current_shell.py + - name: Run packaged Review Queue regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_review_queue_ui.py + - name: Run packaged Review Training contract regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_review_training_contract.py + - name: Run packaged Review Training player UI regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_review_training_player_ui.py + - name: Run packaged Review Training transport regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_review_training_transport.py + - name: Run packaged Review Training syntax regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_review_training_static_syntax.py - name: Diff hygiene shell: bash run: git diff --check diff --git a/.github/workflows/r06-packaged-speech-direct-qualification.yml b/.github/workflows/r06-packaged-speech-direct-qualification.yml new file mode 100644 index 000000000..5c8db193e --- /dev/null +++ b/.github/workflows/r06-packaged-speech-direct-qualification.yml @@ -0,0 +1,113 @@ +name: R06 Packaged Speech Direct Qualification + +on: + pull_request: + paths: + - 'runtime_engine/scripture_archive_runtime/speech.py' + - 'lanes/dev1/repair_overlay/frontend/speech-ui.js' + - 'lanes/dev1/repair_overlay/frontend/transport.js' + - 'lanes/dev1/repair_overlay/run_web_mock.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/speech_application.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_speech.py' + - '.github/workflows/r06-packaged-speech-direct-qualification.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-packaged-speech-direct-${{ github.ref }} + cancel-in-progress: true + +jobs: + packaged-speech-direct-overlay: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + pathsep: ':' + - os: windows-latest + pathsep: ';' + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + PYTHONPATH: "${{ github.workspace }}/r06_platform${{ matrix.pathsep }}${{ github.workspace }}" + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Reconstruct verified speech dependency substrate and apply overlay + shell: bash + run: | + python - <<'PY' + import base64, shutil, zipfile + from pathlib import Path, PurePosixPath + + parts = sorted(Path('lanes/dev1/source_parts').glob('part-*.b64')) + if not parts: + raise SystemExit('missing DEV1 source parts') + archive_bytes = base64.b64decode(''.join(path.read_text(encoding='ascii') for path in parts)) + archive = Path('DEV1_R06_PLATFORM_SOURCE_SPEECH_SUBSTRATE.zip') + archive.write_bytes(archive_bytes) + + # Whole-archive release fidelity remains owned by #146. This bounded + # gate CRC-verifies only the Python platform dependency subtree and + # canonical test fixture required to execute speech composition tests. + platform_prefix = PurePosixPath('r06_platform/scripture_archive_platform') + exact_dependencies = {PurePosixPath('r06_platform/tests/_fixture.py')} + extracted = 0 + with zipfile.ZipFile(archive) as zf: + for info in zf.infolist(): + member = PurePosixPath(info.filename) + wanted = member == platform_prefix or platform_prefix in member.parents or member in exact_dependencies + if not wanted: + continue + try: + zf.extract(info, '.') + except (zipfile.BadZipFile, OSError) as exc: + raise SystemExit(f'corrupt speech dependency member {info.filename}: {exc}') from exc + extracted += 1 + if extracted == 0: + raise SystemExit('DEV1 source parts contain no speech dependency subtree') + + root = Path('r06_platform') + required = [ + root / 'scripture_archive_platform' / 'persistence' / 'store.py', + root / 'scripture_archive_platform' / 'content' / 'loader.py', + root / 'scripture_archive_platform' / 'application' / 'service.py', + root / 'tests' / '_fixture.py', + ] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise SystemExit('speech dependency substrate missing: ' + ', '.join(missing)) + shutil.copytree('lanes/dev1/repair_overlay', root, dirs_exist_ok=True) + PY + - name: Compile packaged speech composition + run: >- + python -m compileall -q + r06_platform/scripture_archive_platform/application/speech_application.py + r06_platform/scripture_archive_platform/transport/contracts.py + r06_platform/scripture_archive_platform/desktop_host/main.py + r06_platform/tests/test_packaged_speech.py + - name: Run packaged speech security and composition regression + run: python r06_platform/tests/test_packaged_speech.py + - name: Verify speech frontend module syntax + run: node --check r06_platform/frontend/speech-ui.js + - name: Verify transport frontend module syntax + run: node --check r06_platform/frontend/transport.js + - name: Diff hygiene + shell: bash + run: git diff --check diff --git a/.github/workflows/r06-pedagogical-quality.yml b/.github/workflows/r06-pedagogical-quality.yml new file mode 100644 index 000000000..c126cab7a --- /dev/null +++ b/.github/workflows/r06-pedagogical-quality.yml @@ -0,0 +1,46 @@ +name: R06 Pedagogical Quality Inventory + +on: + pull_request: + paths: + - 'docs/campaigns/**' + - 'tools/analyze_pedagogical_quality.py' + - 'tools/test_analyze_pedagogical_quality.py' + - 'docs/spec/PEDAGOGICAL_QUALITY_GATE_v1.md' + - '.github/workflows/r06-pedagogical-quality.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-pedagogy-${{ github.ref }} + cancel-in-progress: true + +jobs: + pedagogical-quality: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.13' + - name: Compile analyzer and tests + run: python -m compileall -q tools/analyze_pedagogical_quality.py tools/test_analyze_pedagogical_quality.py + - name: Run analyzer regressions + run: python -m unittest -v tools.test_analyze_pedagogical_quality + - name: Inventory canonical pedagogical quality + run: >- + python tools/analyze_pedagogical_quality.py docs/campaigns + --json-output pedagogical-quality-report.json + --markdown-output pedagogical-quality-report.md + --fail-on none + - name: Upload review report + uses: actions/upload-artifact@v4 + with: + name: R06-pedagogical-quality-report + path: | + pedagogical-quality-report.json + pedagogical-quality-report.md + if-no-files-found: error diff --git a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_01.json b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_01.json index 42287d1d1..1f91c3c2a 100644 --- a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_01.json +++ b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_01.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":1,"nodes":[{"node_id":"LN04-N01","mission_id":"LN-04","task_family":"source selection","difficulty":"1/6","required":true,"skill_target":"source delimitation","knowledge_target":"four Peter-warning passages","why_this_node_exists":"prevents solving from a remembered harmonized story rather than the assigned witnesses.","player_prompt":"Оберіть чотири уривки, які треба зіставити, щоб дослідити попередження Петрові перед зреченням.","source_scope_visible_to_player":"New Testament Gospel references.","response_mode":"citation selection","accepted_answer":"Matthew 26:30–35; Mark 14:26–31; Luke 22:31–34; John 13:36–38.","accepted_variants":"citation ranges that include the same scene without replacing a primary witness.","required_evidence":"all four primary passages.","rejected_answers":"using later denial narratives as substitutes for prediction passages.","rejection_reason":"LN-04 investigates the prediction; fulfilment evidence is reserved for later retrieval and LN-09.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Корпус зібрано. Тепер кожне твердження має бути прив'язане до конкретного свідка.","partial_feedback":"Якщо знайдено три з чотирьох, система називає відсутнє Євангеліє, але не дає точного діапазону до наступної підказки.","failure_feedback":"Не переходьте одразу до сцени зречення. Спочатку встановіть, що саме було передбачено.","hints":{"H1":"not_used","H2":"Назвіть чотири Євангелія.","H3":"Зосередьтеся на Мт 26, Мк 14, Лк 22, Ів 13.","H4":"not_used","H5":"not_used","H6":"Mt 26:30–35; Mk 14:26–31; Lk 22:31–34; Jn 13:36–38.","H7":"not_used"},"on_correct":"LN04-N02","on_partial":"return_to_current_node_missing_witness_only","on_incorrect":"return_to_current_node_after_scene_boundary_reminder","on_hint_threshold":"guided_then_LN04-N02","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N02","mastery_domains":["source-citation","witness-provenance"],"evidence_strength":["recognition","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear labelled citation checklist; keyboard-complete; selected-count and each checkbox state announced."},{"node_id":"LN04-N02","mission_id":"LN-04","task_family":"parallel comparison","difficulty":"2/6","required":true,"skill_target":"extract common core without over-harmonizing","knowledge_target":"three denials before rooster marker","why_this_node_exists":"establishes the minimum proposition supported by all four passages.","player_prompt":"Яке попередження про Петра є спільним для Матвія, Марка, Луки та Івана?","source_scope_visible_to_player":"all four primary passages.","response_mode":"free response","accepted_answer":"Ісус передбачає, що Петро тричі зречеться/відречеться від Нього (у Луки — тричі заперечить, що знає Його) до співу півня.","accepted_variants":"semantic equivalents preserving Peter + three denials + rooster-before/rooster marker.","required_evidence":"Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38.","rejected_answers":"«Усі чотири кажуть, що півень заспіває двічі»; «усі чотири містять наказ зміцнити братів».","rejection_reason":"those details are witness-specific.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Спільне ядро вузьке й сильне: Петро буде тричі заперечувати свою належність/знання Ісуса до визначеного ранкового маркера.","partial_feedback":"Якщо названо три зречення без співу півня, попросити додати часовий маркер.","failure_feedback":"Порівняйте лише речення з самим передбаченням у кожному Євангелії.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Шукайте число та часовий знак.","H5":"not_used","H6":"Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38.","H7":"not_used"},"on_correct":"LN04-N03","on_partial":"return_to_current_node_for_missing_element","on_incorrect":"return_to_current_node_after_prediction_verse_isolation","on_hint_threshold":"guided_then_LN04-N03","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N01","mastery_domains":["Gospel-parallels","prediction"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Four passages presented sequentially under witness headings; free-response field remains reachable without a visual parallel-column layout."},{"node_id":"LN04-N03","mission_id":"LN-04","task_family":"witness-detail comparison","difficulty":"2/6","required":true,"skill_target":"distinguish group warning from Peter-specific warning","knowledge_target":"Matthew/Mark scattering warning","why_this_node_exists":"prevents treating the Peter prediction as the only warning in the scene.","player_prompt":"Які два Євангелія в досліджуваному корпусі прямо містять попередження, що всі учні відступлять/розсіються, і з яким старозавітним образом це пов'язано?","source_scope_visible_to_player":"Mt 26:31–32; Mk 14:27–28.","response_mode":"comparison + citation","accepted_answer":"Matthew and Mark; the struck shepherd and scattered sheep, drawing on Zechariah 13:7.","accepted_variants":"translation-equivalent «fall away / stumble / be offended» plus shepherd/sheep relation.","required_evidence":"Mt 26:31; Mk 14:27; optional verification Zech 13:7.","rejected_answers":"Luke and John as containing this same quoted shepherd/sheep wording in the assigned passages.","rejection_reason":"the assigned Luke and John passages do not contain that quotation.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Матвій і Марко поєднують персональне попередження Петрові з ширшим попередженням усім учням.","partial_feedback":"Якщо свідків названо правильно, але образ пропущено, повторюється лише частина про образ.","failure_feedback":"Знайдіть у Матвія і Марка формулу «написано» та образ пастиря/овець.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"Ключовий образ: пастир.","H6":"Mt 26:31; Mk 14:27; Zech 13:7 optional.","H7":"not_used"},"on_correct":"LN04-N04","on_partial":"return_to_current_node_for_missing_image","on_incorrect":"return_to_current_node_after_source_recheck","on_hint_threshold":"guided_then_LN04-N04","optional_evidence_unlock":"LN04-O01","later_retrieval_effect":"REVIEW_QUEUE LN_GROUP_WARNING_REVIEW","mastery_domains":["cross-reference","witness-attribution"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_GROUP_WARNING_REVIEW","functional_nonvisual_equivalent":"Scripture links and relation are described as text; no graphical arrow is required."},{"node_id":"LN04-N04","mission_id":"LN-04","task_family":"evidence classification","difficulty":"2/6","required":true,"skill_target":"witness-specific attribution","knowledge_target":"Galilee promise in Matthew/Mark","why_this_node_exists":"trains attribution instead of importing a true detail into every account.","player_prompt":"Класифікуйте твердження «після воскресіння Ісус піде попереду учнів до Галилеї»: прямо є / прямо немає в кожному з чотирьох досліджуваних уривків.","source_scope_visible_to_player":"four primary passages.","response_mode":"classification","accepted_answer":"Matthew — present; Mark — present; Luke — absent in 22:31–34; John — absent in 13:36–38.","accepted_variants":"label synonyms only.","required_evidence":"Mt 26:32; Mk 14:28; inspect Lk 22:31–34 and Jn 13:36–38.","rejected_answers":"marking all four present because the fact is known elsewhere.","rejection_reason":"this node asks what each assigned passage explicitly contains.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Істинність деталі не робить її деталлю кожного свідчення. Тут її прямо мають Матвій і Марко.","partial_feedback":"Повторно перевіряється лише помилково класифікований свідок.","failure_feedback":"Працюйте в межах заданих віршів, а не з пам'яті про всю історію.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Шукайте слово/ідею «Галилея» у кожному призначеному уривку.","H5":"not_used","H6":"Mt 26:32; Mk 14:28.","H7":"not_used"},"on_correct":"LN04-N05","on_partial":"return_to_current_node_for_misclassified_witness","on_incorrect":"return_to_current_node_after_witness_isolation","on_hint_threshold":"guided_then_LN04-N05","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_WITNESS_ATTRIBUTION_REVIEW","mastery_domains":["explicit-vs-inferred","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_WITNESS_ATTRIBUTION_REVIEW","functional_nonvisual_equivalent":"Four separate labelled radio groups in witness order; Gospel name announced before choices."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":1,"nodes":[{"node_id":"LN04-N01","mission_id":"LN-04","task_family":"source selection","difficulty":"1/6","required":true,"skill_target":"source delimitation","knowledge_target":"four Peter-warning passages","why_this_node_exists":"prevents solving from a remembered harmonized story rather than the assigned witnesses.","player_prompt":"Оберіть чотири уривки, які треба зіставити, щоб дослідити попередження Петрові перед зреченням.","source_scope_visible_to_player":"New Testament Gospel references.","response_mode":"citation selection","accepted_answer":"Matthew 26:30–35; Mark 14:26–31; Luke 22:31–34; John 13:36–38.","accepted_variants":"citation ranges that include the same scene without replacing a primary witness.","required_evidence":"all four primary passages.","rejected_answers":"using later denial narratives as substitutes for prediction passages.","rejection_reason":"LN-04 investigates the prediction; fulfilment evidence is reserved for later retrieval and LN-09.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Корпус зібрано. Тепер кожне твердження має бути прив'язане до конкретного свідка.","partial_feedback":"Якщо знайдено три з чотирьох, система називає відсутнє Євангеліє, але не дає точного діапазону до наступної підказки.","failure_feedback":"Не переходьте одразу до сцени зречення. Спочатку встановіть, що саме було передбачено.","hints":{"H1":"Спершу відокремте сцену передбачення від пізнішої сцени фактичного зречення.","H2":"Шукайте по одному уривку передбачення в кожному з чотирьох Євангелій: Матвія, Марка, Луки та Івана.","H3":"Звузьте пошук до Мт 26, Мк 14, Лк 22 та Ів 13 — саме там розташовані потрібні діалоги.","H4":"Не підміняйте один первинний уривок паралеллю: у відповіді мають бути представлені всі чотири свідки.","H5":"Перевірте, чи кожний вибраний уривок містить саме попередження Петрові до його зречення, а не виконання передбачення.","H6":"Вирішальні діапазони: Мт 26:30–35; Мк 14:26–31; Лк 22:31–34; Ів 13:36–38.","H7":"Керована модель: Мт 26:30–35; Мк 14:26–31; Лк 22:31–34; Ів 13:36–38. Після розкриття результат фіксується як guided mastery."},"on_correct":"LN04-N02","on_partial":"return_to_current_node_missing_witness_only","on_incorrect":"return_to_current_node_after_scene_boundary_reminder","on_hint_threshold":"guided_then_LN04-N02","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N02","mastery_domains":["source-citation","witness-provenance"],"evidence_strength":["recognition","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear labelled citation checklist; keyboard-complete; selected-count and each checkbox state announced."},{"node_id":"LN04-N02","mission_id":"LN-04","task_family":"parallel comparison","difficulty":"2/6","required":true,"skill_target":"extract common core without over-harmonizing","knowledge_target":"three denials before rooster marker","why_this_node_exists":"establishes the minimum proposition supported by all four passages.","player_prompt":"Яке попередження про Петра є спільним для Матвія, Марка, Луки та Івана?","source_scope_visible_to_player":"all four primary passages.","response_mode":"free response","accepted_answer":"Ісус передбачає, що Петро тричі зречеться/відречеться від Нього (у Луки — тричі заперечить, що знає Його) до співу півня.","accepted_variants":"semantic equivalents preserving Peter + three denials + rooster-before/rooster marker.","required_evidence":"Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38.","rejected_answers":"«Усі чотири кажуть, що півень заспіває двічі»; «усі чотири містять наказ зміцнити братів».","rejection_reason":"those details are witness-specific.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Спільне ядро вузьке й сильне: Петро буде тричі заперечувати свою належність/знання Ісуса до визначеного ранкового маркера.","partial_feedback":"Якщо названо три зречення без співу півня, попросити додати часовий маркер.","failure_feedback":"Порівняйте лише речення з самим передбаченням у кожному Євангелії.","hints":{"H1":"Шукайте лише мінімальне ядро, яке можна підтвердити у всіх чотирьох уривках.","H2":"Порівняйте речення з передбаченням у Мт 26:34, Мк 14:30, Лк 22:34 та Ів 13:38.","H3":"У кожному свідку випишіть окремо: що зробить Петро, скільки разів і який ранковий маркер названо.","H4":"Не переносіть марківське «двічі» або луківське «зміцнюй братів» у спільне ядро чотирьох свідків.","H5":"Якщо відповідь має лише число три, додайте часовий маркер; якщо має лише півня, перевірте кількість зречень.","H6":"Опорні вірші: Мт 26:34; Мк 14:30; Лк 22:34; Ів 13:38.","H7":"Керована модель: усі чотири передбачають три зречення/заперечення Петра до співу півня; інші деталі залишайте прив’язаними до окремих свідків."},"on_correct":"LN04-N03","on_partial":"return_to_current_node_for_missing_element","on_incorrect":"return_to_current_node_after_prediction_verse_isolation","on_hint_threshold":"guided_then_LN04-N03","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N01","mastery_domains":["Gospel-parallels","prediction"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Four passages presented sequentially under witness headings; free-response field remains reachable without a visual parallel-column layout."},{"node_id":"LN04-N03","mission_id":"LN-04","task_family":"witness-detail comparison","difficulty":"2/6","required":true,"skill_target":"distinguish group warning from Peter-specific warning","knowledge_target":"Matthew/Mark scattering warning","why_this_node_exists":"prevents treating the Peter prediction as the only warning in the scene.","player_prompt":"Які два Євангелія в досліджуваному корпусі прямо містять попередження, що всі учні відступлять/розсіються, і з яким старозавітним образом це пов'язано?","source_scope_visible_to_player":"Mt 26:31–32; Mk 14:27–28.","response_mode":"comparison + citation","accepted_answer":"Matthew and Mark; the struck shepherd and scattered sheep, drawing on Zechariah 13:7.","accepted_variants":"translation-equivalent «fall away / stumble / be offended» plus shepherd/sheep relation.","required_evidence":"Mt 26:31; Mk 14:27; optional verification Zech 13:7.","rejected_answers":"Luke and John as containing this same quoted shepherd/sheep wording in the assigned passages.","rejection_reason":"the assigned Luke and John passages do not contain that quotation.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Матвій і Марко поєднують персональне попередження Петрові з ширшим попередженням усім учням.","partial_feedback":"Якщо свідків названо правильно, але образ пропущено, повторюється лише частина про образ.","failure_feedback":"Знайдіть у Матвія і Марка формулу «написано» та образ пастиря/овець.","hints":{"H1":"Відділіть попередження всім учням від персонального передбачення Петрові.","H2":"Перевірте Мт 26:31 та Мк 14:27; Лука й Іван у заданому обсязі не мають цієї цитати.","H3":"Знайдіть формулу «написано» і два образи, пов’язані між собою в цитованому попередженні.","H4":"Потрібно назвати і двох свідків, і старозавітний образ; одного слова «пастир» недостатньо.","H5":"Поставте два питання: кого вражають і що відбувається з вівцями після цього?","H6":"Опорні місця: Мт 26:31; Мк 14:27; для перевірки джерела образу — Зах 13:7.","H7":"Керована модель: Матвій і Марко пов’язують попередження з образом ураженого пастиря та розсіяних овець; Зах 13:7 можна використати для перевірки джерела образу."},"on_correct":"LN04-N04","on_partial":"return_to_current_node_for_missing_image","on_incorrect":"return_to_current_node_after_source_recheck","on_hint_threshold":"guided_then_LN04-N04","optional_evidence_unlock":"LN04-O01","later_retrieval_effect":"REVIEW_QUEUE LN_GROUP_WARNING_REVIEW","mastery_domains":["cross-reference","witness-attribution"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_GROUP_WARNING_REVIEW","functional_nonvisual_equivalent":"Scripture links and relation are described as text; no graphical arrow is required."},{"node_id":"LN04-N04","mission_id":"LN-04","task_family":"evidence classification","difficulty":"2/6","required":true,"skill_target":"witness-specific attribution","knowledge_target":"Galilee promise in Matthew/Mark","why_this_node_exists":"trains attribution instead of importing a true detail into every account.","player_prompt":"Класифікуйте твердження «після воскресіння Ісус піде попереду учнів до Галилеї»: прямо є / прямо немає в кожному з чотирьох досліджуваних уривків.","source_scope_visible_to_player":"four primary passages.","response_mode":"classification","accepted_answer":"Matthew — present; Mark — present; Luke — absent in 22:31–34; John — absent in 13:36–38.","accepted_variants":"label synonyms only.","required_evidence":"Mt 26:32; Mk 14:28; inspect Lk 22:31–34 and Jn 13:36–38.","rejected_answers":"marking all four present because the fact is known elsewhere.","rejection_reason":"this node asks what each assigned passage explicitly contains.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Істинність деталі не робить її деталлю кожного свідчення. Тут її прямо мають Матвій і Марко.","partial_feedback":"Повторно перевіряється лише помилково класифікований свідок.","failure_feedback":"Працюйте в межах заданих віршів, а не з пам'яті про всю історію.","hints":{"H1":"Це завдання про наявність деталі в конкретному уривку, а не про те, чи відома вона з історії загалом.","H2":"Перевірте окремо Мт 26:32, Мк 14:28, Лк 22:31–34 та Ів 13:36–38.","H3":"Шукайте в кожному призначеному уривку явну згадку про рух після воскресіння до Галилеї.","H4":"Для кожного свідка дайте окреме «присутнє/не зазначено»; відсутність у заданому уривку не є запереченням події загалом.","H5":"Якщо деталь знайдена у Матвія або Марка, не переносіть її автоматично до Луки чи Івана.","H6":"Позитивні опорні місця: Мт 26:32; Мк 14:28. Для Лк 22:31–34 та Ів 13:36–38 перевіряється лише заданий обсяг.","H7":"Керована модель: Матвій — присутнє; Марко — присутнє; Лука 22:31–34 — не зазначено; Іван 13:36–38 — не зазначено."},"on_correct":"LN04-N05","on_partial":"return_to_current_node_for_misclassified_witness","on_incorrect":"return_to_current_node_after_witness_isolation","on_hint_threshold":"guided_then_LN04-N05","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_WITNESS_ATTRIBUTION_REVIEW","mastery_domains":["explicit-vs-inferred","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_WITNESS_ATTRIBUTION_REVIEW","functional_nonvisual_equivalent":"Four separate labelled radio groups in witness order; Gospel name announced before choices."}]} diff --git a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_02.json b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_02.json index 2f512c319..233d2ffbf 100644 --- a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_02.json +++ b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_02.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":2,"nodes":[{"node_id":"LN04-N05","mission_id":"LN-04","task_family":"character evidence","difficulty":"2/6","required":true,"skill_target":"compare Peter's self-assessment","knowledge_target":"Peter contrasts himself with possible failure of others","why_this_node_exists":"prepares the later contrast between confidence and fulfilment without moralizing the player.","player_prompt":"Що Петро стверджує після загального попередження в Матвія і Марка?","source_scope_visible_to_player":"Mt 26:33–35; Mk 14:29–31.","response_mode":"free response","accepted_answer":"Навіть якщо інші відступлять/спіткнуться, Петро заявляє, що він не відступить; далі наполягає, що не зречеться навіть перед загрозою смерті.","accepted_variants":"semantic equivalents.","required_evidence":"Mt 26:33,35; Mk 14:29,31.","rejected_answers":"«Петро визнає, що боїться і може зректися».","rejection_reason":"opposite of the stated response.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Петро оцінює власну майбутню вірність дуже високо — це стане retrieval target у LN-09.","partial_feedback":"Якщо дано лише першу заяву, попросити додати продовження про смерть.","failure_feedback":"Знайдіть дві відповіді Петра навколо конкретного передбачення Ісуса.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"Зверніть увагу на контраст «інші / я».","H6":"Mt 26:33,35; Mk 14:29,31.","H7":"not_used"},"on_correct":"LN04-N06","on_partial":"return_to_current_node_for_second_declaration","on_incorrect":"return_to_current_node_after_reread","on_hint_threshold":"guided_then_LN04-N06","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_PETER_CONFIDENCE_REVIEW","mastery_domains":["Peter","recall"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_PETER_CONFIDENCE_REVIEW","functional_nonvisual_equivalent":"Labelled free-response field; semantic equivalence accepted; no verbatim quotation required."},{"node_id":"LN04-N06","mission_id":"LN-04","task_family":"witness-specific extraction","difficulty":"3/6","required":true,"skill_target":"extract multi-part unique witness detail","knowledge_target":"sifting, prayer, turning back, strengthening brothers","why_this_node_exists":"Luke contains a major theological/narrative development absent from the assigned parallels.","player_prompt":"Назвіть чотири пов'язані елементи, які Лука 22:31–32 додає до попередження Петрові.","source_scope_visible_to_player":"Lk 22:31–32.","response_mode":"structured free response","accepted_answer":"(1) Сатана просив/вимагав випробувати учнів як пшеницю; (2) Ісус молився за Симона/Петра, щоб його віра не ослабла/не зникла; (3) передбачається його майбутнє повернення/навернення; (4) після цього він має зміцнювати своїх братів.","accepted_variants":"translation-equivalent wording for ask/demand, sift/test, turn/return.","required_evidence":"Lk 22:31–32.","rejected_answers":"assigning these four details to all four Gospel passages.","rejection_reason":"they are specific to Luke in the assigned corpus.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука показує не лише прогноз падіння, а й перспективу повернення та майбутньої відповідальності Петра.","partial_feedback":"Позначте, який із чотирьох елементів відсутній, не розкриваючи його одразу.","failure_feedback":"Розбийте Лк 22:31–32 на чотири послідовні твердження: загроза → молитва → повернення → доручення.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Чотири слоти: загроза → молитва → повернення → доручення.","H5":"not_used","H6":"Lk 22:31–32.","H7":"Відповідь розкривається як guided mastery."},"on_correct":"LN04-N07","on_partial":"return_to_current_node_for_missing_slots","on_incorrect":"return_to_current_node_after_guided_decomposition","on_hint_threshold":"guided_then_LN04-N07","optional_evidence_unlock":"LN04-O02","later_retrieval_effect":"REVIEW_QUEUE LN_LUKE_PETER_DETAIL_REVIEW","mastery_domains":["Luke-detail","witness-provenance"],"evidence_strength":["recall","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LUKE_PETER_DETAIL_REVIEW","functional_nonvisual_equivalent":"Four labelled fields «Елемент 1–4»; screen reader announces field label and progress."},{"node_id":"LN04-N07","mission_id":"LN-04","task_family":"character evidence","difficulty":"2/6","required":true,"skill_target":"precise witness attribution","knowledge_target":"Luke's formulation of Peter's confidence","why_this_node_exists":"distinguishes Luke's wording from Matthew/Mark and John.","player_prompt":"До чого Петро каже, що готовий іти разом з Ісусом у Лк 22:33?","source_scope_visible_to_player":"Lk 22:33.","response_mode":"short free response","accepted_answer":"До в'язниці і до смерті.","accepted_variants":"prison/imprisonment + death.","required_evidence":"Lk 22:33.","rejected_answers":"«до Галилеї»; «лише до смерті» as complete answer.","rejection_reason":"Luke explicitly gives both imprisonment and death.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука формулює впевненість Петра як готовність розділити і ув'язнення, і смерть.","partial_feedback":"Якщо названо один елемент, попросити другий.","failure_feedback":"Перечитайте одну репліку Петра у в.33.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"not_used","H6":"Lk 22:33.","H7":"not_used"},"on_correct":"LN04-N08","on_partial":"return_to_current_node_for_second_slot","on_incorrect":"return_to_current_node_after_reread","on_hint_threshold":"guided_then_LN04-N08","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LUKE_PETER_DETAIL_REVIEW","mastery_domains":["witness-detail","Peter"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LUKE_PETER_DETAIL_REVIEW","functional_nonvisual_equivalent":"Short labelled text field; no visual-choice dependence."},{"node_id":"LN04-N08","mission_id":"LN-04","task_family":"dialogue reconstruction","difficulty":"3/6","required":true,"skill_target":"reconstruct local witness sequence","knowledge_target":"John's question-follow-later-lay-down-life sequence","why_this_node_exists":"demonstrates that John frames the prediction through a different local dialogue sequence.","player_prompt":"Відновіть локальний порядок Ів 13:36–38: A — Петро обіцяє покласти життя; B — Петро питає, куди Ісус іде; C — Ісус каже, що Петро не може йти зараз, але піде пізніше; D — Ісус передбачає три зречення до співу півня.","source_scope_visible_to_player":"Jn 13:36–38.","response_mode":"ordering","accepted_answer":"B → C → A → D.","accepted_variants":"none; order is explicit within John.","required_evidence":"Jn 13:36–38.","rejected_answers":"any order imported from Synoptic passages.","rejection_reason":"this node asks John's local chronology only.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Іван має власну чітку локальну послідовність; її можна встановити без твердження, що вона визначає точний міжєвангельський порядок усіх сцен.","partial_feedback":"Вкажіть першу переставлену пару.","failure_feedback":"Пройдіть три вірші зверху вниз і позначте, хто говорить першим у кожному обміні.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Почніть із питання Петра.","H5":"not_used","H6":"Jn 13:36–38.","H7":"not_used"},"on_correct":"LN04-N09","on_partial":"return_to_current_node_reorder_only_disputed_steps","on_incorrect":"return_to_current_node_after_textual_order_check","on_hint_threshold":"guided_then_LN04-N09","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LOCAL_CHRONOLOGY_REVIEW","mastery_domains":["local-chronology","John-detail"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LOCAL_CHRONOLOGY_REVIEW","functional_nonvisual_equivalent":"Ordering supports numeric positions and move-up/move-down; drag-and-drop is optional only."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":2,"nodes":[{"node_id":"LN04-N05","mission_id":"LN-04","task_family":"character evidence","difficulty":"2/6","required":true,"skill_target":"compare Peter's self-assessment","knowledge_target":"Peter contrasts himself with possible failure of others","why_this_node_exists":"prepares the later contrast between confidence and fulfilment without moralizing the player.","player_prompt":"Що Петро стверджує після загального попередження в Матвія і Марка?","source_scope_visible_to_player":"Mt 26:33–35; Mk 14:29–31.","response_mode":"free response","accepted_answer":"Навіть якщо інші відступлять/спіткнуться, Петро заявляє, що він не відступить; далі наполягає, що не зречеться навіть перед загрозою смерті.","accepted_variants":"semantic equivalents.","required_evidence":"Mt 26:33,35; Mk 14:29,31.","rejected_answers":"«Петро визнає, що боїться і може зректися».","rejection_reason":"opposite of the stated response.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Петро оцінює власну майбутню вірність дуже високо — це стане retrieval target у LN-09.","partial_feedback":"Якщо дано лише першу заяву, попросити додати продовження про смерть.","failure_feedback":"Знайдіть дві відповіді Петра навколо конкретного передбачення Ісуса.","hints":{"H1":"Слідкуйте за тим, як Петро оцінює власну майбутню вірність після загального попередження.","H2":"Читайте тільки відповіді Петра в Мт 26:33,35 та Мк 14:29,31.","H3":"У кожному свідку знайдіть спочатку контраст «інші можуть відступити — я ні», а потім другу, сильнішу заяву.","H4":"Не підміняйте слова Петра пізнішою подією; тут оцінюється його заявлена готовність до того, як сталося зречення.","H5":"Якщо названо лише «я не відступлю», знайдіть продовження, де згадується крайня загроза.","H6":"Опорні місця: Мт 26:33,35; Мк 14:29,31.","H7":"Керована модель: Петро наполягає, що не відступить навіть якщо інші відступлять, і що не зречеться навіть перед загрозою смерті."},"on_correct":"LN04-N06","on_partial":"return_to_current_node_for_second_declaration","on_incorrect":"return_to_current_node_after_reread","on_hint_threshold":"guided_then_LN04-N06","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_PETER_CONFIDENCE_REVIEW","mastery_domains":["Peter","recall"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_PETER_CONFIDENCE_REVIEW","functional_nonvisual_equivalent":"Labelled free-response field; semantic equivalence accepted; no verbatim quotation required."},{"node_id":"LN04-N06","mission_id":"LN-04","task_family":"witness-specific extraction","difficulty":"3/6","required":true,"skill_target":"extract multi-part unique witness detail","knowledge_target":"sifting, prayer, turning back, strengthening brothers","why_this_node_exists":"Luke contains a major theological/narrative development absent from the assigned parallels.","player_prompt":"Назвіть чотири пов'язані елементи, які Лука 22:31–32 додає до попередження Петрові.","source_scope_visible_to_player":"Lk 22:31–32.","response_mode":"structured free response","accepted_answer":"(1) Сатана просив/вимагав випробувати учнів як пшеницю; (2) Ісус молився за Симона/Петра, щоб його віра не ослабла/не зникла; (3) передбачається його майбутнє повернення/навернення; (4) після цього він має зміцнювати своїх братів.","accepted_variants":"translation-equivalent wording for ask/demand, sift/test, turn/return.","required_evidence":"Lk 22:31–32.","rejected_answers":"assigning these four details to all four Gospel passages.","rejection_reason":"they are specific to Luke in the assigned corpus.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука показує не лише прогноз падіння, а й перспективу повернення та майбутньої відповідальності Петра.","partial_feedback":"Позначте, який із чотирьох елементів відсутній, не розкриваючи його одразу.","failure_feedback":"Розбийте Лк 22:31–32 на чотири послідовні твердження: загроза → молитва → повернення → доручення.","hints":{"H1":"Розбийте Лк 22:31–32 на чотири окремі смислові кроки, не змішуючи їх.","H2":"Працюйте лише з Лукою 22:31–32; ці чотири елементи не треба приписувати іншим Євангеліям.","H3":"Послідовність для пошуку: загроза/випробування → молитва Ісуса → майбутнє повернення Симона → його наступне доручення.","H4":"Кожен із чотирьох слотів має містити окрему дію або стан; не зливайте молитву та доручення в один пункт.","H5":"Перевірте, хто просить випробувати, за кого молиться Ісус, що має статися після повернення і кого Петро має зміцнювати.","H6":"Вирішальне джерело: Лк 22:31–32.","H7":"Керована модель: загроза просіювання учнів → молитва Ісуса за Симона, щоб не ослабла віра → майбутнє повернення Симона → доручення зміцнювати братів."},"on_correct":"LN04-N07","on_partial":"return_to_current_node_for_missing_slots","on_incorrect":"return_to_current_node_after_guided_decomposition","on_hint_threshold":"guided_then_LN04-N07","optional_evidence_unlock":"LN04-O02","later_retrieval_effect":"REVIEW_QUEUE LN_LUKE_PETER_DETAIL_REVIEW","mastery_domains":["Luke-detail","witness-provenance"],"evidence_strength":["recall","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LUKE_PETER_DETAIL_REVIEW","functional_nonvisual_equivalent":"Four labelled fields «Елемент 1–4»; screen reader announces field label and progress."},{"node_id":"LN04-N07","mission_id":"LN-04","task_family":"character evidence","difficulty":"2/6","required":true,"skill_target":"precise witness attribution","knowledge_target":"Luke's formulation of Peter's confidence","why_this_node_exists":"distinguishes Luke's wording from Matthew/Mark and John.","player_prompt":"До чого Петро каже, що готовий іти разом з Ісусом у Лк 22:33?","source_scope_visible_to_player":"Lk 22:33.","response_mode":"short free response","accepted_answer":"До в'язниці і до смерті.","accepted_variants":"prison/imprisonment + death.","required_evidence":"Lk 22:33.","rejected_answers":"«до Галилеї»; «лише до смерті» as complete answer.","rejection_reason":"Luke explicitly gives both imprisonment and death.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука формулює впевненість Петра як готовність розділити і ув'язнення, і смерть.","partial_feedback":"Якщо названо один елемент, попросити другий.","failure_feedback":"Перечитайте одну репліку Петра у в.33.","hints":{"H1":"У відповіді потрібні два об’єкти готовності Петра, а не загальна фраза «піти з Ісусом».","H2":"Читайте одну репліку Петра в Лк 22:33.","H3":"Знайдіть два іменники після заяви про готовність іти разом.","H4":"Не замінюйте луківське формулювання деталями з Матвія, Марка чи Івана.","H5":"Якщо названо лише смерть, поверніться до першого об’єкта готовності в тому самому вірші.","H6":"Опорний вірш: Лк 22:33.","H7":"Керована модель: Петро каже, що готовий іти з Ісусом і до в’язниці, і до смерті."},"on_correct":"LN04-N08","on_partial":"return_to_current_node_for_second_slot","on_incorrect":"return_to_current_node_after_reread","on_hint_threshold":"guided_then_LN04-N08","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LUKE_PETER_DETAIL_REVIEW","mastery_domains":["witness-detail","Peter"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LUKE_PETER_DETAIL_REVIEW","functional_nonvisual_equivalent":"Short labelled text field; no visual-choice dependence."},{"node_id":"LN04-N08","mission_id":"LN-04","task_family":"dialogue reconstruction","difficulty":"3/6","required":true,"skill_target":"reconstruct local witness sequence","knowledge_target":"John's question-follow-later-lay-down-life sequence","why_this_node_exists":"demonstrates that John frames the prediction through a different local dialogue sequence.","player_prompt":"Відновіть локальний порядок Ів 13:36–38: A — Петро обіцяє покласти життя; B — Петро питає, куди Ісус іде; C — Ісус каже, що Петро не може йти зараз, але піде пізніше; D — Ісус передбачає три зречення до співу півня.","source_scope_visible_to_player":"Jn 13:36–38.","response_mode":"ordering","accepted_answer":"B → C → A → D.","accepted_variants":"none; order is explicit within John.","required_evidence":"Jn 13:36–38.","rejected_answers":"any order imported from Synoptic passages.","rejection_reason":"this node asks John's local chronology only.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Іван має власну чітку локальну послідовність; її можна встановити без твердження, що вона визначає точний міжєвангельський порядок усіх сцен.","partial_feedback":"Вкажіть першу переставлену пару.","failure_feedback":"Пройдіть три вірші зверху вниз і позначте, хто говорить першим у кожному обміні.","hints":{"H1":"Відновлюйте тільки локальний порядок Івана 13:36–38, не глобальну міжєвангельську хронологію.","H2":"Пройдіть Ів 13:36–38 зверху вниз і позначайте кожну зміну репліки.","H3":"Першим є питання Петра про те, куди йде Ісус; далі визначте відповідь Ісуса, наступну заяву Петра і фінальне передбачення.","H4":"Порівнюйте не теми, а фактичну послідовність чотирьох даних елементів A–D.","H5":"Якщо вагаєтесь між A і C, перевірте, чи обіцянка покласти життя звучить до чи після слів про «пізніше».","H6":"Вирішальний локальний контекст: Ів 13:36–38.","H7":"Керована модель порядку: B → C → A → D. Після розкриття результат записується як guided mastery."},"on_correct":"LN04-N09","on_partial":"return_to_current_node_reorder_only_disputed_steps","on_incorrect":"return_to_current_node_after_textual_order_check","on_hint_threshold":"guided_then_LN04-N09","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LOCAL_CHRONOLOGY_REVIEW","mastery_domains":["local-chronology","John-detail"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LOCAL_CHRONOLOGY_REVIEW","functional_nonvisual_equivalent":"Ordering supports numeric positions and move-up/move-down; drag-and-drop is optional only."}]} diff --git a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_03.json b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_03.json index 65997a2fd..3f8f57e1b 100644 --- a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_03.json +++ b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_03.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":3,"nodes":[{"node_id":"LN04-N09","mission_id":"LN-04","task_family":"textual-variant aware comparison","difficulty":"4/6","required":true,"skill_target":"distinguish witness wording from textual-transmission variation","knowledge_target":"Mark's twice detail versus other accounts","why_this_node_exists":"prevents false contradiction scoring and implements the project's TX1 policy.","player_prompt":"Класифікуйте передбачення співу півня в основному корпусі: де досліджуваний текст говорить про «двічі», а де лише про спів півня без числа? Потім вкажіть, як гра повинна поводитися з перекладами, що мають іншу марківську текстову форму.","source_scope_visible_to_player":"Mt 26:34; Mk 14:30 plus textual note; Lk 22:34; Jn 13:38.","response_mode":"classification + policy application","accepted_answer":"Mark explicitly has «twice» in common modern critical-text translations; Matthew, Luke and John give the rooster-crow marker without «twice». Because some early manuscripts omit Mark's «twice», a responsible translation/textual note differing here must be accepted and labelled TX1, not graded as ignorance.","accepted_variants":"equivalent explanation preserving witness distinction and non-punitive TX1 handling.","required_evidence":"Mk 14:30 textual footnote; compare Mt 26:34; Lk 22:34; Jn 13:38.","rejected_answers":"«Only one version can be accepted; all others are wrong»; «all four say twice».","rejection_reason":"ignores documented textual variation or witness wording.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Текстологічна прозорість важливіша за штучну однаковість. Гра фіксує різницю і не карає за відповідальну текстову традицію.","partial_feedback":"Якщо свідків класифіковано правильно, але policy застосовано неправильно, відкрийте лише нагадування про textual-variant policy.","failure_feedback":"Перевірте саме Марка 14:30 і примітку до цього вірша.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"Ключовий свідок для «двічі» — Марко.","H6":"Mk 14:30 + textual note.","H7":"TX1 policy: responsible translation forms are accepted without penalty."},"on_correct":"LN04-N10","on_partial":"return_to_current_node_for_TX1_policy_correction","on_incorrect":"return_to_current_node_after_witness_by_witness_recheck","on_hint_threshold":"guided_then_LN04-N10","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N11","mastery_domains":["textual-variants","translation-neutrality"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"TX1 note is a labelled text block visible before grading; no icon/color/tooltip-only encoding."},{"node_id":"LN04-N10","mission_id":"LN-04","task_family":"attribution matrix","difficulty":"3/6","required":true,"skill_target":"witness-specific attribution","knowledge_target":"unique elements across four witnesses","why_this_node_exists":"consolidates distinctions before synthesis.","player_prompt":"Зіставте деталь із досліджуваним свідком: 1) «зміцнюй братів»; 2) «не можеш іти зараз, підеш пізніше»; 3) «після воскресіння піду попереду до Галилеї»; 4) «півень заспіває двічі» у відповідній текстовій формі.","source_scope_visible_to_player":"all four primary passages.","response_mode":"evidence linking","accepted_answer":"1 — Luke; 2 — John; 3 — Matthew and Mark; 4 — Mark.","accepted_variants":"Mark detail subject to TX1 note.","required_evidence":"Lk 22:32; Jn 13:36; Mt 26:32; Mk 14:28,30.","rejected_answers":"assigning all four details to all witnesses.","rejection_reason":"conflates synthesis with source attribution.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Ви відділили авторсько-специфічні елементи від спільного ядра.","partial_feedback":"Збережіть правильні зв’язки й повторіть лише неправильні.","failure_feedback":"Поверніться до кожного свідка окремо й знайдіть ключове речення.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Для кожного пункту знайдіть ключове слово у свідка.","H5":"not_used","H6":"Lk 22:32; Jn 13:36; Mt 26:32; Mk 14:28,30.","H7":"not_used"},"on_correct":"LN04-N11","on_partial":"return_to_current_node_for_mislinked_items","on_incorrect":"return_to_current_node_after_witness_isolation","on_hint_threshold":"guided_then_LN04-N11","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_WITNESS_ATTRIBUTION_REVIEW","mastery_domains":["witness-attribution","textual-variants"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_WITNESS_ATTRIBUTION_REVIEW","functional_nonvisual_equivalent":"Numbered text pairing or two sequential labelled lists; drag-and-drop is never required."},{"node_id":"LN04-N11","mission_id":"LN-04","task_family":"claim audit","difficulty":"4/6","required":true,"skill_target":"classify supported vs overclaimed statements","knowledge_target":"source limits of Peter warning narrative","why_this_node_exists":"operationalizes theological/source transparency.","player_prompt":"Позначте кожне твердження як «прямо підтримане», «підтримане порівнянням», або «надмірне/не доведене цим корпусом»: A) усі чотири передбачають три зречення Петра; B) усі чотири містять фразу про зміцнення братів; C) Матвій і Марко містять образ удареного пастиря й розсіяних овець; D) з чотирьох уривків можна відновити один безсумнівний дослівний діалог; E) Іван повідомляє, що Петро обіцяє покласти життя за Ісуса.","source_scope_visible_to_player":"all primary passages.","response_mode":"classification","accepted_answer":"A — supported comparison (T2); B — overclaim, Luke-specific; C — supported comparison (T2); D — overclaim/D1; E — direct (T1).","accepted_variants":"label synonyms preserving the same classifications.","required_evidence":"all primary passages.","rejected_answers":"treating a true statement from one Gospel as direct in all four.","rejection_reason":"violates witness attribution.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Надійна реконструкція відрізняє істинне твердження від твердження про те, хто саме його засвідчує.","partial_feedback":"На першій спробі пояснюється лише тип помилки категорії, без розкриття правильної відповіді.","failure_feedback":"Для кожного речення поставте два питання: «чи це правда?» і «чи саме цей корпус це прямо каже?»","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Користуйтеся T1/T2/D1 як межами прямого, порівняльного та невизначеного.","H5":"not_used","H6":"Перевірте вирішальні вірші для кожного твердження.","H7":"not_used"},"on_correct":"LN04-N12","on_partial":"return_to_current_node_for_wrong_claims","on_incorrect":"return_to_current_node_after_claim_specific_correction","on_hint_threshold":"guided_then_LN04-N12","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN04-N13","mastery_domains":["evidence-classification","uncertainty"],"evidence_strength":["application","synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Each claim is a separate labelled choice group with full text; categories are spoken, never color-only.","confidence_notes":"Node grades a mixed set of T1/T2/D1 claims; node-level confidence_code T2 reflects the comparison operation."},{"node_id":"LN04-N12","mission_id":"LN-04","task_family":"constrained synthesis","difficulty":"4/6","required":true,"skill_target":"produce a harmonization-safe common reconstruction","knowledge_target":"minimal shared narrative","why_this_node_exists":"prepares final case reasoning and anti-false-harmonization habit.","player_prompt":"Складіть 3–5 речень, які передають лише те, що можна безпечно сказати після зіставлення чотирьох уривків. Не вставляйте деталь як спільну, якщо вона є лише в одному чи двох свідків.","source_scope_visible_to_player":"all primary passages.","response_mode":"constrained free synthesis","accepted_answer":"Semantic synthesis including Peter's expressed confidence/readiness, Jesus' prediction that Peter will deny him three times before the rooster marker, and recognition that witnesses preserve different surrounding details. Broader discipleship warning may be mentioned only if attributed to Matthew/Mark; prayer/strengthening only if attributed to Luke; follow-later dialogue only if attributed to John.","accepted_variants":"many semantic formulations accepted if source attribution is accurate.","required_evidence":"all four passages.","rejected_answers":"a fabricated composite quotation; claiming all unique details occur in every witness.","rejection_reason":"false harmonization.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Ви створили реконструкцію, яка об'єднує докази, не стираючи відмінностей між свідками.","partial_feedback":"Позначте лише речення, яке надмірно узагальнює, і попросіть додати правильне джерело.","failure_feedback":"Почніть із одного речення, яке підтримують усі чотири, а потім додавайте лише чітко підписані деталі.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Шаблон: спільне ядро → Luke-only → John-only → Mt/Mk-only.","H5":"not_used","H6":"not_used","H7":"Модельний каркас дозволено лише як guided mastery."},"on_correct":"LN04-N13","on_partial":"return_to_current_node_edit_unsupported_sentence_only","on_incorrect":"return_to_LN04-N10_or_LN04-N11_based_on_error","on_hint_threshold":"guided_then_LN04-N13","optional_evidence_unlock":"LN04-O01; LN04-O02","later_retrieval_effect":"RESOLVED_NODE LN04-N13","mastery_domains":["Gospel-parallels","anti-false-harmonization"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Multi-line labelled text field; screen reader announces which required concept remains and source-attribution errors by text."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":3,"nodes":[{"node_id":"LN04-N09","mission_id":"LN-04","task_family":"textual-variant aware comparison","difficulty":"4/6","required":true,"skill_target":"distinguish witness wording from textual-transmission variation","knowledge_target":"Mark's twice detail versus other accounts","why_this_node_exists":"prevents false contradiction scoring and implements the project's TX1 policy.","player_prompt":"Класифікуйте передбачення співу півня в основному корпусі: де досліджуваний текст говорить про «двічі», а де лише про спів півня без числа? Потім вкажіть, як гра повинна поводитися з перекладами, що мають іншу марківську текстову форму.","source_scope_visible_to_player":"Mt 26:34; Mk 14:30 plus textual note; Lk 22:34; Jn 13:38.","response_mode":"classification + policy application","accepted_answer":"Mark explicitly has «twice» in common modern critical-text translations; Matthew, Luke and John give the rooster-crow marker without «twice». Because some early manuscripts omit Mark's «twice», a responsible translation/textual note differing here must be accepted and labelled TX1, not graded as ignorance.","accepted_variants":"equivalent explanation preserving witness distinction and non-punitive TX1 handling.","required_evidence":"Mk 14:30 textual footnote; compare Mt 26:34; Lk 22:34; Jn 13:38.","rejected_answers":"«Only one version can be accepted; all others are wrong»; «all four say twice».","rejection_reason":"ignores documented textual variation or witness wording.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Текстологічна прозорість важливіша за штучну однаковість. Гра фіксує різницю і не карає за відповідальну текстову традицію.","partial_feedback":"Якщо свідків класифіковано правильно, але policy застосовано неправильно, відкрийте лише нагадування про textual-variant policy.","failure_feedback":"Перевірте саме Марка 14:30 і примітку до цього вірша.","hints":{"H1":"Спочатку відокремте два питання: що має кожен свідок і як поводитися з марківською текстовою варіацією.","H2":"Порівняйте Мт 26:34, Мк 14:30, Лк 22:34, Ів 13:38 та текстологічну примітку до Мк 14:30.","H3":"З’ясуйте, у якому свідку в досліджуваній текстовій формі є числова деталь про спів півня.","H4":"TX1 не є оцінкою правильності гравця або confidence-кодом; це окрема позначка текстової варіації.","H5":"Не карайте відповідальну перекладацьку форму, якщо вона відображає іншу засвідчену форму Марка.","H6":"Ключ: Мк 14:30 + текстологічна примітка; для порівняння Мт 26:34, Лк 22:34, Ів 13:38.","H7":"Керована модель: у поширеній критичній формі Марко має «двічі», Матвій/Лука/Іван — маркер співу півня без цього числа; відповідальну іншу марківську форму слід прийняти й позначити TX1."},"on_correct":"LN04-N10","on_partial":"return_to_current_node_for_TX1_policy_correction","on_incorrect":"return_to_current_node_after_witness_by_witness_recheck","on_hint_threshold":"guided_then_LN04-N10","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N11","mastery_domains":["textual-variants","translation-neutrality"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"TX1 note is a labelled text block visible before grading; no icon/color/tooltip-only encoding."},{"node_id":"LN04-N10","mission_id":"LN-04","task_family":"attribution matrix","difficulty":"3/6","required":true,"skill_target":"witness-specific attribution","knowledge_target":"unique elements across four witnesses","why_this_node_exists":"consolidates distinctions before synthesis.","player_prompt":"Зіставте деталь із досліджуваним свідком: 1) «зміцнюй братів»; 2) «не можеш іти зараз, підеш пізніше»; 3) «після воскресіння піду попереду до Галилеї»; 4) «півень заспіває двічі» у відповідній текстовій формі.","source_scope_visible_to_player":"all four primary passages.","response_mode":"evidence linking","accepted_answer":"1 — Luke; 2 — John; 3 — Matthew and Mark; 4 — Mark.","accepted_variants":"Mark detail subject to TX1 note.","required_evidence":"Lk 22:32; Jn 13:36; Mt 26:32; Mk 14:28,30.","rejected_answers":"assigning all four details to all witnesses.","rejection_reason":"conflates synthesis with source attribution.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Ви відділили авторсько-специфічні елементи від спільного ядра.","partial_feedback":"Збережіть правильні зв’язки й повторіть лише неправильні.","failure_feedback":"Поверніться до кожного свідка окремо й знайдіть ключове речення.","hints":{"H1":"Розв’язуйте кожну деталь окремо: знайдіть свідка, перш ніж переходити до наступної.","H2":"Джерела для чотирьох зв’язків: Лк 22:32; Ів 13:36; Мт 26:32; Мк 14:28,30.","H3":"Почніть з унікальних деталей Луки та Івана, потім перевірте спільну для Матвія/Марка і окрему марківську.","H4":"Не перетворюйте T2-порівняння на твердження, що всі деталі прямо присутні в кожному свідку.","H5":"Для пункту 4 пам’ятайте TX1: марківське «двічі» залежить від текстової форми, але атрибуція лишається марківською.","H6":"Опорні місця: Лк 22:32; Ів 13:36; Мт 26:32; Мк 14:28,30.","H7":"Керована модель: 1 — Лука; 2 — Іван; 3 — Матвій і Марко; 4 — Марко, з окремою TX1-приміткою щодо текстової форми."},"on_correct":"LN04-N11","on_partial":"return_to_current_node_for_mislinked_items","on_incorrect":"return_to_current_node_after_witness_isolation","on_hint_threshold":"guided_then_LN04-N11","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_WITNESS_ATTRIBUTION_REVIEW","mastery_domains":["witness-attribution","textual-variants"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_WITNESS_ATTRIBUTION_REVIEW","functional_nonvisual_equivalent":"Numbered text pairing or two sequential labelled lists; drag-and-drop is never required."},{"node_id":"LN04-N11","mission_id":"LN-04","task_family":"claim audit","difficulty":"4/6","required":true,"skill_target":"classify supported vs overclaimed statements","knowledge_target":"source limits of Peter warning narrative","why_this_node_exists":"operationalizes theological/source transparency.","player_prompt":"Позначте кожне твердження як «прямо підтримане», «підтримане порівнянням», або «надмірне/не доведене цим корпусом»: A) усі чотири передбачають три зречення Петра; B) усі чотири містять фразу про зміцнення братів; C) Матвій і Марко містять образ удареного пастиря й розсіяних овець; D) з чотирьох уривків можна відновити один безсумнівний дослівний діалог; E) Іван повідомляє, що Петро обіцяє покласти життя за Ісуса.","source_scope_visible_to_player":"all primary passages.","response_mode":"classification","accepted_answer":"A — supported comparison (T2); B — overclaim, Luke-specific; C — supported comparison (T2); D — overclaim/D1; E — direct (T1).","accepted_variants":"label synonyms preserving the same classifications.","required_evidence":"all primary passages.","rejected_answers":"treating a true statement from one Gospel as direct in all four.","rejection_reason":"violates witness attribution.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Надійна реконструкція відрізняє істинне твердження від твердження про те, хто саме його засвідчує.","partial_feedback":"На першій спробі пояснюється лише тип помилки категорії, без розкриття правильної відповіді.","failure_feedback":"Для кожного речення поставте два питання: «чи це правда?» і «чи саме цей корпус це прямо каже?»","hints":{"H1":"Для кожного твердження визначте, чи воно стосується одного свідка, кількох свідків або претендує на глобальну реконструкцію.","H2":"Повертайтеся до чотирьох первинних уривків і перевіряйте кожне твердження A–E окремо.","H3":"Ставте два питання: «це сказано прямо?» і «це встановлюється лише через порівняння?».","H4":"Використайте межі категорій: T1 — пряме локальне твердження; T2 — пряме порівняння; D1 — те, що корпус не дозволяє відповідально звести до одного безсумнівного твердження.","H5":"Особливо перевірте B і D: чи справді одна witness-specific деталь або один дослівний глобальний діалог підтримуються всіма джерелами.","H6":"Опори: три зречення — Мт 26:34/Мк 14:30/Лк 22:34/Ів 13:38; «зміцнюй братів» — Лк 22:32; пастир — Мт 26:31/Мк 14:27; життя за Ісуса — Ів 13:37.","H7":"Керована модель класифікації: A — підтримане порівняння; B — надмірне, лише Лука; C — підтримане порівняння; D — надмірне/D1; E — пряме/T1."},"on_correct":"LN04-N12","on_partial":"return_to_current_node_for_wrong_claims","on_incorrect":"return_to_current_node_after_claim_specific_correction","on_hint_threshold":"guided_then_LN04-N12","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN04-N13","mastery_domains":["evidence-classification","uncertainty"],"evidence_strength":["application","synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Each claim is a separate labelled choice group with full text; categories are spoken, never color-only.","confidence_notes":"Node grades a mixed set of T1/T2/D1 claims; node-level confidence_code T2 reflects the comparison operation."},{"node_id":"LN04-N12","mission_id":"LN-04","task_family":"constrained synthesis","difficulty":"4/6","required":true,"skill_target":"produce a harmonization-safe common reconstruction","knowledge_target":"minimal shared narrative","why_this_node_exists":"prepares final case reasoning and anti-false-harmonization habit.","player_prompt":"Складіть 3–5 речень, які передають лише те, що можна безпечно сказати після зіставлення чотирьох уривків. Не вставляйте деталь як спільну, якщо вона є лише в одному чи двох свідків.","source_scope_visible_to_player":"all primary passages.","response_mode":"constrained free synthesis","accepted_answer":"Semantic synthesis including Peter's expressed confidence/readiness, Jesus' prediction that Peter will deny him three times before the rooster marker, and recognition that witnesses preserve different surrounding details. Broader discipleship warning may be mentioned only if attributed to Matthew/Mark; prayer/strengthening only if attributed to Luke; follow-later dialogue only if attributed to John.","accepted_variants":"many semantic formulations accepted if source attribution is accurate.","required_evidence":"all four passages.","rejected_answers":"a fabricated composite quotation; claiming all unique details occur in every witness.","rejection_reason":"false harmonization.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Ви створили реконструкцію, яка об'єднує докази, не стираючи відмінностей між свідками.","partial_feedback":"Позначте лише речення, яке надмірно узагальнює, і попросіть додати правильне джерело.","failure_feedback":"Почніть із одного речення, яке підтримують усі чотири, а потім додавайте лише чітко підписані деталі.","hints":{"H1":"Почніть з одного речення, яке справді підтримують усі чотири свідки; лише потім додавайте локальні деталі.","H2":"Тримайте перед очима чотири witness headings: Матвій, Марко, Лука, Іван.","H3":"Для кожного наступного речення позначте, чи це спільне ядро, лише Лука, лише Іван або лише Матвій/Марко.","H4":"Не створюйте composite quotation і не перетворюйте witness-specific деталь на спільну.","H5":"Якщо речення не можна підписати конкретним свідком або групою свідків, перевірте, чи воно не є надмірним узагальненням.","H6":"Опорний корпус: Мт 26:30–35; Мк 14:26–31; Лк 22:31–34; Ів 13:36–38.","H7":"Керована модель: спільне — Петро висловлює впевненість/готовність, а Ісус передбачає три заперечення до співу півня; Мт/Мк — пастир і Галилея; Лука — молитва, повернення, зміцнення; Іван — діалог про «піти пізніше»."},"on_correct":"LN04-N13","on_partial":"return_to_current_node_edit_unsupported_sentence_only","on_incorrect":"return_to_LN04-N10_or_LN04-N11_based_on_error","on_hint_threshold":"guided_then_LN04-N13","optional_evidence_unlock":"LN04-O01; LN04-O02","later_retrieval_effect":"RESOLVED_NODE LN04-N13","mastery_domains":["Gospel-parallels","anti-false-harmonization"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Multi-line labelled text field; screen reader announces which required concept remains and source-attribution errors by text."}]} diff --git a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_04.json b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_04.json index 430739b2c..d6926b70c 100644 --- a/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_04.json +++ b/docs/campaigns/LN/LN-04_CANONICAL_v1.2/nodes_part_04.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":4,"nodes":[{"node_id":"LN04-N13","mission_id":"LN-04","task_family":"final case reconstruction","difficulty":"5/6","required":true,"skill_target":"evidence-backed explanation with certainty limits","knowledge_target":"full Peter-warning case","why_this_node_exists":"demonstrates mission-level mastery and creates retrieval anchors for LN-09.","player_prompt":"Дайте фінальний висновок: (1) що було передбачено Петрові; (2) як Петро оцінював власну готовність; (3) що додає Лука; (4) що додає Іван; (5) що спільно додають Матвій і Марко; (6) яку текстологічну обережність треба зберегти щодо співу півня; (7) чого ми не можемо чесно стверджувати про одну точну міжєвангельську послідовність.","source_scope_visible_to_player":"full primary corpus + optional Zech 13:7 + TX1 note.","response_mode":"structured synthesis","accepted_answer":"Must accurately cover all seven requested dimensions with correct witness attribution and certainty limits.","accepted_variants":"semantic equivalents; no required translation wording.","required_evidence":"Mt 26:30–35; Mk 14:26–31; Lk 22:31–34; Jn 13:36–38; Mark textual note for TX1.","rejected_answers":"any synthesis that erases witness differences, forces one exact global chronology, or treats Mark's textual variation as user error.","rejection_reason":"violates canonical source/transparency policy.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Справу закрито: спільне ядро встановлено, деталі правильно приписані свідкам, межі текстової певності збережено. Ці докази повернуться під час дослідження фактичних зречень.","partial_feedback":"Поверніть лише номери відсутніх вимірів і збережіть уже правильні частини.","failure_feedback":"Використайте сім пунктів запиту як окремі підзаголовки й для кожного назвіть свідка/джерело.","hints":{"H1":"Працюйте за сімома вимірами запиту.","H2":"not_used","H3":"not_used","H4":"Перевірте provenance і uncertainty кожного виміру.","H5":"not_used","H6":"Mt 26:30–35; Mk 14:26–31; Lk 22:31–34; Jn 13:36–38.","H7":"Guided model synthesis is allowed and recorded as guided."},"on_correct":"mission_complete","on_partial":"return_to_current_node_for_missing_dimensions","on_incorrect":"return_to_LN04-N09_to_LN04-N12_based_on_error","on_hint_threshold":"guided_mission_complete","optional_evidence_unlock":"LN04-O01; LN04-O02","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["Peter-warning","synthesis","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Seven numbered fields or one field with seven accessible headings; errors announced by numbered requirement.","confidence_notes":"Mixed T1/T2/D1 clauses; node-level comparison/synthesis code is T2 and TX1 is adjunct."},{"node_id":"LN04-O01","mission_id":"LN-04","task_family":"optional cross-reference investigation","difficulty":"4/6","required":false,"skill_target":"trace explicit scriptural citation","knowledge_target":"shepherd/sheep source relation","why_this_node_exists":"deepens cross-reference literacy without making OT interpretation a gate for mission completion.","player_prompt":"Порівняйте Зах 13:7 з Мт 26:31 і Мк 14:27. Яку частину образу Ісус застосовує в обох синоптичних уривках?","source_scope_visible_to_player":"Zech 13:7; Mt 26:31; Mk 14:27.","response_mode":"comparison + evidence linking","accepted_answer":"the struck shepherd / scattered sheep relation.","accepted_variants":"translation equivalents.","required_evidence":"all three references.","rejected_answers":"importing every detail of Zech 13:7–9 as if quoted in the Gospel sentence.","rejection_reason":"the Gospel citation uses a specific portion of the prophetic image.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Ви простежили явний міжтекстовий зв'язок, не розширюючи цитату понад те, що використано в сцені.","partial_feedback":"Попросіть виокремити фразу/образ, присутній у всіх трьох текстах.","failure_feedback":"Зіставте лише образ пастиря та овець.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"not_used","H6":"Zech 13:7; Mt 26:31; Mk 14:27.","H7":"not_used"},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_narrow_comparison","on_incorrect":"return_to_current_node_guided_cross_reference","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_OT_CROSS_REFERENCE_REVIEW","mastery_domains":["cross-reference"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_OT_CROSS_REFERENCE_REVIEW","functional_nonvisual_equivalent":"Three passages are read sequentially; relation is stated in text rather than only as a graph edge."},{"node_id":"LN04-O02","mission_id":"LN-04","task_family":"optional linguistic evidence","difficulty":"5/6","required":false,"skill_target":"observe number shift without doctrinal overreach","knowledge_target":"plural-to-singular address pattern in Luke 22:31–32","why_this_node_exists":"introduces careful language-level observation and translation-note literacy.","player_prompt":"За текстовою/мовною приміткою до Лк 22:31–32, що змінюється у звертанні між загрозою просіювання і молитвою Ісуса, і який мінімальний висновок дозволено зробити?","source_scope_visible_to_player":"Lk 22:31–32 with a translation or Greek-number note that explicitly marks plural/singular forms.","response_mode":"evidence interpretation","accepted_answer":"У в.31 звернення «вас» стосується множини, тоді як у в.32 молитва звернена до Симона в однині; мінімальний висновок — загроза описана ширше щодо учнів, а молитва у формулюванні в.32 персонально адресована Симонові. Не потрібно виводити з граматики ширшу доктрину.","accepted_variants":"equivalent cautious linguistic statement.","required_evidence":"explicit translation/Greek-number note for Lk 22:31–32.","rejected_answers":"constructing a denominational doctrine as the only required answer from the pronoun shift.","rejection_reason":"exceeds the linguistic evidence.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Мовна деталь може бути доказом, але її сила обмежена тим, що вона реально показує.","partial_feedback":"Відділіть граматичне спостереження від подальшого тлумачення.","failure_feedback":"Спочатку назвіть лише число займенника в кожному вірші; тлумачення залиште другим кроком.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"not_used","H6":"Use an explicit language/translation note for Lk 22:31–32.","H7":"Minimal inference only: plural threat context, singular prayer address."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_observation_vs_interpretation","on_incorrect":"return_to_current_node_guided_language_note","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LANGUAGE_NOTE_REVIEW","mastery_domains":["language-note literacy"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LANGUAGE_NOTE_REVIEW","functional_nonvisual_equivalent":"Grammar is announced as literal words «множина/однина», never only formatting or color."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-04","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-04_PETER_WARNING_v1.0.md","sha":"4c445f9fa9ef99916ce4242deedb534b3152ebf7","preserved":true},"part":4,"nodes":[{"node_id":"LN04-N13","mission_id":"LN-04","task_family":"final case reconstruction","difficulty":"5/6","required":true,"skill_target":"evidence-backed explanation with certainty limits","knowledge_target":"full Peter-warning case","why_this_node_exists":"demonstrates mission-level mastery and creates retrieval anchors for LN-09.","player_prompt":"Дайте фінальний висновок: (1) що було передбачено Петрові; (2) як Петро оцінював власну готовність; (3) що додає Лука; (4) що додає Іван; (5) що спільно додають Матвій і Марко; (6) яку текстологічну обережність треба зберегти щодо співу півня; (7) чого ми не можемо чесно стверджувати про одну точну міжєвангельську послідовність.","source_scope_visible_to_player":"full primary corpus + optional Zech 13:7 + TX1 note.","response_mode":"structured synthesis","accepted_answer":"Must accurately cover all seven requested dimensions with correct witness attribution and certainty limits.","accepted_variants":"semantic equivalents; no required translation wording.","required_evidence":"Mt 26:30–35; Mk 14:26–31; Lk 22:31–34; Jn 13:36–38; Mark textual note for TX1.","rejected_answers":"any synthesis that erases witness differences, forces one exact global chronology, or treats Mark's textual variation as user error.","rejection_reason":"violates canonical source/transparency policy.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Справу закрито: спільне ядро встановлено, деталі правильно приписані свідкам, межі текстової певності збережено. Ці докази повернуться під час дослідження фактичних зречень.","partial_feedback":"Поверніть лише номери відсутніх вимірів і збережіть уже правильні частини.","failure_feedback":"Використайте сім пунктів запиту як окремі підзаголовки й для кожного назвіть свідка/джерело.","hints":{"H1":"Перетворіть сім вимог запиту на сім окремих пунктів перевірки перед написанням висновку.","H2":"Для пунктів про Луку, Івана та Матвія/Марка тримайте окремі witness labels; не зливайте їх у безіменний композит.","H3":"Спочатку заповніть спільне передбачення і самооцінку Петра, потім witness-specific додатки, потім TX1 і межу глобальної хронології.","H4":"Для кожного пункту позначте тип твердження: локальний текст, порівняння, TX1-примітка або межа невизначеності.","H5":"Перед завершенням перевірте дві типові помилки: марківське «двічі» не можна зробити обов’язковим для всіх перекладів; з чотирьох уривків не можна примусово скласти один безсумнівний дослівний глобальний діалог.","H6":"Повний опорний корпус: Мт 26:30–35; Мк 14:26–31; Лк 22:31–34; Ів 13:36–38; для TX1 — текстологічна примітка до Мк 14:30.","H7":"Керована модель: 1) три зречення до співу півня; 2) висока заявлена готовність Петра; 3) Лука — просіювання, молитва, повернення, зміцнення; 4) Іван — «не зараз, пізніше» і обіцянка життя; 5) Мт/Мк — пастир/вівці й Галилея; 6) Марківську форму «двічі» обробляти як TX1; 7) один безсумнівний дослівний міжєвангельський порядок не встановлено."},"on_correct":"mission_complete","on_partial":"return_to_current_node_for_missing_dimensions","on_incorrect":"return_to_LN04-N09_to_LN04-N12_based_on_error","on_hint_threshold":"guided_mission_complete","optional_evidence_unlock":"LN04-O01; LN04-O02","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["Peter-warning","synthesis","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN04_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Seven numbered fields or one field with seven accessible headings; errors announced by numbered requirement.","confidence_notes":"Mixed T1/T2/D1 clauses; node-level comparison/synthesis code is T2 and TX1 is adjunct."},{"node_id":"LN04-O01","mission_id":"LN-04","task_family":"optional cross-reference investigation","difficulty":"4/6","required":false,"skill_target":"trace explicit scriptural citation","knowledge_target":"shepherd/sheep source relation","why_this_node_exists":"deepens cross-reference literacy without making OT interpretation a gate for mission completion.","player_prompt":"Порівняйте Зах 13:7 з Мт 26:31 і Мк 14:27. Яку частину образу Ісус застосовує в обох синоптичних уривках?","source_scope_visible_to_player":"Zech 13:7; Mt 26:31; Mk 14:27.","response_mode":"comparison + evidence linking","accepted_answer":"the struck shepherd / scattered sheep relation.","accepted_variants":"translation equivalents.","required_evidence":"all three references.","rejected_answers":"importing every detail of Zech 13:7–9 as if quoted in the Gospel sentence.","rejection_reason":"the Gospel citation uses a specific portion of the prophetic image.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Ви простежили явний міжтекстовий зв'язок, не розширюючи цитату понад те, що використано в сцені.","partial_feedback":"Попросіть виокремити фразу/образ, присутній у всіх трьох текстах.","failure_feedback":"Зіставте лише образ пастиря та овець.","hints":{"H1":"Порівнюйте лише той фрагмент пророчого образу, який явно використаний у Матвія та Марка.","H2":"Читайте Зах 13:7 поруч з Мт 26:31 і Мк 14:27.","H3":"Знайдіть спільні образні ролі та дію: хто зазнає удару і що відбувається з вівцями.","H4":"Не переносіть усі деталі Зах 13:7–9 у євангельську цитату; завдання про конкретний міжтекстовий зв’язок.","H5":"Якщо відповідь виходить за межі пастиря й овець, звузьте її до частини образу, реально присутньої у всіх трьох місцях.","H6":"Опорні місця: Зах 13:7; Мт 26:31; Мк 14:27.","H7":"Керована модель: в обох синоптичних уривках застосовано зв’язок «уражений пастир → розсіяні вівці»; інші деталі Захарії не додаються автоматично."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_narrow_comparison","on_incorrect":"return_to_current_node_guided_cross_reference","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_OT_CROSS_REFERENCE_REVIEW","mastery_domains":["cross-reference"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_OT_CROSS_REFERENCE_REVIEW","functional_nonvisual_equivalent":"Three passages are read sequentially; relation is stated in text rather than only as a graph edge."},{"node_id":"LN04-O02","mission_id":"LN-04","task_family":"optional linguistic evidence","difficulty":"5/6","required":false,"skill_target":"observe number shift without doctrinal overreach","knowledge_target":"plural-to-singular address pattern in Luke 22:31–32","why_this_node_exists":"introduces careful language-level observation and translation-note literacy.","player_prompt":"За текстовою/мовною приміткою до Лк 22:31–32, що змінюється у звертанні між загрозою просіювання і молитвою Ісуса, і який мінімальний висновок дозволено зробити?","source_scope_visible_to_player":"Lk 22:31–32 with a translation or Greek-number note that explicitly marks plural/singular forms.","response_mode":"evidence interpretation","accepted_answer":"У в.31 звернення «вас» стосується множини, тоді як у в.32 молитва звернена до Симона в однині; мінімальний висновок — загроза описана ширше щодо учнів, а молитва у формулюванні в.32 персонально адресована Симонові. Не потрібно виводити з граматики ширшу доктрину.","accepted_variants":"equivalent cautious linguistic statement.","required_evidence":"explicit translation/Greek-number note for Lk 22:31–32.","rejected_answers":"constructing a denominational doctrine as the only required answer from the pronoun shift.","rejection_reason":"exceeds the linguistic evidence.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Мовна деталь може бути доказом, але її сила обмежена тим, що вона реально показує.","partial_feedback":"Відділіть граматичне спостереження від подальшого тлумачення.","failure_feedback":"Спочатку назвіть лише число займенника в кожному вірші; тлумачення залиште другим кроком.","hints":{"H1":"Спочатку зробіть чисте граматичне спостереження; тлумачення додавайте лише другим кроком.","H2":"Потрібна явна перекладацька або мовна примітка до Лк 22:31–32, що показує число форм.","H3":"Порівняйте форму «вас» у в.31 з адресатом молитви у в.32.","H4":"Розділіть observation і inference: множина/однина — текстовий факт примітки; ширша доктрина не випливає автоматично.","H5":"Мінімально допустимий висновок має стосуватися лише ширшого контексту загрози та персональної адресації молитви Симонові.","H6":"Опора: Лк 22:31–32 + явна примітка про plural/singular forms.","H7":"Керована модель: у в.31 «вас» стосується множини, а у в.32 молитва персонально адресована Симонові; дозволений мінімальний висновок — загроза описана ширше щодо учнів, а молитва сформульована щодо Симона, без додаткової доктринальної побудови."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_observation_vs_interpretation","on_incorrect":"return_to_current_node_guided_language_note","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LANGUAGE_NOTE_REVIEW","mastery_domains":["language-note literacy"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LANGUAGE_NOTE_REVIEW","functional_nonvisual_equivalent":"Grammar is announced as literal words «множина/однина», never only formatting or color."}]} diff --git a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_01.json b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_01.json index f87508cb8..db3fe6d4a 100644 --- a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_01.json +++ b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_01.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":1,"nodes":[{"node_id":"LN09-N01","mission_id":"LN-09","task_family":"delayed retrieval","difficulty":"3/6","required":true,"skill_target":"retrieve prediction without hindsight","knowledge_target":"LN-04 common-core prediction","why_this_node_exists":"preserves genuine prediction→fulfilment learning instead of allowing the fulfilment text to rewrite the remembered prediction.","player_prompt":"Не відкриваючи сцену зречення, відтворіть мінімальне передбачення, яке було спільним для чотирьох свідків у LN-04.","source_scope_visible_to_player":"LN-04 memory only; source reveal available through hints.","response_mode":"free response","accepted_answer":"Петро тричі зречеться/заперечить належність або знання Ісуса до співу півня / півнячого маркера.","accepted_variants":"semantic equivalents; Mark-specific «двічі» is not required for the common-core answer.","required_evidence":"retrieval anchors Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38 after response.","rejected_answers":"«один раз»; «Юда зречеться»; forcing «двічі» as common to all four.","rejection_reason":"prediction count/person/common-core mismatch.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Прогноз відновлено до перегляду виконання: Петро, три зречення, півнячий маркер.","partial_feedback":"Названо Петра і три зречення, але пропущено часовий маркер — попросити відновити його.","failure_feedback":"Поверніться до числа зречень і ранкового звукового маркера, зафіксованих у LN-04.","hints":{"H1":"Відновіть лише мінімальне спільне передбачення.","H2":"not_used","H3":"Джерела LN-04: Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38.","H4":"not_used","H5":"Ключове число: три.","H6":"Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38.","H7":"Петро — три зречення — півнячий маркер; guided."},"on_correct":"LN09-N02","on_partial":"return_to_current_node_for_missing_element","on_incorrect":"return_to_current_node_after_prediction_anchor_correction","on_hint_threshold":"guided_then_LN09-N02","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["prediction-to-fulfilment","recall"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Labelled plain-text response; hint levels are announced individually; no timer."},{"node_id":"LN09-N02","mission_id":"LN-09","task_family":"source selection","difficulty":"1/6","required":true,"skill_target":"source delimitation","knowledge_target":"four denial passages","why_this_node_exists":"prevents solving from a single remembered narrative.","player_prompt":"Оберіть чотири уривки, які безпосередньо описують виконання зречень Петра.","source_scope_visible_to_player":"Gospel references.","response_mode":"citation selection","accepted_answer":"Mt 26:69–75; Mk 14:66–72; Lk 22:54–62; Jn 18:15–18,25–27.","accepted_variants":"slightly wider ranges containing the complete scenes.","required_evidence":"all four primary passages.","rejected_answers":"prediction verses as substitutes; unrelated later restoration passages.","rejection_reason":"this node gathers fulfilment evidence.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Корпус виконання зібрано. Відтепер кожна деталь повинна зберігати походження від конкретного свідка.","partial_feedback":"Назвіть лише відсутнє Євангеліє й повторіть його вибір.","failure_feedback":"Шукайте дворові сцени після арешту, а не попередження перед ними.","hints":{"H1":"not_used","H2":"Потрібні всі чотири Євангелія.","H3":"Mt 26; Mk 14; Lk 22; Jn 18.","H4":"not_used","H5":"not_used","H6":"Mt 26:69–75; Mk 14:66–72; Lk 22:54–62; Jn 18:15–18,25–27.","H7":"not_used"},"on_correct":"LN09-N03","on_partial":"return_to_current_node_missing_witness_only","on_incorrect":"return_to_current_node_after_source_boundary_correction","on_hint_threshold":"guided_then_LN09-N03","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_DENIAL_SOURCE_DELIMITATION_REVIEW","mastery_domains":["source-citation"],"evidence_strength":["recognition"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_DENIAL_SOURCE_DELIMITATION_REVIEW","functional_nonvisual_equivalent":"Linear labelled checklist with keyboard selection and spoken checkbox state."},{"node_id":"LN09-N03","mission_id":"LN-09","task_family":"prediction-to-fulfilment comparison","difficulty":"3/6","required":true,"skill_target":"compare prior prediction with later evidence","knowledge_target":"three denials + rooster fulfilment","why_this_node_exists":"turns the scene into evidence comparison rather than trivia.","player_prompt":"Яка частина передбачення LN-04 безпосередньо підтверджується всіма чотирма розповідями виконання?","source_scope_visible_to_player":"four primary passages + retrieved prediction summary.","response_mode":"evidence linking","accepted_answer":"Усі чотири описують три епізоди зречення/заперечення Петра, після яких настає спів півня або півнячий маркер.","accepted_variants":"wording preserving count and rooster relationship without forcing Mark’s «twice» on other witnesses.","required_evidence":"Mt 26:70,72,74–75; Mk 14:68,70–72; Lk 22:57,58,60–61; Jn 18:17,25,27.","rejected_answers":"«усі чотири кажуть, що Петро плакав»; «усі чотири називають трьох однакових обвинувачів».","rejection_reason":"those are not common to all four assigned passages.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Передбачення підтверджене на рівні спільного ядра, але деталі виконання залишаються свідко-специфічними.","partial_feedback":"Попросіть додати лише відсутній count або rooster marker.","failure_feedback":"Порівняйте тільки структуру трьох заперечень і завершальний маркер.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Порахуйте епізоди.","H5":"Знайдіть завершальний півнячий маркер.","H6":"Use the decisive verses listed in required_evidence.","H7":"not_used"},"on_correct":"LN09-N04","on_partial":"return_to_current_node_missing_dimension","on_incorrect":"return_to_current_node_after_witness_count_check","on_hint_threshold":"guided_then_LN09-N04","optional_evidence_unlock":"LN09-O01","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["prediction-to-fulfilment"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear chain `prediction → Matthew → Mark → Luke → John → verdict`; no visual evidence board required."},{"node_id":"LN09-N04","mission_id":"LN-09","task_family":"witness-provenance classification","difficulty":"3/6","required":true,"skill_target":"keep accuser provenance","knowledge_target":"first accuser in each witness","why_this_node_exists":"prevents false one-to-one harmonization of accusers.","player_prompt":"Розкладіть перший епізод за свідками: хто прямо звертається до Петра?","source_scope_visible_to_player":"Mt 26:69–70; Mk 14:66–68; Lk 22:55–57; Jn 18:15–18.","response_mode":"classification","accepted_answer":"Matthew — a servant girl; Mark — one of the high priest’s servant girls; Luke — a servant girl; John — the servant girl/door keeper.","accepted_variants":"translation-equivalent servant/maid terminology.","required_evidence":"cited verse units.","rejected_answers":"asserting the texts identify one named woman across all four; giving a personal name.","rejection_reason":"no personal name is supplied in these passages and cross-witness identity is not established.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Перший епізод має схожий тип обвинувача, але тексти не дають права назвати одну конкретну жінку спільною для всіх чотирьох.","partial_feedback":"Якщо один свідок помилково зіставлений, перевіряється лише він.","failure_feedback":"Працюйте з роллю, яку прямо називає кожен текст, а не з популярною реконструкцією.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Шукайте соціальну/службову роль, а не ім’я.","H5":"not_used","H6":"Mt 26:69–70; Mk 14:66–68; Lk 22:55–57; Jn 18:15–18.","H7":"not_used"},"on_correct":"LN09-N05","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_provenance_correction","on_hint_threshold":"guided_then_LN09-N05","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Each witness is a separate heading and ordinary labelled selection; no drag-and-drop."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":1,"nodes":[{"node_id":"LN09-N01","mission_id":"LN-09","task_family":"delayed retrieval","difficulty":"3/6","required":true,"skill_target":"retrieve prediction without hindsight","knowledge_target":"LN-04 common-core prediction","why_this_node_exists":"preserves genuine prediction→fulfilment learning instead of allowing the fulfilment text to rewrite the remembered prediction.","player_prompt":"Не відкриваючи сцену зречення, відтворіть мінімальне передбачення, яке було спільним для чотирьох свідків у LN-04.","source_scope_visible_to_player":"LN-04 memory only; source reveal available through hints.","response_mode":"free response","accepted_answer":"Петро тричі зречеться/заперечить належність або знання Ісуса до співу півня / півнячого маркера.","accepted_variants":"semantic equivalents; Mark-specific «двічі» is not required for the common-core answer.","required_evidence":"retrieval anchors Mt 26:34; Mk 14:30; Lk 22:34; Jn 13:38 after response.","rejected_answers":"«один раз»; «Юда зречеться»; forcing «двічі» as common to all four.","rejection_reason":"prediction count/person/common-core mismatch.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Прогноз відновлено до перегляду виконання: Петро, три зречення, півнячий маркер.","partial_feedback":"Названо Петра і три зречення, але пропущено часовий маркер — попросити відновити його.","failure_feedback":"Поверніться до числа зречень і ранкового звукового маркера, зафіксованих у LN-04.","hints":{"H1":"Відновлюйте тільки мінімальне спільне передбачення з LN-04, не використовуючи знання про те, як саме воно виконалося.","H2":"Після власної відповіді звірення буде з Мт 26:34, Мк 14:30, Лк 22:34 та Ів 13:38; до того тримайте в пам’яті лише спільне ядро.","H3":"У спільному ядрі мають бути три елементи: особа, кількість заперечень/зречень і півнячий часовий маркер.","H4":"Не робіть марківське «двічі» частиною спільного для всіх чотирьох формулювання — це окрема witness/TX1 деталь.","H5":"Якщо відповідь називає Петра і число три, перевірте, чи додано межу «до співу півня / півнячого маркера».","H6":"Після спроби опорні місця: Мт 26:34; Мк 14:30; Лк 22:34; Ів 13:38.","H7":"Керована модель: Петро тричі зречеться/заперечить свою належність або знання Ісуса до співу півня; після розкриття результат фіксується як guided mastery."},"on_correct":"LN09-N02","on_partial":"return_to_current_node_for_missing_element","on_incorrect":"return_to_current_node_after_prediction_anchor_correction","on_hint_threshold":"guided_then_LN09-N02","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["prediction-to-fulfilment","recall"],"evidence_strength":["recall"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Labelled plain-text response; hint levels are announced individually; no timer."},{"node_id":"LN09-N02","mission_id":"LN-09","task_family":"source selection","difficulty":"1/6","required":true,"skill_target":"source delimitation","knowledge_target":"four denial passages","why_this_node_exists":"prevents solving from a single remembered narrative.","player_prompt":"Оберіть чотири уривки, які безпосередньо описують виконання зречень Петра.","source_scope_visible_to_player":"Gospel references.","response_mode":"citation selection","accepted_answer":"Mt 26:69–75; Mk 14:66–72; Lk 22:54–62; Jn 18:15–18,25–27.","accepted_variants":"slightly wider ranges containing the complete scenes.","required_evidence":"all four primary passages.","rejected_answers":"prediction verses as substitutes; unrelated later restoration passages.","rejection_reason":"this node gathers fulfilment evidence.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Корпус виконання зібрано. Відтепер кожна деталь повинна зберігати походження від конкретного свідка.","partial_feedback":"Назвіть лише відсутнє Євангеліє й повторіть його вибір.","failure_feedback":"Шукайте дворові сцени після арешту, а не попередження перед ними.","hints":{"H1":"Відокремте уривки виконання від уривків передбачення: тут потрібні сцени, де зречення вже відбуваються.","H2":"Знайдіть по одному primary fulfilment passage у Матвія, Марка, Луки та Івана.","H3":"Звузьте пошук до Мт 26, Мк 14, Лк 22 та Ів 18; у кожному потрібен блок із трьома епізодами заперечення.","H4":"Не замінюйте fulfilment passage ані передбаченням, ані пізнішою сценою відновлення Петра.","H5":"Для Івана потрібен розірваний діапазон, бо між першим і наступними запереченнями оповідь повертається до допиту Ісуса.","H6":"Вирішальні діапазони: Мт 26:69–75; Мк 14:66–72; Лк 22:54–62; Ів 18:15–18,25–27.","H7":"Керована модель: оберіть саме Мт 26:69–75; Мк 14:66–72; Лк 22:54–62; Ів 18:15–18,25–27; reveal переводить mastery у guided."},"on_correct":"LN09-N03","on_partial":"return_to_current_node_missing_witness_only","on_incorrect":"return_to_current_node_after_source_boundary_correction","on_hint_threshold":"guided_then_LN09-N03","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_DENIAL_SOURCE_DELIMITATION_REVIEW","mastery_domains":["source-citation"],"evidence_strength":["recognition"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_DENIAL_SOURCE_DELIMITATION_REVIEW","functional_nonvisual_equivalent":"Linear labelled checklist with keyboard selection and spoken checkbox state."},{"node_id":"LN09-N03","mission_id":"LN-09","task_family":"prediction-to-fulfilment comparison","difficulty":"3/6","required":true,"skill_target":"compare prior prediction with later evidence","knowledge_target":"three denials + rooster fulfilment","why_this_node_exists":"turns the scene into evidence comparison rather than trivia.","player_prompt":"Яка частина передбачення LN-04 безпосередньо підтверджується всіма чотирма розповідями виконання?","source_scope_visible_to_player":"four primary passages + retrieved prediction summary.","response_mode":"evidence linking","accepted_answer":"Усі чотири описують три епізоди зречення/заперечення Петра, після яких настає спів півня або півнячий маркер.","accepted_variants":"wording preserving count and rooster relationship without forcing Mark’s «twice» on other witnesses.","required_evidence":"Mt 26:70,72,74–75; Mk 14:68,70–72; Lk 22:57,58,60–61; Jn 18:17,25,27.","rejected_answers":"«усі чотири кажуть, що Петро плакав»; «усі чотири називають трьох однакових обвинувачів».","rejection_reason":"those are not common to all four assigned passages.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Передбачення підтверджене на рівні спільного ядра, але деталі виконання залишаються свідко-специфічними.","partial_feedback":"Попросіть додати лише відсутній count або rooster marker.","failure_feedback":"Порівняйте тільки структуру трьох заперечень і завершальний маркер.","hints":{"H1":"Порівнюйте лише те, що всі чотири fulfilment passages реально мають спільного.","H2":"Для кожного Євангелія окремо порахуйте епізоди заперечення і знайдіть завершальний півнячий маркер.","H3":"Позитивні anchors розподілені так: Мт 26:70,72,74–75; Мк 14:68,70–72; Лк 22:57,58,60–61; Ів 18:17,25,27.","H4":"Не додавайте до спільного ядра плач Петра, погляд Ісуса чи тотожність обвинувачів — ці деталі не підтримуються всіма чотирма.","H5":"Перевірте два компоненти відповіді: три окремі епізоди + спів півня/півнячий маркер після них.","H6":"Опорні вірші: Мт 26:70,72,74–75; Мк 14:68,70–72; Лк 22:57,58,60–61; Ів 18:17,25,27.","H7":"Керована модель: усі чотири свідчення описують три епізоди зречення/заперечення Петра, після яких настає спів півня або відповідний півнячий маркер."},"on_correct":"LN09-N04","on_partial":"return_to_current_node_missing_dimension","on_incorrect":"return_to_current_node_after_witness_count_check","on_hint_threshold":"guided_then_LN09-N04","optional_evidence_unlock":"LN09-O01","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["prediction-to-fulfilment"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear chain `prediction → Matthew → Mark → Luke → John → verdict`; no visual evidence board required."},{"node_id":"LN09-N04","mission_id":"LN-09","task_family":"witness-provenance classification","difficulty":"3/6","required":true,"skill_target":"keep accuser provenance","knowledge_target":"first accuser in each witness","why_this_node_exists":"prevents false one-to-one harmonization of accusers.","player_prompt":"Розкладіть перший епізод за свідками: хто прямо звертається до Петра?","source_scope_visible_to_player":"Mt 26:69–70; Mk 14:66–68; Lk 22:55–57; Jn 18:15–18.","response_mode":"classification","accepted_answer":"Matthew — a servant girl; Mark — one of the high priest’s servant girls; Luke — a servant girl; John — the servant girl/door keeper.","accepted_variants":"translation-equivalent servant/maid terminology.","required_evidence":"cited verse units.","rejected_answers":"asserting the texts identify one named woman across all four; giving a personal name.","rejection_reason":"no personal name is supplied in these passages and cross-witness identity is not established.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Перший епізод має схожий тип обвинувача, але тексти не дають права назвати одну конкретну жінку спільною для всіх чотирьох.","partial_feedback":"Якщо один свідок помилково зіставлений, перевіряється лише він.","failure_feedback":"Працюйте з роллю, яку прямо називає кожен текст, а не з популярною реконструкцією.","hints":{"H1":"Працюйте лише з першим епізодом і з тим, як кожен текст називає того, хто звертається до Петра.","H2":"Читайте Мт 26:69–70; Мк 14:66–68; Лк 22:55–57; Ів 18:15–18 окремо, не зливаючи осіб між свідками.","H3":"У кожному уривку випишіть соціальну/службову роль першого співрозмовника Петра, не шукаючи особистого імені.","H4":"Відмінність полягає у формулюваннях ролі: служниця; одна зі служниць первосвященника; служниця; служниця-привратниця.","H5":"Якщо виникає спокуса назвати одну й ту саму жінку в усіх чотирьох, перевірте, чи хоч один із цих уривків установлює таку тотожність або ім’я.","H6":"Опорні місця: Мт 26:69–70; Мк 14:66–68; Лк 22:55–57; Ів 18:15–18.","H7":"Керована модель: Матвій — служниця; Марко — одна зі служниць первосвященника; Лука — служниця; Іван — служниця/привратниця. Особисте ім’я або єдина cross-witness identity не встановлені."},"on_correct":"LN09-N05","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_provenance_correction","on_hint_threshold":"guided_then_LN09-N05","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Each witness is a separate heading and ordinary labelled selection; no drag-and-drop."}]} diff --git a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_02.json b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_02.json index 6df70f109..9a801776c 100644 --- a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_02.json +++ b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_02.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":2,"nodes":[{"node_id":"LN09-N05","mission_id":"LN-09","task_family":"close-reading comparison","difficulty":"3/6","required":true,"skill_target":"distinguish semantic core from wording","knowledge_target":"first-denial formulations","why_this_node_exists":"teaches semantic equivalence without flattening author wording.","player_prompt":"Порівняйте першу відповідь Петра. Яке спільне смислове ядро і які формулювання не можна оголошувати дослівно однаковими?","source_scope_visible_to_player":"Mt 26:70; Mk 14:68; Lk 22:57; Jn 18:17.","response_mode":"comparison/free response","accepted_answer":"Спільно Петро відкидає зв’язок із Ісусом; Matthew/Mark frame denial as not knowing/understanding the accusation, Luke says he does not know him, John says he is not one of the disciples.","accepted_variants":"semantic paraphrases preserving witness distinctions.","required_evidence":"Mt 26:70; Mk 14:68; Lk 22:57; Jn 18:17.","rejected_answers":"«усі чотири дослівно: “Я не знаю Ісуса”».","rejection_reason":"John’s direct response and Matthew/Mark formulations differ.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Смислове ядро спільне, але форма заперечення різна — саме це і треба зберегти.","partial_feedback":"Позначте, який свідок не відповідає запропонованій універсальній формулі.","failure_feedback":"Не шукайте одну універсальну цитату; порівняйте речення окремо.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"Перевірте, чи кожен текст прямо використовує ідею «know».","H6":"Mt 26:70; Mk 14:68; Lk 22:57; Jn 18:17.","H7":"not_used"},"on_correct":"LN09-N06","on_partial":"return_to_current_node_targeted_comparison","on_incorrect":"return_to_current_node_after_quote_to_witness_correction","on_hint_threshold":"guided_then_LN09-N06","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["wording-vs-proposition","explicit-vs-harmonized"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Four short text blocks in sequential witness order; no visual parallel layout required."},{"node_id":"LN09-N06","mission_id":"LN-09","task_family":"witness-provenance comparison","difficulty":"4/6","required":true,"skill_target":"maintain second-episode provenance","knowledge_target":"second accuser differences","why_this_node_exists":"second denial is a major harmonization trap.","player_prompt":"Хто або яка група ініціює другий епізод у кожному свідченні?","source_scope_visible_to_player":"Mt 26:71–72; Mk 14:69–70; Lk 22:58; Jn 18:25.","response_mode":"witness matrix/classification","accepted_answer":"Matthew — another servant girl speaks to those present; Mark — the servant girl sees him and again tells bystanders; Luke — another person sees/challenges him; John — a plural group asks whether he is one of the disciples.","accepted_variants":"translation-equivalent gender-neutral rendering for Luke where appropriate.","required_evidence":"cited verses.","rejected_answers":"claiming all four explicitly say «друга служниця»; claiming all four identify same person.","rejection_reason":"source provenance differs.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Другий епізод — приклад того, чому рахувати три зречення не означає мати три однакові набори обвинувачів.","partial_feedback":"Повторно перевіряється лише свідок із неправильною відповідністю.","failure_feedback":"Подивіться на граматичного суб’єкта кожного другого звинувачення.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Зосередьтеся на тому, хто говорить.","H5":"not_used","H6":"Mt 26:71–72; Mk 14:69–70; Lk 22:58; Jn 18:25.","H7":"not_used"},"on_correct":"LN09-N07","on_partial":"return_to_current_node_targeted_repair","on_incorrect":"return_to_current_node_after_provenance_correction","on_hint_threshold":"guided_then_LN09-N07","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear matrix `witness → accuser → Peter response → verse`; keyboard-complete."},{"node_id":"LN09-N07","mission_id":"LN-09","task_family":"evidence-reason comparison","difficulty":"4/6","required":true,"skill_target":"distinguish evidentiary grounds","knowledge_target":"third-accusation reasons","why_this_node_exists":"shows that similar event structure can rest on different explicit evidence.","player_prompt":"Які підстави для третього звинувачення прямо називає кожен свідок?","source_scope_visible_to_player":"Mt 26:73; Mk 14:70; Lk 22:59; Jn 18:26.","response_mode":"evidence linking","accepted_answer":"Matthew — Peter’s speech/accent exposes him; Mark — he is identified as Galilean; Luke — accuser says he was with Jesus because he is a Galilean; John — a relative of the man whose ear Peter cut off says he saw Peter in the garden with Jesus.","accepted_variants":"Matthew «speech/manner of speaking/accent»; Mark/Luke «Galilean»; John «seen in the garden».","required_evidence":"Mt 26:73; Mk 14:70; Lk 22:59; Jn 18:26.","rejected_answers":"assigning Malchus’ relative to Matthew/Mark/Luke; saying John uses Galilean accent.","rejection_reason":"witness-provenance error.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Третій епізод спільно посилює ідентифікацію Петра, але доказ різниться за свідком.","partial_feedback":"Ізолюйте тільки неправильного свідка.","failure_feedback":"Шукайте не саму відповідь Петра, а підставу, яку називає обвинувач.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"not_used","H5":"Ключі: speech / Galilean / garden.","H6":"Mt 26:73; Mk 14:70; Lk 22:59; Jn 18:26.","H7":"not_used"},"on_correct":"LN09-N08","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_source_recheck","on_hint_threshold":"guided_then_LN09-N08","optional_evidence_unlock":"LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["evidence-linking","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Every `claim → evidence` pair is available as text; graphical evidence lines are optional."},{"node_id":"LN09-N08","mission_id":"LN-09","task_family":"local chronology reconstruction","difficulty":"3/6","required":true,"skill_target":"reconstruct one witness internally","knowledge_target":"Matthew’s escalation","why_this_node_exists":"local chronology is safe when the witness explicitly supplies it.","player_prompt":"Відновіть лише Матвієву послідовність ескалації від першої відповіді до півня.","source_scope_visible_to_player":"Mt 26:69–75 only.","response_mode":"ordering","accepted_answer":"servant girl accusation → denial before all → gateway/another servant girl → denial with oath → bystanders/accent → curses and swearing + denial → rooster → remembrance → goes out/weeps bitterly.","accepted_variants":"equivalent grouping preserving order.","required_evidence":"Mt 26:69–75.","rejected_answers":"inserting Luke’s look of Jesus; inserting John’s Malchus-relative detail.","rejection_reason":"imported from other witnesses.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Матвієва локальна послідовність відновлена без домішок з інших свідків.","partial_feedback":"Вкажіть перший неправильно розміщений крок.","failure_feedback":"Працюйте тільки всередині Матвія.","hints":{"H1":"not_used","H2":"not_used","H3":"Mt 26:69–75.","H4":"Виділіть три accusation units.","H5":"not_used","H6":"Follow Mt 26:69–75 verse by verse.","H7":"not_used"},"on_correct":"LN09-N09","on_partial":"return_to_current_node_reorder_disputed_steps","on_incorrect":"return_to_current_node_after_witness_boundary_correction","on_hint_threshold":"guided_then_LN09-N09","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LOCAL_CHRONOLOGY_REVIEW","mastery_domains":["local-chronology"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LOCAL_CHRONOLOGY_REVIEW","functional_nonvisual_equivalent":"Ordering uses numbered placement or move-up/move-down; drag-and-drop is never mandatory."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":2,"nodes":[{"node_id":"LN09-N05","mission_id":"LN-09","task_family":"close-reading comparison","difficulty":"3/6","required":true,"skill_target":"distinguish semantic core from wording","knowledge_target":"first-denial formulations","why_this_node_exists":"teaches semantic equivalence without flattening author wording.","player_prompt":"Порівняйте першу відповідь Петра. Яке спільне смислове ядро і які формулювання не можна оголошувати дослівно однаковими?","source_scope_visible_to_player":"Mt 26:70; Mk 14:68; Lk 22:57; Jn 18:17.","response_mode":"comparison/free response","accepted_answer":"Спільно Петро відкидає зв’язок із Ісусом; Matthew/Mark frame denial as not knowing/understanding the accusation, Luke says he does not know him, John says he is not one of the disciples.","accepted_variants":"semantic paraphrases preserving witness distinctions.","required_evidence":"Mt 26:70; Mk 14:68; Lk 22:57; Jn 18:17.","rejected_answers":"«усі чотири дослівно: “Я не знаю Ісуса”».","rejection_reason":"John’s direct response and Matthew/Mark formulations differ.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Смислове ядро спільне, але форма заперечення різна — саме це і треба зберегти.","partial_feedback":"Позначте, який свідок не відповідає запропонованій універсальній формулі.","failure_feedback":"Не шукайте одну універсальну цитату; порівняйте речення окремо.","hints":{"H1":"Спочатку сформулюйте спільний смисл першого заперечення, а вже потім порівнюйте точне словесне оформлення.","H2":"Зіставте тільки Мт 26:70; Мк 14:68; Лк 22:57; Ів 18:17.","H3":"Поставте до кожного тексту питання: Петро заперечує знання/розуміння твердження, знання Ісуса чи належність до учнів?","H4":"Спільний semantic core не дає права створити одну вигадану дослівну цитату для всіх чотирьох свідків.","H5":"Особливо перевірте Івана: його пряма відповідь стосується того, чи є Петро одним з учнів, а не формули «я не знаю Ісуса».","H6":"Опорні вірші: Мт 26:70; Мк 14:68; Лк 22:57; Ів 18:17.","H7":"Керована модель: спільно Петро відкидає зв’язок з Ісусом; Матвій/Марко формулюють це через незнання/нерозуміння обвинувачення, Лука — «не знаю Його», Іван — «я не один з учнів»."},"on_correct":"LN09-N06","on_partial":"return_to_current_node_targeted_comparison","on_incorrect":"return_to_current_node_after_quote_to_witness_correction","on_hint_threshold":"guided_then_LN09-N06","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["wording-vs-proposition","explicit-vs-harmonized"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Four short text blocks in sequential witness order; no visual parallel layout required."},{"node_id":"LN09-N06","mission_id":"LN-09","task_family":"witness-provenance comparison","difficulty":"4/6","required":true,"skill_target":"maintain second-episode provenance","knowledge_target":"second accuser differences","why_this_node_exists":"second denial is a major harmonization trap.","player_prompt":"Хто або яка група ініціює другий епізод у кожному свідченні?","source_scope_visible_to_player":"Mt 26:71–72; Mk 14:69–70; Lk 22:58; Jn 18:25.","response_mode":"witness matrix/classification","accepted_answer":"Matthew — another servant girl speaks to those present; Mark — the servant girl sees him and again tells bystanders; Luke — another person sees/challenges him; John — a plural group asks whether he is one of the disciples.","accepted_variants":"translation-equivalent gender-neutral rendering for Luke where appropriate.","required_evidence":"cited verses.","rejected_answers":"claiming all four explicitly say «друга служниця»; claiming all four identify same person.","rejection_reason":"source provenance differs.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Другий епізод — приклад того, чому рахувати три зречення не означає мати три однакові набори обвинувачів.","partial_feedback":"Повторно перевіряється лише свідок із неправильною відповідністю.","failure_feedback":"Подивіться на граматичного суб’єкта кожного другого звинувачення.","hints":{"H1":"Для другого епізоду простежте, хто саме ініціює нове звинувачення або питання в кожному свідченні.","H2":"Окремо прочитайте Мт 26:71–72; Мк 14:69–70; Лк 22:58; Ів 18:25.","H3":"Запишіть роль/кількість мовців для кожного тексту: інша служниця; та сама/служниця в марківському викладі; інша особа; група.","H4":"Не нормалізуйте всі чотири тексти до «друга служниця» і не встановлюйте cross-witness identity, якої уривки не заявляють.","H5":"Для Івана зверніть увагу на множину запитувачів; для Луки текст говорить про іншу особу без вимоги називати її служницею.","H6":"Опорні місця: Мт 26:71–72; Мк 14:69–70; Лк 22:58; Ів 18:25.","H7":"Керована модель: Матвій — інша служниця говорить присутнім; Марко — служниця знову говорить стороннім; Лука — інша особа кидає виклик; Іван — група питає, чи Петро один з учнів."},"on_correct":"LN09-N07","on_partial":"return_to_current_node_targeted_repair","on_incorrect":"return_to_current_node_after_provenance_correction","on_hint_threshold":"guided_then_LN09-N07","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear matrix `witness → accuser → Peter response → verse`; keyboard-complete."},{"node_id":"LN09-N07","mission_id":"LN-09","task_family":"evidence-reason comparison","difficulty":"4/6","required":true,"skill_target":"distinguish evidentiary grounds","knowledge_target":"third-accusation reasons","why_this_node_exists":"shows that similar event structure can rest on different explicit evidence.","player_prompt":"Які підстави для третього звинувачення прямо називає кожен свідок?","source_scope_visible_to_player":"Mt 26:73; Mk 14:70; Lk 22:59; Jn 18:26.","response_mode":"evidence linking","accepted_answer":"Matthew — Peter’s speech/accent exposes him; Mark — he is identified as Galilean; Luke — accuser says he was with Jesus because he is a Galilean; John — a relative of the man whose ear Peter cut off says he saw Peter in the garden with Jesus.","accepted_variants":"Matthew «speech/manner of speaking/accent»; Mark/Luke «Galilean»; John «seen in the garden».","required_evidence":"Mt 26:73; Mk 14:70; Lk 22:59; Jn 18:26.","rejected_answers":"assigning Malchus’ relative to Matthew/Mark/Luke; saying John uses Galilean accent.","rejection_reason":"witness-provenance error.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Третій епізод спільно посилює ідентифікацію Петра, але доказ різниться за свідком.","partial_feedback":"Ізолюйте тільки неправильного свідка.","failure_feedback":"Шукайте не саму відповідь Петра, а підставу, яку називає обвинувач.","hints":{"H1":"Тут важлива не лише третя репліка, а саме підстава, якою кожен свідок обґрунтовує впізнання Петра.","H2":"Порівняйте Мт 26:73; Мк 14:70; Лк 22:59; Ів 18:26.","H3":"Шукайте чотири різні типи доказу: мова/акцент; галилейська належність; галилейська належність + перебування з Ісусом; особисте спостереження в саду.","H4":"Не переносіть Іванового родича пораненого слуги в синоптиків і не приписуйте Іванові аргумент про галилейський акцент.","H5":"Якщо відповідь зводить Матвія, Марка й Луку до одного формулювання, поверніться до того, що саме кожен текст прямо називає підставою.","H6":"Опорні місця: Мт 26:73; Мк 14:70; Лк 22:59; Ів 18:26.","H7":"Керована модель: Матвій — мова/акцент видає Петра; Марко — його визначають як галилеянина; Лука — він був з Ісусом, бо є галилеянином; Іван — родич пораненого слуги каже, що бачив Петра в саду з Ісусом."},"on_correct":"LN09-N08","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_source_recheck","on_hint_threshold":"guided_then_LN09-N08","optional_evidence_unlock":"LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["evidence-linking","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Every `claim → evidence` pair is available as text; graphical evidence lines are optional."},{"node_id":"LN09-N08","mission_id":"LN-09","task_family":"local chronology reconstruction","difficulty":"3/6","required":true,"skill_target":"reconstruct one witness internally","knowledge_target":"Matthew’s escalation","why_this_node_exists":"local chronology is safe when the witness explicitly supplies it.","player_prompt":"Відновіть лише Матвієву послідовність ескалації від першої відповіді до півня.","source_scope_visible_to_player":"Mt 26:69–75 only.","response_mode":"ordering","accepted_answer":"servant girl accusation → denial before all → gateway/another servant girl → denial with oath → bystanders/accent → curses and swearing + denial → rooster → remembrance → goes out/weeps bitterly.","accepted_variants":"equivalent grouping preserving order.","required_evidence":"Mt 26:69–75.","rejected_answers":"inserting Luke’s look of Jesus; inserting John’s Malchus-relative detail.","rejection_reason":"imported from other witnesses.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Матвієва локальна послідовність відновлена без домішок з інших свідків.","partial_feedback":"Вкажіть перший неправильно розміщений крок.","failure_feedback":"Працюйте тільки всередині Матвія.","hints":{"H1":"Реконструюйте тільки внутрішню послідовність Матвія 26:69–75; інші Євангелія тут не заповнюють прогалини.","H2":"Пройдіть Мт 26:69–75 вірш за віршем і позначте три accusation units, кожну відповідь Петра та завершення.","H3":"Каркас: перша служниця → перше заперечення; біля входу інша служниця → друге; присутні/мова → третє; потім півень і реакція.","H4":"Слідкуйте за ескалацією відповіді Петра: просте заперечення → заперечення з клятвою → прокляття/присягання та заперечення.","H5":"Не вставляйте сюди луківський погляд Ісуса або іванову деталь про родича чоловіка з відтятим вухом.","H6":"Весь вирішальний локальний корпус: Мт 26:69–75.","H7":"Керована модель: служниця → заперечення перед усіма → біля входу інша служниця → заперечення з клятвою → присутні/акцент → прокляття й присягання + заперечення → півень → згадка слів Ісуса → вихід і гіркий плач."},"on_correct":"LN09-N09","on_partial":"return_to_current_node_reorder_disputed_steps","on_incorrect":"return_to_current_node_after_witness_boundary_correction","on_hint_threshold":"guided_then_LN09-N09","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_LOCAL_CHRONOLOGY_REVIEW","mastery_domains":["local-chronology"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_LOCAL_CHRONOLOGY_REVIEW","functional_nonvisual_equivalent":"Ordering uses numbered placement or move-up/move-down; drag-and-drop is never mandatory."}]} diff --git a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_03.json b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_03.json index 67026e3ad..4ceb8f98a 100644 --- a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_03.json +++ b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_03.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":3,"nodes":[{"node_id":"LN09-N09","mission_id":"LN-09","task_family":"witness-specific detail extraction","difficulty":"3/6","required":true,"skill_target":"identify unique narrative details","knowledge_target":"Luke’s timing and look","why_this_node_exists":"prevents projecting memorable Lukan details into all four Gospels.","player_prompt":"Які три важливі деталі після/довкола зречень Лука прямо додає до своєї сцени?","source_scope_visible_to_player":"Lk 22:58–62.","response_mode":"evidence selection/free response","accepted_answer":"Приблизно година минає перед третім звинуваченням; після співу півня Господь обертається і дивиться на Петра; Петро згадує слово Господа, виходить і гірко плаче.","accepted_variants":"semantic equivalents.","required_evidence":"Lk 22:59,61–62.","rejected_answers":"«усі чотири прямо описують погляд Ісуса».","rejection_reason":"the look is explicit in Luke’s assigned passage, not all four.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука додає не лише часовий маркер, а й прямий наративний зв’язок «погляд → пам’ять → вихід/плач».","partial_feedback":"Назвіть відсутню категорію деталі.","failure_feedback":"Перевірте вірші 59, 61 і 62.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Категорії: час / погляд / реакція.","H5":"not_used","H6":"Lk 22:59,61–62.","H7":"not_used"},"on_correct":"LN09-N10","on_partial":"return_to_current_node_missing_category","on_incorrect":"return_to_current_node_after_Luke_only_recheck","on_hint_threshold":"guided_then_LN09-N10","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["Luke-detail","witness-provenance"],"evidence_strength":["recall","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Three text-labelled categories; no visual timeline matching required."},{"node_id":"LN09-N10","mission_id":"LN-09","task_family":"cross-mission retrieval/evidence linking","difficulty":"4/6","required":true,"skill_target":"use earlier evidence without misattributing it","knowledge_target":"Malchus-relative/garden link","why_this_node_exists":"demonstrates meaningful campaign memory.","player_prompt":"Яка деталь третього Іванового звинувачення напряму пов’язує LN-09 з арештом у LN-06?","source_scope_visible_to_player":"Jn 18:10,26–27 + LN-06 memory.","response_mode":"evidence linking","accepted_answer":"Третій обвинувач — слуга первосвященника, родич чоловіка, якому Петро відтяв вухо; він каже, що бачив Петра в саду з Ісусом. Ів 18:10 називає пораненого слугу Малхом.","accepted_variants":"semantic equivalents preserving relative + ear victim + garden.","required_evidence":"Jn 18:10; Jn 18:26.","rejected_answers":"«Іван каже, що сам Малх звинувачує Петра».","rejection_reason":"the accuser is a relative of the man whose ear Peter cut off, not explicitly Malchus himself.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Кампанійна пам’ять працює: деталь LN-06 стає доказом у LN-09, але родича не можна перетворювати на самого Малха.","partial_feedback":"Якщо згадано родича Малха, але пропущено сад, попросіть explicit accusation basis.","failure_feedback":"Порівняйте Ів 18:10 з 18:26.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Знайдіть родинний зв’язок.","H5":"Ключ: ear.","H6":"Jn 18:10; Jn 18:26.","H7":"not_used"},"on_correct":"LN09-N11","on_partial":"return_to_current_node_targeted_retry","on_incorrect":"return_to_current_node_after_relation_correction","on_hint_threshold":"guided_then_LN09-N11","optional_evidence_unlock":"LN09-O02","later_retrieval_effect":"REVIEW_QUEUE LN_PETER_PROVENANCE_REVIEW","mastery_domains":["cross-mission retrieval","John-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_PETER_PROVENANCE_REVIEW","functional_nonvisual_equivalent":"Cross-mission link is stated as words and citations; any visual thread is supplementary."},{"node_id":"LN09-N11","mission_id":"LN-09","task_family":"textual-variant-in-play","difficulty":"5/6","required":true,"skill_target":"handle manuscript/translation variation before grading","knowledge_target":"Mark 14:68,72 crow variation","why_this_node_exists":"the textual variant directly affects prediction-to-fulfilment matching.","player_prompt":"Як треба оцінювати відповідь гравця, якщо його переклад Марка має «півень заспівав удруге / двічі», а інший відповідальний переклад має примітку або коротшу форму без цієї деталі?","source_scope_visible_to_player":"Mk 14:68,72 + visible TX1 note before response.","response_mode":"classification/explanation","accepted_answer":"Обидві відповідальні текстові/перекладні форми мають прийматися; поширена форма містить другий спів/«двічі», але існує рання рукописна варіативність, тому відсутність цієї деталі не є помилкою користувача.","accepted_variants":"equivalent textual-critical explanation without requiring a position on originality.","required_evidence":"Mark textual footnote/variant metadata + canonical TEXTUAL_VARIANT_POLICY v1.0.","rejected_answers":"«переклад без “двічі” неправильний»; «гра повинна визначити єдину богонатхненну англійську/українську форму».","rejection_reason":"exceeds textual evidence and violates canonical policy.","confidence_code":"T1","textual_variant_flag":"TX1","success_feedback":"`TX1` застосовано правильно: варіант показано до оцінювання, а користувача не карають за відповідальну текстову традицію.","partial_feedback":"Прийміть факт варіативності; попросіть окремо відповісти, чи треба карати гравця.","failure_feedback":"Питання не просить вирішити, який рукопис первісний; воно перевіряє чесну поведінку гри при варіанті.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Це manuscript/textual variation.","H5":"Ключовий принцип: no penalty.","H6":"Mk 14:68,72 + textual notes.","H7":"Both responsible forms accepted; originality not graded."},"on_correct":"LN09-N12","on_partial":"return_to_current_node_for_policy_clarification","on_incorrect":"return_to_current_node_after_TX1_note_reread","on_hint_threshold":"guided_then_LN09-N12","optional_evidence_unlock":"LN09-O01","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["textual-variants","translation-neutrality"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"TX1 note is ordinary labelled text before grading; never badge/icon/color/tooltip-only."},{"node_id":"LN09-N12","mission_id":"LN-09","task_family":"post-event witness comparison","difficulty":"4/6","required":true,"skill_target":"distinguish explicit post-rooster details","knowledge_target":"remembrance/weeping/look differences","why_this_node_exists":"memorable later details are often falsely universalized.","player_prompt":"Класифікуйте, що прямо відбувається після півнячого маркера в кожному заданому уривку.","source_scope_visible_to_player":"terminal verses of all four passages.","response_mode":"witness matrix","accepted_answer":"Matthew — Peter remembers Jesus’ word, goes out, weeps bitterly; Mark — Peter remembers the prediction and reacts/weeps according to translation rendering; Luke — the Lord turns and looks at Peter, Peter remembers, goes out and weeps bitterly; John — Peter denies and immediately the rooster crows, with no remembrance/weeping stated in the assigned 18:15–18,25–27 passage.","accepted_variants":"translation-sensitive Mark reaction wording.","required_evidence":"Mt 26:75; Mk 14:72; Lk 22:61–62; Jn 18:27.","rejected_answers":"«Іван прямо каже, що Петро вийшов і плакав»; «усі чотири описують погляд Ісуса».","rejection_reason":"imported from other witnesses.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Спільне виконання не означає спільний набір емоційних деталей. Іванів уривок закінчується півнем без Матвієво-Лукиного опису плачу.","partial_feedback":"Ізолюйте лише свідка з неправильною кінцівкою.","failure_feedback":"Читайте лише останні речення кожного призначеного уривка.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Порівняйте endings.","H5":"not_used","H6":"Mt 26:75; Mk 14:72; Lk 22:61–62; Jn 18:27.","H7":"not_used"},"on_correct":"LN09-N13","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_witness_ending_correction","on_hint_threshold":"guided_then_LN09-N13","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N14","mastery_domains":["witness-provenance"],"evidence_strength":["application","synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Sequential witness list, not a parallel table as the only mode."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":3,"nodes":[{"node_id":"LN09-N09","mission_id":"LN-09","task_family":"witness-specific detail extraction","difficulty":"3/6","required":true,"skill_target":"identify unique narrative details","knowledge_target":"Luke’s timing and look","why_this_node_exists":"prevents projecting memorable Lukan details into all four Gospels.","player_prompt":"Які три важливі деталі після/довкола зречень Лука прямо додає до своєї сцени?","source_scope_visible_to_player":"Lk 22:58–62.","response_mode":"evidence selection/free response","accepted_answer":"Приблизно година минає перед третім звинуваченням; після співу півня Господь обертається і дивиться на Петра; Петро згадує слово Господа, виходить і гірко плаче.","accepted_variants":"semantic equivalents.","required_evidence":"Lk 22:59,61–62.","rejected_answers":"«усі чотири прямо описують погляд Ісуса».","rejection_reason":"the look is explicit in Luke’s assigned passage, not all four.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Лука додає не лише часовий маркер, а й прямий наративний зв’язок «погляд → пам’ять → вихід/плач».","partial_feedback":"Назвіть відсутню категорію деталі.","failure_feedback":"Перевірте вірші 59, 61 і 62.","hints":{"H1":"Шукайте в Луки не загальне ядро зречень, а три додаткові деталі навколо третього епізоду та його наслідку.","H2":"Працюйте тільки з Лк 22:58–62; не приписуйте знайдені деталі іншим свідкам.","H3":"Розбийте пошук на три категорії: часовий проміжок перед третім звинуваченням; дія Господа після півня; реакція Петра.","H4":"Для першої категорії знайдіть приблизний час; для другої — фізичну дію/погляд; для третьої — пам’ять і вихід/плач.","H5":"Якщо відповідь каже «усі чотири описують погляд Ісуса», поверніться до того, де ця дія прямо стоїть у призначеному тексті.","H6":"Опорні вірші: Лк 22:59,61–62.","H7":"Керована модель: приблизно через годину настає третє звинувачення; після співу півня Господь обертається й дивиться на Петра; Петро згадує слово Господа, виходить і гірко плаче."},"on_correct":"LN09-N10","on_partial":"return_to_current_node_missing_category","on_incorrect":"return_to_current_node_after_Luke_only_recheck","on_hint_threshold":"guided_then_LN09-N10","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N13","mastery_domains":["Luke-detail","witness-provenance"],"evidence_strength":["recall","application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Three text-labelled categories; no visual timeline matching required."},{"node_id":"LN09-N10","mission_id":"LN-09","task_family":"cross-mission retrieval/evidence linking","difficulty":"4/6","required":true,"skill_target":"use earlier evidence without misattributing it","knowledge_target":"Malchus-relative/garden link","why_this_node_exists":"demonstrates meaningful campaign memory.","player_prompt":"Яка деталь третього Іванового звинувачення напряму пов’язує LN-09 з арештом у LN-06?","source_scope_visible_to_player":"Jn 18:10,26–27 + LN-06 memory.","response_mode":"evidence linking","accepted_answer":"Третій обвинувач — слуга первосвященника, родич чоловіка, якому Петро відтяв вухо; він каже, що бачив Петра в саду з Ісусом. Ів 18:10 називає пораненого слугу Малхом.","accepted_variants":"semantic equivalents preserving relative + ear victim + garden.","required_evidence":"Jn 18:10; Jn 18:26.","rejected_answers":"«Іван каже, що сам Малх звинувачує Петра».","rejection_reason":"the accuser is a relative of the man whose ear Peter cut off, not explicitly Malchus himself.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Кампанійна пам’ять працює: деталь LN-06 стає доказом у LN-09, але родича не можна перетворювати на самого Малха.","partial_feedback":"Якщо згадано родича Малха, але пропущено сад, попросіть explicit accusation basis.","failure_feedback":"Порівняйте Ів 18:10 з 18:26.","hints":{"H1":"Зв’яжіть третє Іванове звинувачення з ранішою сценою арешту лише через ті деталі, які прямо названі у двох іванових віршах.","H2":"Порівняйте Ів 18:10 з Ів 18:26: перший називає пораненого слугу, другий описує того, хто тепер упізнає Петра.","H3":"Шукайте два зв’язки: родинний стосунок обвинувача до пораненого чоловіка і його твердження про сад.","H4":"Не робіть обвинувачем самого Малха: Ів 18:26 говорить про родича того чоловіка, а не про тотожність із ним.","H5":"Перевірте, що ім’я Малх походить з Ів 18:10, тоді як Ів 18:26 дає relation + garden observation.","H6":"Опорні місця: Ів 18:10; Ів 18:26.","H7":"Керована модель: третій обвинувач — слуга первосвященника, родич чоловіка, якому Петро відтяв вухо; він каже, що бачив Петра в саду з Ісусом. Ів 18:10 називає пораненого Малхом; обвинувач не названий Малхом."},"on_correct":"LN09-N11","on_partial":"return_to_current_node_targeted_retry","on_incorrect":"return_to_current_node_after_relation_correction","on_hint_threshold":"guided_then_LN09-N11","optional_evidence_unlock":"LN09-O02","later_retrieval_effect":"REVIEW_QUEUE LN_PETER_PROVENANCE_REVIEW","mastery_domains":["cross-mission retrieval","John-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_PETER_PROVENANCE_REVIEW","functional_nonvisual_equivalent":"Cross-mission link is stated as words and citations; any visual thread is supplementary."},{"node_id":"LN09-N11","mission_id":"LN-09","task_family":"textual-variant-in-play","difficulty":"5/6","required":true,"skill_target":"handle manuscript/translation variation before grading","knowledge_target":"Mark 14:68,72 crow variation","why_this_node_exists":"the textual variant directly affects prediction-to-fulfilment matching.","player_prompt":"Як треба оцінювати відповідь гравця, якщо його переклад Марка має «півень заспівав удруге / двічі», а інший відповідальний переклад має примітку або коротшу форму без цієї деталі?","source_scope_visible_to_player":"Mk 14:68,72 + visible TX1 note before response.","response_mode":"classification/explanation","accepted_answer":"Обидві відповідальні текстові/перекладні форми мають прийматися; поширена форма містить другий спів/«двічі», але існує рання рукописна варіативність, тому відсутність цієї деталі не є помилкою користувача.","accepted_variants":"equivalent textual-critical explanation without requiring a position on originality.","required_evidence":"Mark textual footnote/variant metadata + canonical TEXTUAL_VARIANT_POLICY v1.0.","rejected_answers":"«переклад без “двічі” неправильний»; «гра повинна визначити єдину богонатхненну англійську/українську форму».","rejection_reason":"exceeds textual evidence and violates canonical policy.","confidence_code":"T1","textual_variant_flag":"TX1","success_feedback":"`TX1` застосовано правильно: варіант показано до оцінювання, а користувача не карають за відповідальну текстову традицію.","partial_feedback":"Прийміть факт варіативності; попросіть окремо відповісти, чи треба карати гравця.","failure_feedback":"Питання не просить вирішити, який рукопис первісний; воно перевіряє чесну поведінку гри при варіанті.","hints":{"H1":"Це завдання перевіряє не вибір «правильної» форми, а коректну поведінку гри перед відомою текстовою варіативністю.","H2":"Зіставте Мк 14:68,72 з видимою TX1-приміткою та канонічною політикою TEXTUAL_VARIANT_POLICY v1.0.","H3":"Відділіть три питання: яка форма поширена; чи існує відповідальна коротша форма; чи має гравець отримувати штраф за таку форму.","H4":"TX1 — окремий textual-variant flag, а не confidence-код і не твердження про те, яка форма «богонатхненна».","H5":"Ключ до grading: відповідальна форма перекладу/тексту не повинна ставати помилкою користувача лише через відсутність «двічі».","H6":"Опорні дані: Мк 14:68,72 + textual notes + TEXTUAL_VARIANT_POLICY v1.0.","H7":"Керована модель: приймайте обидві відповідальні форми; поширена має другий спів/«двічі», але рання рукописна варіативність робить коротшу форму допустимою. Оригінальність не оцінюється, TX1 лишається окремою позначкою."},"on_correct":"LN09-N12","on_partial":"return_to_current_node_for_policy_clarification","on_incorrect":"return_to_current_node_after_TX1_note_reread","on_hint_threshold":"guided_then_LN09-N12","optional_evidence_unlock":"LN09-O01","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["textual-variants","translation-neutrality"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"TX1 note is ordinary labelled text before grading; never badge/icon/color/tooltip-only."},{"node_id":"LN09-N12","mission_id":"LN-09","task_family":"post-event witness comparison","difficulty":"4/6","required":true,"skill_target":"distinguish explicit post-rooster details","knowledge_target":"remembrance/weeping/look differences","why_this_node_exists":"memorable later details are often falsely universalized.","player_prompt":"Класифікуйте, що прямо відбувається після півнячого маркера в кожному заданому уривку.","source_scope_visible_to_player":"terminal verses of all four passages.","response_mode":"witness matrix","accepted_answer":"Matthew — Peter remembers Jesus’ word, goes out, weeps bitterly; Mark — Peter remembers the prediction and reacts/weeps according to translation rendering; Luke — the Lord turns and looks at Peter, Peter remembers, goes out and weeps bitterly; John — Peter denies and immediately the rooster crows, with no remembrance/weeping stated in the assigned 18:15–18,25–27 passage.","accepted_variants":"translation-sensitive Mark reaction wording.","required_evidence":"Mt 26:75; Mk 14:72; Lk 22:61–62; Jn 18:27.","rejected_answers":"«Іван прямо каже, що Петро вийшов і плакав»; «усі чотири описують погляд Ісуса».","rejection_reason":"imported from other witnesses.","confidence_code":"T2","textual_variant_flag":"none","success_feedback":"Спільне виконання не означає спільний набір емоційних деталей. Іванів уривок закінчується півнем без Матвієво-Лукиного опису плачу.","partial_feedback":"Ізолюйте лише свідка з неправильною кінцівкою.","failure_feedback":"Читайте лише останні речення кожного призначеного уривка.","hints":{"H1":"Порівнюйте тільки те, що кожен призначений passage прямо повідомляє після півнячого маркера.","H2":"Відкрийте фінальні вірші: Мт 26:75; Мк 14:72; Лк 22:61–62; Ів 18:27.","H3":"Для кожного свідка окремо перевірте три можливі елементи: згадка передбачення, додаткова дія Ісуса, вихід/плач Петра.","H4":"Відсутність елемента в заданому Івановому уривку означає «не зазначено тут», а не заперечення того, що він відомий з іншого свідка.","H5":"Погляд Ісуса є прямою деталлю Луки; вихід і плач прямо описані в Матвія та Луки; Марківську реакцію передавайте відповідно до відповідального перекладу.","H6":"Опорні місця: Мт 26:75; Мк 14:72; Лк 22:61–62; Ів 18:27.","H7":"Керована модель: Матвій — згадує, виходить, гірко плаче; Марко — згадує передбачення і реагує/плаче за перекладом; Лука — Господь дивиться, Петро згадує, виходить і плаче; Іван — третє заперечення й одразу півень, без згадки/плачу в заданому обсязі."},"on_correct":"LN09-N13","on_partial":"return_to_current_node_targeted_witness","on_incorrect":"return_to_current_node_after_witness_ending_correction","on_hint_threshold":"guided_then_LN09-N13","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN09-N14","mastery_domains":["witness-provenance"],"evidence_strength":["application","synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Sequential witness list, not a parallel table as the only mode."}]} diff --git a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_04.json b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_04.json index e1f705645..48ee969ac 100644 --- a/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_04.json +++ b/docs/campaigns/LN/LN-09_CANONICAL_v1.2/nodes_part_04.json @@ -1 +1 @@ -{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":4,"nodes":[{"node_id":"LN09-N13","mission_id":"LN-09","task_family":"structured synthesis","difficulty":"5/6","required":true,"skill_target":"compare prediction anchors with fulfilment while preserving deltas","knowledge_target":"what was predicted vs what each witness adds in fulfilment","why_this_node_exists":"establishes a reusable campaign mechanic for predictions and fulfilments.","player_prompt":"Побудуйте коротку матрицю «передбачено → виконано → додаткова деталь свідка → межа певності».","source_scope_visible_to_player":"LN-04 prediction verses + all LN-09 primary passages.","response_mode":"structured synthesis","accepted_answer":"Must include (a) Peter; (b) three denials; (c) rooster marker; (d) Mark TX1 caution; (e) at least one accurate witness-specific fulfilment detail for each Gospel; (f) explicit statement that exact cross-Gospel accuser identity/micro-order is not forced.","accepted_variants":"any semantically correct matrix preserving provenance.","required_evidence":"prediction and fulfilment citations.","rejected_answers":"harmonized matrix that labels every detail as present in all four; omission of TX1 while asserting Mark «twice» as universal.","rejection_reason":"loses source provenance and certainty boundaries.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Передбачення і виконання зіставлено без ретроспективного переписування джерел.","partial_feedback":"Назвіть лише відсутній вимір матриці.","failure_feedback":"Почніть із трьох колонок: спільне передбачення, спільне виконання, свідко-специфічні дельти.","hints":{"H1":"Поверніться до мети матриці.","H2":"not_used","H3":"not_used","H4":"Виміри: prediction / fulfilment / witness delta / certainty.","H5":"not_used","H6":"Use LN-04 prediction anchors + LN-09 fulfilment passages.","H7":"Guided model allowed."},"on_correct":"LN09-N14","on_partial":"return_to_current_node_repair_missing_dimensions","on_incorrect":"return_to_LN09-N03_or_LN09-N07_or_LN09-N11_based_on_error","on_hint_threshold":"guided_then_LN09-N14","optional_evidence_unlock":"LN09-O01; LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["prediction-to-fulfilment","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear canonical mode `prediction → fulfilment → witness → delta → certainty`."},{"node_id":"LN09-N14","mission_id":"LN-09","task_family":"final case synthesis","difficulty":"5/6","required":true,"skill_target":"independent evidence-grounded reconstruction","knowledge_target":"complete denial case","why_this_node_exists":"verifies the player can reconstruct the event without false harmonization.","player_prompt":"Складіть фінальний висновок справи у 6–10 реченнях: що було передбачено; як виконання засвідчують усі чотири Євангелія; назвіть щонайменше по одній специфічній деталі Матвія, Марка, Луки та Івана; поясніть `TX1`; і сформулюйте одну річ, якої джерела не дозволяють стверджувати з повною точністю.","source_scope_visible_to_player":"complete LN-09 source set.","response_mode":"free response/synthesis","accepted_answer":"Any evidence-grounded synthesis meeting all six dimensions.","accepted_variants":"semantic equivalents, no preferred denominational interpretation required.","required_evidence":"at least one citation per Gospel + prediction anchor + TX1 acknowledgement.","rejected_answers":"source-free devotional reflection as substitute; exact harmonized identity of all accusers presented as T1; spiritual judgment of Peter/player.","rejection_reason":"mission tests evidence reconstruction, not spiritual worth.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Справу завершено: передбачення перевірено виконанням, а відмінності свідків збережено як дані, а не «проблеми», які треба приховати.","partial_feedback":"Назвіть лише відсутній required dimension.","failure_feedback":"Поверніть висновок до джерел: прогноз, три епізоди, півень, чотири свідки, TX1, межа певності.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Шість вимірів: prediction, shared fulfilment, Matthew, Mark, Luke, John/TX1/uncertainty as requested.","H5":"not_used","H6":"Use complete source ranges.","H7":"Guided outline allowed and recorded as guided."},"on_correct":"mission_complete","on_partial":"return_to_current_node_revision_loop","on_incorrect":"return_to_exact_weak_node","on_hint_threshold":"guided_mission_complete","optional_evidence_unlock":"LN09-O01; LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["source-citation","Gospel-parallels","prediction-to-fulfilment","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Standard multi-line text field; requirements are a numbered text list; errors announced by category.","confidence_notes":"Mixed T1/T2/D1 clauses; T2 is the node-level synthesis code and TX1 is an adjunct."},{"node_id":"LN09-O01","mission_id":"LN-09","task_family":"optional textual-criticism evidence","difficulty":"5/6","required":false,"skill_target":"distinguish widespread reading from manuscript variation","knowledge_target":"Mark first/second crow references","why_this_node_exists":"deepens TX1 literacy without making textual criticism a gate for mission completion.","player_prompt":"Простежте обидва марківські місця, пов’язані зі співом півня, і поясніть, чому їх не можна перетворити на універсальне правило для всіх перекладів.","source_scope_visible_to_player":"Mk 14:68,72 with textual notes.","response_mode":"citation + explanation","accepted_answer":"Widespread form has a crow at/after the first denial and a second crow after the third, matching «before the rooster crows twice»; some early manuscripts omit relevant crow/second-time wording, so gameplay treats this as TX1 and accepts responsible shorter readings.","accepted_variants":"equivalent explanation preserving no-penalty handling and no originality verdict.","required_evidence":"Mk 14:68,72 textual notes.","rejected_answers":"claim that a responsible shorter form is simply wrong; universalizing two-crow wording to all Gospel witnesses.","rejection_reason":"exceeds the textual evidence and project TX1 policy.","confidence_code":"T1","textual_variant_flag":"TX1","success_feedback":"Ви простежили обидва марківські місця і зберегли TX1 без нав’язування одного текстового рішення.","partial_feedback":"Якщо названо два місця, але не пояснено grading policy, попросіть лише policy.","failure_feedback":"Порівняйте Марка 14:68 і 14:72 та прочитайте textual notes before judging the player’s translation.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Two Mark locations matter.","H5":"Do not penalize a responsible shorter reading.","H6":"Mk 14:68,72 textual notes.","H7":"State variant + no-penalty policy; originality remains ungraded."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_policy_only","on_incorrect":"return_to_current_node_after_TX1_reread","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN12-N10","mastery_domains":["textual-variants"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Variant witnesses summarized in plain labelled text; no apparatus-symbol decoding required."},{"node_id":"LN09-O02","mission_id":"LN-09","task_family":"knowledge-boundary check","difficulty":"4/6","required":false,"skill_target":"distinguish explicit naming from traditional identification","knowledge_target":"John 18:15–16 unnamed other disciple","why_this_node_exists":"trains the canonical `not stated in cited text` boundary for identity claims.","player_prompt":"Чи називає Ів 18:15–16 особисте ім’я «іншого учня», який був відомий первосвященнику й допоміг Петрові ввійти?","source_scope_visible_to_player":"Jn 18:15–16.","response_mode":"free response","accepted_answer":"Ні; уривок називає його «іншим учнем» і описує зв’язок із первосвященником, але не дає особистого імені.","accepted_variants":"«не сказано в цьому уривку».","required_evidence":"Jn 18:15–16.","rejected_answers":"any personal name graded as T1 from these verses.","rejection_reason":"imported identification.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Межу джерела збережено: опис є, особистого імені в цьому уривку немає.","partial_feedback":"Якщо відповідь називає традиційну ідентифікацію, попросіть окремо сказати, чи прямо містить її уривок.","failure_feedback":"Перечитайте Ів 18:15–16 і знайдіть, чи подано власне ім’я.","hints":{"H1":"not_used","H2":"not_used","H3":"not_used","H4":"Питання лише про explicit naming.","H5":"not_used","H6":"Jn 18:15–16.","H7":"Correct boundary: personal name is not stated in the cited text."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_explicit_vs_traditional","on_incorrect":"return_to_current_node_after_exact_wording_reread","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_UNNAMED_PERSON_BOUNDARY_REVIEW","mastery_domains":["explicit-vs-inferred","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_UNNAMED_PERSON_BOUNDARY_REVIEW","functional_nonvisual_equivalent":"Plain text source and answer field; no visual identity card required."}]} +{"schema_version":"CONTENT_NODE_SCHEMA_v1.2","mission_id":"LN-09","canonical_status":"AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING","historical_source":{"path":"docs/campaigns/LN/LN-09_THREE_DENIALS_v1.0.md","sha":"f674a1eeb847cd4ac938ecba40aad4e4466723c3","preserved":true},"part":4,"nodes":[{"node_id":"LN09-N13","mission_id":"LN-09","task_family":"structured synthesis","difficulty":"5/6","required":true,"skill_target":"compare prediction anchors with fulfilment while preserving deltas","knowledge_target":"what was predicted vs what each witness adds in fulfilment","why_this_node_exists":"establishes a reusable campaign mechanic for predictions and fulfilments.","player_prompt":"Побудуйте коротку матрицю «передбачено → виконано → додаткова деталь свідка → межа певності».","source_scope_visible_to_player":"LN-04 prediction verses + all LN-09 primary passages.","response_mode":"structured synthesis","accepted_answer":"Must include (a) Peter; (b) three denials; (c) rooster marker; (d) Mark TX1 caution; (e) at least one accurate witness-specific fulfilment detail for each Gospel; (f) explicit statement that exact cross-Gospel accuser identity/micro-order is not forced.","accepted_variants":"any semantically correct matrix preserving provenance.","required_evidence":"prediction and fulfilment citations.","rejected_answers":"harmonized matrix that labels every detail as present in all four; omission of TX1 while asserting Mark «twice» as universal.","rejection_reason":"loses source provenance and certainty boundaries.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Передбачення і виконання зіставлено без ретроспективного переписування джерел.","partial_feedback":"Назвіть лише відсутній вимір матриці.","failure_feedback":"Почніть із трьох колонок: спільне передбачення, спільне виконання, свідко-специфічні дельти.","hints":{"H1":"Будуйте матрицю по рядках: спершу спільне передбачення й виконання, потім witness-specific додаток і межу певності.","H2":"Використайте anchors LN-04 для prediction і чотири fulfilment passages LN-09; не змішуйте їх в одну композитну цитату.","H3":"Обов’язковий каркас містить Петра, три зречення, півнячий маркер, окрему Mark TX1 caution та хоча б одну точну деталь кожного Євангелія.","H4":"У колонці certainty позначайте різницю між прямим локальним текстом, cross-witness comparison і тим, що не можна точно гармонізувати.","H5":"Перед завершенням перевірте дві заборони: не універсалізувати Маркове «двічі» і не встановлювати єдину точну identity/micro-order усіх обвинувачів.","H6":"Опорний набір: LN-04 Мт 26:34; Мк 14:30; Лк 22:34; Ів 13:38 + LN-09 Мт 26:69–75; Мк 14:66–72; Лк 22:54–62; Ів 18:15–18,25–27.","H7":"Керована модель матриці: передбачено — Петро/три/півень; виконано — три denial episodes у всіх чотирьох; додатки — точні witness-specific деталі; Марко — TX1 щодо «двічі»; межа — точну cross-Gospel identity і micro-order усіх обвинувачів не примушувати."},"on_correct":"LN09-N14","on_partial":"return_to_current_node_repair_missing_dimensions","on_incorrect":"return_to_LN09-N03_or_LN09-N07_or_LN09-N11_based_on_error","on_hint_threshold":"guided_then_LN09-N14","optional_evidence_unlock":"LN09-O01; LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["prediction-to-fulfilment","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Linear canonical mode `prediction → fulfilment → witness → delta → certainty`."},{"node_id":"LN09-N14","mission_id":"LN-09","task_family":"final case synthesis","difficulty":"5/6","required":true,"skill_target":"independent evidence-grounded reconstruction","knowledge_target":"complete denial case","why_this_node_exists":"verifies the player can reconstruct the event without false harmonization.","player_prompt":"Складіть фінальний висновок справи у 6–10 реченнях: що було передбачено; як виконання засвідчують усі чотири Євангелія; назвіть щонайменше по одній специфічній деталі Матвія, Марка, Луки та Івана; поясніть `TX1`; і сформулюйте одну річ, якої джерела не дозволяють стверджувати з повною точністю.","source_scope_visible_to_player":"complete LN-09 source set.","response_mode":"free response/synthesis","accepted_answer":"Any evidence-grounded synthesis meeting all six dimensions.","accepted_variants":"semantic equivalents, no preferred denominational interpretation required.","required_evidence":"at least one citation per Gospel + prediction anchor + TX1 acknowledgement.","rejected_answers":"source-free devotional reflection as substitute; exact harmonized identity of all accusers presented as T1; spiritual judgment of Peter/player.","rejection_reason":"mission tests evidence reconstruction, not spiritual worth.","confidence_code":"T2","textual_variant_flag":"TX1","success_feedback":"Справу завершено: передбачення перевірено виконанням, а відмінності свідків збережено як дані, а не «проблеми», які треба приховати.","partial_feedback":"Назвіть лише відсутній required dimension.","failure_feedback":"Поверніть висновок до джерел: прогноз, три епізоди, півень, чотири свідки, TX1, межа певності.","hints":{"H1":"Складіть висновок як доказову реконструкцію, а не як моральну оцінку Петра чи користувача.","H2":"Розбийте 6–10 речень на шість вимог: prediction; shared fulfilment; Matthew detail; Mark detail; Luke detail; John detail + TX1/uncertainty.","H3":"До кожного Євангелія прив’яжіть щонайменше одну citation-supported специфічну деталь і окремо назвіть спільне ядро.","H4":"TX1 поясніть як причину translation-neutral grading Маркової деталі «двічі», а не як confidence-код або вибір єдиного оригіналу.","H5":"Останнє речення має прямо назвати принаймні одну межу: наприклад, джерела не встановлюють з повною точністю одну cross-Gospel identity/micro-order усіх обвинувачів.","H6":"Використайте повний LN-09 source set, щонайменше одну цитату з кожного Євангелія та prediction anchor з LN-04.","H7":"Керований outline: 1) спільне передбачення; 2) його виконання; 3) Матвій; 4) Марко + TX1; 5) Лука; 6) Іван; 7) межа певності. Розкритий outline записується як guided mastery."},"on_correct":"mission_complete","on_partial":"return_to_current_node_revision_loop","on_incorrect":"return_to_exact_weak_node","on_hint_threshold":"guided_mission_complete","optional_evidence_unlock":"LN09-O01; LN09-O02","later_retrieval_effect":"RESOLVED_NODE LN12-N08","mastery_domains":["source-citation","Gospel-parallels","prediction-to-fulfilment","textual-variants"],"evidence_strength":["synthesis"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Standard multi-line text field; requirements are a numbered text list; errors announced by category.","confidence_notes":"Mixed T1/T2/D1 clauses; T2 is the node-level synthesis code and TX1 is an adjunct."},{"node_id":"LN09-O01","mission_id":"LN-09","task_family":"optional textual-criticism evidence","difficulty":"5/6","required":false,"skill_target":"distinguish widespread reading from manuscript variation","knowledge_target":"Mark first/second crow references","why_this_node_exists":"deepens TX1 literacy without making textual criticism a gate for mission completion.","player_prompt":"Простежте обидва марківські місця, пов’язані зі співом півня, і поясніть, чому їх не можна перетворити на універсальне правило для всіх перекладів.","source_scope_visible_to_player":"Mk 14:68,72 with textual notes.","response_mode":"citation + explanation","accepted_answer":"Widespread form has a crow at/after the first denial and a second crow after the third, matching «before the rooster crows twice»; some early manuscripts omit relevant crow/second-time wording, so gameplay treats this as TX1 and accepts responsible shorter readings.","accepted_variants":"equivalent explanation preserving no-penalty handling and no originality verdict.","required_evidence":"Mk 14:68,72 textual notes.","rejected_answers":"claim that a responsible shorter form is simply wrong; universalizing two-crow wording to all Gospel witnesses.","rejection_reason":"exceeds the textual evidence and project TX1 policy.","confidence_code":"T1","textual_variant_flag":"TX1","success_feedback":"Ви простежили обидва марківські місця і зберегли TX1 без нав’язування одного текстового рішення.","partial_feedback":"Якщо названо два місця, але не пояснено grading policy, попросіть лише policy.","failure_feedback":"Порівняйте Марка 14:68 і 14:72 та прочитайте textual notes before judging the player’s translation.","hints":{"H1":"Залишайтеся всередині Марка: простежте обидві локальні згадки співу півня і лише потім застосуйте TX1-політику.","H2":"Читайте Мк 14:68 та 14:72 разом із текстологічними примітками, а не лише основний текст одного перекладу.","H3":"У поширеній формі знайдіть ранню згадку про спів після першого denial і пізнішу про другий спів після третього.","H4":"Потім перевірте примітку: деякі ранні рукописи мають коротшу форму, тому two-crow wording не можна робити універсальним правилом.","H5":"Grading-наслідок: відповідальний коротший переклад не штрафується; TX1 фіксує варіативність, а не визначає «неправильний» текст.","H6":"Опорні місця: Мк 14:68,72 + textual notes.","H7":"Керована модель: поширена форма має спів після першого denial і другий спів після третього, узгоджений з «двічі»; через рукописну варіативність коротші відповідальні форми приймаються без штрафу, а питання оригінальності не grading-иться."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_policy_only","on_incorrect":"return_to_current_node_after_TX1_reread","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"RESOLVED_NODE LN12-N10","mastery_domains":["textual-variants"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN09_WEAKNESS_REVIEW","functional_nonvisual_equivalent":"Variant witnesses summarized in plain labelled text; no apparatus-symbol decoding required."},{"node_id":"LN09-O02","mission_id":"LN-09","task_family":"knowledge-boundary check","difficulty":"4/6","required":false,"skill_target":"distinguish explicit naming from traditional identification","knowledge_target":"John 18:15–16 unnamed other disciple","why_this_node_exists":"trains the canonical `not stated in cited text` boundary for identity claims.","player_prompt":"Чи називає Ів 18:15–16 особисте ім’я «іншого учня», який був відомий первосвященнику й допоміг Петрові ввійти?","source_scope_visible_to_player":"Jn 18:15–16.","response_mode":"free response","accepted_answer":"Ні; уривок називає його «іншим учнем» і описує зв’язок із первосвященником, але не дає особистого імені.","accepted_variants":"«не сказано в цьому уривку».","required_evidence":"Jn 18:15–16.","rejected_answers":"any personal name graded as T1 from these verses.","rejection_reason":"imported identification.","confidence_code":"T1","textual_variant_flag":"none","success_feedback":"Межу джерела збережено: опис є, особистого імені в цьому уривку немає.","partial_feedback":"Якщо відповідь називає традиційну ідентифікацію, попросіть окремо сказати, чи прямо містить її уривок.","failure_feedback":"Перечитайте Ів 18:15–16 і знайдіть, чи подано власне ім’я.","hints":{"H1":"Питання вузьке: не «хто традиційно вважається іншим учнем», а чи дає особисте ім’я сам Ів 18:15–16.","H2":"Читайте лише Ів 18:15–16 і позначте, як автор називає цю особу та який зв’язок із первосвященником описує.","H3":"Відокремте description від identification: «інший учень» і «відомий первосвященнику» — це описи, не особисте ім’я.","H4":"Не імпортуйте традиційне або інше можливе ототожнення в T1-відповідь, якщо цих віршів недостатньо для такого іменування.","H5":"Контрольне питання: чи можна вказати в самому Ів 18:15–16 слово, яке є особистим ім’ям цього учня? Якщо ні — межа знання встановлена.","H6":"Вирішальне джерело: Ів 18:15–16.","H7":"Керована модель: ні; уривок називає його «іншим учнем» і каже, що він був відомий первосвященнику, але особистого імені не подає. Правильна межа — not stated in the cited text."},"on_correct":"return_to_required_path","on_partial":"return_to_current_node_explicit_vs_traditional","on_incorrect":"return_to_current_node_after_exact_wording_reread","on_hint_threshold":"guided_then_return_to_required_path","optional_evidence_unlock":"none","later_retrieval_effect":"REVIEW_QUEUE LN_UNNAMED_PERSON_BOUNDARY_REVIEW","mastery_domains":["explicit-vs-inferred","witness-provenance"],"evidence_strength":["application"],"mastery_mode":"independent; H6/H7 or answer reveal records guided mastery","spaced_retrieval":"yes","review_queue_rule":"LN_UNNAMED_PERSON_BOUNDARY_REVIEW","functional_nonvisual_equivalent":"Plain text source and answer field; no visual identity card required."}]} diff --git a/docs/evidence/OTNT_RELATION_PACK_v0.1.json b/docs/evidence/OTNT_RELATION_PACK_v0.1.json new file mode 100644 index 000000000..e3ba02adf --- /dev/null +++ b/docs/evidence/OTNT_RELATION_PACK_v0.1.json @@ -0,0 +1,87 @@ +{ + "schema_version": "scripture.evidence.otnt-relation-pack.v1", + "pack_id": "OTNT_WEBU_PRIMARY_v0.1", + "version": "0.1.0", + "status": "SOURCE_AUDITED", + "runtime_visibility": "GLOBAL_RESEARCH_UNLOCKED_AFTER_SOURCE_AUDIT", + "source_edition": { + "edition_id": "engwebu", + "name": "World English Bible Updated", + "license": "Public Domain", + "license_url": "https://worldenglish.bible/", + "retrieved_date": "2026-09-12" + }, + "audit": { + "state": "SOURCE_AUDITED", + "auditor": "DIFFERENT_WORKER_SOURCE_AUDIT", + "accepted_at": "2026-09-12T17:58:18Z", + "evidence_ref": "github:#78/issuecomment-5647672951" + }, + "passages": [ + { + "passage_id": "OT.ZEC.13.7.WEBU", + "testament": "OT", + "book": "Zechariah", + "chapter": 13, + "verse_start": 7, + "verse_end": 7, + "witness": "Zechariah 13:7 (WEBU)", + "source_classification": "T1", + "tx1": false, + "source_url": "https://ebible.org/engwebu/ZEC13.htm", + "excerpt": "Strike the shepherd, and the sheep will be scattered; and I will turn my hand against the little ones.", + "excerpt_sha256": "fff7553a917407606b00c9696df0adee33a026c7aad390cb1db8a697c14f34e3" + }, + { + "passage_id": "NT.MAT.26.31.WEBU", + "testament": "NT", + "book": "Matthew", + "chapter": 26, + "verse_start": 31, + "verse_end": 31, + "witness": "Matthew 26:31 (WEBU)", + "source_classification": "T1", + "tx1": false, + "source_url": "https://ebible.org/study/content/texts/engwebu/MT26.html", + "excerpt": "for it is written, ‘I will strike the shepherd, and the sheep of the flock will be scattered.’", + "excerpt_sha256": "bb640d245ad5907e7b096beffafa8d7283814c26d3683fa3cdd063290a50ef73" + } + ], + "evidence": [ + { + "evidence_id": "EV.OTNT.WEBU.ZEC.13.7", + "passage_id": "OT.ZEC.13.7.WEBU", + "proposition": "Zechariah 13:7 contains the shepherd-struck and sheep-scattered wording represented by the cited WEBU excerpt.", + "confidence_code": "T1", + "tx1": false, + "witness": "Zechariah 13:7 (WEBU)", + "relation_ids": ["REL.OTNT.EXPLICIT_WRITTEN_QUOTATION.MAT26_31.ZEC13_7"] + }, + { + "evidence_id": "EV.OTNT.WEBU.MAT.26.31", + "passage_id": "NT.MAT.26.31.WEBU", + "proposition": "Matthew 26:31 explicitly introduces the shepherd-struck and flock-scattered wording with ‘it is written’ in the cited WEBU excerpt.", + "confidence_code": "T1", + "tx1": false, + "witness": "Matthew 26:31 (WEBU)", + "relation_ids": ["REL.OTNT.EXPLICIT_WRITTEN_QUOTATION.MAT26_31.ZEC13_7"] + } + ], + "relations": [ + { + "relation_id": "REL.OTNT.EXPLICIT_WRITTEN_QUOTATION.MAT26_31.ZEC13_7", + "source_evidence_id": "EV.OTNT.WEBU.ZEC.13.7", + "target_evidence_id": "EV.OTNT.WEBU.MAT.26.31", + "relation_type": "EXPLICIT_WRITTEN_QUOTATION", + "relation_confidence": "T2", + "tx1": false, + "witness": null, + "passage_ids": ["OT.ZEC.13.7.WEBU", "NT.MAT.26.31.WEBU"], + "source_basis": "The cited Matthew 26:31 text explicitly says ‘it is written’ and gives the shepherd/flock wording; the cited Zechariah 13:7 text contains the corresponding shepherd/sheep wording. This relation records that explicit textual cross-reference only and does not add chronology, motive, consensus, or harmonized detail.", + "source_urls": [ + "https://ebible.org/engwebu/ZEC13.htm", + "https://ebible.org/study/content/texts/engwebu/MT26.html" + ] + } + ] +} diff --git a/docs/spec/PEDAGOGICAL_QUALITY_GATE_v1.md b/docs/spec/PEDAGOGICAL_QUALITY_GATE_v1.md new file mode 100644 index 000000000..53fbd4b95 --- /dev/null +++ b/docs/spec/PEDAGOGICAL_QUALITY_GATE_v1.md @@ -0,0 +1,94 @@ +# PEDAGOGICAL QUALITY GATE v1 + +Status: R06 report-first quality contract +Scope: `CONTENT_NODE_SCHEMA_v1.2` authored content +Source authority: unchanged; this gate never decides biblical truth + +## Purpose + +Structural JSON validity is not enough for Scripture Archive. A node can contain every required field and still be pedagogically weak if feedback is generic, the hint ladder does not progressively narrow the task, mastery/retrieval semantics are incoherent, or multiple stable IDs merely repeat the same learning event. + +This gate adds a separate pedagogical-quality layer without conflating it with source audit. + +## Non-negotiable distinction + +The analyzer distinguishes: + +- **BLOCKER** — a mechanically provable pedagogical contract failure, such as a missing H1–H7 step, placeholder feedback, collapsed outcome feedback, or a guided reveal that is not reflected in mastery semantics. +- **WARN** — a review signal, such as an identical hint ladder across many nodes or a duplicate prompt+answer fingerprint. WARN does **not** prove that the node is filler, source-wrong, or invalid; a human/source-aware reviewer must decide. +- **INFO** — inventory/context only. + +No finding automatically changes `AUTHORED`, `SOURCE_AUDITED`, or `AUDITOR_ACCEPTED` state. + +## Mechanical BLOCKER checks + +The v1 analyzer checks that: + +1. `hints` is an object containing exactly H1–H7; +2. each hint is non-empty and non-placeholder-like; +3. a hint ladder does not collapse several steps into identical wording; +4. success, partial, and failure feedback are substantive and outcome-specific; +5. `why_this_node_exists`, `skill_target`, `knowledge_target`, and the functional nonvisual equivalent are substantive rather than placeholders; +6. mastery domains are explicit; +7. a guided H7/reveal is represented in `mastery_mode` so assisted success is not silently recorded as independent mastery; +8. retrieval scheduling fields are explicit; +9. the normalized player prompt is not identical to the accepted answer. + +These checks are pedagogical mechanics, not source exegesis. + +## WARN review signals + +The analyzer reports, without auto-repairing: + +- identical complete H1–H7 ladders reused across multiple stable IDs; +- normalized `player_prompt + accepted_answer` duplicates across stable IDs, as a signal for possible wording-only EXACT inflation; +- identical success/partial/failure feedback sets reused across multiple nodes; +- heavily reused generic hint templates that do not obviously narrow the specific node; +- non-explicit `spaced_retrieval` values. + +A WARN may be legitimate. For example, two nodes can intentionally share a feedback structure while targeting different source evidence. The report therefore lists exact node IDs and leaves source-aware adjudication to the author/auditor. + +## Pedagogical intent preserved + +The final game must retain the complete learning loop: + +`learning purpose -> source-bounded prompt -> learner response -> deterministic grading -> substantive outcome feedback -> progressive hints -> independent/guided mastery distinction -> retrieval scheduling -> later validated variation/context transfer`. + +The gate must not encourage shorter or easier content merely to satisfy metrics. It is specifically intended to detect filler, generic scaffolding, and accidental duplicate learning events while preserving source-safe depth. + +## EXACT / VARIANT / retrieval governance + +The project rule remains authoritative: + +- wording-only paraphrase is `EXACT`; +- `VARIANT` requires a genuinely validated change of form, evidence use, or cognitive operation rather than cosmetic wording; +- `PASSAGE_REVISIT`, `CROSS_CONTEXT`, and `SYNTHESIS` remain distinct retrieval categories; +- successful exact tasks are not randomly repeated in adjacent sessions; +- weak knowledge returns earlier, preferably through another validated form; +- scheduler/mastery state is deterministic and never invented by an LLM. + +The v1 duplicate fingerprint is only a discovery signal. It does not automatically assign any of these categories. + +## Report-first rollout + +The initial GitHub workflow runs with `--fail-on none` for the corpus inventory while unit tests still fail on analyzer regressions. This is intentional: introducing the tool must not retroactively relabel existing authored content without review. + +After the inventory is read, high-confidence mechanical findings can be repaired node-by-node and selected BLOCKER classes may then be promoted into mandatory CI. WARN heuristics remain review signals unless a future authoritative rule explicitly promotes them. + +## Accessibility + +Pedagogy is incomplete if the learning operation is inaccessible. Every node must retain a functional nonvisual equivalent, keyboard-complete operation, textual feedback, and a way to understand the evidence/mastery/next-action state without relying on spatial arrangement, color, drag-and-drop, graphics, or speech audio. + +Application TTS, when present, is additional presentation. It never replaces the semantic text/NVDA learning path. + +## Output governance + +The JSON/Markdown report records: + +- files/schema files scanned; +- nodes analyzed; +- exact findings and severity; +- duplicate fingerprints and stable IDs; +- the existing `canonical_status` inventory as read from files. + +It explicitly does not claim biblical/source correctness, independent audit acceptance, authored/source-audited count promotion, or automatic content repair. diff --git a/docs/spec/SPEECH_TTS_PROVIDER_CONTRACT_v1.md b/docs/spec/SPEECH_TTS_PROVIDER_CONTRACT_v1.md new file mode 100644 index 000000000..45fe188b4 --- /dev/null +++ b/docs/spec/SPEECH_TTS_PROVIDER_CONTRACT_v1.md @@ -0,0 +1,110 @@ +# SPEECH / TTS PROVIDER CONTRACT v1 + +Status: R06 foundation contract +Scope: presentation-layer speech synthesis for Scripture Archive +Primary runtime: Windows 11 x64; web portability required + +## 1. Purpose + +Scripture Archive may speak Scripture text, task prompts, feedback, hints, research text, and selected UI text through external text-to-speech providers. Speech is an optional presentation layer. It never replaces semantic HTML, NVDA, keyboard operation, or complete visible text. + +The speech subsystem MUST NOT become a source of biblical truth. The exact already-authorized player-visible text is the synthesis input. A provider may render that text as audio; it may not rewrite, summarize, harmonize, infer a missing speaker, or change grading/evidence semantics. + +## 2. Source-safety rules + +1. Audio text is derived from the exact canonical/player-visible string supplied by the caller. +2. Voice selection is presentation metadata only. A voice called `narrator`, `male`, `Paul`, or any other label does not prove speaker identity. +3. No witness detail may be imported from another witness to improve narration. +4. TX1, T1/T2/C1/I1/D1, evidence IDs, passage scopes, accepted answers, and grading remain owned by canonical content/runtime layers. +5. When a cited text does not establish a speaker or fact, speech must not imply that it does. +6. TTS errors never change task correctness, mastery, branching, or source truth. + +## 3. Stable internal API + +`SpeechRequest` carries exact `text`, `provider_id`, `voice_id`, optional `model`, `response_format`, optional `language`, presentation-only `purpose`, generation `speed`, optional provider-supported `instructions`, and a `private_text` privacy flag. + +`SpeechProviderRegistry` resolves provider adapters. Domain/game logic must depend on the registry/service contract, not vendor HTTP APIs. + +`SpeechService` validates the request, resolves a provider, computes a deterministic cache key, reuses cached output when available, otherwise calls the provider, atomically writes generated audio, and returns artifact metadata/path without changing source truth. + +## 4. Current adapters + +### OpenAI + +Adapter ID: `openai` + +Current official endpoint: `POST https://api.openai.com/v1/audio/speech` + +Credential reference: `OPENAI_API_KEY` + +The key is read from the environment at request time and is never stored in content, state, cache metadata, Git, or release ZIPs. + +The adapter supports response formats accepted by the current OpenAI speech endpoint. The default model is configurable and currently defaults to `gpt-4o-mini-tts`. Provider-specific instructions are rejected when the selected model does not support them. + +The built-in OpenAI adapter pins credential-bearing requests to the official `api.openai.com/v1/audio/speech` host/path. A different proxy or vendor must be implemented as a separate explicit provider adapter rather than silently redirecting this credential. + +The OpenAI endpoint currently documents a 4096-character request-input limit. Longer Scripture/research narration must be segmented by a higher presentation layer; the foundation fails closed rather than silently truncating text. + +### ElevenLabs + +Adapter ID: `elevenlabs` + +Current official endpoint: `POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}` + +Credential reference: `ELEVENLABS_API_KEY` + +The voice ID is explicit presentation configuration. The current default model is configurable and defaults to `eleven_multilingual_v2`. The configured ElevenLabs `output_format` must map to the cache format; the adapter refuses mismatched declarations rather than writing MP3 bytes under a WAV filename. + +OpenAI-style `instructions` are not silently discarded by this adapter; unsupported controls fail closed. The shared `speed` value is forwarded as ElevenLabs `voice_settings.speed` and is constrained to ElevenLabs' documented `0.7–1.2` range. `language_code` is forwarded only for models that support it; `eleven_multilingual_v2` rejects an explicit language code rather than relying on the provider to ignore it. + +The built-in ElevenLabs adapter similarly pins credential-bearing requests to the official `api.elevenlabs.io/v1/text-to-speech` host/path. + +## 5. Privacy boundary + +Network speech is OFF for `private_text=True` unless the provider adapter is explicitly configured with `allow_private_text=True`. + +This matters for personal notes, private research annotations, imported user text, and future connected/private sources. A future UI must state clearly when a network provider will receive text. The application must remain usable with TTS disabled. + +Secrets are referenced only by environment-variable name; do not participate in cache keys; do not appear in sanitized provider errors; and must never be exported in content packs, research exports, state files, logs, or release packages. + +## 6. Cache and offline behavior + +Generated audio is content-addressed by a SHA-256 over canonical request/provider settings. The plain synthesis text is not used as a filename and is not written to speech-cache metadata by this foundation. + +Cache writes are atomic (`fsync` + replace). A cached artifact can be replayed without another paid/network request. + +Long-term release behavior should support a configurable cache location/size limit, clear-cache command, offline replay of cached speech, an optional OS/local speech provider as a no-network fallback, and explicit indication when requested audio is unavailable offline. No external API call is required for core gameplay. + +## 7. Retry and failure policy + +Network adapters use HTTPS-only credential-free endpoints, bounded timeouts, and retries only for transient network errors, HTTP 429, and HTTP 5xx. Retry is bounded exponential backoff with jitter. Authentication/validation failures are not retried as transient, and provider response bodies are not included in runtime exceptions. + +A TTS failure is a presentation error. It does not fail grading, change mastery, or invalidate canonical text. + +## 8. Accessibility / keyboard contract for UI convergence + +The eventual packaged UI must provide keyboard-reachable controls for Speak/Play, Pause/Resume when supported, Stop, Replay, speech rate, provider, voice, and automatic-reading preferences. + +Every control requires a label and visible/focus state. Playback state and errors require text/live-status equivalents. Audio must never be the sole way to receive feedback, hints, evidence, or task instructions. + +NVDA speech and application TTS are independent channels. Application audio must not steal focus. Automatic narration must be user-configurable so it does not fight the screen reader. + +## 9. Pedagogical contract + +Speech supports pedagogy rather than replacing it. Permitted targets include exact cited Scripture/passages, task prompts, substantive feedback, progressive hints, retrieval/review prompts, and research summaries that are already authorized visible text. + +Narration must preserve `EXACT`, `VARIANT`, `PASSAGE_REVISIT`, `CROSS_CONTEXT`, and `SYNTHESIS` distinctions. + +The scheduler, mastery model, hint cost, attempt independence, due state, fatigue logic, and retrieval spacing remain deterministic runtime state. A spoken replay does not create a new answer, mastery event, source exposure class, or correctness result unless the canonical pedagogy specification explicitly defines such an event. + +## 10. Testing requirements + +Foundation tests use fake HTTP/provider boundaries and make no paid network calls. Required regression coverage includes registry duplicate prevention, exact input preservation, deterministic cache reuse, no secret in cache identity, missing-credential fail-closed behavior, private network text blocked by default, correct OpenAI/ElevenLabs HTTP boundaries, output-format consistency, provider-specific speed/language validation, official-host pinning, unsupported provider controls fail-closed, transient retry behavior, sanitized terminal errors, and HTTPS-only endpoints. + +Later UI convergence additionally requires packaged keyboard/accessibility tests and real playback smoke evidence. Automated mocks do not equal physical Windows/WebView2/audio-device or human NVDA acceptance. + +## 11. Integration rule + +This module is intentionally UI-neutral and vendor-neutral. Desktop WebView2 and future web transports should invoke one application-level speech command layer which then uses this registry/service. Vendor API keys remain host/server-side and never cross into browser JavaScript. + +No direct provider call from content JSON, renderer code, or browser frontend is allowed. diff --git a/lanes/dev1/repair_overlay/frontend/app.js b/lanes/dev1/repair_overlay/frontend/app.js index 9071cc79c..14b09eac3 100644 --- a/lanes/dev1/repair_overlay/frontend/app.js +++ b/lanes/dev1/repair_overlay/frontend/app.js @@ -1,35 +1,42 @@ import {chooseTransport,unwrap} from './transport.js';import {renderTask} from './renderers.js';import {HotkeyDispatcher} from './hotkeys.js';import {AuthoringUI} from './authoring.js';import {KeymapUI} from './keymap-ui.js';import {ResearchWorkbenchUI} from './research-workbench.js';import {ResearchExportUI} from './research-export.js';import {RuntimeNextGate} from './player-next.js';import {ActionRegistry} from './action-registry.js';import {CommandPaletteUI} from './command-palette.js'; -const $=id=>document.getElementById(id);let transport,bootstrap,currentTask,currentMission,getAnswer,currentCampaign,nextNodeId=null,nextBusy=false,activeView='home',researchReturn={view:'home',focus:'home-heading'};const views=['home','mission','player','research','export','authoring']; +const $=id=>document.getElementById(id);let transport,bootstrap,currentTask,currentMission,getAnswer,currentCampaign,nextNodeId=null,nextBusy=false,reviewTraining=null,reviewAnswerSubmitted=false,reviewFinishButton=null,activeView='home',researchReturn={view:'home',focus:'home-heading'};const views=['home','mission','player','research','export','authoring']; function announce(text){const s=$('global-status');s.textContent='';requestAnimationFrame(()=>s.textContent=text)} async function api(command,payload={}){return await unwrap(transport,command,payload)} function focusSoon(target){const el=typeof target==='string'?$(target):target;if(el?.isConnected)setTimeout(()=>el.focus(),0)} function showView(name,focusId){if(name!=='export')researchExport?.deactivate();views.forEach(v=>$(`${v}-view`).classList.toggle('hidden',v!==name));activeView=name;if(focusId)focusSoon(focusId)} function badge(text){const s=document.createElement('span');s.className='status-badge';s.setAttribute('role','listitem');s.textContent=text;return s} +function isReviewTraining(){return reviewTraining?.active===true} +function reviewSummaryText(session=reviewTraining){if(!session)return 'Тренування не активне.';const r=session.results||{};const remaining=Number.isInteger(session.remaining_eligible)?` Доступних далі: ${session.remaining_eligible}.`:'';return `Тренування: показано ${session.shown??0}; правильних ${r.CORRECT??0}; часткових ${r.PARTIAL??0}; неправильних ${r.INCORRECT??0}.${remaining}`} +function mountReviewControls(){if(reviewFinishButton||!$('next-button')?.parentElement)return;reviewFinishButton=document.createElement('button');reviewFinishButton.type='button';reviewFinishButton.id='review-finish-button';reviewFinishButton.textContent='Завершити тренування';reviewFinishButton.className='hidden';reviewFinishButton.addEventListener('click',()=>{void finishReview()});$('next-button').parentElement.insertBefore(reviewFinishButton,$('next-button'))} +function updateReviewControls(){const button=$('next-button');if(!button)return;if(isReviewTraining()){button.textContent='Наступне повторення';button.disabled=nextBusy||!reviewAnswerSubmitted;if(reviewFinishButton)reviewFinishButton.classList.remove('hidden')}else{button.textContent='Наступне';button.disabled=nextBusy||!nextNodeId;if(reviewFinishButton)reviewFinishButton.classList.add('hidden')}} async function loadCampaigns(){const data=await api('content.list_campaigns');const host=$('campaign-list');host.replaceChildren();data.campaigns.forEach(c=>{const article=document.createElement('article');article.className='card';article.setAttribute('role','listitem');const h=document.createElement('h3');h.textContent=c.title;const p=document.createElement('p');p.textContent=`${c.mission_count} machine-readable місій · ${c.machine_node_count} вузлів у цій гілці даних`;const b=document.createElement('button');b.type='button';b.textContent=`Відкрити кампанію ${c.title}`;b.onclick=()=>loadMissions(c);article.append(h,p,b);host.append(article)});showView('home','home-heading')} +async function goHome(){if(isReviewTraining()){await finishReview({returnHome:true});return}await loadCampaigns()} async function loadMissions(c){currentCampaign=c;const data=await api('content.list_missions',{campaign_id:c.campaign_id});$('mission-heading').textContent=`Місії — ${c.title}`;$('mission-context').textContent='Показано лише machine-readable canonical mission indexes, які реально існують у repository checkout.';const host=$('mission-list');host.replaceChildren();data.missions.forEach(m=>{const article=document.createElement('article');article.className='card';article.setAttribute('role','listitem');const h=document.createElement('h3');h.textContent=`${m.mission_id} — ${m.title}`;const p=document.createElement('p');p.textContent=`${m.node_count??'?'} вузлів · ${m.difficulty??'складність не вказана'}`;const src=document.createElement('p');src.textContent=`Джерела: ${Array.isArray(m.primary_scripture)?m.primary_scripture.join('; '):m.primary_scripture}`;const b=document.createElement('button');b.type='button';b.textContent='Почати/продовжити місію';b.disabled=!m.entry_node;b.onclick=()=>loadNode(m.entry_node);article.append(h,p,src,b);host.append(article)});showView('mission','mission-heading')} -function presentNode(data){currentTask=data.task;currentMission=data.mission;nextNodeId=null;nextBusy=false;$('task-heading').textContent=data.task.heading||`Завдання ${data.task.node_id}`;$('task-breadcrumb').textContent=`${data.mission.campaign_id} / ${data.mission.mission_id} / ${data.task.node_id}`;$('task-meta').setAttribute('role','list');$('task-meta').replaceChildren(badge(data.task.task_type),badge(data.task.difficulty||'—'),badge(data.task.required?'Обов’язкове':'Опційне')); - $('source-scope').textContent=data.task.source_scope||'Scope не вказано.';const sl=$('source-list');sl.replaceChildren();(data.task.source_references||[]).forEach(x=>sl.append(Object.assign(document.createElement('li'),{textContent:x})));$('player-prompt').textContent=data.task.prompt;getAnswer=renderTask(data.task,$('answer-control'));$('nonvisual-equivalent').textContent=data.task.accessibility?.nonvisual_equivalent||'Клавіатурне лінійне представлення.';$('feedback-panel').className='notice hidden';$('evidence-panel').classList.add('hidden');$('hint-panel').classList.add('hidden');$('next-button').disabled=true;updateProgress(data.progress);$('current-state-text').textContent=`Відкрито ${data.task.node_id}. Тип ${data.task.task_type}. Результат ще не подано.`;research?.setContext({task:data.task,mission:data.mission});showView('player','task-heading');announce(`Відкрито завдання ${data.task.node_id}`)} -async function loadNode(id,preview=null){const data=preview?{task:preview,mission:{mission_id:preview.mission_id,campaign_id:'DRAFT',title:'Preview'},progress:{current:0,machine_node_total:0,text:'Preview'}}:await api('player.load_node',{node_id:id});presentNode(data)} +function presentNode(data){currentTask=data.task;currentMission=data.mission;if(data.review_session&&typeof data.review_session==='object')reviewTraining=data.review_session;reviewAnswerSubmitted=false;nextNodeId=null;nextBusy=false;$('task-heading').textContent=data.task.heading||`Завдання ${data.task.node_id}`;$('task-breadcrumb').textContent=`${data.mission.campaign_id} / ${data.mission.mission_id} / ${data.task.node_id}`;$('task-meta').setAttribute('role','list');$('task-meta').replaceChildren(badge(data.task.task_type),badge(data.task.difficulty||'—'),badge(data.task.required?'Обов’язкове':'Опційне')); + $('source-scope').textContent=data.task.source_scope||'Scope не вказано.';const sl=$('source-list');sl.replaceChildren();(data.task.source_references||[]).forEach(x=>sl.append(Object.assign(document.createElement('li'),{textContent:x})));$('player-prompt').textContent=data.task.prompt;getAnswer=renderTask(data.task,$('answer-control'));$('nonvisual-equivalent').textContent=data.task.accessibility?.nonvisual_equivalent||'Клавіатурне лінійне представлення.';$('feedback-panel').className='notice hidden';$('evidence-panel').classList.add('hidden');$('hint-panel').classList.add('hidden');updateProgress(data.progress);updateReviewControls();$('current-state-text').textContent=isReviewTraining()?`Відкрито повторення ${data.task.node_id}. ${reviewSummaryText()}`:`Відкрито ${data.task.node_id}. Тип ${data.task.task_type}. Результат ще не подано.`;research?.setContext({task:data.task,mission:data.mission});showView('player','task-heading');announce(isReviewTraining()?`Відкрито повторення ${data.task.node_id}. ${reviewSummaryText()}`:`Відкрито завдання ${data.task.node_id}`)} +async function loadNode(id,preview=null){if(!preview&&isReviewTraining())await finishReview({returnHome:false,announceResult:false});const data=preview?{task:preview,mission:{mission_id:preview.mission_id,campaign_id:'DRAFT',title:'Preview'},progress:{current:0,machine_node_total:0,text:'Preview'}}:await api('player.load_node',{node_id:id});presentNode(data)} function updateProgress(p){$('progress-text').textContent=p?.text||'Прогрес недоступний';const progress=$('progress-bar');progress.setAttribute('aria-labelledby','progress-heading progress-text');const total=Number(p?.machine_node_total||0),cur=Number(p?.current||0);progress.max=Math.max(1,total);progress.value=Math.min(cur,total)} -async function submit(e){e?.preventDefault();if(!currentTask||!getAnswer)return;try{const r=await api('player.submit_answer',{node_id:currentTask.node_id,answer:getAnswer()});nextNodeId=r.next_node_id||null;const panel=$('feedback-panel');panel.className=`notice ${r.status==='CORRECT'?'success':r.status==='INCORRECT'?'error':'warning'}`;$('feedback-status').textContent=r.status==='REVIEW_REQUIRED'?'Потрібна безпечна перевірка вільної відповіді':r.status;$('feedback-text').textContent=r.feedback||'';const dl=$('feedback-details');dl.replaceChildren();[['Confidence',r.confidence_code],['Textual variant',r.textual_variant_flag],['Наступний вузол',nextNodeId||'review/terminal queue']].forEach(([k,v])=>{const dt=document.createElement('dt');dt.textContent=k;const dd=document.createElement('dd');dd.textContent=v??'—';dl.append(dt,dd)});setNextBusy(false);updateProgress(r.progress);$('current-state-text').textContent=`Результат ${r.status}. Confidence ${r.confidence_code||'—'}. TX1 ${r.textual_variant_flag||'none'}.`;focusSoon('feedback-heading');announce(`Результат: ${r.status}`)}catch(err){announce(`Помилка: ${err.message}`)}} +async function submit(e){e?.preventDefault();if(!currentTask||!getAnswer)return;try{const reviewMode=isReviewTraining();const r=await api('player.submit_answer',{node_id:currentTask.node_id,answer:getAnswer()});if(reviewMode&&r.review_session&&typeof r.review_session==='object')reviewTraining=r.review_session;reviewAnswerSubmitted=reviewMode;nextNodeId=reviewMode?null:(r.next_node_id||null);const panel=$('feedback-panel');panel.className=`notice ${r.status==='CORRECT'?'success':r.status==='INCORRECT'?'error':'warning'}`;$('feedback-status').textContent=r.status==='REVIEW_REQUIRED'?'Потрібна безпечна перевірка вільної відповіді':r.status;$('feedback-text').textContent=r.feedback||'';const dl=$('feedback-details');dl.replaceChildren();const nextDescription=reviewMode?'Canonical runtime Scheduler після «Наступне повторення»':(nextNodeId||'review/terminal queue');[['Confidence',r.confidence_code],['Textual variant',r.textual_variant_flag],['Наступна дія',nextDescription]].forEach(([k,v])=>{const dt=document.createElement('dt');dt.textContent=k;const dd=document.createElement('dd');dd.textContent=v??'—';dl.append(dt,dd)});setNextBusy(false);updateProgress(r.progress);$('current-state-text').textContent=reviewMode?`Результат ${r.status}. ${reviewSummaryText()}`:`Результат ${r.status}. Confidence ${r.confidence_code||'—'}. TX1 ${r.textual_variant_flag||'none'}.`;focusSoon('feedback-heading');announce(reviewMode?`Результат: ${r.status}. ${reviewSummaryText()}`:`Результат: ${r.status}`)}catch(err){announce(`Помилка: ${err.message}`)}} async function hint(){if(!currentTask)return;const r=await api('player.request_hint',{node_id:currentTask.node_id});$('hint-text').textContent=`H${r.hint_level}: ${r.hint}`;$('hint-panel').classList.remove('hidden');focusSoon('hint-heading');announce(`Підказка H${r.hint_level}`)} async function evidence(){if(!currentTask)return;const r=await api('player.reveal_evidence',{node_id:currentTask.node_id});const ul=$('evidence-list');ul.replaceChildren();(r.evidence||[]).forEach(x=>ul.append(Object.assign(document.createElement('li'),{textContent:x})));$('evidence-notice').textContent=`Confidence: ${r.confidence_code||'—'}; textual variant: ${r.textual_variant_flag||'none'}. ${r.notice||''}`;$('evidence-panel').classList.remove('hidden');research?.setEvidence(r);focusSoon('evidence-heading');announce('Докази відкрито')} function openResearch(){const from=activeView==='research'?researchReturn.view:activeView;const focus=from==='player'?'research-current':from==='mission'?'mission-back':from==='authoring'?'authoring-heading':from==='export'?'nav-export':'nav-research';researchReturn={view:from,focus};research?.setContext({task:currentTask,mission:currentMission});research?.refreshPersistence();showView('research','research-heading');announce(currentTask?`Відкрито дослідження ${currentTask.node_id}`:'Відкрито дослідницький простір')} function returnFromResearch(){const target=researchReturn.view&&researchReturn.view!=='research'?researchReturn.view:'home';showView(target,researchReturn.focus||'home-heading');announce('Повернення з дослідницького простору')} -function setNextBusy(busy){nextBusy=Boolean(busy);$('next-button').disabled=nextBusy||!nextNodeId} -async function next(){if(!currentTask||!nextNodeId||!nextGate)return;await nextGate.run(currentTask.node_id)} -async function saveProgress(){if(!currentTask)return;await api('player.save_checkpoint',{campaign_id:currentMission?.campaign_id,mission_id:currentMission?.mission_id,node_id:currentTask.node_id});announce('Прогрес збережено')} +function setNextBusy(busy){nextBusy=Boolean(busy);updateReviewControls()} +async function nextReview(){if(!isReviewTraining()||!reviewAnswerSubmitted||nextBusy)return;setNextBusy(true);try{const data=await api('player.start_review');if(data?.truth_owner!=='D5/runtime'||!data.review_session)throw new Error('Некоректна відповідь Review Training');reviewTraining=data.review_session;if(!data.task){const summary=reviewSummaryText(data.review_session);reviewTraining=null;reviewAnswerSubmitted=false;currentTask=null;currentMission=null;getAnswer=null;nextNodeId=null;setNextBusy(false);await loadCampaigns();announce(`Тренування завершено. ${summary}`);return}presentNode(data)}catch(err){setNextBusy(false);announce(`Помилка тренування: ${err.message}`)}} +async function next(){if(isReviewTraining()){await nextReview();return}if(!currentTask||!nextNodeId||!nextGate)return;await nextGate.run(currentTask.node_id)} +async function finishReview({returnHome=true,announceResult=true}={}){if(!isReviewTraining())return;const previous=reviewTraining;try{const data=await api('player.finish_review');reviewTraining=null;reviewAnswerSubmitted=false;currentTask=null;currentMission=null;getAnswer=null;nextNodeId=null;setNextBusy(false);if(returnHome)await loadCampaigns();if(announceResult)announce(`Тренування завершено. ${reviewSummaryText(data.review_session||previous)}`)}catch(err){announce(`Не вдалося завершити тренування: ${err.message}`);throw err}} +async function saveProgress(){if(!currentTask)return;await api('player.save_checkpoint',{campaign_id:currentMission?.campaign_id,mission_id:currentMission?.mission_id,node_id:currentTask.node_id});announce(isReviewTraining()?'Стан тренування і прогрес збережено':'Прогрес збережено')} function isRuntimePlayerContext(){return activeView==='player'&&Boolean(currentTask)&¤tMission?.campaign_id!=='DRAFT'} function canSubmitPlayer(){return isRuntimePlayerContext()&&typeof getAnswer==='function'} -function canAdvancePlayer(){return isRuntimePlayerContext()&&Boolean(nextNodeId)&&!nextBusy} +function canAdvancePlayer(){return isRuntimePlayerContext()&&!nextBusy&&(isReviewTraining()?reviewAnswerSubmitted:Boolean(nextNodeId))} function isAuthoringContext(){return activeView==='authoring'&&Boolean(authoring)} function createActionRegistry(){return new ActionRegistry([ - {id:'app.home',label:'Головна',description:'Повернутися до списку кампаній',group:'Навігація',keywords:['кампанії'],handler:()=>loadCampaigns()}, + {id:'app.home',label:'Головна',description:'Повернутися до списку кампаній',group:'Навігація',keywords:['кампанії'],handler:()=>goHome()}, {id:'player.submit',label:'Надіслати відповідь',description:'Перевірити поточну відповідь',group:'Гравець',keywords:['відповідь','перевірити'],isAvailable:canSubmitPlayer,handler:()=>submit()}, {id:'player.hint',label:'Показати підказку',description:'Відкрити наступний рівень підказки',group:'Гравець',keywords:['hint'],isAvailable:isRuntimePlayerContext,handler:()=>hint()}, {id:'player.evidence',label:'Відкрити докази',description:'Показати вже дозволені докази поточного завдання',group:'Дослідження',keywords:['evidence','джерела'],isAvailable:isRuntimePlayerContext,handler:()=>evidence()}, - {id:'player.next',label:'Наступне завдання',description:'Продовжити runtime-owned гілку',group:'Гравець',keywords:['далі','next'],isAvailable:canAdvancePlayer,handler:()=>next()}, + {id:'player.next',label:'Наступне завдання',description:'Продовжити runtime-owned гілку або Review Training Scheduler',group:'Гравець',keywords:['далі','next','повторення'],isAvailable:canAdvancePlayer,handler:()=>next()}, {id:'research.export',label:'Експорт дослідження',description:'Показати unlocked-only JSON, Markdown або HTML',group:'Дослідження',keywords:['export','експорт'],isAvailable:()=>Boolean(researchExport?.enabled),handler:()=>researchExport?.open()}, {id:'authoring.save',label:'Зберегти чернетку',description:'Зберегти поточну Constructor чернетку',group:'Конструктор',keywords:['draft'],isAvailable:isAuthoringContext,handler:()=>authoring?.save()}, {id:'authoring.preview',label:'Попередній перегляд',description:'Відкрити preview поточної чернетки',group:'Конструктор',keywords:['preview'],isAvailable:isAuthoringContext,handler:()=>authoring?.preview()}, @@ -40,5 +47,5 @@ function createActionRegistry(){return new ActionRegistry([ function executeAction(id){return actions?.execute(id)??false} let dispatcher,authoring,keymap,research,researchExport,nextGate,actions,palette,jsonMode='',jsonReturnFocus=null; function setupJsonDialog(){const dialog=$('json-dialog');dialog.addEventListener('close',()=>{focusSoon(jsonReturnFocus);jsonReturnFocus=null});document.addEventListener('scripture-json-dialog',e=>{jsonReturnFocus=document.activeElement;jsonMode=e.detail.mode;$('json-text').value=e.detail.text||'';$('json-text').readOnly=jsonMode==='readonly';$('json-commit').classList.toggle('hidden',jsonMode==='readonly');$('json-error').textContent='';dialog.showModal();focusSoon($('json-text'))});$('import-draft').onclick=()=>{jsonReturnFocus=document.activeElement;jsonMode='draft-import';$('json-text').readOnly=false;$('json-text').value='';$('json-commit').classList.remove('hidden');dialog.showModal();focusSoon($('json-text'))};$('json-commit').onclick=async()=>{try{if(jsonMode==='draft-import'){const d=(await api('authoring.import_draft',{text:$('json-text').value})).draft;$('json-dialog').close();authoring.fill(d);await authoring.refreshList();announce('JSON імпортовано як нову DRAFT чернетку')}else if(jsonMode==='keymap-import'){await keymap.importData(JSON.parse($('json-text').value));$('json-dialog').close()}}catch(e){$('json-error').textContent=e.message}}} -async function init(){try{transport=await chooseTransport();bootstrap=await api('system.bootstrap');actions=createActionRegistry();dispatcher=new HotkeyDispatcher(executeAction);keymap=new KeymapUI(api,dispatcher,announce);await keymap.refresh();authoring=new AuthoringUI(api,announce,bootstrap.registries.task_types);await authoring.refreshList();research=new ResearchWorkbenchUI({announce,onReturn:returnFromResearch,invoke:api,capabilities:bootstrap.capabilities});researchExport=new ResearchExportUI({invoke:api,announce,showView,enabled:Boolean(bootstrap.capabilities?.research_export)});researchExport.mount({nav:document.querySelector('.top-nav'),main:$('main-content')});nextGate=new RuntimeNextGate({invoke:(command,payload)=>api(command,payload),setBusy:setNextBusy,onData:presentNode,onComplete:()=>{nextNodeId=null;setNextBusy(false);$('current-state-text').textContent='Поточну гілку завершено або наступне завдання очікує перевірки.';announce('Поточну гілку завершено або поставлено в чергу перевірки')},onError:error=>announce(`Помилка: ${error.message}`)});palette=new CommandPaletteUI({registry:actions,announce});palette.mount();setupJsonDialog();$('answer-form').onsubmit=submit;$('hint-button').onclick=hint;$('evidence-button').onclick=evidence;$('next-button').onclick=next;$('save-progress').onclick=saveProgress;$('nav-home').onclick=loadCampaigns;$('nav-research').onclick=openResearch;$('research-current').onclick=openResearch;$('mission-back').onclick=loadCampaigns;$('nav-authoring').onclick=()=>{showView('authoring','authoring-heading');authoring.refreshList()};document.addEventListener('scripture-preview-task',e=>loadNode(e.detail.node_id,e.detail));await loadCampaigns();const cp=await api('player.restore_checkpoint');if(cp.checkpoint?.node_id){$('resume-panel').classList.remove('hidden');$('resume-text').textContent=`Збережено ${cp.checkpoint.mission_id||''} / ${cp.checkpoint.node_id}`;$('resume-button').onclick=()=>loadNode(cp.checkpoint.node_id);announce(`Є збережений checkpoint: ${cp.checkpoint.node_id}`)}}catch(err){$('campaign-list').textContent=`Не вдалося запустити platform transport: ${err.message}`;announce('Помилка запуску платформи')}} -window.addEventListener('pywebviewready',()=>init(),{once:true});if(!window.pywebview)setTimeout(init,0); +async function init(){try{transport=await chooseTransport();bootstrap=await api('system.bootstrap');actions=createActionRegistry();dispatcher=new HotkeyDispatcher(executeAction);keymap=new KeymapUI(api,dispatcher,announce);await keymap.refresh();authoring=new AuthoringUI(api,announce,bootstrap.registries.task_types);await authoring.refreshList();research=new ResearchWorkbenchUI({announce,onReturn:returnFromResearch,invoke:api,capabilities:bootstrap.capabilities});researchExport=new ResearchExportUI({invoke:api,announce,showView,enabled:Boolean(bootstrap.capabilities?.research_export)});researchExport.mount({nav:document.querySelector('.top-nav'),main:$('main-content')});nextGate=new RuntimeNextGate({invoke:(command,payload)=>api(command,payload),setBusy:setNextBusy,onData:presentNode,onComplete:()=>{nextNodeId=null;setNextBusy(false);$('current-state-text').textContent='Поточну гілку завершено або наступне завдання очікує перевірки.';announce('Поточну гілку завершено або поставлено в чергу перевірки')},onError:error=>announce(`Помилка: ${error.message}`)});palette=new CommandPaletteUI({registry:actions,announce});palette.mount();mountReviewControls();setupJsonDialog();$('answer-form').onsubmit=submit;$('hint-button').onclick=hint;$('evidence-button').onclick=evidence;$('next-button').onclick=next;$('save-progress').onclick=saveProgress;$('nav-home').onclick=()=>{void goHome()};$('nav-research').onclick=openResearch;$('research-current').onclick=openResearch;$('mission-back').onclick=()=>{void goHome()};$('nav-authoring').onclick=()=>{showView('authoring','authoring-heading');authoring.refreshList()};document.addEventListener('scripture-preview-task',e=>loadNode(e.detail.node_id,e.detail));document.addEventListener('scripture-review-training-started',e=>{const data=e.detail;if(data?.truth_owner!=='D5/runtime'||!data.task||data.review_session?.active!==true){announce('Некоректний запуск Review Training');return}reviewTraining=data.review_session;presentNode(data)});await loadCampaigns();const cp=await api('player.restore_checkpoint');if(cp.checkpoint?.node_id){$('resume-panel').classList.remove('hidden');$('resume-text').textContent=`Збережено ${cp.checkpoint.mission_id||''} / ${cp.checkpoint.node_id}`;$('resume-button').onclick=()=>loadNode(cp.checkpoint.node_id);announce(`Є збережений checkpoint: ${cp.checkpoint.node_id}`)}}catch(err){$('campaign-list').textContent=`Не вдалося запустити platform transport: ${err.message}`;announce('Помилка запуску платформи')}} +window.addEventListener('pywebviewready',()=>init(),{once:true});if(!window.pywebview)setTimeout(init,0); \ No newline at end of file diff --git a/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js b/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js new file mode 100644 index 000000000..d747ccbb9 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js @@ -0,0 +1,86 @@ +import {chooseTransport,unwrap} from './transport.js'; + +const $=id=>document.getElementById(id); +let transport=null,mounted=false; + +async function api(command,payload={}){return await unwrap(transport,command,payload)} +function announce(text){const host=$('global-status');if(host){host.textContent='';requestAnimationFrame(()=>host.textContent=text)}} +function currentDraftId(){const value=$('draft-id')?.value?.trim();if(!value)throw new Error('Спочатку відкрийте збережену чернетку.');return value} +function makeButton(label,handler){const button=document.createElement('button');button.type='button';button.textContent=label;button.onclick=handler;return button} +function text(tag,value){const el=document.createElement(tag);el.textContent=value;return el} +function syncDraftList(){const nav=$('nav-authoring');if(nav)nav.click()} + +async function refreshHistory(){ + const output=$('constructor-v2-output'); + if(!output)return; + output.replaceChildren(); + let draftId; + try{draftId=currentDraftId()}catch(error){output.append(text('p',error.message));return} + try{ + const history=await api('authoring.history',{draft_id:draftId}); + output.append(text('p',`Revision ${history.revision}. Undo: ${history.can_undo?'так':'ні'}. Redo: ${history.can_redo?'так':'ні'}.`)); + const changes=text('h4','Історія змін');output.append(changes); + const changeList=document.createElement('ol'); + (history.change_record||[]).slice(-20).forEach(row=>changeList.append(text('li',`${row.action||'change'} · revision ${row.revision??'—'} · ${row.timestamp??'—'}`))); + if(!changeList.children.length)changeList.append(text('li','Записів змін ще немає.')); + output.append(changeList); + + output.append(text('h4','Snapshots')); + const snapshots=document.createElement('ul'); + for(const row of history.snapshots||[]){ + const li=document.createElement('li'); + li.append(document.createTextNode(`${row.label||row.snapshot_id} · revision ${row.draft_revision??'—'} `)); + li.append(makeButton('Diff до поточної',async()=>{ + try{const diff=await api('authoring.diff_draft',{draft_id:draftId,from_snapshot_id:row.snapshot_id});announce(diff.changed?`Змінено шляхів: ${diff.changed_paths.length}`:'Відмінностей немає');const pre=document.createElement('pre');pre.textContent=(diff.changed_paths||[]).join('\n')||'No changes';li.append(pre)}catch(error){announce(`Constructor: ${error.message}`)} + })); + li.append(makeButton('Відновити snapshot',async()=>{ + try{await api('authoring.restore_snapshot',{draft_id:draftId,snapshot_id:row.snapshot_id});announce('Snapshot відновлено як нову revision; попередній стан збережено safety snapshot. Перевідкрийте чернетку.');syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} + })); + snapshots.append(li); + } + if(!snapshots.children.length)snapshots.append(text('li','Snapshots ще немає.')); + output.append(snapshots); + + output.append(text('h4','Published version artifacts')); + const versions=document.createElement('ul'); + for(const row of history.versions||[]){ + const li=document.createElement('li'); + li.append(document.createTextNode(`${row.version_id} · source revision ${row.draft_revision??'—'} · canonical write: ні `)); + li.append(makeButton('Rollback у draft',async()=>{ + try{await api('authoring.rollback_version',{draft_id:draftId,version_id:row.version_id});announce('Version artifact відновлено у draft як нову revision; canonical content не змінено. Перевідкрийте чернетку.');syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} + })); + versions.append(li); + } + if(!versions.children.length)versions.append(text('li','Version artifacts ще немає.')); + output.append(versions); + }catch(error){output.append(text('p',`Не вдалося прочитати Constructor history: ${error.message}`))} +} + +async function mutate(command,message){ + try{const draftId=currentDraftId();await api(command,{draft_id:draftId});announce(message);syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} +} + +async function installConstructorV2Surface(){ + if(mounted)return; + const form=$('authoring-form'); + if(!form)return; + try{transport=chooseTransport();const bootstrap=await api('system.bootstrap');if(!bootstrap?.capabilities?.constructor_v2_history)return}catch(_error){return} + mounted=true; + const actions=form.querySelector('.sticky-actions')||form; + actions.append( + makeButton('Snapshot',async()=>{try{const draftId=currentDraftId();await api('authoring.create_snapshot',{draft_id:draftId,label:'Manual snapshot'});announce('Snapshot збережено.');await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)}}), + makeButton('Undo saved',()=>mutate('authoring.undo','Undo виконано як нову persisted revision. Перевідкрийте чернетку.')), + makeButton('Redo saved',()=>mutate('authoring.redo','Redo виконано як нову persisted revision. Перевідкрийте чернетку.')), + makeButton('History / versions',refreshHistory), + makeButton('Publish saved version',async()=>{ + try{const draftId=currentDraftId();const compatibility=(await api('authoring.pack_compatibility',{})).compatibility;const result=await api('authoring.publish_version',{draft_id:draftId,compatibility});announce(`Version artifact ${result.version.version_id} створено. Canonical content не змінено.`);await refreshHistory()}catch(error){announce(`Constructor publish: ${error.message}`)} + }), + ); + const section=document.createElement('section');section.id='constructor-v2-panel';section.className='surface subtle';section.setAttribute('aria-labelledby','constructor-v2-heading'); + const heading=text('h3','Constructor V2 — історія та версії');heading.id='constructor-v2-heading';heading.tabIndex=-1; + const note=text('p','Операції працюють лише зі збереженою draft revision. Publish створює version artifact для explicit integration review і ніколи не записує canonical source-audited corpus напряму.'); + const output=document.createElement('div');output.id='constructor-v2-output';output.setAttribute('aria-live','polite'); + section.append(heading,note,output);form.append(section); +} + +export {installConstructorV2Surface}; diff --git a/lanes/dev1/repair_overlay/frontend/library-research-persistence.js b/lanes/dev1/repair_overlay/frontend/library-research-persistence.js new file mode 100644 index 000000000..6766dfd2e --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/library-research-persistence.js @@ -0,0 +1,358 @@ +import {chooseTransport, unwrap} from './transport.js'; +import {validateSearchResponse} from './library-ui.js'; +import { + buildResearchTarget, + findCurrentRecord, + hasTargetCollision, + targetMatchesContext, + validateResearchList, + workspaceEnabled, +} from './research-persistence.js'; + +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/; +const COMMANDS = new Set([ + 'system.bootstrap', + 'library.search', + 'research.list_bookmarks', + 'research.upsert_bookmark', + 'research.delete_bookmark', + 'research.list_notes', + 'research.upsert_note', + 'research.delete_note', +]); +const DELETE_CONTROL_IDS = new Set(['library-bookmark-delete', 'library-note-delete']); +const byId = id => document.getElementById(id); +let transportPromise = null; +let current = null; +let generation = 0; +let capabilities = null; + +function element(tag, text = '', attrs = {}) { + const node = document.createElement(tag); + if (text !== '') node.textContent = String(text); + for (const [name, value] of Object.entries(attrs)) { + if (name === 'className') node.className = String(value); + else node.setAttribute(name, String(value)); + } + return node; +} + +async function invoke(command, payload = {}) { + if (!COMMANDS.has(command)) throw new Error('Library research command is not allowlisted'); + if (!transportPromise) transportPromise = chooseTransport(); + return await unwrap(await transportPromise, command, payload); +} + +export function parseTaskIdentity(text) { + const prefix = 'Завдання: '; + if (typeof text !== 'string' || !text.startsWith(prefix)) return null; + const parts = text.slice(prefix.length).split(' / '); + if (parts.length !== 3 || parts.some(part => !ID_RE.test(part))) return null; + return {campaign_id: parts[0], mission_id: parts[1], node_id: parts[2]}; +} + +export function selectExactTask(data, identity) { + if (!identity || !ID_RE.test(identity.campaign_id || '') || !ID_RE.test(identity.mission_id || '') || !ID_RE.test(identity.node_id || '')) { + throw new Error('invalid Library task identity'); + } + const validated = validateSearchResponse(data); + const matches = validated.results.filter(row => + row.kind === 'task' && + row.id === identity.node_id && + row.campaign_id === identity.campaign_id && + row.mission_id === identity.mission_id + ); + if (matches.length !== 1) throw new Error('Library task no longer resolves uniquely in canonical search'); + return matches[0]; +} + +function taskContext(row) { + const mission = {campaign_id: row.campaign_id, mission_id: row.mission_id}; + const task = { + node_id: row.id, + mission_id: row.mission_id, + source_references: [...row.source_references], + }; + return {task, mission, target: buildResearchTarget(task, mission)}; +} + +function tags(value) { + const out = []; + for (const raw of String(value || '').split(',')) { + const tag = raw.trim(); + if (tag && !out.includes(tag)) out.push(tag); + } + if (out.length > 20 || out.some(tag => tag.length > 50)) throw new Error('Теги: максимум 20 значень до 50 символів.'); + return out; +} + +function status(message) { + const node = byId('library-research-status'); + if (node) node.textContent = String(message || ''); +} + +function setPanelEnabled(enabled) { + const panel = byId('library-research-panel'); + if (!panel) return; + for (const control of panel.querySelectorAll('input,textarea,button')) { + if (!enabled) { + control.disabled = true; + } else if (!DELETE_CONTROL_IDS.has(control.id)) { + control.disabled = false; + } + } +} + +function clearEditors() { + for (const id of ['library-bookmark-title', 'library-bookmark-tags', 'library-note-title', 'library-note-tags', 'library-note-body']) { + const node = byId(id); + if (node) node.value = ''; + } + for (const id of DELETE_CONTROL_IDS) { + const node = byId(id); + if (node) node.disabled = true; + } +} + +export function invalidateLibraryResearchPersistence() { + generation += 1; + current = null; + clearEditors(); + setPanelEnabled(false); + status('Виберіть task у результатах пошуку.'); +} + +function loadEditors(bookmarks, notes, task, mission) { + clearEditors(); + const bookmark = findCurrentRecord('bookmark', bookmarks, task, mission); + const note = findCurrentRecord('note', notes, task, mission); + if (bookmark) { + byId('library-bookmark-title').value = bookmark.title; + byId('library-bookmark-tags').value = bookmark.tags.join(', '); + byId('library-bookmark-delete').disabled = false; + } + if (note) { + byId('library-note-title').value = note.title; + byId('library-note-tags').value = note.tags.join(', '); + byId('library-note-body').value = note.body; + byId('library-note-delete').disabled = false; + } +} + +async function refreshCurrent(expectedGeneration = generation) { + if (!current || expectedGeneration !== generation) return; + const context = current; + const [bookmarkData, noteData] = await Promise.all([ + invoke('research.list_bookmarks', {query: context.target.node_id}), + invoke('research.list_notes', {query: context.target.node_id}), + ]); + if (current !== context || expectedGeneration !== generation) return; + const bookmarks = validateResearchList('bookmark', bookmarkData); + const notes = validateResearchList('note', noteData); + loadEditors(bookmarks, notes, context.task, context.mission); + status(`Особисті записи для ${context.target.node_id} готові.`); +} + +async function activate(identity, button) { + const mine = ++generation; + current = null; + clearEditors(); + setPanelEnabled(false); + button.disabled = true; + button.setAttribute('aria-busy', 'true'); + status('Перевірка canonical task перед відкриттям особистих записів…'); + try { + if (!capabilities) capabilities = (await invoke('system.bootstrap')).capabilities || {}; + if (!workspaceEnabled(capabilities)) throw new Error('Research persistence capability недоступна'); + const result = await invoke('library.search', { + query: identity.node_id, + campaign_id: identity.campaign_id, + mission_id: identity.mission_id, + limit: 50, + }); + if (mine !== generation) return; + current = taskContext(selectExactTask(result, identity)); + await refreshCurrent(mine); + if (mine === generation && current) { + setPanelEnabled(true); + if (!byId('library-view')?.classList.contains('hidden')) byId('library-research-heading')?.focus(); + } + } catch (error) { + if (mine === generation) { + current = null; + clearEditors(); + setPanelEnabled(false); + status(`Не вдалося відкрити особисті записи: ${error.message}`); + } + } finally { + button.disabled = false; + button.setAttribute('aria-busy', 'false'); + } +} + +async function save(kind) { + if (!current) return; + const mine = generation; + const context = current; + try { + const isBookmark = kind === 'bookmark'; + const listCommand = isBookmark ? 'research.list_bookmarks' : 'research.list_notes'; + const existing = validateResearchList(kind, await invoke(listCommand, {})); + if (mine !== generation || current !== context) throw new Error('Research context changed; повторіть дію.'); + if (hasTargetCollision(kind, existing, context.task, context.mission)) { + throw new Error('ID запису вже належить іншому canonical target; збереження заблоковано.'); + } + const title = byId(isBookmark ? 'library-bookmark-title' : 'library-note-title').value.trim(); + if (!title) throw new Error('Назва обов’язкова.'); + const record = { + title, + target: context.target, + tags: tags(byId(isBookmark ? 'library-bookmark-tags' : 'library-note-tags').value), + }; + record[isBookmark ? 'bookmark_id' : 'note_id'] = context.target.node_id; + if (!isBookmark) { + record.body = byId('library-note-body').value.trim(); + if (!record.body) throw new Error('Текст нотатки обов’язковий.'); + } + const command = isBookmark ? 'research.upsert_bookmark' : 'research.upsert_note'; + const response = await invoke(command, {[kind]: record}); + const returned = response[kind]; + validateResearchList(kind, {[isBookmark ? 'bookmarks' : 'notes']: [returned]}); + if (!targetMatchesContext(returned?.target, context.task, context.mission)) { + throw new Error('Backend повернув запис для іншого canonical target.'); + } + if (mine === generation && current === context) { + await refreshCurrent(mine); + if (mine === generation && current === context) { + status(isBookmark ? 'Закладку збережено.' : 'Нотатку збережено.'); + } + } + } catch (error) { + if (mine === generation && current === context) status(`Не вдалося зберегти: ${error.message}`); + } +} + +async function remove(kind) { + if (!current) return; + const mine = generation; + const context = current; + try { + const isBookmark = kind === 'bookmark'; + const listCommand = isBookmark ? 'research.list_bookmarks' : 'research.list_notes'; + const existing = validateResearchList(kind, await invoke(listCommand, {})); + if (mine !== generation || current !== context) throw new Error('Research context changed; повторіть дію.'); + if (hasTargetCollision(kind, existing, context.task, context.mission)) { + throw new Error('ID запису належить іншому canonical target; видалення заблоковано.'); + } + if (!findCurrentRecord(kind, existing, context.task, context.mission)) { + throw new Error('Запис для поточного canonical target уже відсутній.'); + } + const idKey = isBookmark ? 'bookmark_id' : 'note_id'; + const command = isBookmark ? 'research.delete_bookmark' : 'research.delete_note'; + const response = await invoke(command, {[idKey]: context.target.node_id}); + if (!response || typeof response.deleted !== 'boolean') throw new Error('Некоректна delete-відповідь'); + if (mine === generation && current === context) { + await refreshCurrent(mine); + if (mine === generation && current === context) { + status(response.deleted + ? (isBookmark ? 'Закладку видалено.' : 'Нотатку видалено.') + : 'Запис уже був відсутній.'); + } + } + } catch (error) { + if (mine === generation && current === context) status(`Не вдалося видалити: ${error.message}`); + } +} + +function field(parent, tag, id, labelText, attrs = {}) { + const label = element('label', labelText); + label.htmlFor = id; + const control = element(tag, '', {id, ...attrs}); + parent.append(label, control); + return control; +} + +function buildPanel(library) { + if (byId('library-research-panel')) return; + const panel = element('section', '', {id: 'library-research-panel', 'aria-labelledby': 'library-research-heading'}); + const heading = element('h3', 'Закладки й нотатки', {id: 'library-research-heading', tabindex: '-1'}); + const notice = element('p', 'Особисті записи. Вони не є source claims і не змінюють canonical corpus; target та source references повторно перевіряє backend.', {role: 'note'}); + const state = element('p', 'Виберіть task у результатах пошуку.', {id: 'library-research-status', role: 'status', 'aria-live': 'polite'}); + + const bookmark = element('form', '', {id: 'library-bookmark-form'}); + bookmark.append(element('h4', 'Закладка для вибраного task')); + field(bookmark, 'input', 'library-bookmark-title', 'Назва', {maxlength: '200', required: 'required'}); + field(bookmark, 'input', 'library-bookmark-tags', 'Теги через кому', {maxlength: '1000'}); + const saveBookmark = element('button', 'Зберегти / оновити закладку', {type: 'submit'}); + const deleteBookmark = element('button', 'Видалити закладку', {id: 'library-bookmark-delete', type: 'button'}); + bookmark.append(saveBookmark, deleteBookmark); + + const note = element('form', '', {id: 'library-note-form'}); + note.append(element('h4', 'Нотатка для вибраного task')); + field(note, 'input', 'library-note-title', 'Назва нотатки', {maxlength: '200', required: 'required'}); + field(note, 'input', 'library-note-tags', 'Теги через кому', {maxlength: '1000'}); + field(note, 'textarea', 'library-note-body', 'Текст нотатки', {maxlength: '20000', required: 'required'}); + const saveNote = element('button', 'Зберегти / оновити нотатку', {type: 'submit'}); + const deleteNote = element('button', 'Видалити нотатку', {id: 'library-note-delete', type: 'button'}); + note.append(saveNote, deleteNote); + + panel.append(heading, notice, state, bookmark, note); + const back = byId('library-back'); + if (back?.parentElement === library) library.insertBefore(panel, back); + else library.append(panel); + bookmark.addEventListener('submit', event => { event.preventDefault(); void save('bookmark'); }); + note.addEventListener('submit', event => { event.preventDefault(); void save('note'); }); + deleteBookmark.addEventListener('click', () => void remove('bookmark')); + deleteNote.addEventListener('click', () => void remove('note')); + clearEditors(); + setPanelEnabled(false); +} + +function bindResult(article) { + if (article.dataset.libraryResearchBound === 'true') return; + article.dataset.libraryResearchBound = 'true'; + const identityNode = Array.from(article.children).find(node => node.tagName === 'P' && String(node.textContent || '').startsWith('Завдання: ')); + const identity = parseTaskIdentity(identityNode?.textContent || ''); + if (!identity) return; + const button = element('button', 'Закладка / нотатка', { + type: 'button', + 'aria-busy': 'false', + 'aria-controls': 'library-research-panel', + 'aria-label': `Закладка / нотатка для ${identity.node_id}`, + }); + button.addEventListener('click', () => void activate(identity, button)); + article.append(button); +} + +function bindResults(results) { + for (const article of results.querySelectorAll(':scope > article')) bindResult(article); +} + +function install() { + const library = byId('library-view'); + const results = byId('library-results'); + if (!library || !results || library.dataset.researchPersistenceInstalled === 'true') return Boolean(library && results); + library.dataset.researchPersistenceInstalled = 'true'; + buildPanel(library); + bindResults(results); + const resultsObserver = new MutationObserver(() => bindResults(results)); + resultsObserver.observe(results, {childList: true}); + const visibilityObserver = new MutationObserver(() => { + if (library.classList.contains('hidden')) invalidateLibraryResearchPersistence(); + }); + visibilityObserver.observe(library, {attributes: true, attributeFilter: ['class']}); + return true; +} + +function installWhenReady() { + if (install()) return; + const observer = new MutationObserver(() => { + if (install()) observer.disconnect(); + }); + observer.observe(document.documentElement, {childList: true, subtree: true}); +} + +if (typeof document !== 'undefined') { + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', installWhenReady, {once: true}); + else installWhenReady(); +} diff --git a/lanes/dev1/repair_overlay/frontend/library-shell-compat.js b/lanes/dev1/repair_overlay/frontend/library-shell-compat.js index dae666579..5b66187f7 100644 --- a/lanes/dev1/repair_overlay/frontend/library-shell-compat.js +++ b/lanes/dev1/repair_overlay/frontend/library-shell-compat.js @@ -1,4 +1,5 @@ import './chronology-lab-ui.js'; +import './library-research-persistence.js'; const LIBRARY_VIEW_ID = 'library-view'; @@ -21,11 +22,20 @@ export function enforceLibraryExclusivity(main = document.querySelector('main')) return true; } +function disableResearchEditorsDuringTargetChange(event) { + const trigger = event.target?.closest?.('button[aria-controls="library-research-panel"]'); + if (!trigger) return; + const panel = document.getElementById('library-research-panel'); + if (!panel) return; + for (const control of panel.querySelectorAll('input,textarea,button')) control.disabled = true; +} + function install() { const main = document.querySelector('main'); if (!main) return; document.addEventListener('click', event => { + disableResearchEditorsDuringTargetChange(event); const target = event.target?.closest?.('#nav-library'); if (target) hideShellViews(main); }, true); diff --git a/lanes/dev1/repair_overlay/frontend/renderers-base.js b/lanes/dev1/repair_overlay/frontend/renderers-base.js index e25b7400f..6f06a94d9 100644 --- a/lanes/dev1/repair_overlay/frontend/renderers-base.js +++ b/lanes/dev1/repair_overlay/frontend/renderers-base.js @@ -18,5 +18,6 @@ register('CLAIM_EVIDENCE',(task,host)=>{const l=document.createElement('label'); 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('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})}); -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 h=document.createElement('h4');h.textContent=`Крок ${i+1}: ${s.label||s.step_id}`;fs.append(h);const {wrap,input}=labelledInput(`step-${i}`,s.prompt||s.label||'Відповідь');fs.append(wrap);getters.push(()=>({step_id:s.step_id||String(i+1),answer:{text:input.value}}))});host.append(fs);return ()=>dto(task,{steps:getters.map(g=>g())})}); +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())})}); export function renderTask(task,host){host.replaceChildren();host.dataset.taskType=task.task_type;host.classList.add('answer-surface');return RendererRegistry.get(task.task_type).render(task,host)} diff --git a/lanes/dev1/repair_overlay/frontend/review-queue-ui.js b/lanes/dev1/repair_overlay/frontend/review-queue-ui.js index e8ce991e4..fdc02ba85 100644 --- a/lanes/dev1/repair_overlay/frontend/review-queue-ui.js +++ b/lanes/dev1/repair_overlay/frontend/review-queue-ui.js @@ -11,6 +11,7 @@ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+ let transportPromise = null; let loadedOnce = false; let reviewViewActive = false; +let reviewTrainingAvailable = false; const byId = id => document.getElementById(id); const requestGate = createRequestGenerationGate(() => { @@ -35,9 +36,8 @@ function setStatus(message) { } async function api(command, payload = {}) { - if (command !== 'system.bootstrap' && command !== 'player.get_review_queue') { - throw new Error('Review Queue UI attempted a non-read-only review command'); - } + const allowed = new Set(['system.bootstrap', 'player.get_review_queue', 'player.start_review']); + if (!allowed.has(command)) throw new Error('Review Queue UI attempted an unsupported review command'); if (!transportPromise) transportPromise = chooseTransport(); return await unwrap(await transportPromise, command, payload); } @@ -57,7 +57,11 @@ function hideOtherViews() { function deactivateReviewQueue() { if (!reviewViewActive) return; reviewViewActive = false; + loadedOnce = false; + reviewTrainingAvailable = false; requestGate.invalidate(); + const start = byId('review-training-start'); + if (start) start.disabled = true; } function keepViewExclusive() { @@ -92,22 +96,14 @@ function validateQueueItem(raw, index) { const relation = requireSafeText(raw, 'relation', index, {maxLength: 32}); const reason = requireSafeText(raw, 'reason', index, {allowEmpty: true, maxLength: MAX_REASON_LENGTH}); - if (!Object.prototype.hasOwnProperty.call(raw, 'node_id')) { - throw new Error(`Відсутнє поле node_id у review item #${index + 1}`); - } + if (!Object.prototype.hasOwnProperty.call(raw, 'node_id')) throw new Error(`Відсутнє поле node_id у review item #${index + 1}`); const nodeId = raw.node_id; if (nodeId !== null && (typeof nodeId !== 'string' || !nodeId || nodeId.length > MAX_ID_LENGTH || CONTROL_OR_LINE_SEPARATOR.test(nodeId))) { throw new Error(`Некоректне поле node_id у review item #${index + 1}`); } - if (!Object.prototype.hasOwnProperty.call(raw, 'priority') || !Number.isInteger(raw.priority)) { - throw new Error(`Некоректне поле priority у review item #${index + 1}`); - } - if (!REVIEW_RELATIONS.has(relation)) { - throw new Error(`Невідоме поле relation у review item #${index + 1}`); - } - if (!ISO_TIMESTAMP.test(dueAt) || Number.isNaN(Date.parse(dueAt))) { - throw new Error(`Некоректне поле due_at у review item #${index + 1}`); - } + if (!Object.prototype.hasOwnProperty.call(raw, 'priority') || !Number.isInteger(raw.priority)) throw new Error(`Некоректне поле priority у review item #${index + 1}`); + if (!REVIEW_RELATIONS.has(relation)) throw new Error(`Невідоме поле relation у review item #${index + 1}`); + if (!ISO_TIMESTAMP.test(dueAt) || Number.isNaN(Date.parse(dueAt))) throw new Error(`Некоректне поле due_at у review item #${index + 1}`); return {queueId, conceptId, nodeId, dueAt, priority: raw.priority, relation, reason}; } @@ -125,16 +121,12 @@ function renderQueue(rawQueue) { const caption = element('caption', 'Canonical review queue у порядку, повернутому runtime'); const head = element('thead'); const headerRow = element('tr'); - for (const label of ['Queue ID', 'Concept', 'Node', 'Due at', 'Priority', 'Relation', 'Reason']) { - headerRow.append(element('th', label, {scope: 'col'})); - } + for (const label of ['Queue ID', 'Concept', 'Node', 'Due at', 'Priority', 'Relation', 'Reason']) headerRow.append(element('th', label, {scope: 'col'})); head.append(headerRow); const body = element('tbody'); for (const item of validated.slice(0, MAX_VISIBLE_ITEMS)) { const row = element('tr'); - for (const value of [item.queueId, item.conceptId, item.nodeId || '—', item.dueAt, item.priority, item.relation, item.reason || '—']) { - row.append(element('td', value)); - } + for (const value of [item.queueId, item.conceptId, item.nodeId || '—', item.dueAt, item.priority, item.relation, item.reason || '—']) row.append(element('td', value)); body.append(row); } table.append(caption, head, body); @@ -149,31 +141,56 @@ async function loadReviewQueue() { try { const bootstrap = await api('system.bootstrap'); if (!requestGate.isCurrent(generation)) return; - if (bootstrap?.capabilities?.review_queue !== true) { - throw new Error('Canonical runtime review queue недоступна в цьому запуску'); - } + if (bootstrap?.capabilities?.review_queue !== true) throw new Error('Canonical runtime review queue недоступна в цьому запуску'); + reviewTrainingAvailable = bootstrap?.capabilities?.review_training === true; + const start = byId('review-training-start'); + if (start) start.disabled = !reviewTrainingAvailable; const data = await api('player.get_review_queue'); if (!requestGate.isCurrent(generation)) return; - if (data?.truth_owner !== 'D5/runtime') { - throw new Error('Review queue response не підтверджує D5/runtime truth ownership'); - } + if (data?.truth_owner !== 'D5/runtime') throw new Error('Review queue response не підтверджує D5/runtime truth ownership'); const rendered = renderQueue(data.review_queue); if (!requestGate.isCurrent(generation)) return; loadedOnce = true; - if (rendered.total > rendered.shown) { - setStatus(`Canonical queue містить ${rendered.total} записів; показано перші ${rendered.shown} у runtime order без локального re-ranking.`); - } else { - setStatus(`Canonical queue: ${rendered.total} записів. Порядок і поля відображені без локальної scheduling policy.`); - } + const suffix = reviewTrainingAvailable ? ' Тренування обирає завдання тільки через canonical runtime Scheduler.' : ' Режим тренування в цьому запуску недоступний.'; + if (rendered.total > rendered.shown) setStatus(`Canonical queue містить ${rendered.total} записів; показано перші ${rendered.shown} у runtime order без локального re-ranking.${suffix}`); + else setStatus(`Canonical queue: ${rendered.total} записів. Порядок і поля відображені без локальної scheduling policy.${suffix}`); byId('review-queue-heading')?.focus(); } catch (error) { if (!requestGate.isCurrent(generation)) return; loadedOnce = false; + reviewTrainingAvailable = false; + const start = byId('review-training-start'); + if (start) start.disabled = true; byId('review-queue-results')?.replaceChildren(); setStatus(`Review queue недоступна: ${error.message}`); } } +async function startReviewTraining() { + if (!reviewTrainingAvailable) return; + const generation = requestGate.begin(); + if (!requestGate.isCurrent(generation)) return; + const button = byId('review-training-start'); + if (button) button.disabled = true; + setStatus('Canonical runtime обирає наступне доступне повторення…'); + try { + const data = await api('player.start_review'); + if (!requestGate.isCurrent(generation)) return; + if (data?.truth_owner !== 'D5/runtime' || !data.review_session || typeof data.review_session !== 'object') throw new Error('Некоректна відповідь Review Training'); + if (!data.task) { + setStatus('Зараз немає повторень, дозволених canonical runtime Scheduler. Майбутні due items не відкриваються достроково.'); + loadedOnce = false; + await loadReviewQueue(); + return; + } + document.dispatchEvent(new CustomEvent('scripture-review-training-started', {detail: data})); + } catch (error) { + if (!requestGate.isCurrent(generation)) return; + setStatus(`Тренування не запущено: ${error.message}`); + if (button) button.disabled = !reviewTrainingAvailable; + } +} + function buildSurface() { if (byId('nav-review-queue') || byId('review-queue-view')) return; const nav = document.querySelector('.top-nav'); @@ -185,12 +202,14 @@ function buildSurface() { const section = element('section', '', {id: 'review-queue-view', className: 'hidden', 'aria-labelledby': 'review-queue-heading'}); const heading = element('h2', 'Черга повторення', {id: 'review-queue-heading', tabIndex: '-1'}); - const note = element('p', 'Read-only проєкція persisted canonical review queue. Цей екран не визначає due/priority policy, не пересортовує чергу і не обирає наступне завдання.', {id: 'review-queue-contract-note', role: 'note'}); - const status = element('p', '', {id: 'review-queue-status', role: 'status', 'aria-live': 'polite'}); + const note = element('p', 'Черга є read-only проєкцією persisted canonical review state. Кнопка тренування не вибирає рядок у браузері: наступний task визначає існуючий D5/runtime Scheduler з його due, cooldown, fatigue та session-dedup правилами.', {id: 'review-queue-contract-note', role: 'note'}); + const status = element('p', '', {id: 'review-queue-status', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'}); const actions = element('div', '', {className: 'actions'}); + const start = element('button', 'Почати тренування', {id: 'review-training-start', type: 'button', className: 'primary'}); + start.disabled = true; const refresh = element('button', 'Оновити чергу', {id: 'review-queue-refresh', type: 'button'}); const back = element('button', 'Повернутися на головну', {id: 'review-queue-back', type: 'button'}); - actions.append(refresh, back); + actions.append(start, refresh, back); const results = element('div', '', {id: 'review-queue-results'}); section.append(heading, note, status, actions, results); main.append(section); @@ -202,6 +221,7 @@ function buildSurface() { heading.focus(); if (!loadedOnce) void loadReviewQueue(); }); + start.addEventListener('click', () => { void startReviewTraining(); }); refresh.addEventListener('click', () => { void loadReviewQueue(); }); back.addEventListener('click', () => { deactivateReviewQueue(); diff --git a/lanes/dev1/repair_overlay/frontend/speech-ui.js b/lanes/dev1/repair_overlay/frontend/speech-ui.js new file mode 100644 index 000000000..c2b6adcc5 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/speech-ui.js @@ -0,0 +1,202 @@ +import {chooseTransport, unwrap} from './transport.js'; + +const PREF_KEY = 'scripture.archive.speech.preferences.v1'; +let transport = null; + +async function api(command, payload = {}) { + if (!transport) transport = chooseTransport(); + return await unwrap(transport, command, payload); +} + +function make(tag, text) { + const node = document.createElement(tag); + if (text !== undefined) node.textContent = text; + return node; +} + +function readPrefs() { + try { + const value = JSON.parse(localStorage.getItem(PREF_KEY) || '{}'); + return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; + } catch (_) { + return {}; + } +} + +function writePrefs(value) { + try { + localStorage.setItem(PREF_KEY, JSON.stringify(value)); + } catch (_) { + // Preference persistence is best-effort; speech itself remains usable. + } +} + +function requireStatus(data) { + if (!data || data.schema !== 'scripture.packaged-speech.v1' || data.truth_owner !== 'presentation-only' || data.supported_surface !== 'current_canonical_task_prompt_only' || data.private_text_supported !== false || !Array.isArray(data.providers)) { + throw new Error('Speech status failed packaged contract validation'); + } + return data; +} + +function requireAudio(data) { + if (!data || data.schema !== 'scripture.packaged-speech.v1' || data.truth_owner !== 'presentation-only' || data.spoken_surface !== 'current_canonical_task_prompt_only') { + throw new Error('Speech response failed packaged contract validation'); + } + if (typeof data.audio_base64 !== 'string' || !data.audio_base64 || typeof data.mime_type !== 'string' || !data.mime_type.startsWith('audio/') || !Number.isInteger(data.byte_length) || data.byte_length <= 0) { + throw new Error('Speech response did not contain valid audio'); + } + return data; +} + +function buildSurface(config) { + const prompt = document.getElementById('player-prompt'); + if (!prompt || document.getElementById('packaged-speech')) return false; + + const prefs = readPrefs(); + const section = make('section'); + section.id = 'packaged-speech'; + section.setAttribute('aria-labelledby', 'packaged-speech-heading'); + + const heading = make('h3', 'Озвучення поточного завдання'); + heading.id = 'packaged-speech-heading'; + const scope = make('p', 'Озвучення є лише presentation layer. Host передає провайдеру тільки canonical prompt поточного завдання після явної згоди; нотатки, відповіді, evidence і grading не передаються.'); + + const providerLabel = make('label', 'Провайдер '); + providerLabel.htmlFor = 'speech-provider'; + const provider = make('select'); + provider.id = 'speech-provider'; + for (const item of config.providers) { + if (!item || typeof item.provider_id !== 'string' || !item.provider_id) continue; + const option = make('option', item.provider_id); + option.value = item.provider_id; + provider.append(option); + } + + const voiceLabel = make('label', ' Voice ID '); + voiceLabel.htmlFor = 'speech-voice'; + const voice = make('input'); + voice.id = 'speech-voice'; + voice.type = 'text'; + voice.autocomplete = 'off'; + voice.maxLength = 256; + + const speedLabel = make('label', ' Швидкість '); + speedLabel.htmlFor = 'speech-speed'; + const speed = make('input'); + speed.id = 'speech-speed'; + speed.type = 'number'; + speed.min = '0.7'; + speed.max = '1.2'; + speed.step = '0.1'; + speed.value = String(Number(prefs.speed) >= 0.7 && Number(prefs.speed) <= 1.2 ? Number(prefs.speed) : 1.0); + + const consentLabel = make('label'); + const consent = make('input'); + consent.type = 'checkbox'; + consent.id = 'speech-network-consent'; + consentLabel.append(consent, document.createTextNode(' Дозволити мережевий TTS для canonical prompt цього запиту')); + + const prepare = make('button', 'Підготувати аудіо'); + prepare.type = 'button'; + const audio = document.createElement('audio'); + audio.controls = true; + audio.preload = 'none'; + audio.setAttribute('aria-label', 'Озвучення поточного canonical завдання'); + audio.hidden = true; + const status = make('p', 'Озвучення готове до налаштування.'); + status.setAttribute('role', 'status'); + status.setAttribute('aria-live', 'polite'); + status.className = 'notice info'; + + function selectedConfig() { + return config.providers.find(item => item.provider_id === provider.value) || null; + } + function applyVoice() { + const voices = prefs.voices && typeof prefs.voices === 'object' ? prefs.voices : {}; + const saved = voices[provider.value]; + const fallback = selectedConfig()?.default_voice || ''; + voice.value = typeof saved === 'string' && saved ? saved : fallback; + } + function persist() { + const next = readPrefs(); + next.provider_id = provider.value; + next.speed = Number(speed.value) || 1.0; + next.voices = next.voices && typeof next.voices === 'object' ? next.voices : {}; + next.voices[provider.value] = voice.value; + writePrefs(next); + } + + if (config.providers.length) { + const preferred = config.providers.find(item => item.provider_id === prefs.provider_id); + provider.value = preferred ? preferred.provider_id : config.providers[0].provider_id; + applyVoice(); + } else { + prepare.disabled = true; + provider.disabled = true; + voice.disabled = true; + speed.disabled = true; + consent.disabled = true; + status.textContent = 'Мережевий TTS не налаштовано в host environment. Жоден секрет не передано у WebView.'; + } + + provider.addEventListener('change', () => { applyVoice(); persist(); }); + voice.addEventListener('change', persist); + speed.addEventListener('change', persist); + prepare.addEventListener('click', async () => { + audio.pause(); + audio.removeAttribute('src'); + audio.load(); + audio.hidden = true; + if (!consent.checked) { + status.textContent = 'Для мережевого озвучення потрібна явна згода на цей запит.'; + consent.focus(); + return; + } + if (!voice.value.trim()) { + status.textContent = 'Вкажіть Voice ID.'; + voice.focus(); + return; + } + prepare.disabled = true; + status.textContent = 'Готується аудіо canonical prompt…'; + persist(); + try { + const data = requireAudio(await api('speech.synthesize_prompt', { + provider_id: provider.value, + voice_id: voice.value.trim(), + speed: Number(speed.value), + allow_network: true, + })); + audio.src = `data:${data.mime_type};base64,${data.audio_base64}`; + audio.hidden = false; + status.textContent = `Аудіо готове (${data.byte_length} байт${data.from_cache ? ', cache' : ''}). Натисніть Play у стандартних аудіоконтролах.`; + audio.focus(); + } catch (error) { + status.textContent = `Озвучення недоступне: ${error.message}`; + } finally { + prepare.disabled = false; + consent.checked = false; + } + }); + + const controls = make('div'); + controls.className = 'action-row'; + providerLabel.append(provider); + voiceLabel.append(voice); + speedLabel.append(speed); + controls.append(providerLabel, voiceLabel, speedLabel, prepare); + section.append(heading, scope, controls, consentLabel, status, audio); + prompt.insertAdjacentElement('afterend', section); + return true; +} + +export async function installSpeechSurface() { + try { + const bootstrap = await api('system.bootstrap', {}); + if (bootstrap?.capabilities?.speech !== true) return; + const status = requireStatus(await api('speech.status', {})); + buildSurface(status); + } catch (_) { + // Capability discovery fails closed; the existing packaged app remains usable. + } +} diff --git a/lanes/dev1/repair_overlay/frontend/transport.js b/lanes/dev1/repair_overlay/frontend/transport.js index da74dd864..50057a6fc 100644 --- a/lanes/dev1/repair_overlay/frontend/transport.js +++ b/lanes/dev1/repair_overlay/frontend/transport.js @@ -43,3 +43,7 @@ void import('./content-pack-manager.js').then(({installContentPackManagerSurface void import('./evidence-graph-ui.js').then(({installEvidenceGraphSurface})=>installEvidenceGraphSurface()); // Canonical source-local Witness Matrix is a read-only projection from unlocked runtime evidence. void import('./witness-matrix-ui.js').then(({installWitnessMatrixSurface})=>installWitnessMatrixSurface()); +// Constructor V2 augments the existing AuthoringUI; it remains draft/version-only and capability-gated. +void import('./constructor-v2-ui.js').then(({installConstructorV2Surface})=>installConstructorV2Surface()); +// Presentation-only speech uses the current canonical runtime task and never accepts arbitrary browser text. +void import('./speech-ui.js').then(({installSpeechSurface})=>installSpeechSurface()); diff --git a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 index 3aeaab8f8..6bccead6b 100644 --- a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 +++ b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 @@ -48,6 +48,12 @@ if ($actualGitSha -notmatch '^[0-9a-f]{40}$') { throw "Exact 40-hex checkout SHA is required for packaged diagnostics identity" } +$sourceArchive = Join-Path $Repo "DEV1_R06_PLATFORM_SOURCE.zip" +$sourceHash = $null +if (Test-Path $sourceArchive) { + $sourceHash = (Get-FileHash -Algorithm SHA256 $sourceArchive).Hash.ToLowerInvariant() +} + $BuildIdentityDir = Join-Path ([System.IO.Path]::GetTempPath()) ("scripture-build-identity-" + [guid]::NewGuid().ToString("N")) New-Item -ItemType Directory -Force -Path $BuildIdentityDir | Out-Null $BuildIdentity = Join-Path $BuildIdentityDir "build_identity.json" @@ -55,6 +61,22 @@ $BuildIdentityPayload = @{ build_sha = $actualGitSha } | ConvertTo-Json -Compres $Utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($BuildIdentity, $BuildIdentityPayload, $Utf8NoBom) +$PayloadManifest = Join-Path $Dist "packaged_payload_manifest.json" +$FidelityTool = Join-Path $PSScriptRoot "packaged_payload_fidelity.py" +$payloadManifestArgs = @( + "manifest", + "--repo-root", $Repo, + "--platform-root", $PlatformRoot, + "--build-identity", $BuildIdentity, + "--git-sha", $actualGitSha, + "--output", $PayloadManifest +) +if ($sourceHash) { + $payloadManifestArgs += @("--source-archive-sha256", $sourceHash) +} +& $Python $FidelityTool @payloadManifestArgs +Assert-NativeSuccess "packaged payload manifest generation" + $Sep = ";" $Name = "ScriptureArchive-R06-DEV01" $Out = Join-Path $Dist "$Name.exe" @@ -85,13 +107,16 @@ if (-not (Test-Path -LiteralPath $Out -PathType Leaf)) { throw "Expected executable not produced: $Out" } +$PayloadReadback = Join-Path $Dist "packaged_payload_fidelity.json" +& $Python $FidelityTool verify ` + --artifact $Out ` + --manifest $PayloadManifest ` + --output $PayloadReadback +Assert-NativeSuccess "embedded packaged payload fidelity verification" + $hash = (Get-FileHash -Algorithm SHA256 $Out).Hash.ToLowerInvariant() $size = (Get-Item $Out).Length -$sourceArchive = Join-Path $Repo "DEV1_R06_PLATFORM_SOURCE.zip" -$sourceHash = $null -if (Test-Path $sourceArchive) { - $sourceHash = (Get-FileHash -Algorithm SHA256 $sourceArchive).Hash.ToLowerInvariant() -} +$payloadEvidenceHash = (Get-FileHash -Algorithm SHA256 $PayloadReadback).Hash.ToLowerInvariant() $pythonVersion = (& $Python --version 2>&1 | Out-String).Trim() Assert-NativeSuccess "Python version query" @@ -108,13 +133,19 @@ $manifest = [ordered]@{ python_version = $pythonVersion source_archive_sha256 = $sourceHash diagnostics_file = (Split-Path -Leaf $Diagnostics) + packaged_payload_manifest_file = (Split-Path -Leaf $PayloadManifest) + packaged_payload_fidelity_file = (Split-Path -Leaf $PayloadReadback) + packaged_payload_fidelity_sha256 = $payloadEvidenceHash proof_scope = @( "PyInstaller build completed", "artifact size/hash readback verified", + "embedded frontend/campaign/build-identity bytes verified against exact staged manifest", + "Git-tracked embedded frontend overlay/campaign bytes verified against exact checkout Git blob IDs", "WebView2 runtime presence probed before build", "packaged diagnostics build identity bound to exact checkout SHA" ) not_proven = @( + "Python module bytecode identity inside PYZ", "human NVDA acceptance", "full application functional acceptance", "visual correctness", diff --git a/lanes/dev1/repair_overlay/packaging/packaged_payload_fidelity.py b/lanes/dev1/repair_overlay/packaging/packaged_payload_fidelity.py new file mode 100644 index 000000000..fd71bed32 --- /dev/null +++ b/lanes/dev1/repair_overlay/packaging/packaged_payload_fidelity.py @@ -0,0 +1,556 @@ +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import struct +import subprocess +from pathlib import Path +from typing import Any + +_HEX40 = re.compile(r"^[0-9a-f]{40}$") +_DRIVE_PATH = re.compile(r"^[A-Za-z]:") +_PROTECTED_PREFIXES = ("r06_platform/frontend/", "docs/campaigns/") +_PROTECTED_EXACT = {"r06_platform/build_identity.json"} + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def git_blob_sha(data: bytes) -> str: + header = f"blob {len(data)}\0".encode("ascii") + return hashlib.sha1(header + data).hexdigest() + + +def normalize_archive_path(value: str) -> str: + raw = str(value).replace("\\", "/") + if not raw: + raise ValueError("Archive path is empty") + if raw.startswith("/") or _DRIVE_PATH.match(raw): + raise ValueError(f"Archive path must be relative: {value!r}") + parts = raw.split("/") + if any(part in {"", ".", ".."} for part in parts): + raise ValueError(f"Archive path contains unsafe component: {value!r}") + return "/".join(parts) + + +def _is_protected_payload_path(path: str) -> bool: + return path in _PROTECTED_EXACT or any(path.startswith(prefix) for prefix in _PROTECTED_PREFIXES) + + +def _write_json(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def _git_blob_at(repo_root: Path, git_sha: str, repo_path: str) -> str | None: + proc = subprocess.run( + ["git", "-C", str(repo_root), "rev-parse", f"{git_sha}:{repo_path}"], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0: + return None + value = proc.stdout.strip().lower() + if not _HEX40.fullmatch(value): + raise RuntimeError(f"Invalid Git blob identity for {repo_path}: {value!r}") + return value + + +def _entry( + source: Path, + package_path: str, + provenance: str, + *, + repo_path: str | None = None, + git_blob: str | None = None, +) -> dict[str, Any]: + normalized_package_path = normalize_archive_path(package_path) + data = source.read_bytes() + entry: dict[str, Any] = { + "package_path": normalized_package_path, + "size_bytes": len(data), + "sha256": sha256_hex(data), + "provenance": provenance, + } + if repo_path is not None: + entry["repo_path"] = repo_path + if git_blob is not None: + actual_blob = git_blob_sha(data) + if actual_blob != git_blob: + raise RuntimeError( + f"Staged Git blob mismatch for {repo_path}: expected={git_blob} actual={actual_blob}" + ) + entry["git_blob_sha1"] = git_blob + return entry + + +def build_manifest( + repo_root: Path, + platform_root: Path, + build_identity: Path, + git_sha: str, + source_archive_sha256: str | None, +) -> dict[str, Any]: + repo_root = repo_root.resolve() + platform_root = platform_root.resolve() + build_identity = build_identity.resolve() + git_sha = git_sha.strip().lower() + if not _HEX40.fullmatch(git_sha): + raise RuntimeError("Exact 40-hex git SHA is required") + + frontend_root = platform_root / "frontend" + campaigns_root = repo_root / "docs" / "campaigns" + if not frontend_root.is_dir(): + raise RuntimeError(f"Missing staged frontend: {frontend_root}") + if not campaigns_root.is_dir(): + raise RuntimeError(f"Missing campaigns payload: {campaigns_root}") + if not build_identity.is_file(): + raise RuntimeError(f"Missing generated build identity: {build_identity}") + + entries: list[dict[str, Any]] = [] + for source in sorted(path for path in frontend_root.rglob("*") if path.is_file()): + rel = source.relative_to(frontend_root).as_posix() + repo_path = f"lanes/dev1/repair_overlay/frontend/{rel}" + git_blob = _git_blob_at(repo_root, git_sha, repo_path) + provenance = "git_overlay" if git_blob else "immutable_dev1_source" + entries.append( + _entry( + source, + f"r06_platform/frontend/{rel}", + provenance, + repo_path=repo_path if git_blob else None, + git_blob=git_blob, + ) + ) + + for source in sorted(path for path in campaigns_root.rglob("*") if path.is_file()): + rel = source.relative_to(campaigns_root).as_posix() + repo_path = f"docs/campaigns/{rel}" + git_blob = _git_blob_at(repo_root, git_sha, repo_path) + if git_blob is None: + raise RuntimeError(f"Campaign payload is not Git-tracked at {git_sha}: {repo_path}") + entries.append( + _entry( + source, + f"docs/campaigns/{rel}", + "git_campaign", + repo_path=repo_path, + git_blob=git_blob, + ) + ) + + entries.append( + _entry( + build_identity, + "r06_platform/build_identity.json", + "generated_build_identity", + ) + ) + entries.sort(key=lambda item: item["package_path"]) + package_paths = [item["package_path"] for item in entries] + if len(package_paths) != len(set(package_paths)): + raise RuntimeError("Duplicate packaged payload path in fidelity manifest") + + git_pinned = sum(1 for item in entries if item.get("git_blob_sha1")) + source_only = sum(1 for item in entries if item["provenance"] == "immutable_dev1_source") + return { + "schema_version": 1, + "git_sha": git_sha, + "source_archive_sha256": source_archive_sha256, + "entries": entries, + "counts": { + "total": len(entries), + "git_blob_pinned": git_pinned, + "immutable_source_staged": source_only, + }, + "proof_scope": [ + "all PyInstaller --add-data frontend files are pinned to exact staged bytes", + "all PyInstaller --add-data docs/campaigns files are pinned to exact staged bytes and Git blobs", + "Git-tracked frontend overlay files are pinned to exact Git blobs", + "generated build identity is pinned to exact staged bytes", + ], + "not_proven": [ + "Python module bytecode identity inside PYZ", + "human NVDA acceptance", + "visual correctness", + "full functional acceptance", + ], + } + + +def _cookie_package_from_file( + reader: Any, + *, + cookie_format: str, + cookie_length: int, + cookie_magic: bytes, +) -> bytes: + """Read exactly the embedded CArchive package from the real reader-backed file. + + PyInstaller executables can contain bytes before the package and platform signing + data after the package cookie. Locate a structurally valid cookie from the end, + and when the reader exposes a start offset require the cookie's declared archive + length to resolve to that exact start. This avoids treating the physical file EOF + as the CArchive EOF. + """ + filename = getattr(reader, "_filename", None) + if not filename: + raise RuntimeError("CArchive reader filename unavailable") + try: + file_bytes = Path(filename).read_bytes() + except (OSError, TypeError, ValueError) as exc: + raise RuntimeError(f"CArchive backing file read failed: {exc}") from exc + + start_value = getattr(reader, "_start_offset", None) + start_hint: int | None = None + if start_value is not None: + try: + start_hint = int(start_value) + except (TypeError, ValueError) as exc: + raise RuntimeError(f"CArchive start offset is invalid: {start_value!r}") from exc + if start_hint < 0 or start_hint > len(file_bytes): + raise RuntimeError( + f"CArchive start offset outside backing file: {start_hint} / {len(file_bytes)}" + ) + + search_end = len(file_bytes) + lower_bound = start_hint if start_hint is not None else 0 + while search_end > lower_bound: + magic_pos = file_bytes.rfind(cookie_magic, lower_bound, search_end) + if magic_pos < 0: + break + cookie_end = magic_pos + cookie_length + search_end = magic_pos + if cookie_end > len(file_bytes): + continue + cookie_bytes = file_bytes[magic_pos:cookie_end] + try: + unpacked = struct.unpack(cookie_format, cookie_bytes) + except struct.error: + continue + if len(unpacked) < 4 or unpacked[0] != cookie_magic: + continue + try: + archive_length = int(unpacked[1]) + toc_offset = int(unpacked[2]) + toc_length = int(unpacked[3]) + except (TypeError, ValueError): + continue + if archive_length < cookie_length or toc_offset < 0 or toc_length < 0: + continue + package_start = cookie_end - archive_length + if package_start < 0: + continue + if start_hint is not None and package_start != start_hint: + continue + cookie_start_in_package = archive_length - cookie_length + if toc_offset + toc_length > cookie_start_in_package: + continue + return file_bytes[package_start:cookie_end] + + raise RuntimeError("Unable to locate a valid CArchive cookie in reader backing file") + + +def _raw_carchive_member_names(reader: Any) -> list[str]: + """Read non-option member names before CArchiveReader collapses duplicate dict keys.""" + try: + cookie_format = reader._COOKIE_FORMAT + cookie_length = int(reader._COOKIE_LENGTH) + cookie_magic = bytes(reader._COOKIE_MAGIC_PATTERN) + toc_entry_format = reader._TOC_ENTRY_FORMAT + toc_entry_length = int(reader._TOC_ENTRY_LENGTH) + except (AttributeError, TypeError, ValueError) as exc: + raise RuntimeError(f"CArchive reader metadata unavailable: {exc}") from exc + + if cookie_length <= 0 or toc_entry_length <= 0 or not cookie_magic: + raise RuntimeError("CArchive reader metadata contains invalid lengths or magic") + + if getattr(reader, "_filename", None): + raw_pkg = _cookie_package_from_file( + reader, + cookie_format=cookie_format, + cookie_length=cookie_length, + cookie_magic=cookie_magic, + ) + else: + raw_pkg_data = getattr(reader, "raw_pkg_data", None) + if not callable(raw_pkg_data): + raise RuntimeError("CArchive reader exposes neither backing filename nor raw package data") + try: + raw_pkg = raw_pkg_data() + except Exception as exc: + raise RuntimeError(f"CArchive raw package read failed: {exc}") from exc + if not isinstance(raw_pkg, (bytes, bytearray)): + raise RuntimeError(f"CArchive raw package has invalid type: {type(raw_pkg).__name__}") + raw_pkg = bytes(raw_pkg) + + if len(raw_pkg) < cookie_length: + raise RuntimeError("CArchive raw package is shorter than its cookie") + try: + unpacked_cookie = struct.unpack(cookie_format, raw_pkg[-cookie_length:]) + except struct.error as exc: + raise RuntimeError(f"CArchive cookie parse failed: {exc}") from exc + if len(unpacked_cookie) < 4: + raise RuntimeError("CArchive cookie does not contain required archive/TOC fields") + magic = unpacked_cookie[0] + try: + archive_length = int(unpacked_cookie[1]) + toc_offset = int(unpacked_cookie[2]) + toc_length = int(unpacked_cookie[3]) + except (TypeError, ValueError) as exc: + raise RuntimeError(f"CArchive cookie numeric fields are invalid: {exc}") from exc + if magic != cookie_magic: + raise RuntimeError("CArchive raw package cookie magic mismatch") + if archive_length != len(raw_pkg): + raise RuntimeError( + f"CArchive raw package length mismatch: cookie={archive_length} actual={len(raw_pkg)}" + ) + toc_end = toc_offset + toc_length + cookie_start = len(raw_pkg) - cookie_length + if toc_offset < 0 or toc_length < 0 or toc_end > cookie_start: + raise RuntimeError( + f"CArchive TOC bounds invalid: offset={toc_offset} length={toc_length} cookie_start={cookie_start}" + ) + + toc_data = raw_pkg[toc_offset:toc_end] + names: list[str] = [] + cur_pos = 0 + while cur_pos < len(toc_data): + if len(toc_data) - cur_pos < toc_entry_length: + raise RuntimeError("CArchive TOC contains a truncated entry header") + header = toc_data[cur_pos:(cur_pos + toc_entry_length)] + try: + unpacked = struct.unpack(toc_entry_format, header) + except struct.error as exc: + raise RuntimeError(f"CArchive TOC entry parse failed: {exc}") from exc + if len(unpacked) != 6: + raise RuntimeError(f"CArchive TOC entry has unexpected field count: {len(unpacked)}") + entry_length, _entry_offset, _data_length, _uncompressed_length, _compression_flag, typecode = unpacked + try: + entry_length = int(entry_length) + except (TypeError, ValueError) as exc: + raise RuntimeError(f"CArchive TOC entry length is invalid: {entry_length!r}") from exc + if entry_length < toc_entry_length: + raise RuntimeError(f"CArchive TOC entry length is invalid: {entry_length}") + next_pos = cur_pos + entry_length + if next_pos <= cur_pos or next_pos > len(toc_data): + raise RuntimeError("CArchive TOC entry exceeds declared TOC bounds") + raw_name = toc_data[cur_pos + toc_entry_length:next_pos].rstrip(b"\0") + try: + name = raw_name.decode("utf-8") + except UnicodeDecodeError as exc: + raise RuntimeError(f"CArchive TOC name decode failed: {exc}") from exc + if isinstance(typecode, int): + if not 0 <= typecode <= 255: + raise RuntimeError(f"CArchive TOC integer typecode out of range: {typecode}") + typecode_raw = bytes([typecode]) + elif isinstance(typecode, (bytes, bytearray)) and len(typecode) == 1: + typecode_raw = bytes(typecode) + else: + raise RuntimeError(f"CArchive TOC typecode has invalid shape: {typecode!r}") + try: + typecode_text = typecode_raw.decode("ascii") + except UnicodeDecodeError as exc: + raise RuntimeError(f"CArchive TOC typecode decode failed: {exc}") from exc + if typecode_text != "o": + names.append(name) + cur_pos = next_pos + + if cur_pos != len(toc_data): + raise RuntimeError("CArchive TOC parser did not consume the declared TOC length") + return names + + +def _archive_index(reader: Any, archive_names: list[str] | None = None) -> tuple[dict[str, str], list[str]]: + index: dict[str, str] = {} + errors: list[str] = [] + names = archive_names if archive_names is not None else [str(name) for name in getattr(reader, "toc", {})] + for raw_name in names: + name = str(raw_name) + try: + normalized = normalize_archive_path(name) + except ValueError as exc: + errors.append(f"INVALID_ARCHIVE_PATH {name!r}: {exc}") + continue + existing = index.get(normalized) + if existing is not None: + errors.append(f"DUPLICATE_NORMALIZED_PATH {normalized}: {existing!r} vs {name!r}") + else: + index[normalized] = name + return index, errors + + +def verify_reader( + reader: Any, + manifest: dict[str, Any], + *, + archive_names: list[str] | None = None, +) -> dict[str, Any]: + entries = manifest.get("entries") + if manifest.get("schema_version") != 1 or not isinstance(entries, list): + return { + "schema_version": 1, + "ok": False, + "files_expected": 0, + "files_verified": 0, + "errors": ["INVALID_MANIFEST"], + "entries": [], + } + + index, errors = _archive_index(reader, archive_names) + checked: list[dict[str, Any]] = [] + expected_paths: set[str] = set() + verified = 0 + for expected in entries: + if not isinstance(expected, dict): + errors.append("INVALID_MANIFEST_ENTRY") + continue + raw_package_path = str(expected.get("package_path", "")) + try: + package_path = normalize_archive_path(raw_package_path) + except ValueError as exc: + errors.append(f"INVALID_MANIFEST_PATH {raw_package_path!r}: {exc}") + checked.append({"package_path": raw_package_path, "ok": False, "error": "invalid_manifest_path"}) + continue + if package_path in expected_paths: + errors.append(f"DUPLICATE_MANIFEST_PATH {package_path}") + checked.append({"package_path": package_path, "ok": False, "error": "duplicate_manifest_path"}) + continue + expected_paths.add(package_path) + actual_name = index.get(package_path) + row: dict[str, Any] = {"package_path": package_path, "ok": False} + if actual_name is None: + errors.append(f"MISSING {package_path}") + row["error"] = "missing" + checked.append(row) + continue + try: + data = reader.extract(actual_name) + except Exception as exc: + errors.append(f"EXTRACT_ERROR {package_path}: {exc}") + row["error"] = "extract_error" + checked.append(row) + continue + if not isinstance(data, (bytes, bytearray)): + errors.append(f"INVALID_EXTRACT_TYPE {package_path}: {type(data).__name__}") + row["error"] = "invalid_extract_type" + checked.append(row) + continue + actual = bytes(data) + actual_sha = sha256_hex(actual) + actual_size = len(actual) + row["size_bytes"] = actual_size + row["sha256"] = actual_sha + expected_size = expected.get("size_bytes") + expected_sha = expected.get("sha256") + mismatch = False + if actual_size != expected_size: + errors.append(f"SIZE_MISMATCH {package_path}: expected={expected_size} actual={actual_size}") + mismatch = True + if actual_sha != expected_sha: + errors.append(f"SHA256_MISMATCH {package_path}: expected={expected_sha} actual={actual_sha}") + mismatch = True + expected_blob = expected.get("git_blob_sha1") + if expected_blob: + actual_blob = git_blob_sha(actual) + row["git_blob_sha1"] = actual_blob + if actual_blob != expected_blob: + errors.append(f"GIT_BLOB_MISMATCH {package_path}: expected={expected_blob} actual={actual_blob}") + mismatch = True + row["ok"] = not mismatch + if row["ok"]: + verified += 1 + checked.append(row) + + for package_path in sorted(index): + if _is_protected_payload_path(package_path) and package_path not in expected_paths: + errors.append(f"UNEXPECTED_PROTECTED_PAYLOAD {package_path}") + checked.append( + { + "package_path": package_path, + "ok": False, + "error": "unexpected_protected_payload", + } + ) + + return { + "schema_version": 1, + "ok": not errors and verified == len(entries), + "git_sha": manifest.get("git_sha"), + "source_archive_sha256": manifest.get("source_archive_sha256"), + "files_expected": len(entries), + "files_verified": verified, + "errors": errors, + "entries": checked, + "not_proven": manifest.get("not_proven", []), + } + + +def verify_artifact(artifact: Path, manifest: dict[str, Any]) -> dict[str, Any]: + try: + from PyInstaller.archive.readers import CArchiveReader + except Exception as exc: # pragma: no cover - exercised in Windows build environment + raise RuntimeError(f"PyInstaller archive reader unavailable: {exc}") from exc + reader = CArchiveReader(str(artifact)) + archive_names = _raw_carchive_member_names(reader) + result = verify_reader(reader, manifest, archive_names=archive_names) + result["artifact"] = str(artifact) + result["artifact_sha256"] = sha256_hex(artifact.read_bytes()) + return result + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Prove staged and embedded Windows package payload fidelity") + sub = parser.add_subparsers(dest="command", required=True) + + manifest_parser = sub.add_parser("manifest") + manifest_parser.add_argument("--repo-root", required=True) + manifest_parser.add_argument("--platform-root", required=True) + manifest_parser.add_argument("--build-identity", required=True) + manifest_parser.add_argument("--git-sha", required=True) + manifest_parser.add_argument("--source-archive-sha256") + manifest_parser.add_argument("--output", required=True) + + verify_parser = sub.add_parser("verify") + verify_parser.add_argument("--artifact", required=True) + verify_parser.add_argument("--manifest", required=True) + verify_parser.add_argument("--output", required=True) + + ns = parser.parse_args(argv) + try: + if ns.command == "manifest": + payload = build_manifest( + Path(ns.repo_root), + Path(ns.platform_root), + Path(ns.build_identity), + ns.git_sha, + ns.source_archive_sha256, + ) + _write_json(Path(ns.output), payload) + print( + "PACKAGE_FIDELITY_MANIFEST_PASS " + f"files={payload['counts']['total']} git_pinned={payload['counts']['git_blob_pinned']}" + ) + return 0 + + manifest = json.loads(Path(ns.manifest).read_text(encoding="utf-8-sig")) + result = verify_artifact(Path(ns.artifact), manifest) + _write_json(Path(ns.output), result) + print( + f"PACKAGE_FIDELITY_{'PASS' if result['ok'] else 'FAIL'} " + f"verified={result['files_verified']}/{result['files_expected']}" + ) + for error in result["errors"]: + print(f"ERROR {error}") + return 0 if result["ok"] else 1 + except Exception as exc: + print(f"PACKAGE_FIDELITY_ERROR {exc}") + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/lanes/dev1/repair_overlay/run_web_mock.py b/lanes/dev1/repair_overlay/run_web_mock.py index e388f654d..3f2f7582b 100644 --- a/lanes/dev1/repair_overlay/run_web_mock.py +++ b/lanes/dev1/repair_overlay/run_web_mock.py @@ -9,7 +9,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "r06_platform")) -from scripture_archive_platform.application.witness_matrix_application import build_default_application +from scripture_archive_platform.application.speech_application import build_default_application class Handler(SimpleHTTPRequestHandler): app = build_default_application(ROOT) @@ -38,7 +38,7 @@ def do_POST(self): self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("X-Content-Type-Options", "nosniff") - self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'") + self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; media-src 'self' data:; connect-src 'self'") self.send_header("Content-Length", str(len(data))) self.end_headers(); self.wfile.write(data) except Exception: diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/runtime_gateway.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/runtime_gateway.py index 92648d9e2..e7d7a9ed9 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/runtime_gateway.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/runtime_gateway.py @@ -68,12 +68,13 @@ def invoke(self, command: str, payload: Mapping[str, Any] | None = None, *, requ return dict(response) def get_daily_case(self) -> dict[str, Any]: - """Project Daily Case without adding a second runtime command or mutating player state.""" + """Project Daily Case from one atomic snapshot of canonical runtime state.""" if self._runtime_application is None or self._loader is None: raise RuntimeGatewayError("Daily Case requires the canonical runtime application and content loader") from scripture_archive_platform.application.daily_case_projection import DailyCaseProjection - return DailyCaseProjection(self._runtime_application, self._loader).response() + with self._runtime_lock: + return DailyCaseProjection(self._runtime_application, self._loader).response() def get_chronology_lab(self) -> dict[str, Any]: """Project canonical chronology data without inferring it from generic evidence. @@ -193,12 +194,18 @@ def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> Runtime Canonical node bytes are not rewritten. The checked-in R05 provenance registry is projected into ``EvidenceRuntime`` and its explicit node_id→evidence_record_id links replace legacy optional unlock values only in this in-memory packaged - runtime projection. Free-text source fields are not parsed into invented - passage/witness/entity/relation/chronology structure. + runtime projection. The explicit OT↔NT relation pack is validated through its + typed loader but materializes into the same EvidenceRuntime only after an + independent source-audit promotion. Free-text source fields are never parsed + into invented passage/witness/entity/relation/chronology structure. """ from runtime_engine.scripture_archive_runtime.application import RuntimeApplication from runtime_engine.scripture_archive_runtime.content import ContentRepository from runtime_engine.scripture_archive_runtime.evidence_registry import load_r05_evidence_registry + from runtime_engine.scripture_archive_runtime.otnt_relation_pack import ( + load_otnt_relation_pack, + materialize_otnt_relation_pack, + ) from runtime_engine.scripture_archive_runtime.persistence import PersistenceStore from scripture_archive_platform.content.loader import CanonicalContentLoader @@ -206,6 +213,8 @@ def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> Runtime loader = CanonicalContentLoader(repo_root) loader._ensure() evidence_bundle = load_r05_evidence_registry(repo_root) + otnt_bundle = load_otnt_relation_pack(repo_root) + materialize_otnt_relation_pack(evidence_bundle.runtime, otnt_bundle) nodes = [] for source_node in loader._nodes.values(): diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py index 6d35a47cf..2abd19b64 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -13,14 +13,14 @@ from scripture_archive_platform.application.keymap import KeybindingService from scripture_archive_platform.application.content_pack_manager import ContentPackManagerService from scripture_archive_platform.application.research_workspace import ResearchWorkspaceService -from scripture_archive_platform.authoring.service import AuthoringService +from scripture_archive_platform.authoring.recoverable import RecoverableAuthoringService class PlatformApplication: def __init__(self,repo_root:Path,store=None,loader=None,grader=None,player_gateway=None): self.repo_root=Path(repo_root).resolve(); self.store=store or JsonFileStore(JsonFileStore.default_root()) self.loader=loader or CanonicalContentLoader(self.repo_root); self.library=CanonicalLibraryIndex(self.loader); self.mapper=TaskPresentationMapper(); self.grader=grader or ReferenceGrader(); self.player_gateway=player_gateway self.task_types,self.renderers,self.graders,self.editors,self.templates=build_task_registries() - self.keymap=KeybindingService(self.store); self.research=ResearchWorkspaceService(self.store,self.loader,self.mapper); self.authoring=AuthoringService(self.store,self.task_types,self.mapper); self.content_packs=ContentPackManagerService(self.store.root) + self.keymap=KeybindingService(self.store); self.research=ResearchWorkspaceService(self.store,self.loader,self.mapper); self.authoring=RecoverableAuthoringService(self.store,self.task_types,self.mapper); self.content_packs=ContentPackManagerService(self.store.root) self._hint_level:dict[str,int]={}; self._last_node:dict[str,dict[str,Any]]={} def handle(self,request:dict[str,Any])->dict[str,Any]: rid=str(request.get('request_id','invalid')) if isinstance(request,dict) else 'invalid' @@ -54,6 +54,12 @@ def _dispatch(self,cmd,p): if cmd=='player.get_progress':return {'progress':self._progress(self._id(p,'node_id'))} if cmd=='player.get_mastery':return self._mastery() if cmd=='player.get_review_queue':return self._review_queue() + if cmd=='player.start_review': + if p:raise ValueError('player.start_review accepts an empty payload') + return self._start_review() + if cmd=='player.finish_review': + if p:raise ValueError('player.finish_review accepts an empty payload') + return self._finish_review() if cmd=='player.get_daily_case': if p:raise ValueError('player.get_daily_case accepts an empty payload') return self._daily_case() @@ -68,11 +74,21 @@ def _dispatch(self,cmd,p): if cmd=='authoring.fork_record':return {'draft':self.authoring.fork_record(self._id(p,'kind'),p.get('record'),str(p.get('title') or '') or None)} if cmd=='authoring.fork_canonical_node': nid=self._id(p,'node_id'); node=self.loader.load_node(nid); return {'draft':self.authoring.fork_record('node',node,str(p.get('title') or f'Edit {nid}'))} - if cmd=='authoring.move_collection_item': - return {'draft':self.authoring.move_collection_item(p.get('draft'),self._id(p,'path'),p.get('index'),self._id(p,'direction'))} + if cmd=='authoring.move_collection_item':return {'draft':self.authoring.move_collection_item(p.get('draft'),self._id(p,'path'),p.get('index'),self._id(p,'direction'))} if cmd=='authoring.validate_draft':return self.authoring.validate_draft(p.get('draft')) if cmd=='authoring.preview_draft':return self.authoring.preview(p.get('draft')) if cmd=='authoring.prepare_publish_candidate':return {'candidate':self.authoring.prepare_publish_candidate(p.get('draft'))} + if cmd=='authoring.pack_compatibility':return {'compatibility':self.authoring.pack_compatibility()} + if cmd=='authoring.create_snapshot':return {'snapshot':self.authoring.create_snapshot(self._id(p,'draft_id'),str(p.get('label') or ''))} + if cmd=='authoring.list_snapshots':return {'snapshots':self.authoring.list_snapshots(self._id(p,'draft_id'))} + if cmd=='authoring.restore_snapshot':return {'draft':self.authoring.restore_snapshot(self._id(p,'draft_id'),self._id(p,'snapshot_id'))} + if cmd=='authoring.diff_draft':return self.authoring.diff_draft(self._id(p,'draft_id'),self._id(p,'from_snapshot_id'),self._id(p,'to_snapshot_id') if p.get('to_snapshot_id') else None) + if cmd=='authoring.history':return self.authoring.history(self._id(p,'draft_id')) + if cmd=='authoring.undo':return {'draft':self.authoring.undo(self._id(p,'draft_id'))} + if cmd=='authoring.redo':return {'draft':self.authoring.redo(self._id(p,'draft_id'))} + if cmd=='authoring.publish_version':return {'version':self.authoring.publish_version(self._id(p,'draft_id'),p.get('compatibility'))} + if cmd=='authoring.list_versions':return {'versions':self.authoring.list_versions(self._id(p,'draft_id'))} + if cmd=='authoring.rollback_version':return {'draft':self.authoring.rollback_version(self._id(p,'draft_id'),self._id(p,'version_id'))} if cmd=='authoring.export_draft':return {'format':'json','text':self.authoring.export_draft(self._id(p,'draft_id'))} if cmd=='authoring.import_draft':return {'draft':self.authoring.import_draft(str(p.get('text') or ''))} if cmd=='keymap.list':return {'actions':self.keymap.list(p.get('context'),str(p.get('search') or ''))} @@ -90,7 +106,7 @@ def _dispatch(self,cmd,p): raise ValueError('command not implemented') def _bootstrap(self): campaigns=self.loader.list_campaigns() - return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'research_export':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} + return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'constructor_v2_history':True,'constructor_v2_snapshots':True,'constructor_v2_undo_redo':True,'constructor_v2_versioned_publish_rollback':True,'constructor_v2_pack_compatibility':True,'constructor_canonical_write':False,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'research_export':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'review_training':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} def _load_node(self,nid): if self.player_gateway:self.player_gateway.invoke('player.load_node',{'node_id':nid},request_id='load-'+nid) node=self.loader.load_node(nid); mission=self.loader.mission_for_node(nid); renderable=self.mapper.to_renderable(node,mission); self._last_node[nid]=node @@ -100,7 +116,7 @@ def _submit(self,p): if self.player_gateway: rr=self.player_gateway.invoke('player.submit_answer',{'node_id':nid,'task_type':renderable['task_type'],'answer':p.get('answer')},request_id='submit-'+nid) grade=dict(rr.get('grade') or {}); branch=dict(rr.get('branch') or {}); status=str(grade.get('correctness') or 'INCORRECT') - return {'node_id':nid,'status':status,'score':grade.get('score'),'feedback':grade.get('feedback') or '','confidence_code':grade.get('confidence'),'textual_variant_flag':'TX1' if grade.get('tx1') else 'none','evidence':grade.get('evidence') or [],'uncertainty':grade.get('uncertainty'),'next_node_id':branch.get('next_node_id'),'branch':branch,'mastery_consequence':rr.get('mastery_consequence') or [],'accessibility':rr.get('accessibility') or [],'progress':self._progress(nid),'truth_owner':'D5/runtime'} + return {'node_id':nid,'status':status,'score':grade.get('score'),'feedback':grade.get('feedback') or '','confidence_code':grade.get('confidence'),'textual_variant_flag':'TX1' if grade.get('tx1') else 'none','evidence':grade.get('evidence') or [],'uncertainty':grade.get('uncertainty'),'next_node_id':branch.get('next_node_id'),'branch':branch,'mastery_consequence':rr.get('mastery_consequence') or [],'review_session':rr.get('review_session'),'accessibility':rr.get('accessibility') or [],'progress':self._progress(nid),'truth_owner':'D5/runtime'} result=self.grader.grade(node,renderable,p.get('answer')); hist=self.store.get_json('player','history',{}) or {}; rec=hist.setdefault(nid,{'attempts':0,'hints':0,'last_status':None});rec['attempts']+=1;rec['hints']=max(rec['hints'],self._hint_level.get(nid,0));rec['last_status']=result.status;rec['updated_at']=int(time.time());self.store.put_json('player','history',hist) next_id=self.loader.next_node_id(nid,'correct' if result.status=='CORRECT' else 'partial' if result.status in {'PARTIAL','REVIEW_REQUIRED'} else 'incorrect'); data=result.as_dict();data.update({'node_id':nid,'next_node_id':next_id,'progress':self._progress(nid),'truth_owner':'REFERENCE_TEST_ONLY'}); return data def _hint(self,nid): @@ -139,6 +155,19 @@ def _mastery(self): def _review_queue(self): if not self.player_gateway:return {'review_queue':[],'truth_owner':'REFERENCE_TEST_ONLY'} rr=self.player_gateway.invoke('player.get_review_queue',{},request_id='review-queue-player'); return {'review_queue':validate_review_queue_projection(rr.get('review_queue')),'truth_owner':'D5/runtime'} + def _start_review(self): + if not self.player_gateway:raise ValueError('Review Training requires canonical runtime') + rr=self.player_gateway.invoke('player.start_review',{},request_id='review-start-player'); task=rr.get('task'); session=dict(rr.get('review_session') or {}) + if task is None:return {'task':None,'review_session':session,'review_selection':rr.get('review_selection'),'truth_owner':'D5/runtime'} + if not isinstance(task,dict):raise ValueError('runtime review task is invalid') + nid=self._id(task,'node_id'); node=self.loader.load_node(nid); mission=self.loader.mission_for_node(nid) + if task.get('mission_id') not in {None,mission.get('mission_id')}:raise ValueError('runtime review task mission does not match canonical content') + renderable=self.mapper.to_renderable(node,mission); self._last_node[nid]=node + return {'mission':mission,'task':renderable,'progress':self._progress(nid),'hint_level':0,'review_session':session,'review_selection':rr.get('review_selection'),'truth_owner':'D5/runtime'} + def _finish_review(self): + if not self.player_gateway:raise ValueError('Review Training requires canonical runtime') + rr=self.player_gateway.invoke('player.finish_review',{},request_id='review-finish-player') + return {'review_session':rr.get('review_session') or {},'truth_owner':'D5/runtime'} def _daily_case(self): if not self.player_gateway:raise ValueError('Daily Case requires canonical runtime') return self.player_gateway.get_daily_case() diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/speech_application.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/speech_application.py new file mode 100644 index 000000000..8e0a89ae7 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/speech_application.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +import base64 +import os +from pathlib import Path +from typing import Any + +from runtime_engine.scripture_archive_runtime.speech import ( + ElevenLabsSpeechProvider, + OpenAISpeechProvider, + SpeechCache, + SpeechError, + SpeechProviderRegistry, + SpeechRequest, + SpeechService, +) +from scripture_archive_platform.application.witness_matrix_application import ( + WitnessMatrixPlatformApplication, +) +from scripture_archive_platform.persistence.store import JsonFileStore + + +_MAX_AUDIO_BYTES = 8 * 1024 * 1024 +_MIME_TYPES = { + "mp3": "audio/mpeg", + "opus": "audio/ogg", + "aac": "audio/aac", + "flac": "audio/flac", + "wav": "audio/wav", + "pcm": "application/octet-stream", +} + + +class SpeechPlatformApplication(WitnessMatrixPlatformApplication): + """Package presentation-only speech without moving content or grading truth. + + The public synthesis command accepts presentation preferences only. It does + not accept node ids or speech text. The host resolves the runtime's current + canonical node and then resolves the exact visible player prompt from the + canonical loader, so the bridge cannot become an arbitrary-text channel. + """ + + def __init__( + self, + *args, + speech_service: SpeechService | None = None, + speech_defaults: dict[str, str] | None = None, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + if speech_service is None: + speech_service, built_defaults = _build_speech_service(self.store.root) + else: + built_defaults = {} + self.speech_service = speech_service + self.speech_defaults = dict(built_defaults) + if speech_defaults: + self.speech_defaults.update({str(k): str(v) for k, v in speech_defaults.items()}) + + def _dispatch(self, cmd, payload): + if cmd == "speech.status": + if payload: + raise ValueError("speech.status accepts an empty payload") + return self._speech_status() + if cmd == "speech.synthesize_prompt": + return self._synthesize_prompt(payload) + return super()._dispatch(cmd, payload) + + def _bootstrap(self): + data = super()._bootstrap() + configured = bool(self.speech_service.registry.provider_ids()) + data["capabilities"]["speech"] = bool(self.player_gateway) + data["capabilities"]["speech_network_configured"] = configured + return data + + def _speech_status(self) -> dict[str, Any]: + providers = [] + for provider_id in self.speech_service.registry.provider_ids(): + provider = self.speech_service.registry.get(provider_id) + providers.append( + { + "provider_id": provider_id, + "network": bool(getattr(provider, "is_network", False)), + "default_voice": self.speech_defaults.get(provider_id, ""), + } + ) + return { + "schema": "scripture.packaged-speech.v1", + "available": bool(self.player_gateway and providers), + "providers": providers, + "network_consent_required": True, + "supported_surface": "current_canonical_task_prompt_only", + "private_text_supported": False, + "truth_owner": "presentation-only", + } + + def _current_node_id(self) -> str: + gateway = self.player_gateway + getter = getattr(gateway, "_current_node_getter", None) if gateway is not None else None + if not callable(getter): + raise ValueError("speech requires the canonical packaged runtime") + node_id = getter() + if not isinstance(node_id, str) or not node_id.strip(): + raise ValueError("load a canonical task before requesting speech") + return node_id.strip() + + def _synthesize_prompt(self, payload: dict[str, Any]) -> dict[str, Any]: + provider_id = self._id(payload, "provider_id") + voice_id = self._id(payload, "voice_id") + allow_network = payload.get("allow_network") + if type(allow_network) is not bool or not allow_network: + raise ValueError("explicit network speech consent is required") + if provider_id not in self.speech_service.registry.provider_ids(): + raise ValueError("speech provider is not configured") + try: + speed = float(payload.get("speed", 1.0)) + except (TypeError, ValueError) as exc: + raise ValueError("speech speed must be numeric") from exc + + node_id = self._current_node_id() + node = self.loader.load_node(node_id) + mission = self.loader.mission_for_node(node_id) + renderable = self.mapper.to_renderable(node, mission) + prompt = str(renderable.get("prompt") or "").strip() + if not prompt: + raise ValueError("canonical player prompt is empty") + + request = SpeechRequest( + text=prompt, + provider_id=provider_id, + voice_id=voice_id, + response_format="mp3", + purpose="task_prompt", + speed=speed, + private_text=False, + ) + try: + artifact = self.speech_service.synthesize(request) + except SpeechError as exc: + raise ValueError(f"speech synthesis rejected: {exc}") from None + + cache_root = self.speech_service.cache.root.resolve() + cache_path = Path(artifact.cache_path) + if cache_path.is_symlink(): + raise ValueError("speech cache artifact is not a regular file") + resolved = cache_path.resolve() + if resolved.parent != cache_root or not resolved.is_file(): + raise ValueError("speech cache artifact escaped the allowlisted cache root") + size = resolved.stat().st_size + if size <= 0 or size > _MAX_AUDIO_BYTES: + raise ValueError("speech audio exceeds packaged playback limit") + audio = resolved.read_bytes() + if len(audio) != size: + raise ValueError("speech audio changed while being read") + + mime_type = _MIME_TYPES.get(artifact.response_format) + if mime_type is None: + raise ValueError("unsupported packaged speech audio format") + return { + "schema": "scripture.packaged-speech.v1", + "node_id": node_id, + "provider_id": artifact.provider_id, + "voice_id": artifact.voice_id, + "response_format": artifact.response_format, + "mime_type": mime_type, + "audio_base64": base64.b64encode(audio).decode("ascii"), + "byte_length": size, + "from_cache": bool(artifact.from_cache), + "spoken_surface": "current_canonical_task_prompt_only", + "truth_owner": "presentation-only", + } + + +def _build_speech_service(store_root: Path) -> tuple[SpeechService, dict[str, str]]: + registry = SpeechProviderRegistry() + defaults: dict[str, str] = {} + + # Credentials remain process environment only. Their values are never copied + # into status, transport responses, package files, logs, or browser storage. + if os.environ.get("OPENAI_API_KEY", "").strip(): + registry.register(OpenAISpeechProvider()) + defaults["openai"] = os.environ.get("SCRIPTURE_ARCHIVE_OPENAI_VOICE", "alloy").strip() or "alloy" + if os.environ.get("ELEVENLABS_API_KEY", "").strip(): + registry.register(ElevenLabsSpeechProvider()) + defaults["elevenlabs"] = os.environ.get("SCRIPTURE_ARCHIVE_ELEVENLABS_VOICE", "").strip() + + cache = SpeechCache(Path(store_root) / "speech-cache") + return SpeechService(registry, cache), defaults + + +def build_default_application(repo_root: Path | None = None, store_root: Path | None = None): + """Build the exact current packaged app plus the speech presentation adapter.""" + if repo_root is None: + repo_root = Path(__file__).resolve().parents[3] + repo_root = Path(repo_root) + store = JsonFileStore(store_root) if store_root else None + effective_store = store or JsonFileStore(JsonFileStore.default_root()) + runtime_application = repo_root / "runtime_engine" / "scripture_archive_runtime" / "application.py" + if runtime_application.exists(): + from scripture_archive_platform.application.runtime_gateway import build_runtime_gateway + + gateway = build_runtime_gateway(repo_root, effective_store.root) + return SpeechPlatformApplication(repo_root, store=effective_store, player_gateway=gateway) + return SpeechPlatformApplication(repo_root, store=effective_store) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py new file mode 100644 index 000000000..00d9b0a90 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py @@ -0,0 +1,293 @@ +from __future__ import annotations + +import copy +from typing import Any, Iterable + +from .service import ( + HISTORY_SCHEMA, + MAX_HISTORY_DEPTH, + SNAPSHOT_SCHEMA, + AuthoringService, +) + + +TRANSACTION_SCHEMA = "scripture.authoring-transaction.v1" +TRANSACTION_CATEGORY = "authoring_transactions" + + +class RecoverableAuthoringService(AuthoringService): + """Constructor V2 service with restart-recoverable multi-record mutations. + + ``JsonFileStore`` makes each individual JSON record replacement atomic, but + Constructor V2 operations span several records (draft, undo/redo history and + safety snapshots). A crash between those writes used to allow history to + advance while the draft remained at the previous revision. This subclass + records the complete intended post-mutation state first and replays it + idempotently on startup. The intent is deleted only after every component + has been persisted. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._recover_pending_mutations() + + def save_draft(self, draft: Any) -> dict[str, Any]: + draft = self._envelope(draft) + stored = self.store.get_json("drafts", draft["draft_id"]) + now = int(self.clock()) + if stored is not None: + expected = int(stored.get("revision", 1)) + if int(draft.get("revision", expected)) != expected: + raise ValueError("stale draft revision; reload before saving") + created_at = int(stored.get("created_at", now)) + revision = expected + 1 + base_identity = stored.get("base_identity") or draft.get("base_identity") + else: + created_at = int(draft.get("created_at", now)) + revision = max(1, int(draft.get("revision", 1))) + base_identity = draft.get("base_identity") + + out = copy.deepcopy(draft) + out.update({ + "status": "DRAFT", + "created_at": created_at, + "updated_at": now, + "revision": revision, + "base_identity": base_identity, + }) + self._protect_identity(out) + out.setdefault("change_record", []).append({ + "timestamp": now, + "action": "save_draft", + "revision": revision, + }) + + history = None + if stored is not None: + history = self._history_with_prior(out["draft_id"], stored) + self._commit_mutation(out["draft_id"], out, history=history) + return copy.deepcopy(out) + + def restore_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + snapshot = self._load_snapshot(draft_id, snapshot_id) + safety = self._build_snapshot( + current, + label="Automatic safety snapshot before snapshot restore", + ) + history = self._history_with_prior(draft_id, current) + restored = self._build_restored_draft( + current, + snapshot["draft"], + "restore_snapshot", + snapshot_id, + ) + self._commit_mutation( + draft_id, + restored, + history=history, + snapshots=[safety], + ) + return copy.deepcopy(restored) + + def undo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["undo"]: + raise ValueError("nothing to undo") + target = state["undo"].pop() + state["redo"].append(self._json_copy(current)) + state["redo"] = state["redo"][-MAX_HISTORY_DEPTH:] + history = self._normalized_history(draft_id, state) + restored = self._build_restored_draft(current, target, "undo") + self._commit_mutation(draft_id, restored, history=history) + return copy.deepcopy(restored) + + def redo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["redo"]: + raise ValueError("nothing to redo") + target = state["redo"].pop() + state["undo"].append(self._json_copy(current)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + history = self._normalized_history(draft_id, state) + restored = self._build_restored_draft(current, target, "redo") + self._commit_mutation(draft_id, restored, history=history) + return copy.deepcopy(restored) + + def rollback_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + version = self._load_version(draft_id, version_id) + target = self._json_copy(version.get("candidate") or {}) + if target.get("draft_id") != draft_id: + raise ValueError("version draft identity mismatch") + target.pop("publish_manifest", None) + target.pop("publish_change_record", None) + target.pop("canonical_mutation_performed", None) + + safety = self._build_snapshot( + current, + label="Automatic safety snapshot before version rollback", + ) + history = self._history_with_prior(draft_id, current) + restored = self._build_restored_draft( + current, + target, + "rollback_version", + version_id, + ) + self._commit_mutation( + draft_id, + restored, + history=history, + snapshots=[safety], + ) + return copy.deepcopy(restored) + + def _history_with_prior(self, draft_id: str, prior: dict[str, Any]) -> dict[str, Any]: + state = self._history_state(draft_id) + state["undo"].append(self._json_copy(prior)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + state["redo"] = [] + return self._normalized_history(draft_id, state) + + def _normalized_history(self, draft_id: str, state: dict[str, Any]) -> dict[str, Any]: + out = self._json_copy(state) + out.update({"schema": HISTORY_SCHEMA, "draft_id": draft_id}) + out["undo"] = list(out.get("undo", []))[-MAX_HISTORY_DEPTH:] + out["redo"] = list(out.get("redo", []))[-MAX_HISTORY_DEPTH:] + return out + + def _build_restored_draft( + self, + current: dict[str, Any], + target: Any, + action: str, + reference_id: str | None = None, + ) -> dict[str, Any]: + target = self._envelope(target) + if target["draft_id"] != current["draft_id"]: + raise ValueError("restore draft identity mismatch") + out = self._json_copy(target) + now = int(self.clock()) + out["status"] = "DRAFT" + out["created_at"] = int(current.get("created_at", now)) + out["updated_at"] = now + out["revision"] = int(current.get("revision", 1)) + 1 + out["base_identity"] = current.get("base_identity") or out.get("base_identity") + record = { + "timestamp": now, + "action": action, + "revision": out["revision"], + } + if reference_id: + record["reference_id"] = reference_id + out.setdefault("change_record", []).append(record) + self._protect_identity(out) + return out + + def _build_snapshot(self, draft: dict[str, Any], *, label: str) -> dict[str, Any]: + snapshot_id = "snapshot-" + self.id_factory() + self._validate_id(snapshot_id, "snapshot id") + return { + "schema": SNAPSHOT_SCHEMA, + "snapshot_id": snapshot_id, + "draft_id": draft["draft_id"], + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "label": self._label(label), + "draft": self._json_copy(draft), + } + + def _commit_mutation( + self, + draft_id: str, + draft: dict[str, Any], + *, + history: dict[str, Any] | None = None, + snapshots: Iterable[dict[str, Any]] = (), + ) -> None: + self._validate_id(draft_id, "draft id") + transaction = { + "schema": TRANSACTION_SCHEMA, + "draft_id": draft_id, + "draft": self._json_copy(draft), + "history": self._json_copy(history) if history is not None else None, + "snapshots": self._json_copy(list(snapshots)), + } + # Write-ahead ordering is the invariant: no component write occurs before + # the complete recovery intent itself is durable. + self.store.put_json(TRANSACTION_CATEGORY, draft_id, transaction) + self._apply_transaction(transaction) + self.store.delete(TRANSACTION_CATEGORY, draft_id) + + def _recover_pending_mutations(self) -> None: + for draft_id in sorted(self.store.list_keys(TRANSACTION_CATEGORY)): + self._validate_id(draft_id, "draft id") + transaction = self.store.get_json(TRANSACTION_CATEGORY, draft_id) + self._apply_transaction(transaction) + self.store.delete(TRANSACTION_CATEGORY, draft_id) + + def _apply_transaction(self, transaction: Any) -> None: + draft_id, draft, history, snapshots = self._validate_transaction(transaction) + if history is not None: + self.store.put_json("authoring_history", draft_id, history) + for snapshot in snapshots: + self.store.put_json( + "authoring_snapshots", + snapshot["snapshot_id"], + snapshot, + ) + # Draft is deliberately written last. If any earlier component write is + # interrupted, the durable transaction remains and startup completes the + # same intended revision before the Constructor can be used again. + self.store.put_json("drafts", draft_id, draft) + + def _validate_transaction( + self, + transaction: Any, + ) -> tuple[str, dict[str, Any], dict[str, Any] | None, list[dict[str, Any]]]: + if not isinstance(transaction, dict) or transaction.get("schema") != TRANSACTION_SCHEMA: + raise ValueError("invalid persisted authoring transaction") + draft_id = transaction.get("draft_id") + self._validate_id(draft_id, "draft id") + + draft = self._envelope(transaction.get("draft")) + if draft.get("draft_id") != draft_id: + raise ValueError("authoring transaction draft identity mismatch") + self._protect_identity(draft) + + history = transaction.get("history") + if history is not None: + if ( + not isinstance(history, dict) + or history.get("schema") != HISTORY_SCHEMA + or history.get("draft_id") != draft_id + or not isinstance(history.get("undo"), list) + or not isinstance(history.get("redo"), list) + ): + raise ValueError("invalid authoring transaction history") + history = self._normalized_history(draft_id, history) + + raw_snapshots = transaction.get("snapshots") + if not isinstance(raw_snapshots, list): + raise ValueError("invalid authoring transaction snapshots") + snapshots: list[dict[str, Any]] = [] + seen: set[str] = set() + for raw in raw_snapshots: + if not isinstance(raw, dict) or raw.get("schema") != SNAPSHOT_SCHEMA: + raise ValueError("invalid authoring transaction snapshot") + snapshot_id = raw.get("snapshot_id") + self._validate_id(snapshot_id, "snapshot id") + if snapshot_id in seen: + raise ValueError("duplicate authoring transaction snapshot") + seen.add(snapshot_id) + if raw.get("draft_id") != draft_id: + raise ValueError("authoring transaction snapshot identity mismatch") + embedded = self._envelope(raw.get("draft")) + if embedded.get("draft_id") != draft_id: + raise ValueError("authoring transaction snapshot draft identity mismatch") + snapshots.append(self._json_copy(raw)) + + return draft_id, self._json_copy(draft), history, snapshots diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py index 2c864ea48..a7030c66a 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py @@ -7,6 +7,10 @@ import uuid from typing import Any, Callable +from runtime_engine.scripture_archive_runtime.content_packs import ( + CONTENT_PACK_SCHEMA, + CONTENT_SCHEMA_VERSION, +) from scripture_archive_platform.transport.contracts import MAX_IMPORT_BYTES from .model import ( CHANGE_RECORD_SCHEMA, DRAFT_SCHEMA, KINDS, PUBLISH_SCHEMA, @@ -15,6 +19,14 @@ from .validation import identity, identity_errors, publish_blockers, validate_draft +HISTORY_SCHEMA = "scripture.authoring-history.v1" +SNAPSHOT_SCHEMA = "scripture.authoring-snapshot.v1" +VERSION_SCHEMA = "scripture.authoring-version.v1" +PACK_COMPAT_SCHEMA = "scripture.authoring-pack-compat.v1" +MAX_HISTORY_DEPTH = 50 +MAX_DIFF_PATHS = 1000 + + class AuthoringService: """Backward-compatible data-only constructor; never mutates audited canonical files.""" @@ -94,12 +106,15 @@ def save_draft(self, draft: Any) -> dict[str, Any]: out.setdefault("change_record", []).append({ "timestamp": now, "action": "save_draft", "revision": revision, }) + if stored is not None: + self._remember_for_undo(out["draft_id"], stored) self.store.put_json("drafts", out["draft_id"], out) return copy.deepcopy(out) def delete_draft(self, draft_id: str) -> dict[str, Any]: self.load_draft(draft_id) self.store.delete("drafts", draft_id) + self.store.delete("authoring_history", draft_id) return {"draft_id": draft_id, "deleted": True} def fork_record(self, kind: str, record: dict[str, Any], title: str | None = None) -> dict[str, Any]: @@ -181,6 +196,154 @@ def prepare_publish_candidate(self, draft: Any) -> dict[str, Any]: } return candidate + def pack_compatibility(self) -> dict[str, str]: + return { + "schema": PACK_COMPAT_SCHEMA, + "content_pack_schema": CONTENT_PACK_SCHEMA, + "content_schema_version": CONTENT_SCHEMA_VERSION, + "constructor_draft_schema": DRAFT_SCHEMA, + } + + def create_snapshot(self, draft_id: str, label: str = "") -> dict[str, Any]: + draft = self.load_draft(draft_id) + label = self._label(label) + snapshot = self._snapshot_from_draft(draft, label=label) + return copy.deepcopy(snapshot) + + def list_snapshots(self, draft_id: str) -> list[dict[str, Any]]: + self._validate_id(draft_id, "draft id") + out: list[dict[str, Any]] = [] + for key in self.store.list_keys("authoring_snapshots"): + value = self.store.get_json("authoring_snapshots", key, {}) or {} + if value.get("draft_id") != draft_id: + continue + out.append({ + "snapshot_id": value.get("snapshot_id", key), + "draft_id": draft_id, + "draft_revision": value.get("draft_revision"), + "created_at": value.get("created_at"), + "label": value.get("label", ""), + }) + return sorted(out, key=lambda row: (int(row.get("created_at") or 0), str(row.get("snapshot_id")))) + + def restore_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + snapshot = self._load_snapshot(draft_id, snapshot_id) + self._snapshot_from_draft(current, label="Automatic safety snapshot before snapshot restore") + self._remember_for_undo(draft_id, current) + return self._restore_draft(current, snapshot["draft"], "restore_snapshot", snapshot_id) + + def diff_draft(self, draft_id: str, from_snapshot_id: str, + to_snapshot_id: str | None = None) -> dict[str, Any]: + left = self._load_snapshot(draft_id, from_snapshot_id)["draft"] + if to_snapshot_id: + right = self._load_snapshot(draft_id, to_snapshot_id)["draft"] + right_ref = to_snapshot_id + else: + right = self.load_draft(draft_id) + right_ref = "CURRENT" + paths: list[str] = [] + self._diff_paths(left, right, "$", paths) + return { + "schema": "scripture.authoring-diff.v1", + "draft_id": draft_id, + "from": from_snapshot_id, + "to": right_ref, + "changed": bool(paths), + "changed_paths": paths, + "truncated": len(paths) >= MAX_DIFF_PATHS, + } + + def history(self, draft_id: str) -> dict[str, Any]: + draft = self.load_draft(draft_id) + state = self._history_state(draft_id) + return { + "schema": HISTORY_SCHEMA, + "draft_id": draft_id, + "revision": draft.get("revision", 1), + "can_undo": bool(state["undo"]), + "can_redo": bool(state["redo"]), + "change_record": self._json_copy(draft.get("change_record", [])), + "snapshots": self.list_snapshots(draft_id), + "versions": self.list_versions(draft_id), + } + + def undo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["undo"]: + raise ValueError("nothing to undo") + target = state["undo"].pop() + state["redo"].append(self._json_copy(current)) + state["redo"] = state["redo"][-MAX_HISTORY_DEPTH:] + self._write_history(draft_id, state) + return self._restore_draft(current, target, "undo") + + def redo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["redo"]: + raise ValueError("nothing to redo") + target = state["redo"].pop() + state["undo"].append(self._json_copy(current)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + self._write_history(draft_id, state) + return self._restore_draft(current, target, "redo") + + def publish_version(self, draft_id: str, compatibility: Any) -> dict[str, Any]: + draft = self.load_draft(draft_id) + compat = self._validate_pack_compatibility(compatibility) + candidate = self.prepare_publish_candidate(draft) + version_id = "version-" + self.id_factory() + self._validate_id(version_id, "version id") + version = { + "schema": VERSION_SCHEMA, + "version_id": version_id, + "draft_id": draft_id, + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "kind": draft.get("kind", "node"), + "stable_identity": identity(draft.get("kind", "node"), draft.get(draft.get("kind", "node")) or {}), + "compatibility": compat, + "candidate": candidate, + "canonical_mutation_performed": False, + "requires_explicit_integration": True, + } + self.store.put_json("authoring_versions", version_id, version) + return copy.deepcopy(version) + + def list_versions(self, draft_id: str) -> list[dict[str, Any]]: + self._validate_id(draft_id, "draft id") + out: list[dict[str, Any]] = [] + for key in self.store.list_keys("authoring_versions"): + value = self.store.get_json("authoring_versions", key, {}) or {} + if value.get("draft_id") != draft_id: + continue + out.append({ + "version_id": value.get("version_id", key), + "draft_id": draft_id, + "draft_revision": value.get("draft_revision"), + "created_at": value.get("created_at"), + "kind": value.get("kind"), + "stable_identity": value.get("stable_identity"), + "compatibility": self._json_copy(value.get("compatibility", {})), + "canonical_mutation_performed": False, + }) + return sorted(out, key=lambda row: (int(row.get("created_at") or 0), str(row.get("version_id")))) + + def rollback_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + version = self._load_version(draft_id, version_id) + target = self._json_copy(version.get("candidate") or {}) + if target.get("draft_id") != draft_id: + raise ValueError("version draft identity mismatch") + self._snapshot_from_draft(current, label="Automatic safety snapshot before version rollback") + self._remember_for_undo(draft_id, current) + target.pop("publish_manifest", None) + target.pop("publish_change_record", None) + target.pop("canonical_mutation_performed", None) + return self._restore_draft(current, target, "rollback_version", version_id) + def export_draft(self, draft_id: str) -> str: return json.dumps(self.load_draft(draft_id), ensure_ascii=False, indent=2) + "\n" @@ -190,7 +353,7 @@ def import_draft(self, text: str) -> dict[str, Any]: obj = json.loads(text) if not isinstance(obj, dict) or obj.get("draft_schema") != DRAFT_SCHEMA: raise ValueError("invalid imported draft") - obj = self._json_copy(obj) + obj = self._envelope(obj) now = int(self.clock()) obj["draft_id"] = "draft-" + self.id_factory() obj["status"] = "DRAFT" @@ -213,6 +376,123 @@ def _envelope(self, draft: Any) -> dict[str, Any]: raise ValueError(f"{key} must be an object") return out + def _history_state(self, draft_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + state = self.store.get_json("authoring_history", draft_id, None) + if state is None: + return {"schema": HISTORY_SCHEMA, "draft_id": draft_id, "undo": [], "redo": []} + if not isinstance(state, dict) or state.get("schema") != HISTORY_SCHEMA or state.get("draft_id") != draft_id: + raise ValueError("invalid persisted authoring history") + undo = state.get("undo") + redo = state.get("redo") + if not isinstance(undo, list) or not isinstance(redo, list): + raise ValueError("invalid persisted authoring history") + return self._json_copy(state) + + def _write_history(self, draft_id: str, state: dict[str, Any]) -> None: + state = self._json_copy(state) + state.update({"schema": HISTORY_SCHEMA, "draft_id": draft_id}) + state["undo"] = list(state.get("undo", []))[-MAX_HISTORY_DEPTH:] + state["redo"] = list(state.get("redo", []))[-MAX_HISTORY_DEPTH:] + self.store.put_json("authoring_history", draft_id, state) + + def _remember_for_undo(self, draft_id: str, prior: dict[str, Any]) -> None: + state = self._history_state(draft_id) + state["undo"].append(self._json_copy(prior)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + state["redo"] = [] + self._write_history(draft_id, state) + + def _restore_draft(self, current: dict[str, Any], target: Any, + action: str, reference_id: str | None = None) -> dict[str, Any]: + target = self._envelope(target) + if target["draft_id"] != current["draft_id"]: + raise ValueError("restore draft identity mismatch") + out = self._json_copy(target) + now = int(self.clock()) + out["status"] = "DRAFT" + out["created_at"] = int(current.get("created_at", now)) + out["updated_at"] = now + out["revision"] = int(current.get("revision", 1)) + 1 + out["base_identity"] = current.get("base_identity") or out.get("base_identity") + record = {"timestamp": now, "action": action, "revision": out["revision"]} + if reference_id: + record["reference_id"] = reference_id + out.setdefault("change_record", []).append(record) + self._protect_identity(out) + self.store.put_json("drafts", out["draft_id"], out) + return copy.deepcopy(out) + + def _snapshot_from_draft(self, draft: dict[str, Any], *, label: str) -> dict[str, Any]: + snapshot_id = "snapshot-" + self.id_factory() + self._validate_id(snapshot_id, "snapshot id") + snapshot = { + "schema": SNAPSHOT_SCHEMA, + "snapshot_id": snapshot_id, + "draft_id": draft["draft_id"], + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "label": self._label(label), + "draft": self._json_copy(draft), + } + self.store.put_json("authoring_snapshots", snapshot_id, snapshot) + return snapshot + + def _load_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + self._validate_id(snapshot_id, "snapshot id") + value = self.store.get_json("authoring_snapshots", snapshot_id) + if not isinstance(value, dict) or value.get("schema") != SNAPSHOT_SCHEMA: + raise ValueError("snapshot not found") + if value.get("draft_id") != draft_id: + raise ValueError("snapshot belongs to another draft") + return self._json_copy(value) + + def _load_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + self._validate_id(version_id, "version id") + value = self.store.get_json("authoring_versions", version_id) + if not isinstance(value, dict) or value.get("schema") != VERSION_SCHEMA: + raise ValueError("version not found") + if value.get("draft_id") != draft_id: + raise ValueError("version belongs to another draft") + if value.get("compatibility") != self.pack_compatibility(): + raise ValueError("version pack compatibility no longer matches this runtime") + return self._json_copy(value) + + def _validate_pack_compatibility(self, value: Any) -> dict[str, str]: + expected = self.pack_compatibility() + if not isinstance(value, dict) or value != expected: + raise ValueError("pack compatibility mismatch; refresh Constructor compatibility before publish") + return self._json_copy(expected) + + def _diff_paths(self, left: Any, right: Any, path: str, out: list[str]) -> None: + if len(out) >= MAX_DIFF_PATHS: + return + if type(left) is not type(right): + out.append(path) + return + if isinstance(left, dict): + for key in sorted(set(left) | set(right)): + if len(out) >= MAX_DIFF_PATHS: + return + child = f"{path}.{key}" + if key not in left or key not in right: + out.append(child) + else: + self._diff_paths(left[key], right[key], child, out) + return + if isinstance(left, list): + if len(left) != len(right): + out.append(f"{path}.length") + for index, (a, b) in enumerate(zip(left, right)): + if len(out) >= MAX_DIFF_PATHS: + return + self._diff_paths(a, b, f"{path}[{index}]", out) + return + if left != right: + out.append(path) + @staticmethod def _protect_identity(draft: dict[str, Any]) -> None: errors = identity_errors(draft) @@ -233,6 +513,15 @@ def _title(title: str) -> str: raise ValueError("title must be 1..300 characters") return title + @staticmethod + def _label(label: Any) -> str: + if not isinstance(label, str): + raise ValueError("snapshot label must be text") + label = label.strip() + if len(label) > 160: + raise ValueError("snapshot label must be at most 160 characters") + return label + @staticmethod def _validate_id(value: Any, label: str) -> None: if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9._-]{1,80}", value): diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/composite_accessibility.py b/lanes/dev1/repair_overlay/scripture_archive_platform/composite_accessibility.py index 0d6e1881f..e997cfc9f 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/composite_accessibility.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/composite_accessibility.py @@ -10,9 +10,6 @@ from scripture_archive_platform.transport.answer_contracts import canonical_task_type -_COMPOSITE_TEXT_CHILD_TYPES = frozenset({"SHORT_TEXT", "LONG_TEXT", "ARGUMENT"}) - - def _text(value: Any) -> str: return value.strip() if isinstance(value, str) else "" @@ -38,22 +35,6 @@ def _child_contract_missing(path: str) -> AccessibilityFinding: ) -def _child_renderer_parity_mismatch(path: str, task_type: str) -> AccessibilityFinding: - return AccessibilityFinding( - code="A11Y_COMPOSITE_CHILD_RENDERER_PARITY_MISMATCH", - severity="error", - path=f"{path}.task_type", - message=( - "Packaged COMPOSITE_MULTI_STEP currently emits child answers only as {text: ...}, " - f"but {task_type!r} requires a different semantic ANSWER_DTO shape." - ), - remediation=( - "Use a text-answer child type (SHORT_TEXT, LONG_TEXT, or ARGUMENT), or implement " - "semantic child renderer dispatch before allowing this composite to publish." - ), - ) - - def inspect_packaged_task(task: Mapping[str, Any]) -> AccessibilityReport: """Inspect a packaged task and recursively qualify composite child surfaces. @@ -63,11 +44,11 @@ def inspect_packaged_task(task: Mapping[str, Any]) -> AccessibilityReport: explicit nested pointer/visual/media hazards cannot disappear behind the missing contract finding. - The packaged COMPOSITE_MULTI_STEP renderer currently renders every child as one - labelled text input and emits ``{step_id, answer: {text: ...}}``. Until that - renderer dispatches child task types semantically, the inspector must fail closed - for child contracts whose answer shape is not text-based; otherwise it could - certify an interaction that the packaged UI cannot actually perform. + Packaged COMPOSITE_MULTI_STEP now dispatches every child through the same semantic + RendererRegistry used for top-level tasks and preserves that child's ANSWER_DTO_v1 + inside ``{step_id, answer: ...}``. This inspector therefore qualifies every child + recursively against the real task-type contract instead of imposing a text-only + exception. Unsupported child types still fail closed in inspect_renderable_task. """ base = inspect_renderable_task(task) if not isinstance(task, Mapping): @@ -91,8 +72,6 @@ def inspect_packaged_task(task: Mapping[str, Any]) -> AccessibilityReport: canonical_child_type = canonical_task_type(child_type) if child_type else "" if not child_type: findings.append(_child_contract_missing(path)) - elif canonical_child_type not in _COMPOSITE_TEXT_CHILD_TYPES: - findings.append(_child_renderer_parity_mismatch(path, canonical_child_type)) step_id = _text(step.get("step_id")) or str(index + 1) label = _text(step.get("label")) or _text(step.get("prompt")) or f"Step {index + 1}" diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py index b04d933a9..590f85401 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/main.py @@ -4,7 +4,7 @@ import sys from pathlib import Path -from scripture_archive_platform.application.witness_matrix_application import build_default_application +from scripture_archive_platform.application.speech_application import build_default_application from scripture_archive_platform.desktop_host.bridge import DesktopBridge from scripture_archive_platform.desktop_host.diagnostics import NativeDiagnosticsLayer from scripture_archive_platform.desktop_host.update_application import ( @@ -81,4 +81,4 @@ def main() -> int: selector.bind_window(window) logging.info("Starting EdgeChromium WebView; frontend=%s log=%s", front, log_path) webview.start(gui="edgechromium", debug=False, private_mode=True) - return 0 \ No newline at end of file + return 0 diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py index ba8aaf16e..fb97fb268 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -10,15 +10,18 @@ "system.bootstrap", "content.list_campaigns","content.list_missions","library.catalog","library.search","player.load_node", "player.submit_answer","player.request_hint","player.reveal_evidence","player.next", - "player.get_progress","player.get_mastery","player.get_review_queue","player.get_daily_case","player.save_checkpoint","player.restore_checkpoint", + "player.get_progress","player.get_mastery","player.get_review_queue","player.start_review","player.finish_review","player.get_daily_case","player.save_checkpoint","player.restore_checkpoint", "research.list_bookmarks","research.upsert_bookmark","research.delete_bookmark", "research.list_notes","research.upsert_note","research.delete_note","research.get_chronology_lab","research.get_evidence_graph","research.get_witness_matrix","research.export", "authoring.list_drafts","authoring.new_draft","authoring.new_node_from_task_type","authoring.load_draft","authoring.save_draft", "authoring.delete_draft","authoring.fork_record","authoring.fork_canonical_node","authoring.move_collection_item", "authoring.validate_draft","authoring.preview_draft","authoring.prepare_publish_candidate", - "authoring.export_draft","authoring.import_draft", + "authoring.export_draft","authoring.import_draft","authoring.pack_compatibility", + "authoring.create_snapshot","authoring.list_snapshots","authoring.restore_snapshot","authoring.diff_draft","authoring.history", + "authoring.undo","authoring.redo","authoring.publish_version","authoring.list_versions","authoring.rollback_version", "keymap.list","keymap.rebind","keymap.clear","keymap.reset_context","keymap.reset_all", - "keymap.export","keymap.import","settings.get","settings.set" + "keymap.export","keymap.import","settings.get","settings.set", + "speech.status","speech.synthesize_prompt","application_update.select_verify","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -52,6 +55,11 @@ def list_keys(self,namespace:str)->list[str]: ... class TransportAdapterPort(Protocol): def invoke(self,request:dict[str,Any])->dict[str,Any]: ... +def _validate_short_string(payload:dict[str,Any], key:str, *, max_length:int=256)->None: + value=payload.get(key) + if not isinstance(value,str) or not value.strip() or len(value)>max_length or any(ord(ch)<32 for ch in value): + raise ValueError(f'invalid {key}') + def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: if not isinstance(request,dict): raise ValueError('request must be an object') if request.get('api_version')!=TRANSPORT_API_VERSION: raise ValueError('unsupported api_version') @@ -63,8 +71,8 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: unknown=set(payload)-{'node_id'} if unknown: raise ValueError('player.next accepts only current node_id context; target selection is forbidden') if 'node_id' in payload and (not isinstance(payload['node_id'],str) or not payload['node_id'] or len(payload['node_id'])>100): raise ValueError('invalid node_id') - if cmd=='player.get_review_queue' and payload: - raise ValueError('player.get_review_queue accepts an empty payload') + if cmd in {'player.get_review_queue','player.start_review','player.finish_review'} and payload: + raise ValueError(f'{cmd} accepts an empty payload') if cmd=='player.get_daily_case' and payload: raise ValueError('player.get_daily_case accepts an empty payload') if cmd=='research.get_chronology_lab' and payload: @@ -75,6 +83,22 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('research.get_witness_matrix accepts an empty payload') if cmd=='research.export' and payload: raise ValueError('research.export accepts an empty payload') + if cmd=='authoring.pack_compatibility' and payload: + raise ValueError('authoring.pack_compatibility accepts an empty payload') + if cmd=='speech.status' and payload: + raise ValueError('speech.status accepts an empty payload') + if cmd=='speech.synthesize_prompt': + allowed={'provider_id','voice_id','speed','allow_network'} + unknown=set(payload)-allowed + if unknown: + raise ValueError('speech.synthesize_prompt accepts presentation preferences only') + _validate_short_string(payload,'provider_id',max_length=100) + _validate_short_string(payload,'voice_id',max_length=256) + if type(payload.get('allow_network')) is not bool: + raise ValueError('allow_network must be boolean') + try: speed=float(payload.get('speed',1.0)) + except (TypeError,ValueError) as exc: raise ValueError('speech speed must be numeric') from exc + if not 0.25<=speed<=4.0: raise ValueError('speech speed must be between 0.25 and 4.0') return rid,cmd,payload def _redact_private_player_task(value:Any)->Any: @@ -100,4 +124,4 @@ def ok_response(request_id:str,data:Any)->dict[str,Any]: def error_response(request_id:str,code:str,message:str,details:Any=None)->dict[str,Any]: err={"code":code,"message":message} if details is not None: err['details']=details - return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} \ No newline at end of file + return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/runtime_compat.py b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/runtime_compat.py index 3ee312544..620ea224d 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/runtime_compat.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/runtime_compat.py @@ -10,6 +10,7 @@ PLAYER_COMMAND_MAP = { "player.load_node": "load_task", "player.submit_answer": "submit_answer", "player.request_hint": "request_hint", "player.next": "next", "player.get_mastery": "get_mastery", "player.get_review_queue": "get_review_queue", + "player.start_review": "start_review", "player.finish_review": "finish_review", "player.save_checkpoint": "save", "player.restore_checkpoint": "restore", "player.reveal_evidence": "get_evidence", } class RuntimeContractError(ValueError): pass @@ -38,7 +39,7 @@ def to_runtime_request(self, request: Mapping[str, Any]) -> dict[str, Any]: if runtime_payload: raise RuntimeContractError('player.next accepts no caller-selected target payload') runtime_payload={} - if runtime_command in {'save','restore','get_evidence','get_mastery','get_review_queue'}:runtime_payload={} + if runtime_command in {'save','restore','get_evidence','get_mastery','get_review_queue','start_review','finish_review'}:runtime_payload={} return {'api_version':RUNTIME_API_VERSION,'command':runtime_command,'request_id':rid,'payload':runtime_payload} def invoke_runtime(self,request:Mapping[str,Any])->dict[str,Any]: runtime_request=self.to_runtime_request(request);response=self._runtime_invoke(runtime_request) @@ -50,6 +51,18 @@ def invoke_runtime(self,request:Mapping[str,Any])->dict[str,Any]: if runtime_request['command']=='get_review_queue': try:validate_review_queue_projection(normalized.get('review_queue')) except ValueError as exc:raise RuntimeContractError(str(exc)) from exc + if runtime_request['command']=='start_review': + task=normalized.get('task') + session=normalized.get('review_session') + if not isinstance(session,dict):raise RuntimeContractError('runtime start_review response is missing review_session') + if task is not None and (not isinstance(task,dict) or not isinstance(task.get('node_id'),str) or not task.get('node_id')): + raise RuntimeContractError('runtime start_review task is malformed') + if task is None and session.get('active') is not False: + raise RuntimeContractError('runtime empty review response must be inactive') + if runtime_request['command']=='finish_review': + session=normalized.get('review_session') + if not isinstance(session,dict) or session.get('active') is not False: + raise RuntimeContractError('runtime finish_review response must be inactive') return normalized @staticmethod def platform_envelope(request_id:str,runtime_response:Mapping[str,Any])->dict[str,Any]: diff --git a/lanes/dev1/repair_overlay/tests/README_REVIEW_TRAINING_V1.md b/lanes/dev1/repair_overlay/tests/README_REVIEW_TRAINING_V1.md new file mode 100644 index 000000000..21bcf89a3 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/README_REVIEW_TRAINING_V1.md @@ -0,0 +1,18 @@ +# Review Training Session v1 — candidate evidence + +This bounded candidate composes the existing persisted D5/runtime review queue with the existing deterministic runtime Scheduler and the packaged keyboard/NVDA player flow. + +Security boundary: the caller cannot submit a review node target. `player.start_review` and `player.finish_review` accept empty payloads only at both platform and runtime boundaries. The runtime selects the next eligible task using the existing Scheduler. + +Scheduling boundary: no second scheduling policy is implemented in JavaScript or the platform projection. Due time, adjacent EXACT cooldown, session deduplication, fatigue and deterministic scoring remain runtime-owned. + +Content/source boundary: this candidate does not alter D2/D3/D4 canonical content, evidence, source scopes, confidence or TX1 truth. + +Accessibility boundary: training uses the existing semantic task renderer, focus path and live status; a keyboard-reachable Finish control and explicit Next Review action are added. Automated tests do not claim physical Windows 11/WebView2 or human NVDA acceptance. + +Focused regression files: +- `runtime_engine/tests/test_review_training_session.py` +- `tests/test_packaged_review_queue_ui.py` +- `tests/test_packaged_review_training_contract.py` +- `tests/test_packaged_review_training_player_ui.py` +- `tests/test_packaged_review_training_static_syntax.py` diff --git a/lanes/dev1/repair_overlay/tests/test_accessibility.py b/lanes/dev1/repair_overlay/tests/test_accessibility.py index f3b61c030..8b2e7ed49 100644 --- a/lanes/dev1/repair_overlay/tests/test_accessibility.py +++ b/lanes/dev1/repair_overlay/tests/test_accessibility.py @@ -67,6 +67,14 @@ 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_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) + self.assertIn('answer:getChild()', self.renderers) + self.assertIn("section.setAttribute('aria-labelledby',h.id)", self.renderers) + self.assertIn("failure.setAttribute('role','alert')", self.renderers) + self.assertNotIn("answer:{text:input.value}", self.renderers) + def test_shortcut_capture_preserves_escape_tab_scope_and_focus_return(self): self.assertIn("if(e.key==='Escape'){this.clearCapture();return}", self.hotkeys) self.assertIn("if(e.key==='Tab')return", self.hotkeys) diff --git a/lanes/dev1/repair_overlay/tests/test_authoring_transport.py b/lanes/dev1/repair_overlay/tests/test_authoring_transport.py index 0c14c63e8..de7164051 100644 --- a/lanes/dev1/repair_overlay/tests/test_authoring_transport.py +++ b/lanes/dev1/repair_overlay/tests/test_authoring_transport.py @@ -20,6 +20,22 @@ def test_reorder_command_is_data_only(self): d=self.req('authoring.new_node_from_task_type',{'title':'Order','task_type':'ORDERING'})['data']['draft']; d['node']['ui_metadata']['items']=[{'id':'a'},{'id':'b'},{'id':'c'}] r=self.req('authoring.move_collection_item',{'draft':d,'path':'node.ui_metadata.items','index':2,'direction':'up'}); self.assertTrue(r['ok'],r); self.assertEqual(['a','c','b'],[x['id'] for x in r['data']['draft']['node']['ui_metadata']['items']]) self.assertEqual(['a','b','c'],[x['id'] for x in d['node']['ui_metadata']['items']]) + def test_constructor_v2_lifecycle_is_allowlisted_and_fail_closed(self): + expected={'authoring.pack_compatibility','authoring.create_snapshot','authoring.list_snapshots','authoring.restore_snapshot','authoring.diff_draft','authoring.history','authoring.undo','authoring.redo','authoring.publish_version','authoring.list_versions','authoring.rollback_version'} + self.assertTrue(expected.issubset(ALLOWLISTED_COMMANDS)) + r=self.req('authoring.new_draft',{'title':'Campaign','kind':'campaign'}); self.assertTrue(r['ok'],r); d=r['data']['draft']; did=d['draft_id'] + d['campaign']['campaign_id']='ZZ-CAMPAIGN'; d['campaign']['title_ua']='V1' + r=self.req('authoring.save_draft',{'draft':d}); self.assertTrue(r['ok'],r); d=r['data']['draft'] + r=self.req('authoring.create_snapshot',{'draft_id':did,'label':'Known good'}); self.assertTrue(r['ok'],r); sid=r['data']['snapshot']['snapshot_id'] + d['campaign']['title_ua']='V2'; r=self.req('authoring.save_draft',{'draft':d}); self.assertTrue(r['ok'],r); d=r['data']['draft'] + r=self.req('authoring.diff_draft',{'draft_id':did,'from_snapshot_id':sid}); self.assertTrue(r['ok'],r); self.assertIn('$.campaign.title_ua',r['data']['changed_paths']) + r=self.req('authoring.undo',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual('V1',r['data']['draft']['campaign']['title_ua']) + r=self.req('authoring.redo',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual('V2',r['data']['draft']['campaign']['title_ua']) + compat=self.req('authoring.pack_compatibility',{}); self.assertTrue(compat['ok'],compat); compatibility=compat['data']['compatibility'] + bad=dict(compatibility); bad['content_schema_version']='future' + r=self.req('authoring.publish_version',{'draft_id':did,'compatibility':bad}); self.assertFalse(r['ok'],r); self.assertEqual('VALIDATION_ERROR',r['error']['code']) + r=self.req('authoring.publish_version',{'draft_id':did,'compatibility':compatibility}); self.assertTrue(r['ok'],r); version=r['data']['version']; self.assertFalse(version['canonical_mutation_performed']) + r=self.req('authoring.list_versions',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual(version['version_id'],r['data']['versions'][0]['version_id']) def test_player_branch_target_stays_runtime_owned(self): self.assertNotIn('player.navigate_branch',ALLOWLISTED_COMMANDS) self.assertIn('player.next',ALLOWLISTED_COMMANDS) diff --git a/lanes/dev1/repair_overlay/tests/test_composite_accessibility.py b/lanes/dev1/repair_overlay/tests/test_composite_accessibility.py index 84b9736dc..b7e303218 100644 --- a/lanes/dev1/repair_overlay/tests/test_composite_accessibility.py +++ b/lanes/dev1/repair_overlay/tests/test_composite_accessibility.py @@ -28,7 +28,7 @@ def setUp(self) -> None: @staticmethod def _child_accessibility() -> dict[str, str]: return { - "nonvisual_equivalent": "Labelled text field reachable and operable from the keyboard.", + "nonvisual_equivalent": "Labelled control reachable and operable from the keyboard.", "announcements": "Result and next action are announced as text.", } @@ -85,7 +85,7 @@ def test_nested_media_without_text_equivalent_fails(self) -> None: {(item["code"], item["path"]) for item in inspection["findings"]}, ) - def test_keyboard_complete_nested_child_passes(self) -> None: + def test_keyboard_complete_nested_text_child_passes(self) -> None: task = self._render( [ { @@ -104,7 +104,7 @@ def test_keyboard_complete_nested_child_passes(self) -> None: self.assertEqual("SHORT_TEXT", child["task_type"]) self.assertEqual("ANSWER_DTO_v1", child["answer_contract"]["schema"]) - def test_nested_single_choice_fails_packaged_renderer_answer_parity(self) -> None: + def test_nested_single_choice_passes_semantic_renderer_parity(self) -> None: task = self._render( [ { @@ -122,19 +122,14 @@ def test_nested_single_choice_fails_packaged_renderer_answer_parity(self) -> Non ) inspection = task["accessibility"]["inspection"] - self.assertFalse(inspection["passed"]) - self.assertIn( - ( - "A11Y_COMPOSITE_CHILD_RENDERER_PARITY_MISMATCH", - "task.steps[0].task_type", - ), - {(item["code"], item["path"]) for item in inspection["findings"]}, - ) - linear = "\n".join(task["accessibility"]["inspection_linear"]) - self.assertIn("A11Y_COMPOSITE_CHILD_RENDERER_PARITY_MISMATCH", linear) - self.assertIn("task.steps[0].task_type", linear) + self.assertTrue(inspection["passed"]) + self.assertEqual([], inspection["findings"]) + child = task["steps"][0] + self.assertEqual("SINGLE_CHOICE", child["task_type"]) + self.assertEqual("ANSWER_DTO_v1", child["answer_contract"]["schema"]) + self.assertEqual(["a", "b"], [item["id"] for item in child["options"]]) - def test_nested_ordering_fails_packaged_renderer_answer_parity(self) -> None: + def test_nested_ordering_passes_semantic_renderer_parity(self) -> None: task = self._render( [ { @@ -152,15 +147,43 @@ def test_nested_ordering_fails_packaged_renderer_answer_parity(self) -> None: ) inspection = task["accessibility"]["inspection"] - self.assertFalse(inspection["passed"]) - self.assertIn( - ( - "A11Y_COMPOSITE_CHILD_RENDERER_PARITY_MISMATCH", - "task.steps[0].task_type", - ), - {(item["code"], item["path"]) for item in inspection["findings"]}, + self.assertTrue(inspection["passed"]) + self.assertEqual([], inspection["findings"]) + child = task["steps"][0] + self.assertEqual("ORDERING", child["task_type"]) + self.assertEqual(["first", "second"], [item["id"] for item in child["items"]]) + + def test_nested_composite_recurses_into_child_contracts(self) -> None: + task = self._render( + [ + { + "step_id": "outer", + "task_type": "COMPOSITE_MULTI_STEP", + "label": "Outer", + "prompt": "Complete the nested step.", + "accessibility": self._child_accessibility(), + "steps": [ + { + "step_id": "inner", + "task_type": "SINGLE_CHOICE", + "label": "Inner choice", + "prompt": "Choose one.", + "options": [ + {"id": "x", "label": "X"}, + {"id": "y", "label": "Y"}, + ], + "accessibility": self._child_accessibility(), + } + ], + } + ] ) + self.assertTrue(task["accessibility"]["inspection"]["passed"]) + inner = task["steps"][0]["steps"][0] + self.assertEqual("SINGLE_CHOICE", inner["task_type"]) + self.assertEqual("ANSWER_DTO_v1", inner["answer_contract"]["schema"]) + def test_grading_only_step_cannot_be_promoted_to_accessibility_contract(self) -> None: node = dict(self.base_node) node["grading"] = { @@ -177,11 +200,11 @@ def test_grading_only_step_cannot_be_promoted_to_accessibility_contract(self) -> inspection = task["accessibility"]["inspection"] self.assertFalse(inspection["passed"]) self.assertIn( - ("A11Y_COMPOSITE_CHILD_CONTRACT_MISSING", "task.steps[0].task_type"), + ("A11Y_COMPOSITE_STEPS_MISSING", "task.steps"), {(item["code"], item["path"]) for item in inspection["findings"]}, ) - self.assertNotIn("task_type", task["steps"][0]) - self.assertNotIn("answer_contract", task["steps"][0]) + self.assertEqual([], task["steps"]) + self.assertNotIn("grading", task) def test_incomplete_nested_child_still_exposes_explicit_hazard(self) -> None: task = self._render( @@ -206,6 +229,22 @@ def test_incomplete_nested_child_still_exposes_explicit_hazard(self) -> None: pairs, ) + def test_unknown_nested_child_type_still_fails_closed(self) -> None: + node = dict(self.base_node) + node["response_contract"] = { + "steps": [ + { + "step_id": "s1", + "task_type": "UNREGISTERED_WIDGET", + "label": "Unsupported", + "prompt": "Unsupported step.", + "accessibility": self._child_accessibility(), + } + ] + } + with self.assertRaises(Exception): + self.mapper.to_renderable(node, self.mission) + if __name__ == "__main__": unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py new file mode 100644 index 000000000..843e5cd89 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py @@ -0,0 +1,44 @@ +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + + +class ConstructorV2FrontendTests(unittest.TestCase): + def setUp(self): + self.frontend = Path(__file__).resolve().parents[1] / "frontend" + self.source = (self.frontend / "constructor-v2-ui.js").read_text(encoding="utf-8") + + def test_surface_is_semantic_keyboard_native_and_never_uses_unsafe_html(self): + self.assertIn("button.type='button'", self.source) + self.assertIn("aria-live", self.source) + self.assertIn("Constructor V2 — історія та версії", self.source) + self.assertIn("canonical content не змінено", self.source) + self.assertNotIn("innerHTML", self.source) + self.assertNotIn("eval(", self.source) + self.assertNotIn("new Function", self.source) + + def test_module_is_mounted_by_existing_transport_additive_pattern(self): + transport = (self.frontend / "transport.js").read_text(encoding="utf-8") + self.assertIn("./constructor-v2-ui.js", transport) + self.assertIn("installConstructorV2Surface", transport) + + def test_javascript_module_parses_when_node_is_available(self): + node = shutil.which("node") + if not node: + self.skipTest("node is not installed in this local test environment") + with tempfile.TemporaryDirectory() as tmp: + candidate = Path(tmp) / "constructor-v2-ui.mjs" + candidate.write_text(self.source, encoding="utf-8") + completed = subprocess.run( + [node, "--check", str(candidate)], + capture_output=True, + text=True, + timeout=20, + ) + self.assertEqual(0, completed.returncode, completed.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py new file mode 100644 index 000000000..4cfeaf073 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py @@ -0,0 +1,167 @@ +import itertools +import json +import tempfile +import unittest +from pathlib import Path +import sys + +for _parent in Path(__file__).resolve().parents: + _runtime_root = _parent / "runtime_engine" + if (_runtime_root / "scripture_archive_runtime").is_dir(): + sys.path.insert(0, str(_runtime_root)) + break + +from scripture_archive_platform.authoring.recoverable import RecoverableAuthoringService +from scripture_archive_platform.content.loader import TaskPresentationMapper +from scripture_archive_platform.domain.registries import build_task_registries +from scripture_archive_platform.persistence.store import JsonFileStore + + +class ConstructorV2LifecycleTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.ids = itertools.count(1) + self.registry = build_task_registries()[0] + self.service = self._service() + + def tearDown(self): + self.tmp.cleanup() + + def _service(self): + return RecoverableAuthoringService( + JsonFileStore(self.root), self.registry, TaskPresentationMapper(), + clock=lambda: 1700000000, + id_factory=lambda: f"{next(self.ids):012d}", + ) + + def _campaign(self, title="Version one"): + draft = self.service.new_draft("Campaign draft", "campaign") + draft["campaign"].update({ + "campaign_id": "ZZ-CAMPAIGN", + "title_ua": title, + "scope": "Bounded fixture scope", + "player_promise": "Fixture promise", + "estimated_total_time": "5 min", + "completion_reward_type": "none", + "editorial_status": "DRAFT", + "source_audit_status": "NOT_AUDITED", + }) + return self.service.save_draft(draft) + + def test_undo_redo_persist_across_service_restart_with_monotonic_revision(self): + draft = self._campaign("Version one") + draft["campaign"]["title_ua"] = "Version two" + saved = self.service.save_draft(draft) + saved_revision = saved["revision"] + + restarted = self._service() + history = restarted.history(saved["draft_id"]) + self.assertTrue(history["can_undo"]) + self.assertFalse(history["can_redo"]) + + undone = restarted.undo(saved["draft_id"]) + self.assertEqual("Version one", undone["campaign"]["title_ua"]) + self.assertGreater(undone["revision"], saved_revision) + redone = restarted.redo(saved["draft_id"]) + self.assertEqual("Version two", redone["campaign"]["title_ua"]) + self.assertGreater(redone["revision"], undone["revision"]) + + restarted_again = self._service() + self.assertEqual("Version two", restarted_again.load_draft(saved["draft_id"])["campaign"]["title_ua"]) + self.assertTrue(restarted_again.history(saved["draft_id"])["can_undo"]) + + def test_snapshot_diff_restore_is_persisted_and_creates_safety_snapshot(self): + draft = self._campaign("Before snapshot") + snap = self.service.create_snapshot(draft["draft_id"], "Known good") + draft["campaign"]["title_ua"] = "After snapshot" + changed = self.service.save_draft(draft) + + diff = self.service.diff_draft(changed["draft_id"], snap["snapshot_id"]) + self.assertTrue(diff["changed"]) + self.assertIn("$.campaign.title_ua", diff["changed_paths"]) + + restarted = self._service() + restored = restarted.restore_snapshot(changed["draft_id"], snap["snapshot_id"]) + self.assertEqual("Before snapshot", restored["campaign"]["title_ua"]) + self.assertGreater(restored["revision"], changed["revision"]) + snapshots = restarted.list_snapshots(changed["draft_id"]) + self.assertGreaterEqual(len(snapshots), 2) + self.assertIn("Known good", {row["label"] for row in snapshots}) + self.assertIn( + "Automatic safety snapshot before snapshot restore", + {row["label"] for row in snapshots}, + ) + + def test_publish_version_is_fail_closed_compatible_persistent_and_never_canonical_write(self): + draft = self._campaign("Publishable campaign") + expected = self.service.pack_compatibility() + bad = dict(expected) + bad["content_schema_version"] = "CONTENT_NODE_SCHEMA_future" + with self.assertRaisesRegex(ValueError, "pack compatibility mismatch"): + self.service.publish_version(draft["draft_id"], bad) + + version = self.service.publish_version(draft["draft_id"], expected) + self.assertFalse(version["canonical_mutation_performed"]) + self.assertTrue(version["requires_explicit_integration"]) + self.assertFalse(version["candidate"]["canonical_mutation_performed"]) + self.assertEqual(expected, version["compatibility"]) + + draft["campaign"]["title_ua"] = "Later edit" + later = self.service.save_draft(draft) + restarted = self._service() + versions = restarted.list_versions(draft["draft_id"]) + self.assertEqual([version["version_id"]], [row["version_id"] for row in versions]) + + rolled = restarted.rollback_version(draft["draft_id"], version["version_id"]) + self.assertEqual("Publishable campaign", rolled["campaign"]["title_ua"]) + self.assertGreater(rolled["revision"], later["revision"]) + self.assertEqual("DRAFT", rolled["status"]) + self.assertNotIn("publish_manifest", rolled) + self.assertNotIn("canonical_mutation_performed", rolled) + + def test_cross_draft_snapshot_and_version_restore_are_rejected(self): + first = self._campaign("First") + snapshot = self.service.create_snapshot(first["draft_id"], "First only") + version = self.service.publish_version(first["draft_id"], self.service.pack_compatibility()) + second = self._campaign("Second") + with self.assertRaisesRegex(ValueError, "another draft"): + self.service.restore_snapshot(second["draft_id"], snapshot["snapshot_id"]) + with self.assertRaisesRegex(ValueError, "another draft"): + self.service.rollback_version(second["draft_id"], version["version_id"]) + + def test_import_draft_validates_envelope_before_persistence(self): + source = self._campaign("Import source") + exported = json.loads(self.service.export_draft(source["draft_id"])) + baseline = set(self.service.store.list_keys("drafts")) + + malformed = [] + bad_kind = json.loads(json.dumps(exported)) + bad_kind["kind"] = "bogus" + bad_kind["base_identity"] = {"bogus": "ZZ-CAMPAIGN"} + malformed.append((bad_kind, "kind must be campaign, mission or node")) + + bad_title = json.loads(json.dumps(exported)) + bad_title["title"] = "" + malformed.append((bad_title, "title must be 1..300 characters")) + + bad_record = json.loads(json.dumps(exported)) + bad_record["node"] = [] + malformed.append((bad_record, "node must be an object")) + + for payload, expected_error in malformed: + with self.subTest(expected_error=expected_error): + with self.assertRaisesRegex(ValueError, expected_error): + self.service.import_draft(json.dumps(payload)) + self.assertEqual(baseline, set(self.service.store.list_keys("drafts"))) + + exported["campaign"]["player_promise"] = "" + imported = self.service.import_draft(json.dumps(exported)) + self.assertNotEqual(source["draft_id"], imported["draft_id"]) + self.assertEqual("import_data_only", imported["change_record"][0]["action"]) + self.assertIn("