From 5c19d7774817c84e99f86f371b874ae071370787 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Fri, 11 Sep 2026 21:59:34 +0200 Subject: [PATCH 001/125] R06: add single-flight packaged startup gate --- lanes/dev1/repair_overlay/frontend/startup.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/startup.js diff --git a/lanes/dev1/repair_overlay/frontend/startup.js b/lanes/dev1/repair_overlay/frontend/startup.js new file mode 100644 index 000000000..fe8c85321 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/startup.js @@ -0,0 +1,16 @@ +export function installStartup({windowObject=window,locationObject=window.location,init}){ + if(typeof init!=='function')throw new TypeError('init must be a function'); + let started=false,initPromise=null; + const start=()=>{ + if(started)return initPromise; + started=true; + initPromise=Promise.resolve().then(()=>init()); + return initPromise; + }; + const protocol=String(locationObject?.protocol||'').toLowerCase(); + const bridgeReady=Boolean(windowObject?.pywebview?.api?.invoke); + const webMock=protocol==='http:'||protocol==='https:'; + if(bridgeReady||webMock){void start()} + else{windowObject.addEventListener('pywebviewready',()=>{void start()},{once:true})} + return {start,get started(){return started},get promise(){return initPromise}}; +} From 32a7956757c53d131e4f8bc011bc5e675e942a03 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Fri, 11 Sep 2026 21:59:47 +0200 Subject: [PATCH 002/125] R06: regress WebView startup event ordering --- .../repair_overlay/tests/test_startup_gate.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_startup_gate.py diff --git a/lanes/dev1/repair_overlay/tests/test_startup_gate.py b/lanes/dev1/repair_overlay/tests/test_startup_gate.py new file mode 100644 index 000000000..cb52a88a8 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_startup_gate.py @@ -0,0 +1,60 @@ +import json +import shutil +import subprocess +import unittest +from pathlib import Path + + +class StartupGateBehaviorTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root=Path(__file__).parents[1] + cls.module=cls.root/'frontend'/'startup.js' + cls.app=(cls.root/'frontend'/'app.js').read_text(encoding='utf-8') + cls.node=shutil.which('node') + + def _node(self, body: str): + if not self.node:self.skipTest('node unavailable') + source=f"import {{installStartup}} from {json.dumps(self.module.as_uri())};\n"+body + result=subprocess.run([self.node,'--input-type=module','-e',source],capture_output=True,text=True) + self.assertEqual(0,result.returncode,result.stderr or result.stdout) + + def test_file_protocol_waits_for_bridge_and_initializes_once(self): + self._node(r""" +let handler=null,calls=0; +const fakeWindow={pywebview:undefined,addEventListener:(name,fn,opts)=>{if(name!=='pywebviewready'||opts?.once!==true)throw new Error('bad listener');handler=fn}}; +const gate=installStartup({windowObject:fakeWindow,locationObject:{protocol:'file:'},init:async()=>{calls+=1}}); +await Promise.resolve(); +if(calls!==0||gate.started)throw new Error('packaged startup ran before bridge readiness'); +if(typeof handler!=='function')throw new Error('bridge-ready listener missing'); +fakeWindow.pywebview={api:{invoke:()=>{}}}; +handler();handler();await gate.start(); +if(calls!==1||!gate.started)throw new Error(`startup not single-flight: ${calls}`); +""") + + def test_web_mock_starts_immediately_once(self): + self._node(r""" +let calls=0,listeners=0; +const fakeWindow={addEventListener:()=>{listeners+=1}}; +const gate=installStartup({windowObject:fakeWindow,locationObject:{protocol:'http:'},init:async()=>{calls+=1}}); +await gate.start();await gate.start(); +if(calls!==1)throw new Error(`expected one web bootstrap, got ${calls}`); +if(listeners!==0)throw new Error('web mock should not wait for pywebviewready'); +""") + + def test_ready_bridge_starts_immediately_once(self): + self._node(r""" +let calls=0,listeners=0; +const fakeWindow={pywebview:{api:{invoke:()=>{}}},addEventListener:()=>{listeners+=1}}; +const gate=installStartup({windowObject:fakeWindow,locationObject:{protocol:'file:'},init:async()=>{calls+=1}}); +await gate.start();await gate.start(); +if(calls!==1||listeners!==0)throw new Error(`bad ready-bridge lifecycle calls=${calls} listeners=${listeners}`); +""") + + def test_app_uses_gate_without_zero_delay_transport_probe(self): + self.assertIn("installStartup({windowObject:window,locationObject:location,init})",self.app) + self.assertNotIn("setTimeout(init,0)",self.app) + self.assertNotIn("pywebviewready',()=>init()",self.app) + + +if __name__=='__main__':unittest.main() From 23a90327542e25029a189784d6c7b1163f9eac51 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Fri, 11 Sep 2026 22:00:14 +0200 Subject: [PATCH 003/125] R06: gate packaged WebView startup on transport readiness --- lanes/dev1/repair_overlay/frontend/app.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/app.js b/lanes/dev1/repair_overlay/frontend/app.js index 71e0e7158..45793941c 100644 --- a/lanes/dev1/repair_overlay/frontend/app.js +++ b/lanes/dev1/repair_overlay/frontend/app.js @@ -1,4 +1,4 @@ -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 {RuntimeNextGate} from './player-next.js'; +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 {RuntimeNextGate} from './player-next.js';import {installStartup} from './startup.js'; const $=id=>document.getElementById(id);let transport,bootstrap,currentTask,currentMission,getAnswer,currentCampaign,nextNodeId=null,activeView='home',researchReturn={view:'home',focus:'home-heading'};const views=['home','mission','player','research','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)} @@ -23,4 +23,4 @@ function executeAction(id){const map={'app.home':()=>loadCampaigns(),'player.sub let dispatcher,authoring,keymap,research,nextGate,jsonMode=''; function setupJsonDialog(){document.addEventListener('scripture-json-dialog',e=>{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='';$('json-dialog').showModal()});$('import-draft').onclick=()=>{jsonMode='draft-import';$('json-text').readOnly=false;$('json-text').value='';$('json-commit').classList.remove('hidden');$('json-dialog').showModal();$('json-text').focus()};$('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');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});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}`)});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); +installStartup({windowObject:window,locationObject:location,init}); From d88bd269bc278419db89b59a9e707b167779456e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Fri, 11 Sep 2026 22:05:42 +0200 Subject: [PATCH 004/125] R06 packaged startup: bound missing-bridge failure --- lanes/dev1/repair_overlay/frontend/startup.js | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/startup.js b/lanes/dev1/repair_overlay/frontend/startup.js index fe8c85321..5ee40e7e3 100644 --- a/lanes/dev1/repair_overlay/frontend/startup.js +++ b/lanes/dev1/repair_overlay/frontend/startup.js @@ -1,16 +1,37 @@ -export function installStartup({windowObject=window,locationObject=window.location,init}){ +export function installStartup({windowObject=window,locationObject=window.location,init,bridgeTimeoutMs=10000,onBridgeTimeout=null}){ if(typeof init!=='function')throw new TypeError('init must be a function'); - let started=false,initPromise=null; + if(!Number.isSafeInteger(bridgeTimeoutMs)||bridgeTimeoutMs<=0)throw new TypeError('bridgeTimeoutMs must be a positive safe integer'); + if(onBridgeTimeout!==null&&typeof onBridgeTimeout!=='function')throw new TypeError('onBridgeTimeout must be a function or null'); + let started=false,initPromise=null,bridgeTimer=null; + const bridgeUsable=()=>typeof windowObject?.pywebview?.api?.invoke==='function'; + const clearBridgeTimer=()=>{if(bridgeTimer!==null){clearTimeout(bridgeTimer);bridgeTimer=null}}; + const reportBridgeTimeout=()=>{ + if(onBridgeTimeout){onBridgeTimeout();return} + const doc=windowObject?.document; + const detail='Не вдалося підключити Windows platform bridge. Перевірте WebView2 і перезапустіть застосунок.'; + const campaignList=doc?.getElementById?.('campaign-list'); + if(campaignList)campaignList.textContent=detail; + const status=doc?.getElementById?.('global-status'); + if(status)status.textContent='Помилка запуску платформи: Windows bridge недоступний.'; + }; const start=()=>{ if(started)return initPromise; started=true; + clearBridgeTimer(); initPromise=Promise.resolve().then(()=>init()); return initPromise; }; const protocol=String(locationObject?.protocol||'').toLowerCase(); - const bridgeReady=Boolean(windowObject?.pywebview?.api?.invoke); const webMock=protocol==='http:'||protocol==='https:'; - if(bridgeReady||webMock){void start()} - else{windowObject.addEventListener('pywebviewready',()=>{void start()},{once:true})} + if(bridgeUsable()||webMock){void start()} + else{ + windowObject.addEventListener('pywebviewready',()=>{void start()},{once:true}); + bridgeTimer=setTimeout(()=>{ + bridgeTimer=null; + if(started)return; + if(bridgeUsable()){void start();return} + reportBridgeTimeout(); + },bridgeTimeoutMs); + } return {start,get started(){return started},get promise(){return initPromise}}; } From c737d19e410740686d8e39880602f7aebde76dcb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Fri, 11 Sep 2026 22:06:02 +0200 Subject: [PATCH 005/125] R06 packaged startup: regress missing bridge recovery --- .../repair_overlay/tests/test_startup_gate.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_startup_gate.py b/lanes/dev1/repair_overlay/tests/test_startup_gate.py index cb52a88a8..a1d121d4b 100644 --- a/lanes/dev1/repair_overlay/tests/test_startup_gate.py +++ b/lanes/dev1/repair_overlay/tests/test_startup_gate.py @@ -30,6 +30,36 @@ def test_file_protocol_waits_for_bridge_and_initializes_once(self): fakeWindow.pywebview={api:{invoke:()=>{}}}; handler();handler();await gate.start(); if(calls!==1||!gate.started)throw new Error(`startup not single-flight: ${calls}`); +""") + + def test_missing_bridge_reports_accessible_failure_and_late_ready_recovers(self): + self._node(r""" +let handler=null,calls=0; +const nodes={'campaign-list':{textContent:''},'global-status':{textContent:''}}; +const fakeWindow={ + pywebview:undefined, + document:{getElementById:id=>nodes[id]||null}, + addEventListener:(name,fn,opts)=>{if(name!=='pywebviewready'||opts?.once!==true)throw new Error('bad listener');handler=fn} +}; +const gate=installStartup({windowObject:fakeWindow,locationObject:{protocol:'file:'},bridgeTimeoutMs:5,init:async()=>{calls+=1}}); +await new Promise(resolve=>setTimeout(resolve,20)); +if(calls!==0||gate.started)throw new Error('timeout must not probe transport or mark startup complete'); +if(!nodes['campaign-list'].textContent.includes('WebView2'))throw new Error('visible startup diagnostic missing'); +if(!nodes['global-status'].textContent.includes('Windows bridge'))throw new Error('live-region startup diagnostic missing'); +fakeWindow.pywebview={api:{invoke:()=>{}}}; +handler();await gate.start(); +if(calls!==1||!gate.started)throw new Error(`late bridge did not recover exactly once: ${calls}`); +""") + + def test_bridge_that_appears_before_timeout_starts_without_event(self): + self._node(r""" +let calls=0,reports=0; +const fakeWindow={pywebview:undefined,addEventListener:()=>{}}; +const gate=installStartup({windowObject:fakeWindow,locationObject:{protocol:'file:'},bridgeTimeoutMs:10,onBridgeTimeout:()=>{reports+=1},init:async()=>{calls+=1}}); +setTimeout(()=>{fakeWindow.pywebview={api:{invoke:()=>{}}}},2); +await new Promise(resolve=>setTimeout(resolve,25)); +await gate.start(); +if(calls!==1||reports!==0||!gate.started)throw new Error(`lost-event recovery failed calls=${calls} reports=${reports}`); """) def test_web_mock_starts_immediately_once(self): From e97de99b05ed55be0591edf875a9381f452e72a5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:20:58 +0200 Subject: [PATCH 006/125] R06 packaged dossier: expose canonical read-only dossier gateway --- .../application/runtime_gateway.py | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) 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 efda10c82..dfcb8b9f2 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 @@ -15,10 +15,12 @@ class RuntimeBackedPlayerGateway: Presentation remains a platform concern. Grading, branching, mastery, player memory, evidence unlock state and player persistence are runtime-owned. + Read-only dossier views are derived from that same runtime evidence instance. """ - def __init__(self, runtime_invoke): + def __init__(self, runtime_invoke, *, dossier_invoke=None): self.adapter = RuntimeEngineContractAdapter(runtime_invoke) + self._dossier_invoke = dossier_invoke @staticmethod def _request(command: str, payload: Mapping[str, Any], request_id: str) -> dict[str, Any]: @@ -33,6 +35,34 @@ def invoke(self, command: str, payload: Mapping[str, Any] | None = None, *, requ response = self.adapter.invoke_runtime(self._request(command, payload or {}, request_id)) return dict(response) + def get_dossier(self, subject_id: str, display_name: str, kind: str) -> dict[str, Any]: + if self._dossier_invoke is None: + raise RuntimeGatewayError("canonical runtime dossier view is unavailable") + data = self._dossier_invoke(subject_id, display_name, kind) + if not isinstance(data, Mapping): + raise RuntimeGatewayError("canonical runtime dossier view must be an object") + return dict(data) + + +def build_runtime_dossier(runtime, subject_id: str, display_name: str, kind: str) -> dict[str, Any]: + """Build an unlocked-only dossier from the runtime-owned EvidenceRuntime.""" + from runtime_engine.scripture_archive_runtime.dossiers import ( + DossierAssembler, + DossierKind, + DossierSubject, + ) + + subject = DossierSubject( + subject_id=subject_id, + display_name=display_name, + kind=DossierKind(kind), + ) + view = DossierAssembler(runtime.evidence).build(subject, unlocked_only=True) + dossier = view.to_dict() + dossier["linear"] = list(view.linearize()) + dossier["evidence_scope"] = "unlocked_only" + return {"dossier": dossier} + def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> RuntimeBackedPlayerGateway: """Build the exact D5 runtime against the same canonical repository checkout.""" @@ -47,4 +77,9 @@ def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> Runtime content = ContentRepository(nodes, adapt_legacy=True, lane="DEV-A") runtime_store = PersistenceStore(Path(platform_store_root) / "runtime-v2") runtime = RuntimeApplication(content, persistence=runtime_store) - return RuntimeBackedPlayerGateway(runtime.handle) + return RuntimeBackedPlayerGateway( + runtime.handle, + dossier_invoke=lambda subject_id, display_name, kind: build_runtime_dossier( + runtime, subject_id, display_name, kind + ), + ) From cbb252f22bb3f41fac801800933035e93fda7328 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:21:14 +0200 Subject: [PATCH 007/125] R06 packaged dossier: allowlist strict dossier query payload --- .../transport/contracts.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) 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 a8a2a5040..85e96dfaa 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -5,6 +5,7 @@ MAX_REQUEST_BYTES = 262_144 MAX_IMPORT_BYTES = 2_000_000 +DOSSIER_KINDS = frozenset({"PERSON", "EVENT", "PLACE", "THEME"}) ALLOWLISTED_COMMANDS = frozenset({ "system.bootstrap", @@ -15,7 +16,7 @@ "authoring.validate_draft","authoring.preview_draft","authoring.prepare_publish_candidate", "authoring.export_draft","authoring.import_draft", "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","dossier.get" }) class ContentLoaderPort(Protocol): @@ -33,6 +34,13 @@ def list_keys(self,namespace:str)->list[str]: ... class TransportAdapterPort(Protocol): def invoke(self,request:dict[str,Any])->dict[str,Any]: ... +def _require_clean_text(value:Any,key:str,max_length:int)->str: + if not isinstance(value,str) or not value or len(value)>max_length or value!=value.strip(): + raise ValueError(f'invalid {key}') + if any(ord(ch)<32 or ord(ch)==127 for ch in value): + raise ValueError(f'invalid {key}') + return value + 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') @@ -40,6 +48,13 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: if not isinstance(rid,str) or not rid or len(rid)>128: raise ValueError('invalid request_id') if cmd not in ALLOWLISTED_COMMANDS: raise ValueError('command not allowlisted') if not isinstance(payload,dict): raise ValueError('payload must be an object') + if cmd=='dossier.get': + if set(payload)!={'subject_id','display_name','kind'}: + raise ValueError('dossier.get requires exactly subject_id, display_name and kind') + _require_clean_text(payload.get('subject_id'),'subject_id',100) + _require_clean_text(payload.get('display_name'),'display_name',160) + if payload.get('kind') not in DOSSIER_KINDS: + raise ValueError('invalid dossier kind') if cmd=='player.next': unknown=set(payload)-{'node_id'} if unknown: raise ValueError('player.next accepts only current node_id context; target selection is forbidden') From 92932331fa7469a082e9d97295251b21b9b2b860 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:21:51 +0200 Subject: [PATCH 008/125] R06 packaged dossier: attest read-only runtime dossier response --- .../application/service.py | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) 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 43f1abd38..c24645402 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -37,6 +37,7 @@ def _dispatch(self,cmd,p): if cmd=='player.get_mastery':return self._mastery() if cmd=='player.save_checkpoint':return self._save_checkpoint(p) if cmd=='player.restore_checkpoint':return self._restore_checkpoint() + if cmd=='dossier.get':return self._dossier(p) if cmd=='authoring.list_drafts':return {'drafts':self.authoring.list_drafts()} if cmd=='authoring.new_draft':return {'draft':self.authoring.new_draft(str(p.get('title') or 'Нова чернетка'),str(p.get('kind') or 'node'))} if cmd=='authoring.load_draft':return {'draft':self.authoring.load_draft(self._id(p,'draft_id'))} @@ -61,7 +62,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,'arbitrary_filesystem':False,'shell':False,'python_eval':False,'runtime_truth':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,'web_portable_transport':True,'allowlisted_bridge':True,'arbitrary_filesystem':False,'shell':False,'python_eval':False,'dossiers':bool(self.player_gateway and hasattr(self.player_gateway,'get_dossier')),'runtime_truth':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 @@ -93,6 +94,34 @@ def _next(self,p): def _mastery(self): if not self.player_gateway:return {'mastery':[],'truth_owner':'REFERENCE_TEST_ONLY'} rr=self.player_gateway.invoke('player.get_mastery',{},request_id='mastery-player'); return {'mastery':rr.get('mastery') or [],'truth_owner':'D5/runtime'} + def _dossier(self,p): + if not self.player_gateway or not hasattr(self.player_gateway,'get_dossier'): + raise ValueError('dossier requires canonical runtime') + subject_id=p['subject_id']; display_name=p['display_name']; kind=p['kind'] + data=self.player_gateway.get_dossier(subject_id,display_name,kind) + dossier=data.get('dossier') if isinstance(data,dict) else None + if not isinstance(dossier,dict):raise ValueError('runtime dossier must be object') + if dossier.get('schema')!='scripture.dossier-view.v1':raise ValueError('unexpected dossier schema') + if dossier.get('evidence_scope')!='unlocked_only':raise ValueError('packaged dossier must remain unlocked_only') + subject=dossier.get('subject') + if not isinstance(subject,dict) or subject!={'subject_id':subject_id,'kind':kind,'display_name':display_name}: + raise ValueError('runtime dossier subject mismatch') + if type(dossier.get('stated')) is not bool:raise ValueError('runtime dossier stated must be boolean') + if not isinstance(dossier.get('status_text'),str) or len(dossier['status_text'])>500:raise ValueError('invalid dossier status_text') + rows=dossier.get('rows'); linear=dossier.get('linear') + if not isinstance(rows,list) or len(rows)>1000:raise ValueError('invalid dossier rows') + if not isinstance(linear,list) or len(linear)>2000 or any(not isinstance(line,str) or len(line)>4000 for line in linear):raise ValueError('invalid dossier linear representation') + for row in rows: + if not isinstance(row,dict):raise ValueError('invalid dossier row') + if row.get('row_type') not in {'EVIDENCE','CLAIM','RELATION'}:raise ValueError('invalid dossier row type') + if not isinstance(row.get('row_id'),str) or not row['row_id'] or len(row['row_id'])>160:raise ValueError('invalid dossier row id') + if not isinstance(row.get('proposition'),str) or len(row['proposition'])>4000:raise ValueError('invalid dossier proposition') + if row.get('confidence') not in {None,'T1','T2','C1','I1','D1'}:raise ValueError('invalid dossier confidence') + if type(row.get('tx1')) is not bool:raise ValueError('invalid dossier TX1 flag') + for key in ('passage_ids','evidence_ids'): + values=row.get(key) + if not isinstance(values,list) or len(values)>500 or any(not isinstance(value,str) or not value or len(value)>200 for value in values):raise ValueError(f'invalid dossier {key}') + return {'dossier':dossier,'truth_owner':'D5/runtime'} def _save_checkpoint(self,p): checkpoint={'campaign_id':p.get('campaign_id'),'mission_id':p.get('mission_id'),'node_id':p.get('node_id'),'saved_at':int(time.time()),'checkpoint_schema':'scripture.player.checkpoint.v1'} if self.player_gateway:self.player_gateway.invoke('player.save_checkpoint',{},request_id='save-'+str(p.get('node_id') or 'current')) From 79515d54dd591144acd4f10ea11698aac915d81d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:22:20 +0200 Subject: [PATCH 009/125] R06 packaged dossier: add semantic keyboard dossier UI --- .../repair_overlay/frontend/dossier-ui.js | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/dossier-ui.js diff --git a/lanes/dev1/repair_overlay/frontend/dossier-ui.js b/lanes/dev1/repair_overlay/frontend/dossier-ui.js new file mode 100644 index 000000000..f73063097 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/dossier-ui.js @@ -0,0 +1,139 @@ +const KINDS=new Set(['PERSON','EVENT','PLACE','THEME']); + +function element(tag,{id=null,className=null,text=null}={}){ + const node=document.createElement(tag); + if(id)node.id=id; + if(className)node.className=className; + if(text!==null)node.textContent=text; + return node; +} + +function clean(value,max){ + return typeof value==='string'&&value.length>0&&value.length<=max&&value===value.trim()&&!/[\u0000-\u001f\u007f]/.test(value); +} + +export class DossierUI{ + constructor({invoke,announce,showView,enabled=true}){ + this.invoke=invoke; + this.announce=announce; + this.showView=showView; + this.enabled=Boolean(enabled); + this.inFlight=null; + } + + mount({nav,main}){ + if(!nav||!main)throw new Error('DossierUI requires nav and main hosts'); + if(document.getElementById('dossier-view'))return; + + const navButton=element('button',{id:'nav-dossier',text:'Досьє'}); + navButton.type='button'; + navButton.disabled=!this.enabled; + navButton.setAttribute('aria-disabled',String(!this.enabled)); + if(!this.enabled)navButton.title='Досьє недоступні без канонічного runtime'; + navButton.onclick=()=>this.open(); + nav.append(navButton); + this.navButton=navButton; + + const section=element('section',{id:'dossier-view',className:'hidden'}); + section.setAttribute('aria-labelledby','dossier-heading'); + const eyebrow=element('p',{className:'eyebrow',text:'Canonical Evidence · unlocked only'}); + const heading=element('h2',{id:'dossier-heading',text:'Досьє'}); + heading.tabIndex=-1; + const explanation=element('p',{text:'Досьє є лише похідним представленням поточного runtime-owned evidence. Воно не додає біографію, хронологію, consensus або зв’язки, яких немає у канонічних доказах.'}); + const safety=element('p',{className:'notice info',text:'Якщо cited canonical runtime не містить безпечної підтримки суб’єкта, правильний результат: “Not stated in cited text”.'}); + + const form=document.createElement('form'); + form.id='dossier-form'; + const idLabel=element('label',{text:'Canonical subject ID'});idLabel.htmlFor='dossier-subject-id'; + const subjectId=document.createElement('input');subjectId.id='dossier-subject-id';subjectId.name='subject_id';subjectId.maxLength=100;subjectId.required=true; + const nameLabel=element('label',{text:'Display name'});nameLabel.htmlFor='dossier-display-name'; + const displayName=document.createElement('input');displayName.id='dossier-display-name';displayName.name='display_name';displayName.maxLength=160;displayName.required=true; + const kindLabel=element('label',{text:'Kind'});kindLabel.htmlFor='dossier-kind'; + const kind=document.createElement('select');kind.id='dossier-kind';kind.name='kind'; + [['PERSON','Person'],['EVENT','Event'],['PLACE','Place'],['THEME','Theme']].forEach(([value,label])=>{const option=document.createElement('option');option.value=value;option.textContent=label;kind.append(option)}); + const submit=element('button',{id:'dossier-submit',text:'Відкрити досьє'});submit.type='submit'; + form.append(idLabel,subjectId,nameLabel,displayName,kindLabel,kind,submit); + form.onsubmit=event=>{event.preventDefault();this.load();}; + + const status=element('div',{id:'dossier-status',className:'sr-status'});status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const resultHeading=element('h3',{id:'dossier-result-heading',text:'Результат'});resultHeading.tabIndex=-1; + const summary=element('p',{id:'dossier-summary',text:'Ще не завантажено.'}); + const table=document.createElement('table');table.id='dossier-table';table.setAttribute('aria-labelledby','dossier-result-heading'); + const caption=element('caption',{text:'Semantic dossier rows from visible canonical evidence'});table.append(caption); + const thead=document.createElement('thead');const tr=document.createElement('tr');['Type','ID','Statement','Provenance'].forEach(text=>{const th=element('th',{text});th.scope='col';tr.append(th)});thead.append(tr); + const tbody=document.createElement('tbody');table.append(thead,tbody); + const linearHeading=element('h3',{id:'dossier-linear-heading',text:'Повний лінійний еквівалент'}); + const linear=element('pre',{id:'dossier-linear'});linear.tabIndex=0;linear.setAttribute('aria-labelledby','dossier-linear-heading');linear.textContent='Not stated in cited text'; + const back=element('button',{id:'dossier-back',text:'Повернутися на головну'});back.type='button';back.onclick=()=>this.showView('home','home-heading'); + section.append(eyebrow,heading,explanation,safety,form,status,resultHeading,summary,table,linearHeading,linear,back); + main.append(section); + Object.assign(this,{section,heading,form,subjectId,displayName,kind,submit,status,resultHeading,summary,tbody,linear}); + } + + open(){ + if(!this.enabled){this.announce?.('Досьє недоступні без канонічного runtime');return;} + this.showView('dossier','dossier-heading'); + setTimeout(()=>this.subjectId?.focus(),0); + } + + request(){ + const subject_id=this.subjectId.value; + const display_name=this.displayName.value; + const kind=this.kind.value; + if(!clean(subject_id,100))throw new Error('Некоректний canonical subject ID'); + if(!clean(display_name,160))throw new Error('Некоректна display name'); + if(!KINDS.has(kind))throw new Error('Некоректний kind'); + return {subject_id,display_name,kind}; + } + + async load(){ + if(!this.enabled||this.inFlight)return this.inFlight; + let request; + try{request=this.request();}catch(error){this.status.textContent=error.message;this.announce?.(error.message);return;} + this.submit.disabled=true;this.status.textContent='Завантаження source-safe досьє…'; + const run=(async()=>{ + try{ + const data=await this.invoke('dossier.get',request); + const dossier=this.validate(data,request); + this.render(dossier); + this.status.textContent='Досьє оновлено.'; + this.announce?.(`Досьє ${request.display_name} оновлено`); + this.resultHeading.focus(); + }catch(error){ + this.tbody.replaceChildren();this.summary.textContent='Досьє недоступне.';this.linear.textContent=''; + this.status.textContent=`Помилка досьє: ${error?.message||'невідома помилка'}`;this.announce?.(this.status.textContent); + }finally{this.submit.disabled=false;} + })(); + this.inFlight=run; + try{await run;}finally{if(this.inFlight===run)this.inFlight=null;} + } + + validate(data,request){ + const d=data?.dossier; + if(!d||typeof d!=='object'||d.schema!=='scripture.dossier-view.v1')throw new Error('Некоректна dossier schema'); + if(d.evidence_scope!=='unlocked_only')throw new Error('Досьє порушило unlocked_only scope'); + if(!d.subject||d.subject.subject_id!==request.subject_id||d.subject.display_name!==request.display_name||d.subject.kind!==request.kind)throw new Error('Досьє повернуло інший subject'); + if(typeof d.stated!=='boolean'||typeof d.status_text!=='string')throw new Error('Некоректний dossier status'); + if(!Array.isArray(d.rows)||d.rows.length>1000)throw new Error('Некоректні dossier rows'); + if(!Array.isArray(d.linear)||d.linear.length>2000||d.linear.some(line=>typeof line!=='string'||line.length>4000))throw new Error('Некоректний linear equivalent'); + for(const row of d.rows){ + if(!row||typeof row!=='object'||!['EVIDENCE','CLAIM','RELATION'].includes(row.row_type))throw new Error('Некоректний dossier row'); + if(!clean(row.row_id,160)||typeof row.proposition!=='string'||row.proposition.length>4000)throw new Error('Некоректний dossier row content'); + if(![null,'T1','T2','C1','I1','D1'].includes(row.confidence)||typeof row.tx1!=='boolean')throw new Error('Некоректний provenance code'); + } + return d; + } + + render(d){ + this.tbody.replaceChildren(); + this.summary.textContent=d.status_text; + for(const row of d.rows){ + const tr=document.createElement('tr'); + const provenance=[row.confidence,row.tx1?'TX1':null,row.witness?`witness=${row.witness}`:null,row.source_scope?`scope=${row.source_scope}`:null,row.uncertainty?`uncertainty=${row.uncertainty}`:null].filter(Boolean).join('; ')||'No additional provenance stated'; + [row.row_type,row.row_id,row.proposition,provenance].forEach(text=>tr.append(element('td',{text}))); + this.tbody.append(tr); + } + if(!d.rows.length){const tr=document.createElement('tr');const td=element('td',{text:'Not stated in cited text'});td.colSpan=4;tr.append(td);this.tbody.append(tr);} + this.linear.textContent=d.linear.join('\n'); + } +} From 1fa2b59cc097fbbb689870ecec9ac3dbebac3098 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:22:48 +0200 Subject: [PATCH 010/125] R06 packaged dossier: mount dossier surface in packaged app --- lanes/dev1/repair_overlay/frontend/app.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/app.js b/lanes/dev1/repair_overlay/frontend/app.js index 45793941c..c5e5cbb49 100644 --- a/lanes/dev1/repair_overlay/frontend/app.js +++ b/lanes/dev1/repair_overlay/frontend/app.js @@ -1,5 +1,5 @@ -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 {RuntimeNextGate} from './player-next.js';import {installStartup} from './startup.js'; -const $=id=>document.getElementById(id);let transport,bootstrap,currentTask,currentMission,getAnswer,currentCampaign,nextNodeId=null,activeView='home',researchReturn={view:'home',focus:'home-heading'};const views=['home','mission','player','research','authoring']; +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 {DossierUI} from './dossier-ui.js';import {RuntimeNextGate} from './player-next.js';import {installStartup} from './startup.js'; +const $=id=>document.getElementById(id);let transport,bootstrap,currentTask,currentMission,getAnswer,currentCampaign,nextNodeId=null,activeView='home',researchReturn={view:'home',focus:'home-heading'};const views=['home','mission','player','research','dossier','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 showView(name,focusId){views.forEach(v=>$(`${v}-view`).classList.toggle('hidden',v!==name));activeView=name;if(focusId)setTimeout(()=>$(`${focusId}`)?.focus(),0)} @@ -14,13 +14,13 @@ async function submit(e){e?.preventDefault();if(!currentTask||!getAnswer)return; 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');$('hint-heading').focus();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);$('evidence-heading').focus();announce('Докази відкрито')} -function openResearch(){const from=activeView==='research'?researchReturn.view:activeView;const focus=from==='player'?'research-current':from==='mission'?'mission-back':from==='authoring'?'authoring-heading':'nav-research';researchReturn={view:from,focus};research?.setContext({task:currentTask,mission:currentMission});showView('research','research-heading');announce(currentTask?`Відкрито дослідження ${currentTask.node_id}`:'Відкрито дослідницький простір')} +function openResearch(){const from=activeView==='research'?researchReturn.view:activeView;const focus=from==='player'?'research-current':from==='mission'?'mission-back':from==='authoring'?'authoring-heading':from==='dossier'?'nav-dossier':'nav-research';researchReturn={view:from,focus};research?.setContext({task:currentTask,mission:currentMission});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){$('next-button').disabled=Boolean(busy)||!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 executeAction(id){const map={'app.home':()=>loadCampaigns(),'player.submit':()=>submit(),'player.hint':hint,'player.evidence':evidence,'player.next':next,'authoring.save':()=>authoring.save(),'authoring.preview':()=>authoring.preview(),'authoring.validate':()=>authoring.validate(),'settings.keymap':()=>keymap.open()};map[id]?.()} -let dispatcher,authoring,keymap,research,nextGate,jsonMode=''; +let dispatcher,authoring,keymap,research,dossier,nextGate,jsonMode=''; function setupJsonDialog(){document.addEventListener('scripture-json-dialog',e=>{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='';$('json-dialog').showModal()});$('import-draft').onclick=()=>{jsonMode='draft-import';$('json-text').readOnly=false;$('json-text').value='';$('json-commit').classList.remove('hidden');$('json-dialog').showModal();$('json-text').focus()};$('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');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});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}`)});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('Помилка запуску платформи')}} +async function init(){try{transport=await chooseTransport();bootstrap=await api('system.bootstrap');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});dossier=new DossierUI({invoke:api,announce,showView,enabled:Boolean(bootstrap.capabilities?.dossiers)});dossier.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}`)});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('Помилка запуску платформи')}} installStartup({windowObject:window,locationObject:location,init}); From 121834046000f7fa16c0170d46367269dc9da386 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:23:13 +0200 Subject: [PATCH 011/125] R06 packaged dossier: add transport and runtime composition regressions --- .../tests/test_dossier_composition.py | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_dossier_composition.py diff --git a/lanes/dev1/repair_overlay/tests/test_dossier_composition.py b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py new file mode 100644 index 000000000..d5f0bd298 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py @@ -0,0 +1,130 @@ +import unittest + +from scripture_archive_platform.application.runtime_gateway import ( + RuntimeBackedPlayerGateway, + RuntimeGatewayError, + build_runtime_dossier, +) +from scripture_archive_platform.application.service import PlatformApplication +from scripture_archive_platform.transport.contracts import validate_request_shape +from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime +from scripture_archive_runtime.models import Confidence + + +def safe_dossier(subject_id="PERSON:PAUL", display_name="Paul", kind="PERSON"): + return { + "dossier": { + "schema": "scripture.dossier-view.v1", + "subject": { + "subject_id": subject_id, + "kind": kind, + "display_name": display_name, + }, + "stated": False, + "status_text": "Not stated in cited text", + "rows": [], + "linear": [f"Dossier {kind} {subject_id}: {display_name}", "Not stated in cited text"], + "evidence_scope": "unlocked_only", + } + } + + +class FakeGateway: + def __init__(self, data=None): + self.data = data if data is not None else safe_dossier() + + def get_dossier(self, subject_id, display_name, kind): + return self.data + + +class DossierCompositionTests(unittest.TestCase): + def test_transport_requires_exact_bounded_dossier_subject(self): + request = { + "api_version": "scripture.transport.v1", + "request_id": "dossier-1", + "command": "dossier.get", + "payload": {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}, + } + rid, command, payload = validate_request_shape(request) + self.assertEqual((rid, command), ("dossier-1", "dossier.get")) + self.assertEqual(payload, request["payload"]) + + bad_payloads = ( + {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON", "path": "../x"}, + {"subject_id": " PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul\nInjected", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "BIOGRAPHY"}, + ) + for payload in bad_payloads: + with self.assertRaises(ValueError): + validate_request_shape({**request, "payload": payload}) + + def test_platform_attests_scope_subject_and_schema(self): + app = object.__new__(PlatformApplication) + app.player_gateway = FakeGateway() + request = {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"} + result = app._dossier(request) + self.assertEqual(result["truth_owner"], "D5/runtime") + self.assertEqual(result["dossier"]["evidence_scope"], "unlocked_only") + + widened = safe_dossier() + widened["dossier"]["evidence_scope"] = "all_runtime_evidence" + app.player_gateway = FakeGateway(widened) + with self.assertRaises(ValueError): + app._dossier(request) + + substituted = safe_dossier(subject_id="PERSON:OTHER") + app.player_gateway = FakeGateway(substituted) + with self.assertRaises(ValueError): + app._dossier(request) + + def test_gateway_callback_must_return_mapping(self): + gateway = RuntimeBackedPlayerGateway( + lambda request: {"api_version": "runtime.v1", "request_id": request["request_id"]}, + dossier_invoke=lambda subject_id, display_name, kind: safe_dossier(subject_id, display_name, kind), + ) + self.assertEqual( + gateway.get_dossier("PERSON:PAUL", "Paul", "PERSON")["dossier"]["schema"], + "scripture.dossier-view.v1", + ) + bad = RuntimeBackedPlayerGateway(lambda request: {}, dossier_invoke=lambda *args: "bad") + with self.assertRaises(RuntimeGatewayError): + bad.get_dossier("PERSON:PAUL", "Paul", "PERSON") + + def test_packaged_helper_uses_same_runtime_and_hides_locked_dependencies(self): + evidence = EvidenceRuntime() + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-VISIBLE", + passage_refs=(), + proposition="Visible canonical proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-LOCKED", + passage_refs=(), + proposition="Locked proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_claim(Claim( + claim_id="CL-LOCKED", + proposition="Claim needing locked evidence", + confidence=Confidence.T2, + required_evidence_ids=("EV-VISIBLE", "EV-LOCKED"), + )) + evidence.unlock("EV-VISIBLE") + runtime = type("Runtime", (), {"evidence": evidence})() + + packaged = build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON")["dossier"] + self.assertEqual(packaged["evidence_scope"], "unlocked_only") + self.assertEqual([row["row_id"] for row in packaged["rows"]], ["EV-VISIBLE"]) + rendered = "\n".join(packaged["linear"]) + self.assertIn("EV-VISIBLE", rendered) + self.assertNotIn("EV-LOCKED", rendered) + self.assertNotIn("CL-LOCKED", rendered) + self.assertNotIn("Locked proposition", rendered) + + +if __name__ == "__main__": + unittest.main() From 79a56069bb9fdf9a173599496a06962de63d1bd7 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 01:23:30 +0200 Subject: [PATCH 012/125] R06 packaged dossier: add UI source-safety and accessibility regressions --- .../repair_overlay/tests/test_dossier_ui.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_dossier_ui.py diff --git a/lanes/dev1/repair_overlay/tests/test_dossier_ui.py b/lanes/dev1/repair_overlay/tests/test_dossier_ui.py new file mode 100644 index 000000000..4756c602e --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_dossier_ui.py @@ -0,0 +1,53 @@ +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +FRONTEND = ROOT / "frontend" + + +class DossierUiContractTests(unittest.TestCase): + def test_dossier_ui_is_reachable_and_uses_only_allowlisted_query(self): + app = (FRONTEND / "app.js").read_text(encoding="utf-8") + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("DossierUI", app) + self.assertIn("'dossier'", app) + self.assertIn("bootstrap.capabilities?.dossiers", app) + self.assertIn("this.invoke('dossier.get',request)", ui) + for forbidden in ("include_locked", "filesystem", "shell", "eval(", "fetch("): + self.assertNotIn(forbidden, ui) + + def test_untrusted_runtime_strings_are_text_only(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("node.textContent=text", ui) + self.assertIn("this.linear.textContent=d.linear.join", ui) + self.assertNotIn("innerHTML", ui) + self.assertNotIn("insertAdjacentHTML", ui) + self.assertNotIn("document.write", ui) + + def test_keyboard_labels_live_status_focus_and_linear_equivalent_are_explicit(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + for token in ( + "heading.tabIndex=-1", + "resultHeading.tabIndex=-1", + "linear.tabIndex=0", + "aria-live", + "idLabel.htmlFor='dossier-subject-id'", + "nameLabel.htmlFor='dossier-display-name'", + "kindLabel.htmlFor='dossier-kind'", + "Повний лінійний еквівалент", + "Not stated in cited text", + ): + self.assertIn(token, ui) + + def test_client_rejects_scope_subject_schema_and_oversize_results(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("d.schema!=='scripture.dossier-view.v1'", ui) + self.assertIn("d.evidence_scope!=='unlocked_only'", ui) + self.assertIn("d.subject.subject_id!==request.subject_id", ui) + self.assertIn("d.rows.length>1000", ui) + self.assertIn("d.linear.length>2000", ui) + + +if __name__ == "__main__": + unittest.main() From 69bcb2f50920e3a6c75acb8931477ee883d70cf9 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:34:34 +0200 Subject: [PATCH 013/125] R06 packaged dossier: add stale-safe accessible UI --- .../repair_overlay/frontend/dossier-ui.js | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/dossier-ui.js diff --git a/lanes/dev1/repair_overlay/frontend/dossier-ui.js b/lanes/dev1/repair_overlay/frontend/dossier-ui.js new file mode 100644 index 000000000..da520efba --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/dossier-ui.js @@ -0,0 +1,172 @@ +const KINDS=new Set(['PERSON','EVENT','PLACE','THEME']); + +function element(tag,{id=null,className=null,text=null}={}){ + const node=document.createElement(tag); + if(id)node.id=id; + if(className)node.className=className; + if(text!==null)node.textContent=text; + return node; +} + +function hasForbiddenControl(value){ + for(const char of value){ + const code=char.codePointAt(0); + if(code<0x20||(code>=0x7f&&code<=0x9f)||code===0x2028||code===0x2029)return true; + } + return false; +} + +function clean(value,max){ + return typeof value==='string'&&value.length>0&&value.length<=max&&value===value.trim()&&!hasForbiddenControl(value); +} + +export class DossierUI{ + constructor({invoke,announce,showView,isActiveView=()=>true,enabled=true}){ + this.invoke=invoke; + this.announce=announce; + this.showView=showView; + this.isActiveView=isActiveView; + this.enabled=Boolean(enabled); + this.generation=0; + this.inFlight=null; + this.visible=false; + } + + mount({nav,main}){ + if(!nav||!main)throw new Error('DossierUI requires nav and main hosts'); + if(document.getElementById('dossier-view'))return; + + const navButton=element('button',{id:'nav-dossier',text:'Досьє'}); + navButton.type='button'; + navButton.disabled=!this.enabled; + navButton.setAttribute('aria-disabled',String(!this.enabled)); + if(!this.enabled)navButton.title='Досьє недоступні без канонічного runtime'; + navButton.onclick=()=>this.open(); + nav.append(navButton); + this.navButton=navButton; + + const section=element('section',{id:'dossier-view',className:'hidden'}); + section.setAttribute('aria-labelledby','dossier-heading'); + const eyebrow=element('p',{className:'eyebrow',text:'Canonical Evidence · unlocked only'}); + const heading=element('h2',{id:'dossier-heading',text:'Досьє'}); + heading.tabIndex=-1; + const explanation=element('p',{text:'Досьє є лише похідним представленням поточного runtime-owned evidence. Воно не додає біографію, хронологію, консенсус або зв’язки, яких немає у канонічних доказах.'}); + const safety=element('p',{className:'notice info',text:'Якщо поточна видима доказова область не встановлює твердження, досьє чесно показує, що cited support у current scope недоступний; “Not stated in cited text” використовується лише коли відсутність встановлена.'}); + + const form=document.createElement('form'); + form.id='dossier-form'; + const idLabel=element('label',{text:'Canonical subject ID'});idLabel.htmlFor='dossier-subject-id'; + const subjectId=document.createElement('input');subjectId.id='dossier-subject-id';subjectId.name='subject_id';subjectId.maxLength=100;subjectId.required=true; + const nameLabel=element('label',{text:'Display name'});nameLabel.htmlFor='dossier-display-name'; + const displayName=document.createElement('input');displayName.id='dossier-display-name';displayName.name='display_name';displayName.maxLength=160;displayName.required=true; + const kindLabel=element('label',{text:'Kind'});kindLabel.htmlFor='dossier-kind'; + const kind=document.createElement('select');kind.id='dossier-kind';kind.name='kind'; + [['PERSON','Person'],['EVENT','Event'],['PLACE','Place'],['THEME','Theme']].forEach(([value,label])=>{const option=document.createElement('option');option.value=value;option.textContent=label;kind.append(option)}); + const submit=element('button',{id:'dossier-submit',text:'Відкрити досьє'});submit.type='submit'; + form.append(idLabel,subjectId,nameLabel,displayName,kindLabel,kind,submit); + form.onsubmit=event=>{event.preventDefault();this.load();}; + + const status=element('div',{id:'dossier-status',className:'sr-status'});status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const resultHeading=element('h3',{id:'dossier-result-heading',text:'Результат'});resultHeading.tabIndex=-1; + const summary=element('p',{id:'dossier-summary',text:'Ще не завантажено.'}); + const table=document.createElement('table');table.id='dossier-table';table.setAttribute('aria-labelledby','dossier-result-heading'); + const caption=element('caption',{text:'Semantic dossier rows from visible canonical evidence'});table.append(caption); + const thead=document.createElement('thead');const tr=document.createElement('tr');['Type','ID','Statement','Provenance'].forEach(text=>{const th=element('th',{text});th.scope='col';tr.append(th)});thead.append(tr); + const tbody=document.createElement('tbody');table.append(thead,tbody); + const linearHeading=element('h3',{id:'dossier-linear-heading',text:'Повний лінійний еквівалент'}); + const linear=element('pre',{id:'dossier-linear'});linear.tabIndex=0;linear.setAttribute('aria-labelledby','dossier-linear-heading');linear.textContent='No cited support available in current scope'; + const back=element('button',{id:'dossier-back',text:'Повернутися на головну'});back.type='button';back.onclick=()=>this.showView('home','home-heading'); + section.append(eyebrow,heading,explanation,safety,form,status,resultHeading,summary,table,linearHeading,linear,back); + main.append(section); + Object.assign(this,{section,heading,form,subjectId,displayName,kind,submit,status,resultHeading,summary,tbody,linear}); + } + + setVisible(visible){ + const next=Boolean(visible); + if(this.visible&&!next){ + this.generation+=1; + this.inFlight=null; + if(this.submit)this.submit.disabled=false; + } + this.visible=next; + } + + open(){ + if(!this.enabled){this.announce?.('Досьє недоступні без канонічного runtime');return;} + this.showView('dossier','dossier-heading'); + setTimeout(()=>this.subjectId?.focus(),0); + } + + request(){ + const subject_id=this.subjectId.value; + const display_name=this.displayName.value; + const kind=this.kind.value; + if(!clean(subject_id,100))throw new Error('Некоректний canonical subject ID'); + if(!clean(display_name,160))throw new Error('Некоректна display name'); + if(!KINDS.has(kind))throw new Error('Некоректний kind'); + return {subject_id,display_name,kind}; + } + + isCurrent(token){ + return this.visible&&this.isActiveView()&&this.generation===token; + } + + async load(){ + if(!this.enabled||this.inFlight!==null)return this.inFlight; + let request; + try{request=this.request();}catch(error){this.status.textContent=error.message;this.announce?.(error.message);return;} + const token=++this.generation; + this.inFlight=token; + this.submit.disabled=true; + this.status.textContent='Завантаження source-safe досьє…'; + try{ + const data=await this.invoke('dossier.get',request); + if(!this.isCurrent(token))return; + const dossier=this.validate(data,request); + this.render(dossier); + this.status.textContent='Досьє оновлено.'; + this.announce?.(`Досьє ${request.display_name} оновлено`); + this.resultHeading.focus(); + }catch(error){ + if(!this.isCurrent(token))return; + this.tbody.replaceChildren();this.summary.textContent='Досьє недоступне.';this.linear.textContent=''; + this.status.textContent=`Помилка досьє: ${error?.message||'невідома помилка'}`; + this.announce?.(this.status.textContent); + }finally{ + if(this.inFlight===token){ + this.inFlight=null; + if(this.submit)this.submit.disabled=false; + } + } + } + + validate(data,request){ + const d=data?.dossier; + if(!d||typeof d!=='object'||d.schema!=='scripture.dossier-view.v1')throw new Error('Некоректна dossier schema'); + if(d.evidence_scope!=='unlocked_only')throw new Error('Досьє порушило unlocked_only scope'); + if(!d.subject||d.subject.subject_id!==request.subject_id||d.subject.display_name!==request.display_name||d.subject.kind!==request.kind)throw new Error('Досьє повернуло інший subject'); + if(typeof d.stated!=='boolean'||typeof d.status_text!=='string'||d.status_text.length>500)throw new Error('Некоректний dossier status'); + if(!Array.isArray(d.rows)||d.rows.length>1000)throw new Error('Некоректні dossier rows'); + if(!Array.isArray(d.linear)||d.linear.length>2000||d.linear.some(line=>typeof line!=='string'||line.length>4000))throw new Error('Некоректний linear equivalent'); + for(const row of d.rows){ + if(!row||typeof row!=='object'||!['EVIDENCE','CLAIM','RELATION'].includes(row.row_type))throw new Error('Некоректний dossier row'); + if(!clean(row.row_id,160)||typeof row.proposition!=='string'||row.proposition.length>4000)throw new Error('Некоректний dossier row content'); + if(![null,'T1','T2','C1','I1','D1'].includes(row.confidence)||typeof row.tx1!=='boolean')throw new Error('Некоректний provenance code'); + if(row.witness!==null&&row.witness!==undefined&&!clean(row.witness,160))throw new Error('Некоректний dossier witness'); + } + return d; + } + + render(d){ + this.tbody.replaceChildren(); + this.summary.textContent=d.status_text; + for(const row of d.rows){ + const tr=document.createElement('tr'); + const provenance=[row.confidence,row.tx1?'TX1':null,row.witness?`witness=${row.witness}`:null,row.source_scope?`scope=${row.source_scope}`:null,row.uncertainty?`uncertainty=${row.uncertainty}`:null].filter(Boolean).join('; ')||'No additional provenance stated'; + [row.row_type,row.row_id,row.proposition,provenance].forEach(text=>tr.append(element('td',{text}))); + this.tbody.append(tr); + } + if(!d.rows.length){const tr=document.createElement('tr');const td=element('td',{text:d.status_text});td.colSpan=4;tr.append(td);this.tbody.append(tr);} + this.linear.textContent=d.linear.join('\n'); + } +} From df94ea95d545a4cf1bd7b3c6735e1bfeef389ad3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:34:52 +0200 Subject: [PATCH 014/125] R06 packaged dossier: harden allowlisted subject contract --- .../transport/contracts.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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 2432b0992..ea43c3ab7 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -5,6 +5,7 @@ MAX_REQUEST_BYTES = 262_144 MAX_IMPORT_BYTES = 2_000_000 +DOSSIER_KINDS = frozenset({"PERSON", "EVENT", "PLACE", "THEME"}) ALLOWLISTED_COMMANDS = frozenset({ "system.bootstrap", @@ -18,7 +19,7 @@ "authoring.validate_draft","authoring.preview_draft","authoring.prepare_publish_candidate", "authoring.export_draft","authoring.import_draft", "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","dossier.get" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -52,6 +53,13 @@ def list_keys(self,namespace:str)->list[str]: ... class TransportAdapterPort(Protocol): def invoke(self,request:dict[str,Any])->dict[str,Any]: ... +def _require_clean_text(value:Any,key:str,max_length:int)->str: + if not isinstance(value,str) or not value or len(value)>max_length or value!=value.strip(): + raise ValueError(f'invalid {key}') + if any(ord(ch)<0x20 or 0x7f<=ord(ch)<=0x9f or ch in {'\u2028','\u2029'} for ch in value): + raise ValueError(f'invalid {key}') + return value + 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') @@ -59,6 +67,13 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: if not isinstance(rid,str) or not rid or len(rid)>128: raise ValueError('invalid request_id') if cmd not in ALLOWLISTED_COMMANDS: raise ValueError('command not allowlisted') if not isinstance(payload,dict): raise ValueError('payload must be an object') + if cmd=='dossier.get': + if set(payload)!={'subject_id','display_name','kind'}: + raise ValueError('dossier.get requires exactly subject_id, display_name and kind') + _require_clean_text(payload.get('subject_id'),'subject_id',100) + _require_clean_text(payload.get('display_name'),'display_name',160) + if payload.get('kind') not in DOSSIER_KINDS: + raise ValueError('invalid dossier kind') if cmd=='player.next': unknown=set(payload)-{'node_id'} if unknown: raise ValueError('player.next accepts only current node_id context; target selection is forbidden') @@ -92,4 +107,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} From a676544ce3ac7b84d9396c67b839f13cabd3a960 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:35:08 +0200 Subject: [PATCH 015/125] R06 packaged dossier: expose locked runtime dossier projection --- .../application/runtime_gateway.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) 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 846465585..79540e0c1 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 @@ -75,6 +75,33 @@ def get_daily_case(self) -> dict[str, Any]: return DailyCaseProjection(self._runtime_application, self._loader).response() + def get_dossier(self, subject_id: str, display_name: str, kind: str) -> dict[str, Any]: + """Project an unlocked-only dossier from this exact runtime instance.""" + if self._runtime_application is None: + raise RuntimeGatewayError("canonical runtime dossier view is unavailable") + with self._runtime_lock: + return build_runtime_dossier(self._runtime_application, subject_id, display_name, kind) + + +def build_runtime_dossier(runtime, subject_id: str, display_name: str, kind: str) -> dict[str, Any]: + """Build an unlocked-only dossier without creating a second evidence truth.""" + from runtime_engine.scripture_archive_runtime.dossiers import ( + DossierAssembler, + DossierKind, + DossierSubject, + ) + + subject = DossierSubject( + subject_id=subject_id, + display_name=display_name, + kind=DossierKind(kind), + ) + view = DossierAssembler(runtime.evidence).build(subject, unlocked_only=True) + dossier = view.to_dict() + dossier["linear"] = list(view.linearize()) + dossier["evidence_scope"] = "unlocked_only" + return {"dossier": dossier} + def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> RuntimeBackedPlayerGateway: """Build the exact D5 runtime against the same canonical repository checkout.""" From 70d8e5911a7d8370ad62cecfe56ae17287c40e0e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:35:45 +0200 Subject: [PATCH 016/125] R06 dossier: require positive canonical witness support --- .../scripture_archive_runtime/dossiers.py | 79 +++++++++---------- 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/dossiers.py b/runtime_engine/scripture_archive_runtime/dossiers.py index 52421410e..4cef458bf 100644 --- a/runtime_engine/scripture_archive_runtime/dossiers.py +++ b/runtime_engine/scripture_archive_runtime/dossiers.py @@ -5,6 +5,11 @@ from typing import Any from .evidence import EvidenceRecord, EvidenceRuntime +from .evidence_provenance import ( + resolve_evidence_witness, + validated_claim_witness, + validated_relation_witness, +) from .models import Confidence @@ -147,8 +152,10 @@ class DossierAssembler: """Build read-only dossier views from explicit EvidenceRuntime truth. The assembler never creates canonical facts. Locked evidence and dependent - claims/relations are omitted from the default player-safe view. Explicit - witness contradictions fail closed rather than being harmonized. + claims/relations are omitted from the default player-safe view. Witness + attribution is delegated to the shared fail-closed provenance validator: + absent, malformed, contradictory, mixed or hidden support never acquires a + declared witness merely because a claim/relation metadata field says so. """ def __init__(self, runtime: EvidenceRuntime): @@ -156,19 +163,14 @@ def __init__(self, runtime: EvidenceRuntime): @staticmethod def _record_witness(record: EvidenceRecord) -> tuple[bool, str | None]: - passage_witnesses = { - passage.witness.strip() - for passage in record.passage_refs - if isinstance(passage.witness, str) and passage.witness.strip() - } - record_witness = record.witness.strip() if isinstance(record.witness, str) and record.witness.strip() else None - if record_witness is not None and any(witness != record_witness for witness in passage_witnesses): + """Distinguish safe witness-less evidence from unsafe witness metadata.""" + has_declared_witness = record.witness is not None or any( + passage.witness is not None for passage in record.passage_refs + ) + resolved = resolve_evidence_witness(record) + if has_declared_witness and resolved is None: return False, None - if record_witness is not None: - return True, record_witness - if len(passage_witnesses) == 1: - return True, next(iter(passage_witnesses)) - return True, None + return True, resolved @staticmethod def _passage_ids(records: tuple[EvidenceRecord, ...]) -> tuple[str, ...]: @@ -196,25 +198,6 @@ def _passage_witnesses(records: tuple[EvidenceRecord, ...]) -> tuple[tuple[str, } return tuple(sorted(refs, key=lambda item: (item[0], item[1] or ""))) - @staticmethod - def _declared_witness_matches_support( - declared_witness: str | None, - records: tuple[EvidenceRecord, ...], - ) -> bool: - if not isinstance(declared_witness, str) or not declared_witness.strip(): - return True - declared = declared_witness.strip() - for record in records: - safe, effective = DossierAssembler._record_witness(record) - if not safe: - return False - if effective is not None and effective != declared: - return False - for passage in record.passage_refs: - if isinstance(passage.witness, str) and passage.witness.strip() and passage.witness.strip() != declared: - return False - return True - def build( self, subject: DossierSubject, @@ -269,8 +252,15 @@ def build( if any(evidence_id not in visible_evidence_ids for evidence_id in required): continue required_records = tuple(self.runtime.evidence[evidence_id] for evidence_id in required) - if not self._declared_witness_matches_support(claim.witness, required_records): - continue + claim_witness = None + if claim.witness is not None: + claim_witness = validated_claim_witness( + self.runtime, + claim, + visible_evidence_ids=visible_evidence_ids, + ) + if claim_witness is None: + continue rows.append( DossierRow( row_type="CLAIM", @@ -278,7 +268,7 @@ def build( proposition=claim.proposition, confidence=claim.confidence, tx1=claim.tx1, - witness=claim.witness, + witness=claim_witness, source_scope=claim.source_scope, uncertainty=claim.uncertainty, passage_ids=self._passage_ids(required_records), @@ -297,8 +287,17 @@ def build( ) if unlocked_only and not support: continue - if support and not self._declared_witness_matches_support(relation.witness, support): - continue + support_ids = tuple(sorted(record.evidence_id for record in support)) + relation_witness = None + if relation.witness is not None: + relation_witness = validated_relation_witness( + self.runtime, + relation, + support_ids, + visible_evidence_ids=visible_evidence_ids, + ) + if relation_witness is None: + continue related_id = relation.target_id if relation.source_id == subject.subject_id else relation.source_id if unlocked_only and related_id in self.runtime.evidence and related_id not in visible_evidence_ids: continue @@ -314,10 +313,10 @@ def build( row_type="RELATION", row_id=relation.relation_id, proposition=f"{subject.subject_id} {relation.relation_type} {related_id}", - witness=relation.witness, + witness=relation_witness, passage_ids=tuple(sorted(set(relation_passages).union(support_passages))), passage_witnesses=self._passage_witnesses(support), - evidence_ids=tuple(sorted(record.evidence_id for record in support)), + evidence_ids=support_ids, relation_type=relation.relation_type, related_id=related_id, ) From c38f2af8e2f55df717a107f2bce647522e322158 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:36:29 +0200 Subject: [PATCH 017/125] R06 packaged dossier: compose runtime projection into app service --- .../application/service.py | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) 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 334e134f4..d0b49b8ce 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -54,6 +54,7 @@ def _dispatch(self,cmd,p): return self._daily_case() if cmd=='player.save_checkpoint':return self._save_checkpoint(p) if cmd=='player.restore_checkpoint':return self._restore_checkpoint() + if cmd=='dossier.get':return self._dossier(p) if cmd=='authoring.list_drafts':return {'drafts':self.authoring.list_drafts()} if cmd=='authoring.new_draft':return {'draft':self.authoring.new_draft(str(p.get('title') or 'Нова чернетка'),str(p.get('kind') or 'node'))} if cmd=='authoring.new_node_from_task_type':return {'draft':self.authoring.new_node_from_task_type(str(p.get('title') or 'Нова чернетка'),self._id(p,'task_type'))} @@ -85,7 +86,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,'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,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'dossiers':bool(self.player_gateway and hasattr(self.player_gateway,'get_dossier')),'runtime_truth':bool(self.player_gateway),'review_queue':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 @@ -123,6 +124,34 @@ def _review_queue(self): def _daily_case(self): if not self.player_gateway:raise ValueError('Daily Case requires canonical runtime') return self.player_gateway.get_daily_case() + def _dossier(self,p): + if not self.player_gateway or not hasattr(self.player_gateway,'get_dossier'): + raise ValueError('dossier requires canonical runtime') + subject_id=p['subject_id']; display_name=p['display_name']; kind=p['kind'] + data=self.player_gateway.get_dossier(subject_id,display_name,kind) + dossier=data.get('dossier') if isinstance(data,dict) else None + if not isinstance(dossier,dict):raise ValueError('runtime dossier must be object') + if dossier.get('schema')!='scripture.dossier-view.v1':raise ValueError('unexpected dossier schema') + if dossier.get('evidence_scope')!='unlocked_only':raise ValueError('packaged dossier must remain unlocked_only') + subject=dossier.get('subject') + if not isinstance(subject,dict) or subject!={'subject_id':subject_id,'kind':kind,'display_name':display_name}: + raise ValueError('runtime dossier subject mismatch') + if type(dossier.get('stated')) is not bool:raise ValueError('runtime dossier stated must be boolean') + if not isinstance(dossier.get('status_text'),str) or len(dossier['status_text'])>500:raise ValueError('invalid dossier status_text') + rows=dossier.get('rows'); linear=dossier.get('linear') + if not isinstance(rows,list) or len(rows)>1000:raise ValueError('invalid dossier rows') + if not isinstance(linear,list) or len(linear)>2000 or any(not isinstance(line,str) or len(line)>4000 for line in linear):raise ValueError('invalid dossier linear representation') + for row in rows: + if not isinstance(row,dict):raise ValueError('invalid dossier row') + if row.get('row_type') not in {'EVIDENCE','CLAIM','RELATION'}:raise ValueError('invalid dossier row type') + if not isinstance(row.get('row_id'),str) or not row['row_id'] or len(row['row_id'])>160:raise ValueError('invalid dossier row id') + if not isinstance(row.get('proposition'),str) or len(row['proposition'])>4000:raise ValueError('invalid dossier proposition') + if row.get('confidence') not in {None,'T1','T2','C1','I1','D1'}:raise ValueError('invalid dossier confidence') + if type(row.get('tx1')) is not bool:raise ValueError('invalid dossier TX1 flag') + for key in ('passage_ids','evidence_ids'): + values=row.get(key) + if not isinstance(values,list) or len(values)>500 or any(not isinstance(value,str) or not value or len(value)>200 for value in values):raise ValueError(f'invalid dossier {key}') + return {'dossier':dossier,'truth_owner':'D5/runtime'} def _save_checkpoint(self,p): checkpoint={'campaign_id':p.get('campaign_id'),'mission_id':p.get('mission_id'),'node_id':p.get('node_id'),'saved_at':int(time.time()),'checkpoint_schema':'scripture.player.checkpoint.v1'} if self.player_gateway:self.player_gateway.invoke('player.save_checkpoint',{},request_id='save-'+str(p.get('node_id') or 'current')) @@ -155,4 +184,4 @@ def build_default_application(repo_root:Path|None=None,store_root:Path|None=None 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 PlatformApplication(repo_root,store=effective_store,player_gateway=gateway) - return PlatformApplication(repo_root,store=effective_store) \ No newline at end of file + return PlatformApplication(repo_root,store=effective_store) From e9e71e12b79ae93a3c6aae73afe2e3a437793018 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:37:04 +0200 Subject: [PATCH 018/125] R06 packaged dossier: compose view into current app shell --- lanes/dev1/repair_overlay/frontend/app.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/app.js b/lanes/dev1/repair_overlay/frontend/app.js index 3706199f5..3006dbec0 100644 --- a/lanes/dev1/repair_overlay/frontend/app.js +++ b/lanes/dev1/repair_overlay/frontend/app.js @@ -1,8 +1,8 @@ -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 {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','authoring']; +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 {DossierUI} from './dossier-ui.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','dossier','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 showView(name,focusId){views.forEach(v=>$(`${v}-view`).classList.toggle('hidden',v!==name));activeView=name;if(focusId)setTimeout(()=>$(`${focusId}`)?.focus(),0)} +function showView(name,focusId){dossier?.setVisible(name==='dossier');views.forEach(v=>$(`${v}-view`)?.classList.toggle('hidden',v!==name));activeView=name;if(focusId)setTimeout(()=>$(`${focusId}`)?.focus(),0)} function badge(text){const s=document.createElement('span');s.className='status-badge';s.textContent=text;return s} 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 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')} @@ -14,7 +14,7 @@ async function submit(e){e?.preventDefault();if(!currentTask||!getAnswer)return; 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');$('hint-heading').focus();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);$('evidence-heading').focus();announce('Докази відкрито')} -function openResearch(){const from=activeView==='research'?researchReturn.view:activeView;const focus=from==='player'?'research-current':from==='mission'?'mission-back':from==='authoring'?'authoring-heading':'nav-research';researchReturn={view:from,focus};research?.setContext({task:currentTask,mission:currentMission});research?.refreshPersistence();showView('research','research-heading');announce(currentTask?`Відкрито дослідження ${currentTask.node_id}`:'Відкрито дослідницький простір')} +function openResearch(){const from=activeView==='research'?researchReturn.view:activeView;const focus=from==='player'?'research-current':from==='mission'?'mission-back':from==='authoring'?'authoring-heading':from==='dossier'?'nav-dossier':'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)} @@ -36,7 +36,7 @@ function createActionRegistry(){return new ActionRegistry([ {id:'app.command_palette',label:'Палітра команд',description:'Знайти доступну команду з клавіатури',group:'Навігація',keywords:['команди','palette'],isAvailable:()=>Boolean(palette),handler:()=>palette?.open()}, ])} function executeAction(id){return actions?.execute(id)??false} -let dispatcher,authoring,keymap,research,nextGate,actions,palette,jsonMode=''; +let dispatcher,authoring,keymap,research,dossier,nextGate,actions,palette,jsonMode=''; function setupJsonDialog(){document.addEventListener('scripture-json-dialog',e=>{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='';$('json-dialog').showModal()});$('import-draft').onclick=()=>{jsonMode='draft-import';$('json-text').readOnly=false;$('json-text').value='';$('json-commit').classList.remove('hidden');$('json-dialog').showModal();$('json-text').focus()};$('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});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('Помилка запуску платформи')}} +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});dossier=new DossierUI({invoke:api,announce,showView,isActiveView:()=>activeView==='dossier',enabled:Boolean(bootstrap.capabilities?.dossiers)});dossier.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); From 4b2840d72e8413510d3df479e3841617fbe51982 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:37:28 +0200 Subject: [PATCH 019/125] R06 packaged dossier: add composition and input regressions --- .../tests/test_dossier_composition.py | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_dossier_composition.py diff --git a/lanes/dev1/repair_overlay/tests/test_dossier_composition.py b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py new file mode 100644 index 000000000..8f5e540d1 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py @@ -0,0 +1,120 @@ +import unittest + +from scripture_archive_platform.application.runtime_gateway import build_runtime_dossier +from scripture_archive_platform.application.service import PlatformApplication +from scripture_archive_platform.transport.contracts import validate_request_shape +from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime +from scripture_archive_runtime.models import Confidence + + +def safe_dossier(subject_id="PERSON:PAUL", display_name="Paul", kind="PERSON"): + return { + "dossier": { + "schema": "scripture.dossier-view.v1", + "subject": { + "subject_id": subject_id, + "kind": kind, + "display_name": display_name, + }, + "stated": False, + "status_text": "No cited support available in current scope", + "rows": [], + "linear": [ + f"Dossier {kind} {subject_id}: {display_name}", + "No cited support available in current scope", + ], + "evidence_scope": "unlocked_only", + } + } + + +class FakeGateway: + def __init__(self, data=None): + self.data = data if data is not None else safe_dossier() + + def get_dossier(self, subject_id, display_name, kind): + return self.data + + +class DossierCompositionTests(unittest.TestCase): + def test_transport_requires_exact_bounded_control_safe_subject(self): + request = { + "api_version": "scripture.transport.v1", + "request_id": "dossier-1", + "command": "dossier.get", + "payload": {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}, + } + rid, command, payload = validate_request_shape(request) + self.assertEqual((rid, command), ("dossier-1", "dossier.get")) + self.assertEqual(payload, request["payload"]) + + bad_payloads = ( + {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON", "path": "../x"}, + {"subject_id": " PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul\nInjected", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL\u0085X", "display_name": "Paul", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul\u2028Injected", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul\u2029Injected", "kind": "PERSON"}, + {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "BIOGRAPHY"}, + ) + for payload in bad_payloads: + with self.subTest(payload=payload): + with self.assertRaises(ValueError): + validate_request_shape({**request, "payload": payload}) + + def test_platform_attests_scope_subject_and_schema(self): + app = object.__new__(PlatformApplication) + app.player_gateway = FakeGateway() + request = {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"} + result = app._dossier(request) + self.assertEqual(result["truth_owner"], "D5/runtime") + self.assertEqual(result["dossier"]["evidence_scope"], "unlocked_only") + + widened = safe_dossier() + widened["dossier"]["evidence_scope"] = "all_runtime_evidence" + app.player_gateway = FakeGateway(widened) + with self.assertRaises(ValueError): + app._dossier(request) + + substituted = safe_dossier(subject_id="PERSON:OTHER") + app.player_gateway = FakeGateway(substituted) + with self.assertRaises(ValueError): + app._dossier(request) + + def test_packaged_helper_uses_same_runtime_and_hides_locked_dependencies(self): + evidence = EvidenceRuntime() + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-VISIBLE", + passage_refs=(), + proposition="Visible canonical proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-LOCKED", + passage_refs=(), + proposition="Locked proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_claim(Claim( + claim_id="CL-LOCKED", + proposition="Claim needing locked evidence", + confidence=Confidence.T2, + required_evidence_ids=("EV-VISIBLE", "EV-LOCKED"), + )) + evidence.unlock("EV-VISIBLE") + runtime = type("Runtime", (), {"evidence": evidence})() + + packaged = build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON")["dossier"] + self.assertEqual(packaged["evidence_scope"], "unlocked_only") + self.assertEqual([row["row_id"] for row in packaged["rows"]], ["EV-VISIBLE"]) + rendered = "\n".join(packaged["linear"]) + self.assertIn("EV-VISIBLE", rendered) + self.assertNotIn("EV-LOCKED", rendered) + self.assertNotIn("CL-LOCKED", rendered) + self.assertNotIn("Locked proposition", rendered) + + +if __name__ == "__main__": + unittest.main() From 3585a4c7cf005df70fd581b1212af0d46d5b9efa Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:37:57 +0200 Subject: [PATCH 020/125] R06 packaged dossier: add deferred lifecycle regression --- .../repair_overlay/tests/test_dossier_ui.py | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_dossier_ui.py diff --git a/lanes/dev1/repair_overlay/tests/test_dossier_ui.py b/lanes/dev1/repair_overlay/tests/test_dossier_ui.py new file mode 100644 index 000000000..1e5680b90 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_dossier_ui.py @@ -0,0 +1,146 @@ +from pathlib import Path +import shutil +import subprocess +import textwrap +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +FRONTEND = ROOT / "frontend" + + +class DossierUiContractTests(unittest.TestCase): + def test_dossier_ui_is_reachable_and_uses_only_allowlisted_query(self): + app = (FRONTEND / "app.js").read_text(encoding="utf-8") + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("DossierUI", app) + self.assertIn("'dossier'", app) + self.assertIn("bootstrap.capabilities?.dossiers", app) + self.assertIn("this.invoke('dossier.get',request)", ui) + for forbidden in ("include_locked", "filesystem", "shell", "eval(", "fetch("): + self.assertNotIn(forbidden, ui) + + def test_untrusted_runtime_strings_are_text_only(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("node.textContent=text", ui) + self.assertIn("this.linear.textContent=d.linear.join", ui) + self.assertNotIn("innerHTML", ui) + self.assertNotIn("insertAdjacentHTML", ui) + self.assertNotIn("document.write", ui) + + def test_keyboard_labels_live_status_focus_and_linear_equivalent_are_explicit(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + for token in ( + "heading.tabIndex=-1", + "resultHeading.tabIndex=-1", + "linear.tabIndex=0", + "aria-live", + "idLabel.htmlFor='dossier-subject-id'", + "nameLabel.htmlFor='dossier-display-name'", + "kindLabel.htmlFor='dossier-kind'", + "Повний лінійний еквівалент", + "No cited support available in current scope", + ): + self.assertIn(token, ui) + + def test_client_rejects_scope_subject_schema_and_oversize_results(self): + ui = (FRONTEND / "dossier-ui.js").read_text(encoding="utf-8") + self.assertIn("d.schema!=='scripture.dossier-view.v1'", ui) + self.assertIn("d.evidence_scope!=='unlocked_only'", ui) + self.assertIn("d.subject.subject_id!==request.subject_id", ui) + self.assertIn("d.rows.length>1000", ui) + self.assertIn("d.linear.length>2000", ui) + self.assertIn("code>=0x7f&&code<=0x9f", ui) + self.assertIn("code===0x2028||code===0x2029", ui) + + @unittest.skipUnless(shutil.which("node"), "node is required for executable Dossier UI lifecycle regression") + def test_late_completion_is_inert_after_leave_and_after_reopen(self): + script = textwrap.dedent( + r""" + import {readFileSync} from 'node:fs'; + const source=readFileSync(process.argv[1],'utf8'); + const moduleUrl='data:text/javascript;base64,'+Buffer.from(source).toString('base64'); + const {DossierUI}=await import(moduleUrl); + + const resolvers=[]; + const announcements=[]; + const renders=[]; + let focusCount=0; + let active=true; + const invoke=(_command,_request)=>new Promise(resolve=>resolvers.push(resolve)); + const ui=new DossierUI({ + invoke, + announce:text=>announcements.push(text), + showView:()=>{}, + isActiveView:()=>active, + enabled:true, + }); + Object.assign(ui,{ + subjectId:{value:'PERSON:PAUL'}, + displayName:{value:'Paul'}, + kind:{value:'PERSON'}, + submit:{disabled:false}, + status:{textContent:''}, + tbody:{replaceChildren(){}}, + summary:{textContent:''}, + linear:{textContent:''}, + resultHeading:{focus(){focusCount+=1;}}, + }); + ui.render=d=>renders.push(d.subject.display_name); + const response=name=>({dossier:{ + schema:'scripture.dossier-view.v1', + subject:{subject_id:name==='Peter'?'PERSON:PETER':'PERSON:PAUL',display_name:name,kind:'PERSON'}, + stated:false, + status_text:'No cited support available in current scope', + rows:[], + linear:['No cited support available in current scope'], + evidence_scope:'unlocked_only', + }}); + const assert=(condition,message)=>{if(!condition)throw new Error(message);}; + + ui.setVisible(true); + const left=ui.load(); + assert(resolvers.length===1,'first request did not start'); + active=false; + ui.setVisible(false); + resolvers[0](response('Paul')); + await left; + assert(renders.length===0,'late completion rendered after leave'); + assert(announcements.length===0,'late completion announced after leave'); + assert(focusCount===0,'late completion moved focus after leave'); + + active=true; + ui.setVisible(true); + ui.subjectId.value='PERSON:PAUL';ui.displayName.value='Paul'; + const oldRequest=ui.load(); + assert(resolvers.length===2,'old request did not start'); + active=false; + ui.setVisible(false); + active=true; + ui.setVisible(true); + ui.subjectId.value='PERSON:PETER';ui.displayName.value='Peter'; + const newRequest=ui.load(); + assert(resolvers.length===3,'reopen was blocked by stale promise'); + resolvers[1](response('Paul')); + await oldRequest; + assert(renders.length===0,'old request rendered into reopened view'); + assert(announcements.length===0,'old request announced into reopened view'); + assert(focusCount===0,'old request moved focus in reopened view'); + resolvers[2](response('Peter')); + await newRequest; + assert(renders.length===1&&renders[0]==='Peter','new request did not exclusively render'); + assert(announcements.length===1,'new request announcement missing or duplicated'); + assert(focusCount===1,'new request focus transition missing or duplicated'); + """ + ) + result = subprocess.run( + [shutil.which("node"), "--input-type=module", "-e", script, str(FRONTEND / "dossier-ui.js")], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr or result.stdout) + + +if __name__ == "__main__": + unittest.main() From eb9978dc632cffc42291f703052d543bf4855d01 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:38:12 +0200 Subject: [PATCH 021/125] R06 dossier: add witnessless support fail-closed regression --- .../tests/test_dossier_witness_regressions.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 runtime_engine/tests/test_dossier_witness_regressions.py diff --git a/runtime_engine/tests/test_dossier_witness_regressions.py b/runtime_engine/tests/test_dossier_witness_regressions.py new file mode 100644 index 000000000..526e0d289 --- /dev/null +++ b/runtime_engine/tests/test_dossier_witness_regressions.py @@ -0,0 +1,53 @@ +import unittest + +from scripture_archive_runtime.dossiers import DossierAssembler, DossierKind, DossierSubject +from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime, Relation +from scripture_archive_runtime.models import Confidence + + +class DossierWitnessRegressionTests(unittest.TestCase): + def test_declared_claim_and_relation_witness_require_positive_visible_support(self): + runtime = EvidenceRuntime() + runtime.add_evidence( + EvidenceRecord( + evidence_id="EV-WITNESSLESS", + passage_refs=(), + proposition="Canonical proposition with no witness attribution.", + confidence=Confidence.T1, + entity_ids=("PERSON-X",), + relation_ids=("REL-WITNESSLESS",), + ) + ) + runtime.add_claim( + Claim( + claim_id="CLAIM-WITNESSLESS", + proposition="A declared witness must not be borrowed from metadata alone.", + confidence=Confidence.T2, + required_evidence_ids=("EV-WITNESSLESS",), + witness="Luke", + ) + ) + runtime.add_relation( + Relation( + relation_id="REL-WITNESSLESS", + source_id="PERSON-X", + relation_type="appears_in", + target_id="EVENT-X", + witness="Luke", + ) + ) + runtime.unlock("EV-WITNESSLESS") + + view = DossierAssembler(runtime).build( + DossierSubject("PERSON-X", DossierKind.PERSON, "X") + ) + ids = [row.row_id for row in view.rows] + self.assertIn("EV-WITNESSLESS", ids) + self.assertNotIn("CLAIM-WITNESSLESS", ids) + self.assertNotIn("REL-WITNESSLESS", ids) + rendered = "\n".join(view.linearize()) + self.assertNotIn("witness=Luke", rendered) + + +if __name__ == "__main__": + unittest.main() From 3520ceef1b8287de03e9cb544e3b715b761330bf Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 14:39:43 +0200 Subject: [PATCH 022/125] R06 dossier: run packaged regressions in cross-OS integration CI --- .../test_packaged_dossier_integration.py | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 runtime_engine/tests/test_packaged_dossier_integration.py diff --git a/runtime_engine/tests/test_packaged_dossier_integration.py b/runtime_engine/tests/test_packaged_dossier_integration.py new file mode 100644 index 000000000..12503d5fa --- /dev/null +++ b/runtime_engine/tests/test_packaged_dossier_integration.py @@ -0,0 +1,101 @@ +from pathlib import Path +import shutil +import subprocess +import sys +import textwrap +import unittest + + +REPO_ROOT = Path(__file__).resolve().parents[2] +PLATFORM_ROOT = REPO_ROOT / "lanes" / "dev1" / "repair_overlay" +if str(PLATFORM_ROOT) not in sys.path: + sys.path.insert(0, str(PLATFORM_ROOT)) + +from scripture_archive_platform.application.service import PlatformApplication +from scripture_archive_platform.transport.contracts import validate_request_shape + + +class FakeGateway: + def get_dossier(self, subject_id, display_name, kind): + return { + "dossier": { + "schema": "scripture.dossier-view.v1", + "subject": {"subject_id": subject_id, "display_name": display_name, "kind": kind}, + "stated": False, + "status_text": "No cited support available in current scope", + "rows": [], + "linear": ["No cited support available in current scope"], + "evidence_scope": "unlocked_only", + } + } + + +class PackagedDossierIntegrationTests(unittest.TestCase): + def test_allowlisted_contract_rejects_extended_control_separators(self): + request = { + "api_version": "scripture.transport.v1", + "request_id": "dossier-ci", + "command": "dossier.get", + "payload": {"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}, + } + self.assertEqual(validate_request_shape(request)[1], "dossier.get") + for key, bad in ( + ("subject_id", "PERSON:PAUL\u0085X"), + ("display_name", "Paul\u2028Injected"), + ("display_name", "Paul\u2029Injected"), + ): + payload = dict(request["payload"]) + payload[key] = bad + with self.subTest(key=key, bad=repr(bad)): + with self.assertRaises(ValueError): + validate_request_shape({**request, "payload": payload}) + + def test_platform_dossier_attests_exact_runtime_subject_and_unlocked_scope(self): + app = object.__new__(PlatformApplication) + app.player_gateway = FakeGateway() + result = app._dossier({"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}) + self.assertEqual(result["truth_owner"], "D5/runtime") + self.assertEqual(result["dossier"]["evidence_scope"], "unlocked_only") + self.assertEqual(result["dossier"]["subject"]["subject_id"], "PERSON:PAUL") + + def test_deferred_ui_completion_is_inert_after_leave_and_reopen(self): + node = shutil.which("node") + self.assertIsNotNone(node, "hosted integration runner must expose Node for executable WebView module regression") + ui_path = PLATFORM_ROOT / "frontend" / "dossier-ui.js" + script = textwrap.dedent( + r""" + import {readFileSync} from 'node:fs'; + const source=readFileSync(process.argv[1],'utf8'); + const {DossierUI}=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64')); + const resolvers=[];const announcements=[];const renders=[];let focusCount=0;let active=true; + const ui=new DossierUI({invoke:()=>new Promise(resolve=>resolvers.push(resolve)),announce:text=>announcements.push(text),showView:()=>{},isActiveView:()=>active,enabled:true}); + Object.assign(ui,{subjectId:{value:'PERSON:PAUL'},displayName:{value:'Paul'},kind:{value:'PERSON'},submit:{disabled:false},status:{textContent:''},tbody:{replaceChildren(){}},summary:{textContent:''},linear:{textContent:''},resultHeading:{focus(){focusCount+=1;}}}); + ui.render=d=>renders.push(d.subject.display_name); + const response=(id,name)=>({dossier:{schema:'scripture.dossier-view.v1',subject:{subject_id:id,display_name:name,kind:'PERSON'},stated:false,status_text:'No cited support available in current scope',rows:[],linear:['No cited support available in current scope'],evidence_scope:'unlocked_only'}}); + const assert=(value,message)=>{if(!value)throw new Error(message);}; + + ui.setVisible(true);const first=ui.load();assert(resolvers.length===1,'first request missing'); + active=false;ui.setVisible(false);resolvers[0](response('PERSON:PAUL','Paul'));await first; + assert(renders.length===0&&announcements.length===0&&focusCount===0,'late leave completion was not inert'); + + active=true;ui.setVisible(true);const old=ui.load();assert(resolvers.length===2,'old reopen request missing'); + active=false;ui.setVisible(false);active=true;ui.setVisible(true);ui.subjectId.value='PERSON:PETER';ui.displayName.value='Peter'; + const fresh=ui.load();assert(resolvers.length===3,'fresh request blocked by stale promise'); + resolvers[1](response('PERSON:PAUL','Paul'));await old; + assert(renders.length===0&&announcements.length===0&&focusCount===0,'old completion mutated reopened view'); + resolvers[2](response('PERSON:PETER','Peter'));await fresh; + assert(renders.length===1&&renders[0]==='Peter','fresh completion did not exclusively render'); + assert(announcements.length===1&&focusCount===1,'fresh completion accessibility effects incorrect'); + """ + ) + result = subprocess.run( + [node, "--input-type=module", "-e", script, str(ui_path)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr or result.stdout) + + +if __name__ == "__main__": + unittest.main() From 97ebe7b56985eedf2f35cefc30ebec746a0f99ad Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 15:04:16 +0200 Subject: [PATCH 023/125] test: fix packaged dossier cross-root qualification import --- runtime_engine/tests/test_packaged_dossier_integration.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/runtime_engine/tests/test_packaged_dossier_integration.py b/runtime_engine/tests/test_packaged_dossier_integration.py index 12503d5fa..876ab3d3b 100644 --- a/runtime_engine/tests/test_packaged_dossier_integration.py +++ b/runtime_engine/tests/test_packaged_dossier_integration.py @@ -8,6 +8,8 @@ REPO_ROOT = Path(__file__).resolve().parents[2] PLATFORM_ROOT = REPO_ROOT / "lanes" / "dev1" / "repair_overlay" +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) if str(PLATFORM_ROOT) not in sys.path: sys.path.insert(0, str(PLATFORM_ROOT)) From 8eeb89ed1066e5b6603c1739bf655d44d6719242 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 15:28:30 +0200 Subject: [PATCH 024/125] R06: isolate Dossier runtime regression from partial DEV1 overlay --- .../test_packaged_dossier_integration.py | 66 ++++++++++++------- 1 file changed, 43 insertions(+), 23 deletions(-) diff --git a/runtime_engine/tests/test_packaged_dossier_integration.py b/runtime_engine/tests/test_packaged_dossier_integration.py index 876ab3d3b..81cc99af6 100644 --- a/runtime_engine/tests/test_packaged_dossier_integration.py +++ b/runtime_engine/tests/test_packaged_dossier_integration.py @@ -13,23 +13,17 @@ if str(PLATFORM_ROOT) not in sys.path: sys.path.insert(0, str(PLATFORM_ROOT)) -from scripture_archive_platform.application.service import PlatformApplication +# This runtime-level suite may import only self-contained repair-overlay modules. +# PlatformApplication depends on the immutable DEV1 base package, which is restored +# only by r06-dev1-platform.yml before the overlay is applied. Its real composition +# and output-attestation regression therefore lives in +# lanes/dev1/repair_overlay/tests/test_dossier_composition.py, where that topology +# exists. Importing PlatformApplication directly from the partial overlay here makes +# unrelated runtime workflows fail before exercising any Dossier production bytes. +from scripture_archive_platform.application.runtime_gateway import build_runtime_dossier from scripture_archive_platform.transport.contracts import validate_request_shape - - -class FakeGateway: - def get_dossier(self, subject_id, display_name, kind): - return { - "dossier": { - "schema": "scripture.dossier-view.v1", - "subject": {"subject_id": subject_id, "display_name": display_name, "kind": kind}, - "stated": False, - "status_text": "No cited support available in current scope", - "rows": [], - "linear": ["No cited support available in current scope"], - "evidence_scope": "unlocked_only", - } - } +from runtime_engine.scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime +from runtime_engine.scripture_archive_runtime.models import Confidence class PackagedDossierIntegrationTests(unittest.TestCase): @@ -52,13 +46,39 @@ def test_allowlisted_contract_rejects_extended_control_separators(self): with self.assertRaises(ValueError): validate_request_shape({**request, "payload": payload}) - def test_platform_dossier_attests_exact_runtime_subject_and_unlocked_scope(self): - app = object.__new__(PlatformApplication) - app.player_gateway = FakeGateway() - result = app._dossier({"subject_id": "PERSON:PAUL", "display_name": "Paul", "kind": "PERSON"}) - self.assertEqual(result["truth_owner"], "D5/runtime") - self.assertEqual(result["dossier"]["evidence_scope"], "unlocked_only") - self.assertEqual(result["dossier"]["subject"]["subject_id"], "PERSON:PAUL") + def test_runtime_projection_stays_unlocked_only_and_hides_locked_dependencies(self): + evidence = EvidenceRuntime() + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-VISIBLE", + passage_refs=(), + proposition="Visible canonical proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_evidence(EvidenceRecord( + evidence_id="EV-LOCKED", + passage_refs=(), + proposition="Locked proposition", + confidence=Confidence.T1, + entity_ids=("PERSON:PAUL",), + )) + evidence.add_claim(Claim( + claim_id="CL-LOCKED", + proposition="Claim needing locked evidence", + confidence=Confidence.T2, + required_evidence_ids=("EV-VISIBLE", "EV-LOCKED"), + )) + evidence.unlock("EV-VISIBLE") + runtime = type("Runtime", (), {"evidence": evidence})() + + dossier = build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON")["dossier"] + self.assertEqual(dossier["evidence_scope"], "unlocked_only") + self.assertEqual([row["row_id"] for row in dossier["rows"]], ["EV-VISIBLE"]) + rendered = "\n".join(dossier["linear"]) + self.assertIn("EV-VISIBLE", rendered) + self.assertNotIn("EV-LOCKED", rendered) + self.assertNotIn("CL-LOCKED", rendered) + self.assertNotIn("Locked proposition", rendered) def test_deferred_ui_completion_is_inert_after_leave_and_reopen(self): node = shutil.which("node") From 2842c07dde5e32dc0d6d57de99581772ad284f76 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:29:10 +0200 Subject: [PATCH 025/125] R06: add packaged OT-NT source-safe projection --- .../application/cross_testament_projection.py | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py new file mode 100644 index 000000000..b3348114f --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from collections.abc import Mapping +import unicodedata + +from runtime_engine.scripture_archive_runtime.cross_testament import project_cross_testament +from runtime_engine.scripture_archive_runtime.evidence import EvidenceRuntime + + +SCHEMA = "scripture.research.cross-testament.v1" +MAX_LINKS = 512 +MAX_LINEAR_LINES = 4096 +MAX_LIST_ITEMS = 1024 +MAX_TEXT = 512 + +_OT_BOOKS = ( + "Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy", "Joshua", "Judges", "Ruth", + "1 Samuel", "2 Samuel", "1 Kings", "2 Kings", "1 Chronicles", "2 Chronicles", "Ezra", "Nehemiah", + "Esther", "Job", "Psalms", "Proverbs", "Ecclesiastes", "Song of Songs", "Isaiah", "Jeremiah", + "Lamentations", "Ezekiel", "Daniel", "Hosea", "Joel", "Amos", "Obadiah", "Jonah", "Micah", "Nahum", + "Habakkuk", "Zephaniah", "Haggai", "Zechariah", "Malachi", +) +_NT_BOOKS = ( + "Matthew", "Mark", "Luke", "John", "Acts", "Romans", "1 Corinthians", "2 Corinthians", "Galatians", + "Ephesians", "Philippians", "Colossians", "1 Thessalonians", "2 Thessalonians", "1 Timothy", "2 Timothy", + "Titus", "Philemon", "Hebrews", "James", "1 Peter", "2 Peter", "1 John", "2 John", "3 John", "Jude", + "Revelation", +) +BOOK_TESTAMENTS: Mapping[str, str] = { + **{book: "OT" for book in _OT_BOOKS}, + **{book: "NT" for book in _NT_BOOKS}, +} + + +def _bounded_text(value: str, field: str) -> None: + if not isinstance(value, str): + raise ValueError(f"{field} must be text") + if len(value) > MAX_TEXT: + raise ValueError(f"{field} exceeds packaged text bound") + if any( + unicodedata.category(character).startswith("C") + or character in {"\u2028", "\u2029"} + for character in value + ): + raise ValueError(f"{field} contains unsafe Unicode control text") + + +def _validate_value(value: object, field: str, *, depth: int = 0) -> None: + if depth > 8: + raise ValueError(f"{field} exceeds packaged nesting bound") + if isinstance(value, str): + _bounded_text(value, field) + return + if value is None or isinstance(value, (bool, int)): + return + if isinstance(value, list): + if len(value) > MAX_LIST_ITEMS: + raise ValueError(f"{field} exceeds packaged list bound") + for index, item in enumerate(value): + _validate_value(item, f"{field}[{index}]", depth=depth + 1) + return + if isinstance(value, dict): + if len(value) > 64: + raise ValueError(f"{field} exceeds packaged object bound") + for key, item in value.items(): + _bounded_text(key, f"{field}.key") + _validate_value(item, f"{field}.{key}", depth=depth + 1) + return + raise ValueError(f"{field} contains unsupported packaged value") + + +def project_packaged_cross_testament(runtime: EvidenceRuntime) -> dict[str, object]: + """Return the bounded read-only OT↔NT projection used by the packaged app. + + Testament classification is an explicit allowlist. The canonical runtime owns + relation truth and provenance; this boundary never synthesizes links from + topics, entities, chronology, or prose similarity. + """ + projection = project_cross_testament( + runtime, + book_testaments=BOOK_TESTAMENTS, + unlocked_only=True, + ) + structured = projection.to_dict() + links = structured.get("links") + if not isinstance(links, list) or len(links) > MAX_LINKS: + raise ValueError("Cross-Testament link count exceeds packaged bound") + linear = projection.linearize() + if len(linear) > MAX_LINEAR_LINES: + raise ValueError("Cross-Testament linear view exceeds packaged bound") + _validate_value(structured, "cross_testament") + _validate_value(linear, "cross_testament.linear") + return { + "schema": SCHEMA, + "projection_schema": structured["schema"], + "status": structured["status"], + "links": links, + "linear": linear, + "read_only": True, + "evidence_scope": "unlocked_only", + "truth_owner": "D5/runtime", + } From d5fb2f507daf5ec3dbe14ac7ede41e7dcabb63c3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:29:30 +0200 Subject: [PATCH 026/125] R06: expose packaged OT-NT runtime projection --- .../application/runtime_gateway.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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 1dd9163f2..ab4534b92 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 @@ -133,6 +133,15 @@ def get_witness_matrix(self) -> dict[str, Any]: "truth_owner": "D5/runtime", } + def get_cross_testament(self) -> dict[str, Any]: + """Project explicit source-backed OT↔NT links from canonical unlocked evidence.""" + if self._runtime_application is None: + raise RuntimeGatewayError("Cross-Testament requires the canonical runtime application") + from scripture_archive_platform.application.cross_testament_projection import project_packaged_cross_testament + + with self._runtime_lock: + return project_packaged_cross_testament(self._runtime_application.evidence) + def get_evidence_graph(self) -> dict[str, Any]: """Derive the packaged graph from the canonical in-process evidence runtime. @@ -195,4 +204,4 @@ def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> Runtime current_node_getter=lambda: runtime.current_node_id, runtime_application=runtime, loader=loader, - ) + ) \ No newline at end of file From 37efd7c627be4100a606471a0c01985c9a5489eb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:30:08 +0200 Subject: [PATCH 027/125] R06: allowlist packaged OT-NT research command --- .../scripture_archive_platform/application/service.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 46226f51d..3b51d59f9 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -42,6 +42,9 @@ def _dispatch(self,cmd,p): if cmd=='research.upsert_note':return {'note':self.research.upsert_note(p.get('note'))} if cmd=='research.delete_note':return {'deleted':self.research.delete_note(p.get('note_id'))} if cmd=='research.get_evidence_graph':return self._evidence_graph() + if cmd=='research.get_cross_testament': + if p:raise ValueError('research.get_cross_testament accepts an empty payload') + return self._cross_testament() if cmd=='research.get_chronology_lab': if p:raise ValueError('research.get_chronology_lab accepts an empty payload') return self._chronology_lab() @@ -89,7 +92,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),'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,'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),'cross_testament':bool(self.player_gateway),'chronology_lab':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'}} 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 @@ -114,6 +117,9 @@ def _evidence(self,nid): def _evidence_graph(self): if not self.player_gateway:raise ValueError('Evidence Graph requires canonical runtime') return self.player_gateway.get_evidence_graph() + def _cross_testament(self): + if not self.player_gateway:raise ValueError('Cross-Testament requires canonical runtime') + return self.player_gateway.get_cross_testament() def _next(self,p): nid=self._id(p,'node_id') if self.player_gateway: From bab5b0875621362cfc246f1d581d41f2e4d589b0 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:30:35 +0200 Subject: [PATCH 028/125] R06: add accessible packaged OT-NT research surface --- .../frontend/cross-testament-ui.js | 180 ++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/cross-testament-ui.js diff --git a/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js b/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js new file mode 100644 index 000000000..4125f6e20 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js @@ -0,0 +1,180 @@ +import {chooseTransport, unwrap} from './transport.js'; + +const COMMAND = 'research.get_cross_testament'; +const MAX_LINKS = 512; +const MAX_EVIDENCE = 1024; +const MAX_LINEAR = 4096; +const MAX_TEXT = 512; +let transportPromise = null; +let busy = false; + +const byId = id => document.getElementById(id); +const record = value => value !== null && typeof value === 'object' && !Array.isArray(value); + +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 if (name === 'tabIndex') node.tabIndex = Number(value); + else node.setAttribute(name, String(value)); + } + return node; +} + +function boundedText(value, field, {nullable = false} = {}) { + if (value === null && nullable) return null; + if (typeof value !== 'string' || value.length === 0 || value.length > MAX_TEXT) throw new Error(`${field} must be bounded text`); + if (/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\u2028\u2029]/u.test(value)) throw new Error(`${field} contains unsafe Unicode`); + return value; +} + +function positiveInt(value, field) { + if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer`); + return value; +} + +function validateEvidence(item, field) { + if (!record(item)) throw new Error(`${field} is invalid`); + boundedText(item.evidence_id, `${field}.evidence_id`); + boundedText(item.confidence, `${field}.confidence`); + if (typeof item.tx1 !== 'boolean') throw new Error(`${field}.tx1 must be boolean`); + boundedText(item.witness, `${field}.witness`, {nullable: true}); +} + +function validateEndpoint(endpoint, testament, field) { + if (!record(endpoint) || endpoint.testament !== testament) throw new Error(`${field} has invalid testament`); + boundedText(endpoint.passage_id, `${field}.passage_id`); + boundedText(endpoint.book, `${field}.book`); + positiveInt(endpoint.chapter, `${field}.chapter`); + positiveInt(endpoint.verse_start, `${field}.verse_start`); + if (endpoint.verse_end !== null) positiveInt(endpoint.verse_end, `${field}.verse_end`); + boundedText(endpoint.witness, `${field}.witness`, {nullable: true}); + if (!Array.isArray(endpoint.evidence) || endpoint.evidence.length > MAX_EVIDENCE) throw new Error(`${field}.evidence is invalid`); + endpoint.evidence.forEach((item, index) => validateEvidence(item, `${field}.evidence[${index}]`)); +} + +export function validateCrossTestamentResponse(data) { + if (!record(data) || data.schema !== 'scripture.research.cross-testament.v1') throw new Error('Некоректний OT↔NT contract'); + if (data.projection_schema !== 'CROSS_TESTAMENT_v1') throw new Error('Некоректна canonical OT↔NT projection'); + if (data.evidence_scope !== 'unlocked_only' || data.read_only !== true || data.truth_owner !== 'D5/runtime') throw new Error('OT↔NT must remain read-only and unlocked-only'); + if (!['LINKS', 'NOT_STATED_IN_CITED_TEXT'].includes(data.status)) throw new Error('Некоректний OT↔NT status'); + if (!Array.isArray(data.links) || data.links.length > MAX_LINKS) throw new Error('Некоректний список OT↔NT зв’язків'); + if (!Array.isArray(data.linear) || data.linear.length === 0 || data.linear.length > MAX_LINEAR) throw new Error('Некоректний лінійний OT↔NT view'); + const ids = new Set(); + data.links.forEach((link, index) => { + const field = `links[${index}]`; + if (!record(link)) throw new Error(`${field} is invalid`); + const relationId = boundedText(link.relation_id, `${field}.relation_id`); + if (ids.has(relationId)) throw new Error(`Duplicate relation ${relationId}`); + ids.add(relationId); + boundedText(link.relation_type, `${field}.relation_type`); + boundedText(link.relation_witness, `${field}.relation_witness`, {nullable: true}); + validateEndpoint(link.ot, 'OT', `${field}.ot`); + validateEndpoint(link.nt, 'NT', `${field}.nt`); + }); + data.linear.forEach((line, index) => boundedText(line, `linear[${index}]`)); + if (data.status === 'NOT_STATED_IN_CITED_TEXT' && data.links.length !== 0) throw new Error('Empty-state status conflicts with links'); + if (data.status === 'LINKS' && data.links.length === 0) throw new Error('Link status requires links'); + return data; +} + +async function api() { + if (!transportPromise) transportPromise = chooseTransport(); + return validateCrossTestamentResponse(await unwrap(await transportPromise, COMMAND, {})); +} + +function passage(endpoint) { + const end = endpoint.verse_end === null || endpoint.verse_end === endpoint.verse_start ? '' : `-${endpoint.verse_end}`; + return `${endpoint.book} ${endpoint.chapter}:${endpoint.verse_start}${end} (${endpoint.passage_id})`; +} + +function evidenceText(endpoint) { + if (!endpoint.evidence.length) return 'not stated'; + return endpoint.evidence.map(item => `${item.evidence_id} · ${item.confidence}${item.tx1 ? ' · TX1' : ''} · witness ${item.witness || 'not stated'}`).join(' | '); +} + +function render(data) { + const rows = byId('cross-testament-rows'); + rows.replaceChildren(); + if (!data.links.length) { + const tr = document.createElement('tr'); + const td = element('td', 'Not stated in cited text. Немає unlocked explicit source-backed OT↔NT relation у поточному canonical runtime.'); + td.colSpan = 6; + tr.append(td); + rows.append(tr); + } else { + for (const link of data.links) { + const tr = document.createElement('tr'); + const cells = [ + link.relation_id, + link.relation_type, + passage(link.ot), + passage(link.nt), + link.relation_witness || 'not stated', + `OT: ${evidenceText(link.ot)}; NT: ${evidenceText(link.nt)}`, + ]; + cells.forEach(value => tr.append(element('td', value))); + rows.append(tr); + } + } + const linear = byId('cross-testament-linear'); + linear.replaceChildren(); + data.linear.forEach(line => linear.append(element('li', line))); + byId('cross-testament-summary').textContent = `Scope: unlocked_only · explicit links ${data.links.length} · truth owner D5/runtime. Similarity, chronology and consensus are not inferred.`; + byId('cross-testament-status').textContent = data.links.length ? `OT↔NT оновлено: ${data.links.length} source-backed зв’язків.` : 'OT↔NT оновлено: Not stated in cited text.'; +} + +async function refresh() { + if (busy) return; + busy = true; + const button = byId('cross-testament-refresh'); + button.disabled = true; + button.setAttribute('aria-busy', 'true'); + byId('cross-testament-status').textContent = 'Завантаження canonical OT↔NT evidence…'; + try { + render(await api()); + } catch (error) { + byId('cross-testament-status').textContent = `OT↔NT недоступний: ${error.message}`; + } finally { + busy = false; + button.disabled = false; + button.setAttribute('aria-busy', 'false'); + } +} + +function makeTable() { + const wrapper = element('div', '', {className: 'table-scroll', tabIndex: '0', 'aria-label': 'Source-backed OT↔NT links'}); + const table = document.createElement('table'); + table.append(element('caption', 'Explicit source-backed Cross-Testament relations')); + const thead = document.createElement('thead'); + const tr = document.createElement('tr'); + ['Relation ID', 'Type', 'OT passage', 'NT passage', 'Relation witness', 'Evidence provenance'].forEach(label => tr.append(element('th', label, {scope: 'col'}))); + thead.append(tr); + table.append(thead, element('tbody', '', {id: 'cross-testament-rows'})); + wrapper.append(table); + return wrapper; +} + +export function installCrossTestamentSurface() { + if (byId('cross-testament-surface')) return; + const research = byId('research-view'); + if (!research) return; + const section = element('section', '', {id: 'cross-testament-surface', className: 'surface', 'aria-labelledby': 'cross-testament-heading'}); + section.append( + element('h3', 'OT↔NT — Cross-Testament', {id: 'cross-testament-heading'}), + element('p', 'Read-only проєкція тільки explicit source-backed relation з canonical unlocked evidence. Відсутність зв’язку показується як “Not stated in cited text”; подібність, chronology, history або consensus не домислюються.'), + element('button', 'Оновити OT↔NT', {id: 'cross-testament-refresh', type: 'button'}), + element('p', 'OT↔NT ще не завантажено.', {id: 'cross-testament-status', className: 'notice info', role: 'status', 'aria-live': 'polite', 'aria-atomic': 'true'}), + element('p', 'Scope: unlocked_only.', {id: 'cross-testament-summary'}), + element('h4', 'Структуроване представлення'), + makeTable(), + element('h4', 'Повний лінійний еквівалент'), + element('p', 'Лінійний список формується з тієї самої canonical projection, що й таблиця, для keyboard/NVDA review.'), + ); + const linear = element('ol', '', {id: 'cross-testament-linear'}); + linear.append(element('li', 'Завантажте OT↔NT, щоб отримати лінійне представлення.')); + section.append(linear); + byId('cross-testament-refresh').addEventListener('click', refresh); + research.append(section); +} \ No newline at end of file From a20453ab28bc909b012403e85552f2fd4240ad74 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:30:44 +0200 Subject: [PATCH 029/125] R06: mount packaged OT-NT research surface --- lanes/dev1/repair_overlay/frontend/transport.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lanes/dev1/repair_overlay/frontend/transport.js b/lanes/dev1/repair_overlay/frontend/transport.js index da74dd864..18200e486 100644 --- a/lanes/dev1/repair_overlay/frontend/transport.js +++ b/lanes/dev1/repair_overlay/frontend/transport.js @@ -43,3 +43,5 @@ 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()); +// Explicit source-backed OT↔NT relations share the same unlocked canonical runtime and Research Workbench. +void import('./cross-testament-ui.js').then(({installCrossTestamentSurface})=>installCrossTestamentSurface()); \ No newline at end of file From 2247b7f55f9b5675cec7a72fb7cb5b6fe2e21fa5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:31:11 +0200 Subject: [PATCH 030/125] R06: allowlist read-only OT-NT transport command --- .../scripture_archive_platform/transport/contracts.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 d69447d69..d6dce410e 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -12,7 +12,7 @@ "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", "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.list_notes","research.upsert_note","research.delete_note","research.get_chronology_lab","research.get_evidence_graph","research.get_witness_matrix","research.get_cross_testament", "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", @@ -73,6 +73,8 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('research.get_evidence_graph accepts an empty payload') if cmd=='research.get_witness_matrix' and payload: raise ValueError('research.get_witness_matrix accepts an empty payload') + if cmd=='research.get_cross_testament' and payload: + raise ValueError('research.get_cross_testament accepts an empty payload') return rid,cmd,payload def _redact_private_player_task(value:Any)->Any: From b7898ba5faf4bd69741382ffbf0001bb9d37a0c8 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:31:41 +0200 Subject: [PATCH 031/125] R06: qualify packaged OT-NT contract --- .../test_packaged_cross_testament_contract.py | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py new file mode 100644 index 000000000..63339838a --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py @@ -0,0 +1,171 @@ +import ast +import unittest +from pathlib import Path + +from scripture_archive_platform.application.cross_testament_projection import project_packaged_cross_testament +from scripture_archive_platform.application.service import PlatformApplication +from scripture_archive_platform.transport.contracts import validate_request_shape +from runtime_engine.scripture_archive_runtime.evidence import EvidenceRecord, EvidenceRuntime, PassageRef, Relation +from runtime_engine.scripture_archive_runtime.models import Confidence + + +class _CrossTestamentGateway: + def __init__(self): + self.calls = 0 + + def get_cross_testament(self): + self.calls += 1 + return { + "schema": "scripture.research.cross-testament.v1", + "projection_schema": "CROSS_TESTAMENT_v1", + "status": "NOT_STATED_IN_CITED_TEXT", + "links": [], + "linear": ["Not stated in cited text"], + "read_only": True, + "evidence_scope": "unlocked_only", + "truth_owner": "D5/runtime", + } + + +class PackagedCrossTestamentContractTests(unittest.TestCase): + @staticmethod + def _request(payload): + return { + "api_version": "scripture.transport.v1", + "request_id": "cross-testament-contract", + "command": "research.get_cross_testament", + "payload": payload, + } + + @staticmethod + def _runtime(*, unlock_nt=True, witness="Matthew"): + runtime = EvidenceRuntime() + runtime.add_evidence( + EvidenceRecord( + "EV-OT", + (PassageRef("ISA7:14", "Isaiah", 7, 14, witness="Isaiah"),), + "OT proposition", + Confidence.T1, + witness="Isaiah", + ) + ) + runtime.add_evidence( + EvidenceRecord( + "EV-NT", + (PassageRef("MT1:23", "Matthew", 1, 23, witness=witness),), + "NT proposition", + Confidence.T2, + tx1=True, + witness=witness, + ) + ) + runtime.add_relation( + Relation( + "REL-X", + "EV-OT", + "explicit_cross_reference", + "EV-NT", + passage_ids=("ISA7:14", "MT1:23"), + ) + ) + runtime.unlock("EV-OT") + if unlock_nt: + runtime.unlock("EV-NT") + return runtime + + def test_transport_is_allowlisted_but_accepts_only_empty_scope(self): + rid, command, payload = validate_request_shape(self._request({})) + self.assertEqual((rid, command, payload), ("cross-testament-contract", "research.get_cross_testament", {})) + for forbidden in ( + {"include_locked_evidence": True}, + {"infer_from_topics": True}, + {"book_testaments": {"Isaiah": "NT"}}, + ): + with self.subTest(payload=forbidden): + with self.assertRaises(ValueError): + validate_request_shape(self._request(forbidden)) + + def test_platform_dispatch_routes_only_to_canonical_gateway(self): + gateway = _CrossTestamentGateway() + app = object.__new__(PlatformApplication) + app.player_gateway = gateway + response = app.handle(self._request({})) + self.assertTrue(response["ok"]) + self.assertEqual(response["data"]["schema"], "scripture.research.cross-testament.v1") + self.assertEqual(response["data"]["truth_owner"], "D5/runtime") + self.assertEqual(gateway.calls, 1) + + rejected = app.handle(self._request({"include_locked_evidence": True})) + self.assertFalse(rejected["ok"]) + self.assertEqual(rejected["error"]["code"], "VALIDATION_ERROR") + self.assertEqual(gateway.calls, 1) + + def test_packaged_projection_preserves_explicit_relation_provenance(self): + data = project_packaged_cross_testament(self._runtime()) + self.assertEqual(data["schema"], "scripture.research.cross-testament.v1") + self.assertEqual(data["projection_schema"], "CROSS_TESTAMENT_v1") + self.assertEqual(data["status"], "LINKS") + self.assertTrue(data["read_only"]) + self.assertEqual(data["evidence_scope"], "unlocked_only") + self.assertEqual(data["truth_owner"], "D5/runtime") + self.assertEqual(len(data["links"]), 1) + link = data["links"][0] + self.assertEqual(link["relation_id"], "REL-X") + self.assertEqual(link["ot"]["passage_id"], "ISA7:14") + self.assertEqual(link["nt"]["passage_id"], "MT1:23") + self.assertEqual(link["ot"]["evidence"][0]["confidence"], "T1") + self.assertEqual(link["nt"]["evidence"][0]["confidence"], "T2") + self.assertTrue(link["nt"]["evidence"][0]["tx1"]) + linear = "\n".join(data["linear"]) + for expected in ("REL-X", "ISA7:14", "MT1:23", "witness=Isaiah", "witness=Matthew"): + self.assertIn(expected, linear) + + def test_locked_endpoint_remains_honest_not_stated_empty_state(self): + data = project_packaged_cross_testament(self._runtime(unlock_nt=False)) + self.assertEqual(data["status"], "NOT_STATED_IN_CITED_TEXT") + self.assertEqual(data["links"], []) + self.assertEqual(data["linear"], ["Not stated in cited text"]) + serialized = repr(data) + self.assertNotIn("MT1:23", serialized) + self.assertNotIn("EV-NT", serialized) + + def test_packaged_boundary_rejects_invisible_unicode_in_provenance(self): + with self.assertRaisesRegex(ValueError, "unsafe Unicode"): + project_packaged_cross_testament(self._runtime(witness="Matthew\u200bhidden")) + + def test_runtime_gateway_holds_projection_under_runtime_lock(self): + gateway_path = ( + Path(__file__).resolve().parents[1] + / "scripture_archive_platform" + / "application" + / "runtime_gateway.py" + ) + source = gateway_path.read_text(encoding="utf-8") + module = ast.parse(source) + gateway = next(node for node in module.body if isinstance(node, ast.ClassDef) and node.name == "RuntimeBackedPlayerGateway") + method = next(node for node in gateway.body if isinstance(node, ast.FunctionDef) and node.name == "get_cross_testament") + locks = [ + node for node in method.body + if isinstance(node, ast.With) + and any(ast.unparse(item.context_expr) == "self._runtime_lock" for item in node.items) + ] + self.assertEqual(len(locks), 1) + locked_source = ast.get_source_segment(source, locks[0]) or "" + self.assertIn("project_packaged_cross_testament(self._runtime_application.evidence)", locked_source) + self.assertNotIn("include_locked", locked_source) + + def test_frontend_is_semantic_text_first_and_linear_equivalent(self): + frontend = Path(__file__).resolve().parents[1] / "frontend" + ui = (frontend / "cross-testament-ui.js").read_text(encoding="utf-8") + transport = (frontend / "transport.js").read_text(encoding="utf-8") + self.assertIn("research.get_cross_testament", ui) + self.assertIn("document.createElement('table')", ui) + self.assertIn("Повний лінійний еквівалент", ui) + self.assertIn("Not stated in cited text", ui) + self.assertIn("aria-live", ui) + self.assertNotIn("innerHTML", ui) + self.assertIn("cross-testament-ui.js", transport) + + +if __name__ == "__main__": + unittest.main() From bade60c37a2cd6cbf6d3984dd8a523bea3e18ca1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 04:26:54 +0200 Subject: [PATCH 032/125] Repair current-shell qualification for packaged Cross-Testament surface Update only the inherited packaged current-shell qualification contract so the exact loader set and Node syntax coverage include the newly composed cross-testament-ui.js surface. Product/runtime/source bytes from the qualified #160 reconvergence remain unchanged. --- .../tests/test_packaged_library_current_shell.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 83857d600..2a308dffa 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -40,6 +40,7 @@ def test_current_transport_preserves_package_loaders_and_composes_coordinator_su "./evidence-graph-ui.js", "./witness-matrix-ui.js", "./constructor-v2-ui.js", + "./cross-testament-ui.js", } imports = set(re.findall(r"void import\('([^']+)'\)", self.transport)) self.assertEqual(imports, expected_loaders) @@ -57,6 +58,14 @@ def test_current_transport_preserves_package_loaders_and_composes_coordinator_su "void import('./witness-matrix-ui.js').then(({installWitnessMatrixSurface})=>installWitnessMatrixSurface());", self.transport, ) + self.assertIn( + "void import('./constructor-v2-ui.js').then(({installConstructorV2Surface})=>installConstructorV2Surface());", + self.transport, + ) + self.assertIn( + "void import('./cross-testament-ui.js').then(({installCrossTestamentSurface})=>installCrossTestamentSurface());", + self.transport, + ) self.assertIn("import './chronology-lab-ui.js';", self.compat) def test_library_calls_only_read_only_canonical_contracts(self): @@ -125,6 +134,7 @@ def test_javascript_syntax(self): ROOT / "evidence-graph-ui.js", ROOT / "witness-matrix-ui.js", ROOT / "constructor-v2-ui.js", + ROOT / "cross-testament-ui.js", ): completed = subprocess.run( ["node", "--check", str(path)], From f0745f768c941a716be5cbe07c12ba2fb46b7a8f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:28:47 +0200 Subject: [PATCH 033/125] =?UTF-8?q?Test=20packaged=20OT=E2=86=94NT=20throu?= =?UTF-8?q?gh=20production=20runtime=20gateway?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Close the prior #160 QA gap by proving the exact packaged build_runtime_gateway consumes the checked-in SOURCE_AUDITED OT↔NT pack and exposes its canonical relation IDs through the read-only Research projection. No source records or product behavior changed. --- .../test_packaged_cross_testament_contract.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py index 63339838a..9ca40b074 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py @@ -1,12 +1,15 @@ import ast import unittest from pathlib import Path +from tempfile import TemporaryDirectory from scripture_archive_platform.application.cross_testament_projection import project_packaged_cross_testament +from scripture_archive_platform.application.runtime_gateway import build_runtime_gateway from scripture_archive_platform.application.service import PlatformApplication from scripture_archive_platform.transport.contracts import validate_request_shape from runtime_engine.scripture_archive_runtime.evidence import EvidenceRecord, EvidenceRuntime, PassageRef, Relation from runtime_engine.scripture_archive_runtime.models import Confidence +from runtime_engine.scripture_archive_runtime.otnt_relation_pack import load_otnt_relation_pack class _CrossTestamentGateway: @@ -100,6 +103,27 @@ def test_platform_dispatch_routes_only_to_canonical_gateway(self): self.assertEqual(rejected["error"]["code"], "VALIDATION_ERROR") self.assertEqual(gateway.calls, 1) + def test_production_gateway_materializes_checked_in_source_audited_pack(self): + repo_root = Path(__file__).resolve().parents[4] + source_bundle = load_otnt_relation_pack(repo_root) + self.assertTrue(source_bundle.source_audited) + expected_relation_ids = sorted(source_bundle.runtime.relations) + self.assertTrue(expected_relation_ids) + + with TemporaryDirectory() as directory: + gateway = build_runtime_gateway(repo_root, Path(directory)) + data = gateway.get_cross_testament() + + self.assertEqual(data["schema"], "scripture.research.cross-testament.v1") + self.assertEqual(data["status"], "LINKS") + self.assertTrue(data["read_only"]) + self.assertEqual(data["evidence_scope"], "unlocked_only") + self.assertEqual(data["truth_owner"], "D5/runtime") + self.assertEqual( + [link["relation_id"] for link in data["links"]], + expected_relation_ids, + ) + def test_packaged_projection_preserves_explicit_relation_provenance(self): data = project_packaged_cross_testament(self._runtime()) self.assertEqual(data["schema"], "scripture.research.cross-testament.v1") From fd244f70c44975abe60b7888d899e769b4ad584b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:34:52 +0200 Subject: [PATCH 034/125] =?UTF-8?q?Qualify=20packaged=20OT=E2=86=94NT=20pr?= =?UTF-8?q?oduction=20gateway=20on=20both=20OS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a narrow exact-head Ubuntu/Windows Actions gate for the existing packaged Cross-Testament production-gateway regression. This supplies the terminal execution evidence requested by independent QA without changing product, runtime, corpus, relation, or source bytes and without bypassing shared DEV1 #146. --- .../r06-packaged-cross-testament.yml | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 .github/workflows/r06-packaged-cross-testament.yml diff --git a/.github/workflows/r06-packaged-cross-testament.yml b/.github/workflows/r06-packaged-cross-testament.yml new file mode 100644 index 000000000..deb2ddf92 --- /dev/null +++ b/.github/workflows/r06-packaged-cross-testament.yml @@ -0,0 +1,55 @@ +name: R06 Packaged Cross-Testament Qualification + +on: + push: + paths: + - 'lanes/dev1/repair_overlay/frontend/cross-testament-ui.js' + - 'lanes/dev1/repair_overlay/frontend/transport.js' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py' + - '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/tests/test_packaged_cross_testament_contract.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py' + - '.github/workflows/r06-packaged-cross-testament.yml' + pull_request: + paths: + - 'lanes/dev1/repair_overlay/frontend/cross-testament-ui.js' + - 'lanes/dev1/repair_overlay/frontend/transport.js' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py' + - '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/tests/test_packaged_cross_testament_contract.py' + - 'lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py' + - '.github/workflows/r06-packaged-cross-testament.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + packaged-cross-testament: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + PYTHONPATH: ${{ github.workspace }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Run packaged Cross-Testament production-gateway regression + run: python lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py + - name: Diff hygiene + shell: bash + run: git diff --check From 204850b72084f124d0bb7c5be95de79fda489ced Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:34:59 +0200 Subject: [PATCH 035/125] Qualify packaged OT-NT production gateway on both OS --- .github/workflows/r06-packaged-library-current-shell.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/r06-packaged-library-current-shell.yml b/.github/workflows/r06-packaged-library-current-shell.yml index 95be4186c..307e1b4d1 100644 --- a/.github/workflows/r06-packaged-library-current-shell.yml +++ b/.github/workflows/r06-packaged-library-current-shell.yml @@ -15,6 +15,8 @@ on: - '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/frontend/cross-testament-ui.js' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py' - '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' @@ -31,6 +33,7 @@ on: - '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' + - 'lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py' - '.github/workflows/r06-packaged-library-current-shell.yml' workflow_dispatch: @@ -82,6 +85,8 @@ jobs: 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: Run packaged Cross-Testament production-gateway regression + run: python -m unittest discover -s lanes/dev1/repair_overlay/tests -p 'test_packaged_cross_testament_contract.py' -t lanes/dev1/repair_overlay -v - name: Diff hygiene shell: bash run: git diff --check From 2dfce6096c90ebce752f521c83ad4d1f456c63a8 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:36:08 +0200 Subject: [PATCH 036/125] Fix OT-NT qualification overlay import path --- .github/workflows/r06-packaged-cross-testament.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-packaged-cross-testament.yml b/.github/workflows/r06-packaged-cross-testament.yml index deb2ddf92..91ab0952d 100644 --- a/.github/workflows/r06-packaged-cross-testament.yml +++ b/.github/workflows/r06-packaged-cross-testament.yml @@ -49,7 +49,7 @@ jobs: shell: bash run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - name: Run packaged Cross-Testament production-gateway regression - run: python lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py + run: python -c "import runpy,sys; sys.path.insert(0, 'lanes/dev1/repair_overlay'); runpy.run_path('lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py', run_name='__main__')" - name: Diff hygiene shell: bash run: git diff --check From 6050c2e7da88cf3b286d8d500a8f4c50c07f1e11 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:36:24 +0200 Subject: [PATCH 037/125] Converge OT-NT qualification into dedicated gate --- .github/workflows/r06-packaged-library-current-shell.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/r06-packaged-library-current-shell.yml b/.github/workflows/r06-packaged-library-current-shell.yml index 307e1b4d1..95be4186c 100644 --- a/.github/workflows/r06-packaged-library-current-shell.yml +++ b/.github/workflows/r06-packaged-library-current-shell.yml @@ -15,8 +15,6 @@ on: - '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/frontend/cross-testament-ui.js' - - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py' - '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' @@ -33,7 +31,6 @@ on: - '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' - - 'lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py' - '.github/workflows/r06-packaged-library-current-shell.yml' workflow_dispatch: @@ -85,8 +82,6 @@ jobs: 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: Run packaged Cross-Testament production-gateway regression - run: python -m unittest discover -s lanes/dev1/repair_overlay/tests -p 'test_packaged_cross_testament_contract.py' -t lanes/dev1/repair_overlay -v - name: Diff hygiene shell: bash run: git diff --check From 45638a044a3335470611d919188341987d758b66 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 05:38:46 +0200 Subject: [PATCH 038/125] Qualify OT-NT on verified DEV1 base donor --- .../r06-packaged-cross-testament.yml | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.github/workflows/r06-packaged-cross-testament.yml b/.github/workflows/r06-packaged-cross-testament.yml index 91ab0952d..08f4294d2 100644 --- a/.github/workflows/r06-packaged-cross-testament.yml +++ b/.github/workflows/r06-packaged-cross-testament.yml @@ -38,6 +38,8 @@ jobs: env: EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} PYTHONPATH: ${{ github.workspace }} + DEV01_BASE_DONOR: 90a13aca71d2a5f832846a84acbdf0f7c89f5da9 + DEV01_BASE_SOURCE_SHA256: 10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35 steps: - uses: actions/checkout@v4 with: @@ -48,8 +50,25 @@ jobs: - name: Confirm exact source checkout shell: bash run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Materialize independently verified FINALPREP02 base donor + shell: bash + run: | + git fetch --no-tags --depth=1 origin "$DEV01_BASE_DONOR" + git archive --format=zip --output=dev1-base-donor.zip "$DEV01_BASE_DONOR" \ + release_inputs/dev1_finalprep02 \ + lanes/dev1/verify_source_archive.py \ + lanes/dev1/FINALPREP02_RESOLVED_SOURCE_SHA256.json \ + lanes/dev1/FINALPREP02_RESOLVED_SOURCE_MANIFEST.json + python -m zipfile -e dev1-base-donor.zip . + python -c "from pathlib import Path; import base64; p=sorted(Path('release_inputs/dev1_finalprep02').glob('part-*.b64')); assert p; Path('DEV1_R06_PLATFORM_SOURCE.zip').write_bytes(base64.b64decode(''.join(x.read_text(encoding='ascii') for x in p)))" + python lanes/dev1/verify_source_archive.py DEV1_R06_PLATFORM_SOURCE.zip "$DEV01_BASE_SOURCE_SHA256" + python -m zipfile -e DEV1_R06_PLATFORM_SOURCE.zip . + test -d r06_platform + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Compose exact candidate overlay onto verified base + run: python -c "import shutil; shutil.copytree('lanes/dev1/repair_overlay', 'r06_platform', dirs_exist_ok=True)" - name: Run packaged Cross-Testament production-gateway regression - run: python -c "import runpy,sys; sys.path.insert(0, 'lanes/dev1/repair_overlay'); runpy.run_path('lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py', run_name='__main__')" + run: python -c "import runpy,sys; sys.path.insert(0, 'r06_platform'); runpy.run_path('lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py', run_name='__main__')" - name: Diff hygiene shell: bash run: git diff --check From a872059af12cd9dd8371729f2743028da4b058ab Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 17:51:39 +0200 Subject: [PATCH 039/125] Fail closed Dossier subject metadata against canonical catalog G3 R2 FIRST-09 same-lineage repair for sa:dossier-subject-integrity. Resolve Dossier metadata through the runtime-owned canonical subject_catalog, fail closed when the catalog/subject is unavailable or caller display_name/kind disagrees, and retain unlocked-only evidence projection. Add wrong-label/wrong-allowed-kind regressions without copying or inferring #155 source truth. Current packaged truth still lacks #155 serialization, so this commit does not claim integration readiness or auditor acceptance. --- .../application/runtime_gateway.py | 73 +++++++++++++++++-- .../tests/test_dossier_composition.py | 51 ++++++++++++- .../test_packaged_dossier_integration.py | 39 +++++++++- 3 files changed, 153 insertions(+), 10 deletions(-) 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 0fdaa37f2..ca0c2b3da 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 @@ -33,11 +33,13 @@ def __init__( current_node_getter: Callable[[], str | None] | None = None, runtime_application=None, loader=None, + subject_catalog: Mapping[str, Any] | None = None, ): self.adapter = RuntimeEngineContractAdapter(runtime_invoke) self._current_node_getter = current_node_getter self._runtime_application = runtime_application self._loader = loader + self._subject_catalog = subject_catalog self._runtime_lock = threading.RLock() @staticmethod @@ -192,21 +194,79 @@ def get_dossier(self, subject_id: str, display_name: str, kind: str) -> dict[str if self._runtime_application is None: raise RuntimeGatewayError("canonical runtime dossier view is unavailable") with self._runtime_lock: - return build_runtime_dossier(self._runtime_application, subject_id, display_name, kind) + return build_runtime_dossier( + self._runtime_application, + subject_id, + display_name, + kind, + subject_catalog=self._subject_catalog, + ) -def build_runtime_dossier(runtime, subject_id: str, display_name: str, kind: str) -> dict[str, Any]: - """Build an unlocked-only dossier without creating a second evidence truth.""" +def _canonical_dossier_subject( + subject_catalog: Mapping[str, Any] | None, + subject_id: str, + display_name: str, + kind: str, +) -> tuple[str, str, str]: + """Resolve caller metadata against the canonical audited subject catalog.""" + if subject_catalog is None: + raise RuntimeGatewayError("canonical dossier subject catalog is unavailable") + + metadata = subject_catalog.get(subject_id) + if metadata is None: + raise RuntimeGatewayError("unknown canonical dossier subject") + + def field(name: str): + if isinstance(metadata, Mapping): + return metadata.get(name) + return getattr(metadata, name, None) + + canonical_subject_id = field("subject_id") + canonical_display_name = field("display_name") + canonical_kind = field("kind") + if not all( + isinstance(value, str) and value.strip() + for value in (canonical_subject_id, canonical_display_name, canonical_kind) + ): + raise RuntimeGatewayError("canonical dossier subject metadata is invalid") + if canonical_subject_id != subject_id: + raise RuntimeGatewayError("canonical dossier subject id mismatch") + if (display_name, kind) != (canonical_display_name, canonical_kind): + raise RuntimeGatewayError("dossier subject metadata does not match canonical catalog") + return canonical_subject_id, canonical_display_name, canonical_kind + + +def build_runtime_dossier( + runtime, + subject_id: str, + display_name: str, + kind: str, + *, + subject_catalog: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Build an unlocked-only dossier from canonical subject metadata.""" from runtime_engine.scripture_archive_runtime.dossiers import ( DossierAssembler, DossierKind, DossierSubject, ) + canonical_subject_id, canonical_display_name, canonical_kind = _canonical_dossier_subject( + subject_catalog, + subject_id, + display_name, + kind, + ) + try: + dossier_kind = DossierKind(canonical_kind) + except (TypeError, ValueError) as exc: + raise RuntimeGatewayError("canonical dossier subject kind is invalid") from exc + subject = DossierSubject( - subject_id=subject_id, - display_name=display_name, - kind=DossierKind(kind), + subject_id=canonical_subject_id, + display_name=canonical_display_name, + kind=dossier_kind, ) view = DossierAssembler(runtime.evidence).build(subject, unlocked_only=True) dossier = view.to_dict() @@ -264,4 +324,5 @@ def build_runtime_gateway(repo_root: Path, platform_store_root: Path) -> Runtime current_node_getter=lambda: runtime.current_node_id, runtime_application=runtime, loader=loader, + subject_catalog=getattr(evidence_bundle, "subject_catalog", None), ) diff --git a/lanes/dev1/repair_overlay/tests/test_dossier_composition.py b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py index 8f5e540d1..8eaf7aba8 100644 --- a/lanes/dev1/repair_overlay/tests/test_dossier_composition.py +++ b/lanes/dev1/repair_overlay/tests/test_dossier_composition.py @@ -1,12 +1,22 @@ import unittest -from scripture_archive_platform.application.runtime_gateway import build_runtime_dossier +from scripture_archive_platform.application.runtime_gateway import RuntimeGatewayError, build_runtime_dossier from scripture_archive_platform.application.service import PlatformApplication from scripture_archive_platform.transport.contracts import validate_request_shape from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime from scripture_archive_runtime.models import Confidence +def canonical_subject_catalog(): + return { + "PERSON:PAUL": { + "subject_id": "PERSON:PAUL", + "display_name": "Paul", + "kind": "PERSON", + } + } + + def safe_dossier(subject_id="PERSON:PAUL", display_name="Paul", kind="PERSON"): return { "dossier": { @@ -106,7 +116,13 @@ def test_packaged_helper_uses_same_runtime_and_hides_locked_dependencies(self): evidence.unlock("EV-VISIBLE") runtime = type("Runtime", (), {"evidence": evidence})() - packaged = build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON")["dossier"] + packaged = build_runtime_dossier( + runtime, + "PERSON:PAUL", + "Paul", + "PERSON", + subject_catalog=canonical_subject_catalog(), + )["dossier"] self.assertEqual(packaged["evidence_scope"], "unlocked_only") self.assertEqual([row["row_id"] for row in packaged["rows"]], ["EV-VISIBLE"]) rendered = "\n".join(packaged["linear"]) @@ -116,5 +132,36 @@ def test_packaged_helper_uses_same_runtime_and_hides_locked_dependencies(self): self.assertNotIn("Locked proposition", rendered) + def test_packaged_helper_fails_closed_on_noncanonical_subject_metadata(self): + evidence = EvidenceRuntime() + runtime = type("Runtime", (), {"evidence": evidence})() + catalog = canonical_subject_catalog() + + for display_name, kind in (("Not Paul", "PERSON"), ("Paul", "PLACE")): + with self.subTest(display_name=display_name, kind=kind): + with self.assertRaisesRegex( + RuntimeGatewayError, + "does not match canonical catalog", + ): + build_runtime_dossier( + runtime, + "PERSON:PAUL", + display_name, + kind, + subject_catalog=catalog, + ) + + with self.assertRaisesRegex(RuntimeGatewayError, "catalog is unavailable"): + build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON") + with self.assertRaisesRegex(RuntimeGatewayError, "unknown canonical dossier subject"): + build_runtime_dossier( + runtime, + "PERSON:UNKNOWN", + "Unknown", + "PERSON", + subject_catalog=catalog, + ) + + if __name__ == "__main__": unittest.main() diff --git a/runtime_engine/tests/test_packaged_dossier_integration.py b/runtime_engine/tests/test_packaged_dossier_integration.py index 81cc99af6..24e637b0d 100644 --- a/runtime_engine/tests/test_packaged_dossier_integration.py +++ b/runtime_engine/tests/test_packaged_dossier_integration.py @@ -20,12 +20,22 @@ # lanes/dev1/repair_overlay/tests/test_dossier_composition.py, where that topology # exists. Importing PlatformApplication directly from the partial overlay here makes # unrelated runtime workflows fail before exercising any Dossier production bytes. -from scripture_archive_platform.application.runtime_gateway import build_runtime_dossier +from scripture_archive_platform.application.runtime_gateway import RuntimeGatewayError, build_runtime_dossier from scripture_archive_platform.transport.contracts import validate_request_shape from runtime_engine.scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime from runtime_engine.scripture_archive_runtime.models import Confidence +def canonical_subject_catalog(): + return { + "PERSON:PAUL": { + "subject_id": "PERSON:PAUL", + "display_name": "Paul", + "kind": "PERSON", + } + } + + class PackagedDossierIntegrationTests(unittest.TestCase): def test_allowlisted_contract_rejects_extended_control_separators(self): request = { @@ -71,7 +81,13 @@ def test_runtime_projection_stays_unlocked_only_and_hides_locked_dependencies(se evidence.unlock("EV-VISIBLE") runtime = type("Runtime", (), {"evidence": evidence})() - dossier = build_runtime_dossier(runtime, "PERSON:PAUL", "Paul", "PERSON")["dossier"] + dossier = build_runtime_dossier( + runtime, + "PERSON:PAUL", + "Paul", + "PERSON", + subject_catalog=canonical_subject_catalog(), + )["dossier"] self.assertEqual(dossier["evidence_scope"], "unlocked_only") self.assertEqual([row["row_id"] for row in dossier["rows"]], ["EV-VISIBLE"]) rendered = "\n".join(dossier["linear"]) @@ -80,6 +96,25 @@ def test_runtime_projection_stays_unlocked_only_and_hides_locked_dependencies(se self.assertNotIn("CL-LOCKED", rendered) self.assertNotIn("Locked proposition", rendered) + + def test_runtime_projection_rejects_canonical_subject_relabeling(self): + runtime = type("Runtime", (), {"evidence": EvidenceRuntime()})() + catalog = canonical_subject_catalog() + + for display_name, kind in (("Peter", "PERSON"), ("Paul", "PLACE")): + with self.subTest(display_name=display_name, kind=kind): + with self.assertRaisesRegex( + RuntimeGatewayError, + "does not match canonical catalog", + ): + build_runtime_dossier( + runtime, + "PERSON:PAUL", + display_name, + kind, + subject_catalog=catalog, + ) + def test_deferred_ui_completion_is_inert_after_leave_and_reopen(self): node = shutil.which("node") self.assertIsNotNone(node, "hosted integration runner must expose Node for executable WebView module regression") From b9a702d3b87278a83b934aad273155fea1165ead Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 16:22:49 +0200 Subject: [PATCH 040/125] Fix Dossier mixed-provenance visibility --- .../scripture_archive_runtime/dossiers.py | 42 +++++++++++++++---- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/dossiers.py b/runtime_engine/scripture_archive_runtime/dossiers.py index 4cef458bf..14ac2d92e 100644 --- a/runtime_engine/scripture_archive_runtime/dossiers.py +++ b/runtime_engine/scripture_archive_runtime/dossiers.py @@ -162,15 +162,43 @@ def __init__(self, runtime: EvidenceRuntime): self.runtime = runtime @staticmethod - def _record_witness(record: EvidenceRecord) -> tuple[bool, str | None]: - """Distinguish safe witness-less evidence from unsafe witness metadata.""" - has_declared_witness = record.witness is not None or any( - passage.witness is not None for passage in record.passage_refs - ) + def _clean_witness_token(value: object) -> str | None: + """Validate one authored witness token without normalizing it.""" + if not isinstance(value, str) or not value or value != value.strip(): + return None + if any( + ord(character) < 0x20 + or 0x7F <= ord(character) <= 0x9F + or character in {"\\u2028", "\\u2029"} + for character in value + ): + return None + return value + + @classmethod + def _record_witness(cls, record: EvidenceRecord) -> tuple[bool, str | None]: + """Distinguish safe mixed/witness-less evidence from unsafe metadata. + + The shared resolver intentionally returns None both when no single witness + is attributable and when witness metadata is malformed or contradictory. + A Dossier evidence row may still expose canonical mixed provenance when + every per-passage token is clean; it must only avoid inventing one + aggregate witness. Malformed tokens and record/passages conflicts remain + fail-closed. + """ resolved = resolve_evidence_witness(record) - if has_declared_witness and resolved is None: + if resolved is not None: + return True, resolved + + if record.witness is not None: return False, None - return True, resolved + for passage in record.passage_refs: + if ( + passage.witness is not None + and cls._clean_witness_token(passage.witness) is None + ): + return False, None + return True, None @staticmethod def _passage_ids(records: tuple[EvidenceRecord, ...]) -> tuple[str, ...]: From 89fd48ee6842048e75fb188e30b921ee1b29674b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 16:22:51 +0200 Subject: [PATCH 041/125] Regress Dossier mixed witness classification --- .../tests/test_dossier_witness_regressions.py | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/runtime_engine/tests/test_dossier_witness_regressions.py b/runtime_engine/tests/test_dossier_witness_regressions.py index 526e0d289..79eb75fab 100644 --- a/runtime_engine/tests/test_dossier_witness_regressions.py +++ b/runtime_engine/tests/test_dossier_witness_regressions.py @@ -1,11 +1,63 @@ import unittest from scripture_archive_runtime.dossiers import DossierAssembler, DossierKind, DossierSubject -from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime, Relation +from scripture_archive_runtime.evidence import Claim, EvidenceRecord, EvidenceRuntime, PassageRef, Relation from scripture_archive_runtime.models import Confidence class DossierWitnessRegressionTests(unittest.TestCase): + def test_clean_mixed_passage_provenance_remains_visible_without_aggregate_witness(self): + runtime = EvidenceRuntime() + runtime.add_evidence( + EvidenceRecord( + evidence_id="EV-MIXED", + passage_refs=( + PassageRef("Acts.9.7", "Acts", 9, 7, witness="Acts 9 narrator"), + PassageRef("Acts.22.9", "Acts", 22, 9, witness="Acts 22 Paul speech"), + ), + proposition="Canonical mixed-provenance proposition.", + confidence=Confidence.T1, + witness=None, + entity_ids=("EVENT-X",), + ) + ) + runtime.unlock("EV-MIXED") + + view = DossierAssembler(runtime).build( + DossierSubject("EVENT-X", DossierKind.EVENT, "X") + ) + row = next(row for row in view.rows if row.row_id == "EV-MIXED") + self.assertIsNone(row.witness) + self.assertEqual( + ( + ("Acts.22.9", "Acts 22 Paul speech"), + ("Acts.9.7", "Acts 9 narrator"), + ), + row.passage_witnesses, + ) + + def test_malformed_mixed_passage_witness_remains_fail_closed(self): + runtime = EvidenceRuntime() + runtime.add_evidence( + EvidenceRecord( + evidence_id="EV-MALFORMED", + passage_refs=( + PassageRef("Acts.9.7", "Acts", 9, 7, witness="Acts 9 narrator"), + PassageRef("Acts.22.9", "Acts", 22, 9, witness=" Acts 22 Paul speech"), + ), + proposition="Malformed witness metadata must not become visible.", + confidence=Confidence.T1, + witness=None, + entity_ids=("EVENT-X",), + ) + ) + runtime.unlock("EV-MALFORMED") + + view = DossierAssembler(runtime).build( + DossierSubject("EVENT-X", DossierKind.EVENT, "X") + ) + self.assertNotIn("EV-MALFORMED", {row.row_id for row in view.rows}) + def test_declared_claim_and_relation_witness_require_positive_visible_support(self): runtime = EvidenceRuntime() runtime.add_evidence( From 973f9724d6e5846e823d4fc5c6dafe48e88c91ed Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 16:25:25 +0200 Subject: [PATCH 042/125] Fix Dossier Unicode witness guard escaping --- runtime_engine/scripture_archive_runtime/dossiers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime_engine/scripture_archive_runtime/dossiers.py b/runtime_engine/scripture_archive_runtime/dossiers.py index 14ac2d92e..30afc2c29 100644 --- a/runtime_engine/scripture_archive_runtime/dossiers.py +++ b/runtime_engine/scripture_archive_runtime/dossiers.py @@ -169,7 +169,7 @@ def _clean_witness_token(value: object) -> str | None: if any( ord(character) < 0x20 or 0x7F <= ord(character) <= 0x9F - or character in {"\\u2028", "\\u2029"} + or character in {"\u2028", "\u2029"} for character in value ): return None From c4051d62bbdda05bd3f066037edf43692c6ab9d2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 16:25:27 +0200 Subject: [PATCH 043/125] Regress Unicode separator witness rejection --- .../tests/test_dossier_witness_regressions.py | 44 +++++++++++-------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/runtime_engine/tests/test_dossier_witness_regressions.py b/runtime_engine/tests/test_dossier_witness_regressions.py index 79eb75fab..c633d04df 100644 --- a/runtime_engine/tests/test_dossier_witness_regressions.py +++ b/runtime_engine/tests/test_dossier_witness_regressions.py @@ -37,26 +37,32 @@ def test_clean_mixed_passage_provenance_remains_visible_without_aggregate_witnes ) def test_malformed_mixed_passage_witness_remains_fail_closed(self): - runtime = EvidenceRuntime() - runtime.add_evidence( - EvidenceRecord( - evidence_id="EV-MALFORMED", - passage_refs=( - PassageRef("Acts.9.7", "Acts", 9, 7, witness="Acts 9 narrator"), - PassageRef("Acts.22.9", "Acts", 22, 9, witness=" Acts 22 Paul speech"), - ), - proposition="Malformed witness metadata must not become visible.", - confidence=Confidence.T1, - witness=None, - entity_ids=("EVENT-X",), - ) - ) - runtime.unlock("EV-MALFORMED") + for suffix, malformed in ( + ("SPACE", " Acts 22 Paul speech"), + ("U2028", "Acts 22\u2028Paul speech"), + ): + with self.subTest(suffix=suffix): + runtime = EvidenceRuntime() + evidence_id = f"EV-MALFORMED-{suffix}" + runtime.add_evidence( + EvidenceRecord( + evidence_id=evidence_id, + passage_refs=( + PassageRef("Acts.9.7", "Acts", 9, 7, witness="Acts 9 narrator"), + PassageRef("Acts.22.9", "Acts", 22, 9, witness=malformed), + ), + proposition="Malformed witness metadata must not become visible.", + confidence=Confidence.T1, + witness=None, + entity_ids=("EVENT-X",), + ) + ) + runtime.unlock(evidence_id) - view = DossierAssembler(runtime).build( - DossierSubject("EVENT-X", DossierKind.EVENT, "X") - ) - self.assertNotIn("EV-MALFORMED", {row.row_id for row in view.rows}) + view = DossierAssembler(runtime).build( + DossierSubject("EVENT-X", DossierKind.EVENT, "X") + ) + self.assertNotIn(evidence_id, {row.row_id for row in view.rows}) def test_declared_claim_and_relation_witness_require_positive_visible_support(self): runtime = EvidenceRuntime() From 93abad980af924fbd888959e484f42962d993627 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 16:29:49 +0200 Subject: [PATCH 044/125] Fix canonical Psalm classification in Cross-Testament projection --- .../application/cross_testament_projection.py | 6 ++++++ .../test_packaged_cross_testament_contract.py | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py index b3348114f..4ee44440f 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py @@ -26,9 +26,15 @@ "Titus", "Philemon", "Hebrews", "James", "1 Peter", "2 Peter", "1 John", "2 John", "3 John", "Jude", "Revelation", ) +# The independently accepted D4 relation shards author Psalms references with +# the singular book token "Psalm". Keep that exact canonical token explicit +# here; do not normalize source records or admit arbitrary aliases. +_CANONICAL_BOOK_ALIASES: Mapping[str, str] = {"Psalm": "OT"} + BOOK_TESTAMENTS: Mapping[str, str] = { **{book: "OT" for book in _OT_BOOKS}, **{book: "NT" for book in _NT_BOOKS}, + **_CANONICAL_BOOK_ALIASES, } diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py index a50c5a716..67b4c3f4e 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py @@ -3,7 +3,7 @@ from pathlib import Path from tempfile import TemporaryDirectory -from scripture_archive_platform.application.cross_testament_projection import project_packaged_cross_testament +from scripture_archive_platform.application.cross_testament_projection import BOOK_TESTAMENTS, project_packaged_cross_testament from scripture_archive_platform.application.runtime_gateway import build_runtime_gateway from scripture_archive_platform.application.service import PlatformApplication from scripture_archive_platform.transport.contracts import validate_request_shape @@ -128,6 +128,20 @@ def test_production_gateway_materializes_checked_in_source_audited_pack(self): expected_relation_ids, ) + def test_materialized_canonical_book_tokens_are_explicitly_classified(self): + repo_root = Path(__file__).resolve().parents[4] + bundles = ( + load_otnt_relation_pack(repo_root), + load_independently_audited_d4_otnt(repo_root), + ) + seen = {} + for bundle in bundles: + for record in bundle.runtime.evidence.values(): + for passage in record.passage_refs: + self.assertIn(passage.book, BOOK_TESTAMENTS) + seen[passage.book] = BOOK_TESTAMENTS[passage.book] + self.assertEqual(seen.get("Psalm"), "OT") + def test_packaged_projection_preserves_explicit_relation_provenance(self): data = project_packaged_cross_testament(self._runtime()) self.assertEqual(data["schema"], "scripture.research.cross-testament.v1") From 0b7d100f770330f27025e92c7ecac496e9d66c99 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 19:55:36 +0200 Subject: [PATCH 045/125] Fix mixed per-passage witness provenance in Cross-Testament projection --- .../scripture_archive_runtime/cross_testament.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/cross_testament.py b/runtime_engine/scripture_archive_runtime/cross_testament.py index 82e6be4b5..0c51a405f 100644 --- a/runtime_engine/scripture_archive_runtime/cross_testament.py +++ b/runtime_engine/scripture_archive_runtime/cross_testament.py @@ -276,10 +276,12 @@ def _index_passages( record = evidence[evidence_id] _validate_evidence(record, expected_id=evidence_id) resolved_witness = resolve_evidence_witness(record) - has_witness_signal = record.witness is not None or any( - passage.witness is not None for passage in record.passage_refs - ) - if has_witness_signal and resolved_witness is None: + # A record-level witness is an assertion about every cited passage and + # therefore must resolve exactly. A witness-null record may intentionally + # aggregate multiple source-local passage witnesses; preserve each one at + # the passage provenance boundary instead of treating plurality as a + # contradiction (for example EV-PA-0016/0017). + if record.witness is not None and resolved_witness is None: raise ValueError( f"Evidence {record.evidence_id} witness conflicts with passage or is malformed" ) @@ -296,7 +298,11 @@ def _index_passages( evidence_id=record.evidence_id, confidence=record.confidence.value, tx1=record.tx1, - witness=resolved_witness, + witness=( + resolved_witness + if resolved_witness is not None + else passage.witness + ), ) ) return passages, { From 2eeb7e0ddab4ade3f5ee29dc648cf44157a40750 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 19:57:25 +0200 Subject: [PATCH 046/125] R06 Cross-Testament: scope projection to explicit relation support --- .../application/cross_testament_projection.py | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py index 4ee44440f..4101f0e60 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py @@ -75,6 +75,49 @@ def _validate_value(value: object, field: str, *, depth: int = 0) -> None: raise ValueError(f"{field} contains unsupported packaged value") +def _relation_scoped_runtime(runtime: EvidenceRuntime) -> EvidenceRuntime: + """Copy only explicit Cross-Testament relation support into a read-only snapshot. + + The canonical runtime also contains evidence for unrelated research surfaces. + Those records are not Cross-Testament inputs merely because they share the same + EvidenceRuntime. Keep every explicit relation, every evidence-backed endpoint, + and every record that names a passage explicitly declared by a relation. The + unchanged generic projector then retains its strict validation for all relevant + support, while unrelated mixed-provenance evidence cannot block this surface. + """ + if not isinstance(runtime, EvidenceRuntime): + raise TypeError("runtime must be an EvidenceRuntime") + + relation_passage_ids = { + passage_id + for relation in runtime.relations.values() + for passage_id in relation.passage_ids + } + endpoint_evidence_ids = { + endpoint_id + for relation in runtime.relations.values() + for endpoint_id in (relation.source_id, relation.target_id) + if endpoint_id in runtime.evidence + } + + scoped = EvidenceRuntime() + for evidence_id, record in sorted(runtime.evidence.items()): + supports_relation_passage = any( + passage.passage_id in relation_passage_ids + for passage in record.passage_refs + ) + if evidence_id in endpoint_evidence_ids or supports_relation_passage: + scoped.add_evidence(record) + + for relation_id in sorted(runtime.relations): + scoped.add_relation(runtime.relations[relation_id]) + + for evidence_id in sorted(runtime.unlocked): + if evidence_id in scoped.evidence: + scoped.unlock(evidence_id) + return scoped + + def project_packaged_cross_testament(runtime: EvidenceRuntime) -> dict[str, object]: """Return the bounded read-only OT↔NT projection used by the packaged app. @@ -83,7 +126,7 @@ def project_packaged_cross_testament(runtime: EvidenceRuntime) -> dict[str, obje topics, entities, chronology, or prose similarity. """ projection = project_cross_testament( - runtime, + _relation_scoped_runtime(runtime), book_testaments=BOOK_TESTAMENTS, unlocked_only=True, ) From 90ac82ac103ae771211fe0c712f0e2c712b78665 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 19:57:28 +0200 Subject: [PATCH 047/125] Regress mixed per-passage witness provenance in Cross-Testament --- .../test_cross_testament_mixed_provenance.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 runtime_engine/tests/test_cross_testament_mixed_provenance.py diff --git a/runtime_engine/tests/test_cross_testament_mixed_provenance.py b/runtime_engine/tests/test_cross_testament_mixed_provenance.py new file mode 100644 index 000000000..99ead99c6 --- /dev/null +++ b/runtime_engine/tests/test_cross_testament_mixed_provenance.py @@ -0,0 +1,56 @@ +import unittest + +from scripture_archive_runtime.cross_testament import project_cross_testament +from scripture_archive_runtime.evidence import EvidenceRecord, EvidenceRuntime, PassageRef, Relation +from scripture_archive_runtime.models import Confidence + + +class MixedWitnessProvenanceTests(unittest.TestCase): + def test_witness_null_mixed_record_preserves_passage_local_witnesses(self): + runtime = EvidenceRuntime() + ot = PassageRef("ISA7:14", "Isaiah", 7, 14, witness="Isaiah unit") + nt = PassageRef("MT1:23", "Matthew", 1, 23, witness="Matthew unit") + + runtime.add_evidence( + EvidenceRecord( + "EV-MIXED", + (ot, nt), + "One technical evidence record intentionally spans distinct source-local witnesses.", + Confidence.T1, + witness=None, + ) + ) + runtime.add_evidence( + EvidenceRecord("EV-OT", (ot,), "OT support", Confidence.T1, witness="Isaiah unit") + ) + runtime.add_evidence( + EvidenceRecord("EV-NT", (nt,), "NT support", Confidence.T1, witness="Matthew unit") + ) + runtime.add_relation( + Relation( + "REL-X", + "EV-OT", + "explicit_cross_reference", + "EV-NT", + passage_ids=("ISA7:14", "MT1:23"), + ) + ) + for evidence_id in ("EV-MIXED", "EV-OT", "EV-NT"): + runtime.unlock(evidence_id) + + projection = project_cross_testament( + runtime, + book_testaments={"Isaiah": "OT", "Matthew": "NT"}, + ) + + self.assertEqual(len(projection.links), 1) + link = projection.links[0] + ot_provenance = {item.evidence_id: item.witness for item in link.ot.evidence} + nt_provenance = {item.evidence_id: item.witness for item in link.nt.evidence} + self.assertEqual(ot_provenance["EV-MIXED"], "Isaiah unit") + self.assertEqual(nt_provenance["EV-MIXED"], "Matthew unit") + self.assertNotEqual(ot_provenance["EV-MIXED"], nt_provenance["EV-MIXED"]) + + +if __name__ == "__main__": + unittest.main() From a2a1f5c232c70b066b66cfb9f54d16dac942eb2e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 19:57:58 +0200 Subject: [PATCH 048/125] R06 Cross-Testament: cover unrelated mixed-provenance evidence --- .../test_packaged_cross_testament_contract.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py index 67b4c3f4e..8925bd3f7 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py @@ -162,6 +162,30 @@ def test_packaged_projection_preserves_explicit_relation_provenance(self): for expected in ("REL-X", "ISA7:14", "MT1:23", "witness=Isaiah", "witness=Matthew"): self.assertIn(expected, linear) + def test_unrelated_mixed_provenance_evidence_does_not_block_explicit_relations(self): + runtime = self._runtime() + runtime.add_evidence( + EvidenceRecord( + "EV-UNRELATED-MIXED", + ( + PassageRef("ACT9:7", "Acts", 9, 7, witness="Acts 9 narrator"), + PassageRef("ACT22:9", "Acts", 22, 9, witness="Acts 22 Paul speech"), + ), + "Mixed source-local provenance outside the relation scope", + Confidence.T1, + witness=None, + ) + ) + runtime.unlock("EV-UNRELATED-MIXED") + + data = project_packaged_cross_testament(runtime) + + self.assertEqual([link["relation_id"] for link in data["links"]], ["REL-X"]) + serialized = repr(data) + self.assertNotIn("EV-UNRELATED-MIXED", serialized) + self.assertNotIn("ACT9:7", serialized) + self.assertNotIn("ACT22:9", serialized) + def test_locked_endpoint_remains_honest_not_stated_empty_state(self): data = project_packaged_cross_testament(self._runtime(unlock_nt=False)) self.assertEqual(data["status"], "NOT_STATED_IN_CITED_TEXT") From f245766b693b6c11f5d7558f080b0503eb911976 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:00:10 +0200 Subject: [PATCH 049/125] R06 Cross-Testament: converge on canonical mixed-witness runtime semantics --- .../application/cross_testament_projection.py | 45 +------------------ 1 file changed, 1 insertion(+), 44 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py index 4101f0e60..4ee44440f 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/cross_testament_projection.py @@ -75,49 +75,6 @@ def _validate_value(value: object, field: str, *, depth: int = 0) -> None: raise ValueError(f"{field} contains unsupported packaged value") -def _relation_scoped_runtime(runtime: EvidenceRuntime) -> EvidenceRuntime: - """Copy only explicit Cross-Testament relation support into a read-only snapshot. - - The canonical runtime also contains evidence for unrelated research surfaces. - Those records are not Cross-Testament inputs merely because they share the same - EvidenceRuntime. Keep every explicit relation, every evidence-backed endpoint, - and every record that names a passage explicitly declared by a relation. The - unchanged generic projector then retains its strict validation for all relevant - support, while unrelated mixed-provenance evidence cannot block this surface. - """ - if not isinstance(runtime, EvidenceRuntime): - raise TypeError("runtime must be an EvidenceRuntime") - - relation_passage_ids = { - passage_id - for relation in runtime.relations.values() - for passage_id in relation.passage_ids - } - endpoint_evidence_ids = { - endpoint_id - for relation in runtime.relations.values() - for endpoint_id in (relation.source_id, relation.target_id) - if endpoint_id in runtime.evidence - } - - scoped = EvidenceRuntime() - for evidence_id, record in sorted(runtime.evidence.items()): - supports_relation_passage = any( - passage.passage_id in relation_passage_ids - for passage in record.passage_refs - ) - if evidence_id in endpoint_evidence_ids or supports_relation_passage: - scoped.add_evidence(record) - - for relation_id in sorted(runtime.relations): - scoped.add_relation(runtime.relations[relation_id]) - - for evidence_id in sorted(runtime.unlocked): - if evidence_id in scoped.evidence: - scoped.unlock(evidence_id) - return scoped - - def project_packaged_cross_testament(runtime: EvidenceRuntime) -> dict[str, object]: """Return the bounded read-only OT↔NT projection used by the packaged app. @@ -126,7 +83,7 @@ def project_packaged_cross_testament(runtime: EvidenceRuntime) -> dict[str, obje topics, entities, chronology, or prose similarity. """ projection = project_cross_testament( - _relation_scoped_runtime(runtime), + runtime, book_testaments=BOOK_TESTAMENTS, unlocked_only=True, ) From 4def16629176644a8ccf9b50317cb190fdc7c9e5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:28:57 +0200 Subject: [PATCH 050/125] R06: add fail-closed trusted update staging core --- .../application_update_staging.py | 242 ++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_staging.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_staging.py b/runtime_engine/scripture_archive_runtime/application_update_staging.py new file mode 100644 index 000000000..8138d3013 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_staging.py @@ -0,0 +1,242 @@ +"""Trusted staging for a locally verified Scripture Archive application update. + +Staging is deliberately narrower than installation. It copies already-selected local +bytes into a host-owned per-user update state, verifies those copied bytes again, +and atomically records a bounded pending journal. It never executes, unpacks, +replaces, restarts, or rolls back an application executable. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import secrets +import stat +from typing import Any + +from .application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, + verify_local_update, +) + + +STAGING_JOURNAL_SCHEMA = "scripture.application-update-staging.v1" +_PENDING_DIRECTORY = "pending" +_JOURNAL_NAME = "pending-update.json" +_MAX_JOURNAL_BYTES = 16 * 1024 +_COPY_CHUNK_BYTES = 1024 * 1024 + + +@dataclass(frozen=True) +class StagedApplicationUpdate: + product_id: str + target_platform: str + current_version: str + target_version: str + source_head: str + artifact_name: str + artifact_size: int + artifact_sha256: str + authenticity: str = "same_publisher_authenticode_verified" + status: str = "staged" + + +def stage_local_update( + manifest: ApplicationUpdateManifest, + artifact_path: str | os.PathLike[str], + staging_root: str | os.PathLike[str], + *, + current_version: str, + same_publisher_authenticode_verified: bool, +) -> StagedApplicationUpdate: + """Copy exact candidate bytes into trusted state and persist a pending journal. + + The caller must supply a positive native same-publisher Authenticode decision. + This function does not trust that decision as byte identity: source bytes are + verified before copying, the copy is hashed while written, and the staged file + is verified again through the canonical application-update verifier. + + ``staging_root`` is host-owned state. The journal intentionally contains no + original local path and no absolute staged path. A future apply operation must + reconstruct its host-owned path and repeat both exact-byte and authenticity + verification instead of treating this journal as install authority. + """ + + if same_publisher_authenticode_verified is not True: + raise ApplicationUpdateError( + "same-publisher Authenticode verification is required before staging" + ) + + verified_source = verify_local_update( + manifest, + artifact_path, + current_version=current_version, + ) + root = Path(staging_root) + _ensure_directory(root) + pending_root = root / _PENDING_DIRECTORY + _ensure_directory(pending_root) + digest_root = pending_root / verified_source.artifact_sha256 + _ensure_directory(digest_root) + + destination = digest_root / verified_source.artifact_name + temporary = digest_root / ( + f".{verified_source.artifact_name}.tmp-{secrets.token_hex(12)}" + ) + source = Path(artifact_path) + + try: + copied_size, copied_digest = _copy_exact_bytes(source, temporary) + if copied_size != verified_source.artifact_size: + raise ApplicationUpdateError("staged artifact size does not match manifest") + if copied_digest != verified_source.artifact_sha256: + raise ApplicationUpdateError("staged artifact SHA-256 does not match manifest") + _ensure_directory(digest_root) + os.replace(temporary, destination) + _fsync_directory(digest_root) + except Exception: + try: + temporary.unlink(missing_ok=True) + except OSError: + pass + raise + + verified_staged = verify_local_update( + manifest, + destination, + current_version=current_version, + ) + staged = StagedApplicationUpdate( + product_id=verified_staged.product_id, + target_platform=verified_staged.target_platform, + current_version=verified_staged.current_version, + target_version=verified_staged.target_version, + source_head=verified_staged.source_head, + artifact_name=verified_staged.artifact_name, + artifact_size=verified_staged.artifact_size, + artifact_sha256=verified_staged.artifact_sha256, + ) + _write_pending_journal(root, staged) + return staged + + +def _ensure_directory(path: Path) -> None: + try: + path.mkdir(parents=True, exist_ok=True) + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("trusted update staging directory is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError("trusted update staging path must be a real directory") + + +def _copy_exact_bytes(source: Path, destination: Path) -> tuple[int, str]: + try: + before = source.lstat() + except OSError as exc: + raise ApplicationUpdateError("update artifact is unavailable for staging") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update artifact must remain a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + + digest = hashlib.sha256() + total = 0 + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + try: + output_fd = os.open(destination, flags, 0o600) + with source.open("rb") as input_handle, os.fdopen(output_fd, "wb") as output_handle: + opened_before = os.fstat(input_handle.fileno()) + opened_identity = ( + opened_before.st_dev, + opened_before.st_ino, + opened_before.st_size, + opened_before.st_mtime_ns, + ) + if opened_identity != before_identity or not stat.S_ISREG(opened_before.st_mode): + raise ApplicationUpdateError("update artifact changed before staging copy") + while True: + chunk = input_handle.read(_COPY_CHUNK_BYTES) + if not chunk: + break + total += len(chunk) + digest.update(chunk) + output_handle.write(chunk) + output_handle.flush() + os.fsync(output_handle.fileno()) + opened_after = os.fstat(input_handle.fileno()) + after_open_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if after_open_identity != opened_identity: + raise ApplicationUpdateError("update artifact changed during staging copy") + after = source.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("update artifact could not be staged safely") from exc + + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if after_identity != before_identity: + raise ApplicationUpdateError("update artifact changed during staging copy") + return total, digest.hexdigest() + + +def _write_pending_journal(root: Path, staged: StagedApplicationUpdate) -> None: + payload: dict[str, Any] = { + "schema": STAGING_JOURNAL_SCHEMA, + "status": staged.status, + "product_id": staged.product_id, + "target_platform": staged.target_platform, + "current_version": staged.current_version, + "target_version": staged.target_version, + "source_head": staged.source_head, + "artifact_name": staged.artifact_name, + "artifact_size": staged.artifact_size, + "artifact_sha256": staged.artifact_sha256, + "authenticity": staged.authenticity, + } + encoded = (json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + if len(encoded) > _MAX_JOURNAL_BYTES: + raise ApplicationUpdateError("pending update journal exceeds size limit") + + temporary = root / f".{_JOURNAL_NAME}.tmp-{secrets.token_hex(12)}" + journal = root / _JOURNAL_NAME + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + try: + descriptor = os.open(temporary, flags, 0o600) + with os.fdopen(descriptor, "wb") as handle: + handle.write(encoded) + handle.flush() + os.fsync(handle.fileno()) + _ensure_directory(root) + os.replace(temporary, journal) + _fsync_directory(root) + except Exception: + try: + temporary.unlink(missing_ok=True) + except OSError: + pass + raise + + +def _fsync_directory(path: Path) -> None: + """Best-effort metadata durability where directory fsync is supported.""" + + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + except OSError: + pass + finally: + os.close(descriptor) From 0f7868b9ac87a74d2d4a941120e015bc90cb6777 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:29:28 +0200 Subject: [PATCH 051/125] R06: compose native trusted update staging --- .../desktop_host/update_application.py | 72 ++++++++++++++++--- 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py index 62e725451..eb89c0f73 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py @@ -15,6 +15,7 @@ ) UPDATE_COMMAND = "application_update.select_verify" +STAGE_UPDATE_COMMAND = "application_update.select_verify_stage" MAX_UPDATE_MANIFEST_BYTES = 16 * 1024 @@ -73,13 +74,17 @@ def _one_path(value: Any) -> str | None: class NativeApplicationUpdateLayer: - """Wrap the platform app with one packaged-Windows-only update command. + """Wrap the platform app with packaged-Windows-only update commands. All ordinary commands remain owned by the wrapped application. The browser can request update selection only with an empty payload; local paths are created by the native picker and are never serialized into a successful or failed response. - Hash/size verification remains independent from the optional fail-closed Windows - same-publisher Authenticode signal. Nothing is installed or executed here. + + Verification proves exact manifest bytes independently from the optional + same-publisher Authenticode signal. Trusted staging is a separate command and is + allowed only after that Authenticode signal is positive. Staging copies and + re-verifies bytes in host-owned state; it still does not install, execute, + replace, restart, or roll back the application. """ def __init__( @@ -90,6 +95,7 @@ def __init__( *, current_version: str, authenticity_verifier: Callable[[Path], bool] | None = None, + staging_root: Path | None = None, ) -> None: self._app = app self._repo_root = Path(repo_root).resolve() @@ -100,14 +106,18 @@ def __init__( if authenticity_verifier is not None else self._default_authenticity_verifier ) + self._staging_root = Path(staging_root) if staging_root is not None else None def handle(self, request: Any) -> dict[str, Any]: - if not isinstance(request, dict) or request.get("command") != UPDATE_COMMAND: + if not isinstance(request, dict) or request.get("command") not in { + UPDATE_COMMAND, + STAGE_UPDATE_COMMAND, + }: return self._app.handle(request) rid = str(request.get("request_id", "invalid")) try: rid, command, payload = validate_request_shape(request) - if command != UPDATE_COMMAND or payload: + if command not in {UPDATE_COMMAND, STAGE_UPDATE_COMMAND} or payload: raise ValueError("application update verification requires an empty payload") selection = self._selector() if selection is None: @@ -115,6 +125,7 @@ def handle(self, request: Any) -> dict[str, Any]: rid, { "verified": False, + "staged": False, "status": "cancelled", "message": "Вибір локального оновлення скасовано.", }, @@ -127,7 +138,7 @@ def handle(self, request: Any) -> dict[str, Any]: raise ValueError("native update picker returned an invalid selection") manifest_path, artifact_path = map(Path, selection) manifest_payload = self._read_manifest_fail_closed(manifest_path) - ApplicationUpdateManifest, verify_local_update = self._load_update_core() + ApplicationUpdateManifest, verify_local_update, stage_local_update = self._load_update_core() manifest = ApplicationUpdateManifest.from_json(manifest_payload) verified = verify_local_update( manifest, @@ -152,10 +163,50 @@ def handle(self, request: Any) -> dict[str, Any]: ) authenticity = "same_publisher_authenticode_verified" + if command == STAGE_UPDATE_COMMAND: + if not authenticity_verified: + return error_response( + rid, + "UPDATE_AUTHENTICITY_REQUIRED", + "Trusted staging requires a valid same-publisher Authenticode signature.", + ) + if self._staging_root is None: + return error_response( + rid, + "UPDATE_STAGING_UNAVAILABLE", + "Trusted application update staging is unavailable.", + ) + staged = stage_local_update( + manifest, + artifact_path, + self._staging_root, + current_version=self._current_version, + same_publisher_authenticode_verified=True, + ) + return ok_response( + rid, + { + "verified": True, + "staged": True, + "status": staged.status, + "product_id": staged.product_id, + "target_platform": staged.target_platform, + "current_version": staged.current_version, + "target_version": staged.target_version, + "source_head": staged.source_head, + "artifact_name": staged.artifact_name, + "artifact_size": staged.artifact_size, + "artifact_sha256": staged.artifact_sha256, + "authenticity": staged.authenticity, + "installation_performed": False, + }, + ) + return ok_response( rid, { "verified": True, + "staged": False, "status": "verified", "product_id": verified.product_id, "target_platform": verified.target_platform, @@ -186,7 +237,7 @@ def handle(self, request: Any) -> dict[str, Any]: def _default_authenticity_verifier(self, candidate: Path) -> bool: return verify_same_publisher_authenticode(Path(sys.executable), candidate) - def _load_update_core(self) -> tuple[Any, Any]: + def _load_update_core(self) -> tuple[Any, Any, Any]: root_text = str(self._repo_root) if root_text not in sys.path: sys.path.insert(0, root_text) @@ -194,8 +245,11 @@ def _load_update_core(self) -> tuple[Any, Any]: ApplicationUpdateManifest, verify_local_update, ) + from runtime_engine.scripture_archive_runtime.application_update_staging import ( + stage_local_update, + ) - return ApplicationUpdateManifest, verify_local_update + return ApplicationUpdateManifest, verify_local_update, stage_local_update @staticmethod def _read_manifest_fail_closed(path: Path) -> bytes: @@ -210,4 +264,4 @@ def _read_manifest_fail_closed(path: Path) -> bytes: after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) if before_identity != after_identity or len(payload) != before.st_size: raise ValueError("update manifest changed while being read") - return payload \ No newline at end of file + return payload From 380c3f74fafe11b90bfc61aed4fa599b16efabb7 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:29:42 +0200 Subject: [PATCH 052/125] R06: bind trusted update staging to app state --- .../scripture_archive_platform/desktop_host/main.py | 1 + 1 file changed, 1 insertion(+) 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 590f85401..334870a1b 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 @@ -57,6 +57,7 @@ def main() -> int: root, selector, current_version=CURRENT_APPLICATION_VERSION, + staging_root=Path(platform_app.store.root) / "application-updates", ) app = NativeDiagnosticsLayer( app, From c005a1f3d78fd6e31dc1b210214d8cf4a745310b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:30:11 +0200 Subject: [PATCH 053/125] R06: cover trusted update staging fail-closed boundaries --- ...est_packaged_application_update_staging.py | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py new file mode 100644 index 000000000..7cf19f01f --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py @@ -0,0 +1,163 @@ +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import ( + STAGING_JOURNAL_SCHEMA, + stage_local_update, +) +from scripture_archive_platform.desktop_host.update_application import ( + NativeApplicationUpdateLayer, + STAGE_UPDATE_COMMAND, + UPDATE_COMMAND, +) + + +class FakeBaseApplication: + def __init__(self): + self.calls = [] + + def handle(self, request): + self.calls.append(request) + return {"ok": True, "data": {"passthrough": True}} + + +def repository_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "runtime_engine" / "scripture_archive_runtime" / "application_update.py").exists(): + return parent + raise RuntimeError("repository root with application_update.py not found") + + +def request(command, payload=None): + return { + "api_version": "scripture.transport.v1", + "request_id": "update-staging-test-1", + "command": command, + "payload": {} if payload is None else payload, + } + + +class PackagedApplicationUpdateStagingTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"trusted-staging-exact-update-bytes") + self.digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + self.manifest = self.root / "update-manifest.json" + self.manifest.write_text( + json.dumps( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "b" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": self.digest, + } + ), + encoding="utf-8", + ) + self.staging = self.root / "host-state" / "application-updates" + self.base = FakeBaseApplication() + self.selection_calls = 0 + + def tearDown(self): + self.temp.cleanup() + + def selector(self): + self.selection_calls += 1 + return str(self.manifest), str(self.artifact) + + def layer(self, authenticity=True, *, staging_root=None): + return NativeApplicationUpdateLayer( + self.base, + repository_root(), + self.selector, + current_version="0.6.0-r06.3dev.a", + authenticity_verifier=lambda candidate: authenticity, + staging_root=self.staging if staging_root is None else staging_root, + ) + + def test_positive_same_publisher_candidate_is_staged_and_reverified(self): + response = self.layer(True).handle(request(STAGE_UPDATE_COMMAND)) + self.assertTrue(response["ok"]) + data = response["data"] + self.assertTrue(data["verified"]) + self.assertTrue(data["staged"]) + self.assertEqual("staged", data["status"]) + self.assertEqual("same_publisher_authenticode_verified", data["authenticity"]) + self.assertFalse(data["installation_performed"]) + + staged = self.staging / "pending" / self.digest / self.artifact.name + self.assertEqual(self.artifact.read_bytes(), staged.read_bytes()) + journal_path = self.staging / "pending-update.json" + journal = json.loads(journal_path.read_text(encoding="utf-8")) + self.assertEqual(STAGING_JOURNAL_SCHEMA, journal["schema"]) + self.assertEqual("staged", journal["status"]) + self.assertEqual(self.digest, journal["artifact_sha256"]) + self.assertEqual(self.artifact.name, journal["artifact_name"]) + self.assertEqual("same_publisher_authenticode_verified", journal["authenticity"]) + serialized = json.dumps(journal, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn(str(self.artifact), serialized) + self.assertNotIn("staged_path", journal) + self.assertNotIn("source_path", journal) + + def test_unsigned_or_unproven_publisher_cannot_be_staged(self): + response = self.layer(False).handle(request(STAGE_UPDATE_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_AUTHENTICITY_REQUIRED", response["error"]["code"]) + self.assertFalse((self.staging / "pending-update.json").exists()) + self.assertFalse((self.staging / "pending").exists()) + + def test_verify_only_keeps_existing_non_staging_semantics(self): + response = self.layer(True).handle(request(UPDATE_COMMAND)) + self.assertTrue(response["ok"]) + self.assertTrue(response["data"]["verified"]) + self.assertFalse(response["data"]["staged"]) + self.assertEqual("verified", response["data"]["status"]) + self.assertFalse(self.staging.exists()) + + def test_browser_cannot_supply_stage_or_filesystem_path(self): + response = self.layer(True).handle( + request(STAGE_UPDATE_COMMAND, {"path": "C:\\Users\\attacker\\payload.exe"}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual(0, self.selection_calls) + self.assertFalse(self.staging.exists()) + + def test_unusable_staging_root_fails_closed_without_path_disclosure(self): + bad_root = self.root / "not-a-directory" + bad_root.write_text("occupied", encoding="utf-8") + response = self.layer(True, staging_root=bad_root).handle(request(STAGE_UPDATE_COMMAND)) + self.assertFalse(response["ok"]) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn(str(self.artifact), serialized) + + def test_runtime_stager_refuses_missing_authenticity_authority(self): + manifest = ApplicationUpdateManifest.from_json(self.manifest.read_bytes()) + with self.assertRaises(ApplicationUpdateError): + stage_local_update( + manifest, + self.artifact, + self.staging, + current_version="0.6.0-r06.3dev.a", + same_publisher_authenticode_verified=False, + ) + self.assertFalse(self.staging.exists()) + + +if __name__ == "__main__": + unittest.main() From 48e49aac132468d62b227420e8245471927f8964 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:30:52 +0200 Subject: [PATCH 054/125] R06: expose accessible trusted update staging action --- .../frontend/application-update.js | 70 ++++++++++++++----- 1 file changed, 53 insertions(+), 17 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/application-update.js b/lanes/dev1/repair_overlay/frontend/application-update.js index be2fbdf22..42e0abd85 100644 --- a/lanes/dev1/repair_overlay/frontend/application-update.js +++ b/lanes/dev1/repair_overlay/frontend/application-update.js @@ -1,5 +1,6 @@ const API_VERSION='scripture.transport.v1'; -const UPDATE_COMMAND='application_update.select_verify'; +const VERIFY_UPDATE_COMMAND='application_update.select_verify'; +const STAGE_UPDATE_COMMAND='application_update.select_verify_stage'; const $=id=>document.getElementById(id); let sequence=0; @@ -19,7 +20,7 @@ function openUpdateView(){ const view=$('application-update-view'); view?.classList.remove('hidden'); setTimeout(()=>$('application-update-heading')?.focus(),0); - announce('Оновлення: виберіть локальний manifest і пакет для перевірки. Файли не встановлюються.'); + announce('Оновлення: можна лише перевірити локальний пакет або перевірити й підготувати його у приватному сховищі програми. Встановлення не виконується.'); } function hideUpdateView(){ @@ -45,7 +46,7 @@ function renderDetails(data){ if(!host)return; host.replaceChildren(); const rows=[ - ['Статус','Перевірено'], + ['Статус',data.staged===true?'Перевірено й підготовлено':'Перевірено'], ['Продукт',data.product_id], ['Платформа',data.target_platform], ['Поточна версія',data.current_version], @@ -63,27 +64,39 @@ function renderDetails(data){ } } -async function invokeNativeVerification(){ +async function invokeNativeUpdate(command){ const invoke=window.pywebview?.api?.invoke; - if(typeof invoke!=='function')throw new Error('Перевірка оновлення доступна лише у packaged Windows application.'); + if(typeof invoke!=='function')throw new Error('Оновлення доступне лише у packaged Windows application.'); const response=await invoke({ api_version:API_VERSION, request_id:`update-ui-${Date.now()}-${++sequence}`, - command:UPDATE_COMMAND, + command, payload:{}, }); - if(!response?.ok)throw new Error(response?.error?.message||'Локальна перевірка оновлення завершилась помилкою.'); + if(!response?.ok)throw new Error(response?.error?.message||'Локальна операція оновлення завершилась помилкою.'); return response.data??{}; } -async function selectAndVerify(){ - const button=$('application-update-select'); - if(button)button.disabled=true; +function setBusy(busy){ + for(const id of ['application-update-select','application-update-stage']){ + const button=$(id); + if(button)button.disabled=busy; + } +} + +async function selectAndVerify(command=VERIFY_UPDATE_COMMAND){ + const staging=command===STAGE_UPDATE_COMMAND; + setBusy(true); clearDetails(); - announce('Відкрито native file picker. Спочатку виберіть manifest, потім локальний пакет.'); + announce(staging + ?'Відкрито native file picker. Після перевірки підпису й точних байтів пакет буде скопійовано у приватне сховище програми; встановлення не виконується.' + :'Відкрито native file picker. Спочатку виберіть manifest, потім локальний пакет.'); try{ - const data=await invokeNativeVerification(); - if(data.verified===true&&data.status==='verified'){ + const data=await invokeNativeUpdate(command); + if(data.verified===true&&data.status==='staged'&&data.staged===true){ + renderDetails(data); + announce(`Локальний пакет ${data.artifact_name??'пакет'} перевірено та підготовлено для майбутнього оновлення. Same-publisher Authenticode підтверджено. Нічого не встановлено, не замінено й не запущено.`); + }else if(data.verified===true&&data.status==='verified'){ renderDetails(data); const publisherStatus=data.authenticity==='same_publisher_authenticode_verified' ?' Видавець підтверджений чинним Authenticode і збігається з поточною програмою.' @@ -92,19 +105,42 @@ async function selectAndVerify(){ }else if(data.status==='cancelled'){ announce(data.message||'Вибір локального оновлення скасовано.'); }else{ - throw new Error('Native verifier не підтвердив локальний пакет.'); + throw new Error(staging?'Native staging не підтвердив підготовку пакета.':'Native verifier не підтвердив локальний пакет.'); } }catch(error){ clearDetails(); - announce(`Оновлення не перевірено: ${error?.message||'невідома помилка'}`); + announce(`${staging?'Оновлення не підготовлено':'Оновлення не перевірено'}: ${error?.message||'невідома помилка'}`); }finally{ - if(button)button.disabled=false; + setBusy(false); + } +} + +function mountStagingControl(){ + const verify=$('application-update-select'); + if(!verify||$('application-update-stage'))return; + const stage=document.createElement('button'); + stage.type='button'; + stage.id='application-update-stage'; + stage.textContent='Перевірити й підготувати оновлення'; + stage.setAttribute('aria-describedby','application-update-stage-help'); + verify.insertAdjacentElement('afterend',stage); + + const help=document.createElement('p'); + help.id='application-update-stage-help'; + help.textContent='Підготовка дозволена лише для пакета з чинним same-publisher Authenticode. Точні байти копіюються у приватне сховище програми та перевіряються повторно. Install, replace, restart і rollback не виконуються.'; + stage.insertAdjacentElement('afterend',help); + stage.addEventListener('click',()=>selectAndVerify(STAGE_UPDATE_COMMAND)); + + const intro=document.querySelector('#application-update-view > p:not(.eyebrow)'); + if(intro){ + intro.textContent='Цей екран перевіряє локальний manifest і пакет через native Windows file picker. Browser не передає шлях до файлу. Окрема дія може підготувати лише same-publisher пакет у приватному сховищі програми; жодне встановлення або заміна executable тут не виконується.'; } } function mount(){ + mountStagingControl(); $('nav-application-update')?.addEventListener('click',openUpdateView); - $('application-update-select')?.addEventListener('click',selectAndVerify); + $('application-update-select')?.addEventListener('click',()=>selectAndVerify(VERIFY_UPDATE_COMMAND)); for(const id of ['nav-home','nav-research','nav-authoring'])$(''+id)&&$(id)?.addEventListener('click',hideUpdateView); const update=$('application-update-view'); if(update){ From 6fffedc5b3bce5e5bb0e66a3fce64a8aa4b0f022 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:31:01 +0200 Subject: [PATCH 055/125] R06: cover accessible trusted staging UI contract --- .../test_application_update_staging_ui.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py new file mode 100644 index 000000000..4148a98f1 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py @@ -0,0 +1,25 @@ +import unittest +from pathlib import Path + + +class ApplicationUpdateStagingUiTests(unittest.TestCase): + def test_staging_action_is_semantic_empty_payload_and_truthful_about_boundary(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "application-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.select_verify", script) + self.assertIn("application_update.select_verify_stage", script) + self.assertIn("payload:{}", script) + self.assertIn("application-update-stage", script) + self.assertIn("aria-describedby", script) + self.assertIn("same-publisher Authenticode", script) + self.assertIn("Install, replace, restart і rollback не виконуються", script) + self.assertIn("Нічого не встановлено, не замінено й не запущено", script) + self.assertNotIn("innerHTML", script) + compact = script.replace(" ", "") + self.assertNotIn("payload:{path", compact) + self.assertNotIn("staged_path", script) + self.assertNotIn("source_path", script) + + +if __name__ == "__main__": + unittest.main() From 692a53f588f118491463cb9d5d55ae4897d8b847 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:32:49 +0200 Subject: [PATCH 056/125] R06: syntax-qualify update staging JavaScript --- ...st_application_update_staging_js_syntax.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py new file mode 100644 index 000000000..e028c6cec --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_js_syntax.py @@ -0,0 +1,24 @@ +import shutil +import subprocess +import unittest +from pathlib import Path + + +@unittest.skipUnless(shutil.which("node"), "Node.js is required for frontend syntax qualification") +class ApplicationUpdateStagingJavaScriptSyntaxTests(unittest.TestCase): + def test_application_update_module_parses_as_javascript(self): + platform = Path(__file__).resolve().parents[1] + script = platform / "frontend" / "application-update.js" + completed = subprocess.run( + [shutil.which("node"), "--check", str(script)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + self.assertEqual(0, completed.returncode, completed.stderr or completed.stdout) + + +if __name__ == "__main__": + unittest.main() From 77c563078bb0773c25731298e4e6f55137961ecf Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 20:34:19 +0200 Subject: [PATCH 057/125] R06: prove staging refuses symlinked host state --- ...est_application_update_staging_symlinks.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py new file mode 100644 index 000000000..a319c95fa --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py @@ -0,0 +1,75 @@ +import hashlib +import json +import os +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update + + +@unittest.skipUnless(hasattr(os, "symlink"), "symlink support required") +class ApplicationUpdateStagingSymlinkTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"symlink-boundary-update") + digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + self.manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "c" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": digest, + } + ) + + def tearDown(self): + self.temp.cleanup() + + def stage(self, root): + return stage_local_update( + self.manifest, + self.artifact, + root, + current_version="0.6.0-r06.3dev.a", + same_publisher_authenticode_verified=True, + ) + + def _make_directory_symlink_or_skip(self, link, target): + target.mkdir(parents=True, exist_ok=True) + try: + link.symlink_to(target, target_is_directory=True) + except (OSError, NotImplementedError) as exc: + self.skipTest(f"directory symlink unavailable: {exc}") + + def test_staging_root_symlink_fails_closed(self): + external = self.root / "external-root" + link = self.root / "application-updates" + self._make_directory_symlink_or_skip(link, external) + with self.assertRaises(ApplicationUpdateError): + self.stage(link) + self.assertEqual([], list(external.iterdir())) + + def test_pending_directory_symlink_fails_closed(self): + staging = self.root / "application-updates" + staging.mkdir() + external = self.root / "external-pending" + self._make_directory_symlink_or_skip(staging / "pending", external) + with self.assertRaises(ApplicationUpdateError): + self.stage(staging) + self.assertEqual([], list(external.iterdir())) + self.assertFalse((staging / "pending-update.json").exists()) + + +if __name__ == "__main__": + unittest.main() From 2d7e0007ba24a1fd750be433736a3e573d2d4e78 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:04:33 +0200 Subject: [PATCH 058/125] Fix staging copy descriptor lifetime --- .../application_update_staging.py | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_staging.py b/runtime_engine/scripture_archive_runtime/application_update_staging.py index 8138d3013..3e93f3ecb 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_staging.py +++ b/runtime_engine/scripture_archive_runtime/application_update_staging.py @@ -147,8 +147,7 @@ def _copy_exact_bytes(source: Path, destination: Path) -> tuple[int, str]: total = 0 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL try: - output_fd = os.open(destination, flags, 0o600) - with source.open("rb") as input_handle, os.fdopen(output_fd, "wb") as output_handle: + with source.open("rb") as input_handle: opened_before = os.fstat(input_handle.fileno()) opened_identity = ( opened_before.st_dev, @@ -158,15 +157,24 @@ def _copy_exact_bytes(source: Path, destination: Path) -> tuple[int, str]: ) if opened_identity != before_identity or not stat.S_ISREG(opened_before.st_mode): raise ApplicationUpdateError("update artifact changed before staging copy") - while True: - chunk = input_handle.read(_COPY_CHUNK_BYTES) - if not chunk: - break - total += len(chunk) - digest.update(chunk) - output_handle.write(chunk) - output_handle.flush() - os.fsync(output_handle.fileno()) + + output_fd = os.open(destination, flags, 0o600) + try: + output_handle = os.fdopen(output_fd, "wb") + except Exception: + os.close(output_fd) + raise + with output_handle: + while True: + chunk = input_handle.read(_COPY_CHUNK_BYTES) + if not chunk: + break + total += len(chunk) + digest.update(chunk) + output_handle.write(chunk) + output_handle.flush() + os.fsync(output_handle.fileno()) + opened_after = os.fstat(input_handle.fileno()) after_open_identity = ( opened_after.st_dev, From 62fd3e5e47e9ce5a43391f428487447e8ead8812 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:04:54 +0200 Subject: [PATCH 059/125] Add regression for staging source-open failure --- .../tests/test_packaged_application_update_staging.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py index 7cf19f01f..9f4419846 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py @@ -3,6 +3,7 @@ import tempfile import unittest from pathlib import Path +from unittest.mock import patch from runtime_engine.scripture_archive_runtime.application_update import ( ApplicationUpdateError, @@ -10,6 +11,7 @@ ) from runtime_engine.scripture_archive_runtime.application_update_staging import ( STAGING_JOURNAL_SCHEMA, + _copy_exact_bytes, stage_local_update, ) from scripture_archive_platform.desktop_host.update_application import ( @@ -158,6 +160,13 @@ def test_runtime_stager_refuses_missing_authenticity_authority(self): ) self.assertFalse(self.staging.exists()) + def test_copy_does_not_create_destination_if_source_open_fails_after_lstat(self): + destination = self.root / "copy-never-created.tmp" + with patch.object(Path, "open", side_effect=OSError("source disappeared")): + with self.assertRaises(ApplicationUpdateError): + _copy_exact_bytes(self.artifact, destination) + self.assertFalse(destination.exists()) + if __name__ == "__main__": unittest.main() From fb02364117132d21fdd8665cd065f47a63466302 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:05:39 +0200 Subject: [PATCH 060/125] R06: close staging journal descriptor ownership --- .../application_update_staging.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_staging.py b/runtime_engine/scripture_archive_runtime/application_update_staging.py index 3e93f3ecb..d40bfa65e 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_staging.py +++ b/runtime_engine/scripture_archive_runtime/application_update_staging.py @@ -219,7 +219,12 @@ def _write_pending_journal(root: Path, staged: StagedApplicationUpdate) -> None: flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL try: descriptor = os.open(temporary, flags, 0o600) - with os.fdopen(descriptor, "wb") as handle: + try: + handle = os.fdopen(descriptor, "wb") + except Exception: + os.close(descriptor) + raise + with handle: handle.write(encoded) handle.flush() os.fsync(handle.fileno()) From 25f34cb6b2683729332d78fa85dfa424270d2e5b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:06:04 +0200 Subject: [PATCH 061/125] R06: regress staging descriptor cleanup --- ...est_application_update_staging_symlinks.py | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py index a319c95fa..87d507311 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py @@ -4,12 +4,59 @@ import tempfile import unittest from pathlib import Path +from unittest.mock import patch from runtime_engine.scripture_archive_runtime.application_update import ( ApplicationUpdateError, ApplicationUpdateManifest, ) -from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update +from runtime_engine.scripture_archive_runtime.application_update_staging import ( + StagedApplicationUpdate, + _copy_exact_bytes, + _write_pending_journal, + stage_local_update, +) + + +class ApplicationUpdateStagingDescriptorTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"descriptor-boundary-update") + + def tearDown(self): + self.temp.cleanup() + + def test_copy_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): + destination = self.root / ".copy.tmp" + with patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", + side_effect=OSError("fdopen failed"), + ): + with self.assertRaises(ApplicationUpdateError): + _copy_exact_bytes(self.artifact, destination) + self.assertFalse(destination.exists()) + + def test_journal_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): + staged = StagedApplicationUpdate( + product_id="scripture-archive", + target_platform="windows-x64", + current_version="0.6.0-r06.3dev.a", + target_version="0.6.1", + source_head="c" * 40, + artifact_name=self.artifact.name, + artifact_size=self.artifact.stat().st_size, + artifact_sha256=hashlib.sha256(self.artifact.read_bytes()).hexdigest(), + ) + with patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", + side_effect=OSError("fdopen failed"), + ): + with self.assertRaises(OSError): + _write_pending_journal(self.root, staged) + self.assertEqual([], list(self.root.glob(".pending-update.json.tmp-*"))) + self.assertFalse((self.root / "pending-update.json").exists()) @unittest.skipUnless(hasattr(os, "symlink"), "symlink support required") From b464061708921ae47e78de04972feb6b7bbbaa06 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:06:29 +0200 Subject: [PATCH 062/125] R06: align descriptor cleanup regression with helper contract --- .../test_application_update_staging_symlinks.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py index 87d507311..b51a4336a 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py @@ -28,15 +28,18 @@ def setUp(self): def tearDown(self): self.temp.cleanup() - def test_copy_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): + def test_copy_fdopen_failure_closes_descriptor(self): destination = self.root / ".copy.tmp" with patch( "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", side_effect=OSError("fdopen failed"), - ): + ), patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.close", + wraps=os.close, + ) as close_mock: with self.assertRaises(ApplicationUpdateError): _copy_exact_bytes(self.artifact, destination) - self.assertFalse(destination.exists()) + close_mock.assert_called_once() def test_journal_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): staged = StagedApplicationUpdate( @@ -52,9 +55,13 @@ def test_journal_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): with patch( "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", side_effect=OSError("fdopen failed"), - ): + ), patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.close", + wraps=os.close, + ) as close_mock: with self.assertRaises(OSError): _write_pending_journal(self.root, staged) + close_mock.assert_called_once() self.assertEqual([], list(self.root.glob(".pending-update.json.tmp-*"))) self.assertFalse((self.root / "pending-update.json").exists()) From 84ad6f22a27fca25dd99577f0b809951c80fe13d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:06:46 +0200 Subject: [PATCH 063/125] Cover journal descriptor cleanup failure --- ...est_packaged_application_update_staging.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py index 9f4419846..95647fd19 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py @@ -1,5 +1,6 @@ import hashlib import json +import os import tempfile import unittest from pathlib import Path @@ -11,7 +12,9 @@ ) from runtime_engine.scripture_archive_runtime.application_update_staging import ( STAGING_JOURNAL_SCHEMA, + StagedApplicationUpdate, _copy_exact_bytes, + _write_pending_journal, stage_local_update, ) from scripture_archive_platform.desktop_host.update_application import ( @@ -167,6 +170,42 @@ def test_copy_does_not_create_destination_if_source_open_fails_after_lstat(self) _copy_exact_bytes(self.artifact, destination) self.assertFalse(destination.exists()) + def test_pending_journal_closes_descriptor_if_fdopen_fails(self): + self.staging.mkdir(parents=True) + staged = StagedApplicationUpdate( + product_id="scripture-archive", + target_platform="windows-x64", + current_version="0.6.0-r06.3dev.a", + target_version="0.6.1", + source_head="b" * 40, + artifact_name=self.artifact.name, + artifact_size=self.artifact.stat().st_size, + artifact_sha256=self.digest, + ) + opened_descriptors = [] + real_open = os.open + + def recording_open(path, flags, mode=0o777): + descriptor = real_open(path, flags, mode) + opened_descriptors.append(descriptor) + return descriptor + + with patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.open", + side_effect=recording_open, + ), patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", + side_effect=OSError("fdopen failed"), + ): + with self.assertRaises(OSError): + _write_pending_journal(self.staging, staged) + + self.assertEqual(1, len(opened_descriptors)) + with self.assertRaises(OSError): + os.fstat(opened_descriptors[0]) + self.assertFalse((self.staging / "pending-update.json").exists()) + self.assertEqual([], list(self.staging.glob(".pending-update.json.tmp-*"))) + if __name__ == "__main__": unittest.main() From 24d67c8c4a1dc78d66019e055195b541084a8500 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:07:59 +0200 Subject: [PATCH 064/125] R06: deduplicate staging descriptor regression --- ...est_application_update_staging_symlinks.py | 56 +------------------ 1 file changed, 1 insertion(+), 55 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py index b51a4336a..a319c95fa 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_symlinks.py @@ -4,66 +4,12 @@ import tempfile import unittest from pathlib import Path -from unittest.mock import patch from runtime_engine.scripture_archive_runtime.application_update import ( ApplicationUpdateError, ApplicationUpdateManifest, ) -from runtime_engine.scripture_archive_runtime.application_update_staging import ( - StagedApplicationUpdate, - _copy_exact_bytes, - _write_pending_journal, - stage_local_update, -) - - -class ApplicationUpdateStagingDescriptorTests(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.root = Path(self.temp.name) - self.artifact = self.root / "ScriptureArchive-0.6.1.exe" - self.artifact.write_bytes(b"descriptor-boundary-update") - - def tearDown(self): - self.temp.cleanup() - - def test_copy_fdopen_failure_closes_descriptor(self): - destination = self.root / ".copy.tmp" - with patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", - side_effect=OSError("fdopen failed"), - ), patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.close", - wraps=os.close, - ) as close_mock: - with self.assertRaises(ApplicationUpdateError): - _copy_exact_bytes(self.artifact, destination) - close_mock.assert_called_once() - - def test_journal_fdopen_failure_closes_descriptor_and_leaves_no_temp_file(self): - staged = StagedApplicationUpdate( - product_id="scripture-archive", - target_platform="windows-x64", - current_version="0.6.0-r06.3dev.a", - target_version="0.6.1", - source_head="c" * 40, - artifact_name=self.artifact.name, - artifact_size=self.artifact.stat().st_size, - artifact_sha256=hashlib.sha256(self.artifact.read_bytes()).hexdigest(), - ) - with patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", - side_effect=OSError("fdopen failed"), - ), patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.close", - wraps=os.close, - ) as close_mock: - with self.assertRaises(OSError): - _write_pending_journal(self.root, staged) - close_mock.assert_called_once() - self.assertEqual([], list(self.root.glob(".pending-update.json.tmp-*"))) - self.assertFalse((self.root / "pending-update.json").exists()) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update @unittest.skipUnless(hasattr(os, "symlink"), "symlink support required") From fc45cc84a85cc9d91bd133115107d07e56623375 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:08:04 +0200 Subject: [PATCH 065/125] Deduplicate staging descriptor regression --- ...est_packaged_application_update_staging.py | 39 ------------------- 1 file changed, 39 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py index 95647fd19..9f4419846 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py @@ -1,6 +1,5 @@ import hashlib import json -import os import tempfile import unittest from pathlib import Path @@ -12,9 +11,7 @@ ) from runtime_engine.scripture_archive_runtime.application_update_staging import ( STAGING_JOURNAL_SCHEMA, - StagedApplicationUpdate, _copy_exact_bytes, - _write_pending_journal, stage_local_update, ) from scripture_archive_platform.desktop_host.update_application import ( @@ -170,42 +167,6 @@ def test_copy_does_not_create_destination_if_source_open_fails_after_lstat(self) _copy_exact_bytes(self.artifact, destination) self.assertFalse(destination.exists()) - def test_pending_journal_closes_descriptor_if_fdopen_fails(self): - self.staging.mkdir(parents=True) - staged = StagedApplicationUpdate( - product_id="scripture-archive", - target_platform="windows-x64", - current_version="0.6.0-r06.3dev.a", - target_version="0.6.1", - source_head="b" * 40, - artifact_name=self.artifact.name, - artifact_size=self.artifact.stat().st_size, - artifact_sha256=self.digest, - ) - opened_descriptors = [] - real_open = os.open - - def recording_open(path, flags, mode=0o777): - descriptor = real_open(path, flags, mode) - opened_descriptors.append(descriptor) - return descriptor - - with patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.open", - side_effect=recording_open, - ), patch( - "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", - side_effect=OSError("fdopen failed"), - ): - with self.assertRaises(OSError): - _write_pending_journal(self.staging, staged) - - self.assertEqual(1, len(opened_descriptors)) - with self.assertRaises(OSError): - os.fstat(opened_descriptors[0]) - self.assertFalse((self.staging / "pending-update.json").exists()) - self.assertEqual([], list(self.staging.glob(".pending-update.json.tmp-*"))) - if __name__ == "__main__": unittest.main() From 35196af7fa7f4067444357e228fed977b808280d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:09:18 +0200 Subject: [PATCH 066/125] Cover journal fdopen cleanup regression --- ...est_packaged_application_update_staging.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py index 9f4419846..d23453143 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_staging.py @@ -1,5 +1,6 @@ import hashlib import json +import os import tempfile import unittest from pathlib import Path @@ -11,7 +12,9 @@ ) from runtime_engine.scripture_archive_runtime.application_update_staging import ( STAGING_JOURNAL_SCHEMA, + StagedApplicationUpdate, _copy_exact_bytes, + _write_pending_journal, stage_local_update, ) from scripture_archive_platform.desktop_host.update_application import ( @@ -167,6 +170,31 @@ def test_copy_does_not_create_destination_if_source_open_fails_after_lstat(self) _copy_exact_bytes(self.artifact, destination) self.assertFalse(destination.exists()) + def test_pending_journal_fdopen_failure_closes_descriptor_and_temp_file(self): + self.staging.mkdir(parents=True) + staged = StagedApplicationUpdate( + product_id="scripture-archive", + target_platform="windows-x64", + current_version="0.6.0-r06.3dev.a", + target_version="0.6.1", + source_head="b" * 40, + artifact_name=self.artifact.name, + artifact_size=self.artifact.stat().st_size, + artifact_sha256=self.digest, + ) + with patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.fdopen", + side_effect=OSError("fdopen failed"), + ), patch( + "runtime_engine.scripture_archive_runtime.application_update_staging.os.close", + wraps=os.close, + ) as close_mock: + with self.assertRaises(OSError): + _write_pending_journal(self.staging, staged) + close_mock.assert_called_once() + self.assertFalse((self.staging / "pending-update.json").exists()) + self.assertEqual([], list(self.staging.glob(".pending-update.json.tmp-*"))) + if __name__ == "__main__": unittest.main() From 04f26663dba34b5e5beed46ab4b634bc48f5c353 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 21:18:24 +0200 Subject: [PATCH 067/125] R06: bind update manifest reads to file identity --- .../desktop_host/update_application.py | 32 +++++++++++++-- ...st_application_update_manifest_identity.py | 41 +++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_manifest_identity.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py index eb89c0f73..aa115eccd 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_application.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import stat import sys from pathlib import Path @@ -258,10 +259,35 @@ def _read_manifest_fail_closed(path: Path) -> bytes: raise ValueError("update manifest must be a regular non-symlink file") if before.st_size <= 0 or before.st_size > MAX_UPDATE_MANIFEST_BYTES: raise ValueError("update manifest is empty or exceeds the size limit") - payload = path.read_bytes() - after = path.lstat() before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if opened_identity != before_identity or not stat.S_ISREG(opened.st_mode): + raise ValueError("update manifest changed before being read") + payload = handle.read(MAX_UPDATE_MANIFEST_BYTES + 1) + opened_after = os.fstat(handle.fileno()) + opened_after_identity = ( + opened_after.st_dev, + opened_after.st_ino, + opened_after.st_size, + opened_after.st_mtime_ns, + ) + if opened_after_identity != opened_identity: + raise ValueError("update manifest changed while being read") + + after = path.lstat() after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) - if before_identity != after_identity or len(payload) != before.st_size: + if ( + after_identity != before_identity + or len(payload) != before.st_size + or len(payload) > MAX_UPDATE_MANIFEST_BYTES + ): raise ValueError("update manifest changed while being read") return payload diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_manifest_identity.py b/lanes/dev1/repair_overlay/tests/test_application_update_manifest_identity.py new file mode 100644 index 000000000..7f100bf2d --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_manifest_identity.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from scripture_archive_platform.desktop_host.update_application import ( + NativeApplicationUpdateLayer, +) + + +class ApplicationUpdateManifestIdentityTests(unittest.TestCase): + def test_manifest_path_swap_between_lstat_and_open_fails_closed(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + manifest = root / "update-manifest.json" + replacement = root / "replacement-manifest.json" + manifest.write_text('{"schema":"original-authority"}\n', encoding="utf-8") + replacement.write_text('{"schema":"replacement-data"}\n', encoding="utf-8") + + original_open = Path.open + swapped = False + + def racing_open(path: Path, *args, **kwargs): + nonlocal swapped + if path == manifest and not swapped: + swapped = True + os.replace(replacement, manifest) + return original_open(path, *args, **kwargs) + + with patch.object(Path, "open", new=racing_open): + with self.assertRaisesRegex(ValueError, "changed before being read"): + NativeApplicationUpdateLayer._read_manifest_fail_closed(manifest) + + self.assertTrue(swapped) + + +if __name__ == "__main__": + unittest.main() From f929f8e286efa6262489db716e4561708c11b1ff Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:01:25 +0200 Subject: [PATCH 068/125] R06: harden Cross-Testament qualification dependency coverage Keep product/runtime/source bytes unchanged. Extend the dedicated Cross-Testament gate to watch direct shared provenance, evidence materialization/registry, Confidence-model, and canonical R05/PA02 authority inputs exercised by the real production-gateway regression. Add a focused workflow-surface regression so those dependencies cannot silently fall out of the gate. --- .../r06-packaged-cross-testament.yml | 18 ++++++++ ...t_cross_testament_qualification_surface.py | 41 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py diff --git a/.github/workflows/r06-packaged-cross-testament.yml b/.github/workflows/r06-packaged-cross-testament.yml index 9e5c69963..0fc578c30 100644 --- a/.github/workflows/r06-packaged-cross-testament.yml +++ b/.github/workflows/r06-packaged-cross-testament.yml @@ -10,11 +10,19 @@ on: - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py' - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py' + - 'lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py' - 'runtime_engine/scripture_archive_runtime/cross_testament.py' - 'runtime_engine/scripture_archive_runtime/evidence.py' + - 'runtime_engine/scripture_archive_runtime/evidence_provenance.py' + - 'runtime_engine/scripture_archive_runtime/evidence_registry.py' + - 'runtime_engine/scripture_archive_runtime/evidence_materialization.py' + - 'runtime_engine/scripture_archive_runtime/models.py' - 'runtime_engine/scripture_archive_runtime/otnt_relation_pack.py' - 'runtime_engine/scripture_archive_runtime/d4_otnt_relation_registry.py' + - 'docs/evidence/R05_EVIDENCE_PROVENANCE_REGISTRY_v0.1*.json' + - 'docs/evidence/R06_PA02_STRUCTURED_EVIDENCE_INDEX_v0.1.json' + - 'docs/evidence/PA02_DAMASCUS_ROAD_WITNESS_PACK_v0.1.md' - 'docs/evidence/OTNT_RELATION_PACK_v0.1.json' - 'docs/evidence/D4_OTNT_INDEPENDENT_AUDIT_MANIFEST_v1.json' - 'docs/campaigns/OT/R06_D4_STAGE05_READABLE/relations/**' @@ -28,11 +36,19 @@ on: - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py' - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py' + - 'lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py' - 'lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py' - 'runtime_engine/scripture_archive_runtime/cross_testament.py' - 'runtime_engine/scripture_archive_runtime/evidence.py' + - 'runtime_engine/scripture_archive_runtime/evidence_provenance.py' + - 'runtime_engine/scripture_archive_runtime/evidence_registry.py' + - 'runtime_engine/scripture_archive_runtime/evidence_materialization.py' + - 'runtime_engine/scripture_archive_runtime/models.py' - 'runtime_engine/scripture_archive_runtime/otnt_relation_pack.py' - 'runtime_engine/scripture_archive_runtime/d4_otnt_relation_registry.py' + - 'docs/evidence/R05_EVIDENCE_PROVENANCE_REGISTRY_v0.1*.json' + - 'docs/evidence/R06_PA02_STRUCTURED_EVIDENCE_INDEX_v0.1.json' + - 'docs/evidence/PA02_DAMASCUS_ROAD_WITNESS_PACK_v0.1.md' - 'docs/evidence/OTNT_RELATION_PACK_v0.1.json' - 'docs/evidence/D4_OTNT_INDEPENDENT_AUDIT_MANIFEST_v1.json' - 'docs/campaigns/OT/R06_D4_STAGE05_READABLE/relations/**' @@ -86,6 +102,8 @@ jobs: run: python -c "import shutil; shutil.copytree('lanes/dev1/repair_overlay', 'r06_platform', dirs_exist_ok=True)" - name: Check Cross-Testament UI syntax run: node --check lanes/dev1/repair_overlay/frontend/cross-testament-ui.js + - name: Run Cross-Testament qualification dependency-surface regression + run: python -m unittest lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py -v - name: Run packaged Cross-Testament production-gateway regression run: python -c "import runpy,sys; sys.path.insert(0, 'r06_platform'); runpy.run_path('lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py', run_name='__main__')" - name: Diff hygiene diff --git a/lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py b/lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py new file mode 100644 index 000000000..b7b62c377 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py @@ -0,0 +1,41 @@ +from pathlib import Path +import unittest + + +REPO_ROOT = Path(__file__).resolve().parents[4] +WORKFLOW = REPO_ROOT / ".github" / "workflows" / "r06-packaged-cross-testament.yml" + +DIRECT_TRUTH_DEPENDENCIES = ( + "runtime_engine/scripture_archive_runtime/evidence_provenance.py", + "runtime_engine/scripture_archive_runtime/evidence_registry.py", + "runtime_engine/scripture_archive_runtime/evidence_materialization.py", + "runtime_engine/scripture_archive_runtime/models.py", + "docs/evidence/R05_EVIDENCE_PROVENANCE_REGISTRY_v0.1*.json", + "docs/evidence/R06_PA02_STRUCTURED_EVIDENCE_INDEX_v0.1.json", + "docs/evidence/PA02_DAMASCUS_ROAD_WITNESS_PACK_v0.1.md", +) + + +class CrossTestamentQualificationSurfaceTests(unittest.TestCase): + def test_direct_truth_dependencies_are_watched_on_push_and_pull_request(self): + workflow = WORKFLOW.read_text(encoding="utf-8") + for path in DIRECT_TRUTH_DEPENDENCIES: + token = f"- '{path}'" + self.assertEqual( + 2, + workflow.count(token), + f"Cross-Testament qualification must watch {path} on push and pull_request", + ) + + def test_surface_regression_is_watched_and_executed(self): + workflow = WORKFLOW.read_text(encoding="utf-8") + own_path = "lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py" + self.assertEqual(2, workflow.count(f"- '{own_path}'")) + self.assertIn( + "python -m unittest lanes/dev1/repair_overlay/tests/test_cross_testament_qualification_surface.py -v", + workflow, + ) + + +if __name__ == "__main__": + unittest.main() From ac5a122345660d59f590c03a2ddea2249372bb5a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:19:39 +0200 Subject: [PATCH 069/125] R06: expose qualified D4 corpus read-only in Library --- .../content/library.py | 217 +++++++++++++++++- 1 file changed, 205 insertions(+), 12 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index 914528bf1..c2e93be14 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -1,22 +1,30 @@ from __future__ import annotations +import json import re +from pathlib import Path from typing import Any -from scripture_archive_platform.content.loader import CanonicalContentLoader +from scripture_archive_platform.content.loader import CanonicalContentLoader, ContentLoadError SEARCH_SCHEMA = "scripture.library.search.v1" CATALOG_SCHEMA = "scripture.library.catalog.v1" +_D4_RELATIVE_ROOT = Path("docs/campaigns/OT/R06_D4_STAGE05_READABLE") +_D4_CAMPAIGN_ID = "OT-R06-D4" +_D4_EDITORIAL_STATUS = "AUTHOR_COMPLETE / DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING" +_D4_SOURCE_AUDIT_STATUS = "DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING" +_D4_MISSION_COUNT = 15 +_D4_NODE_COUNT = 450 class CanonicalLibraryIndex: - """Read-only search/catalog view over the canonical content loader. + """Read-only search/catalog view over canonical and qualified readable content. - This class deliberately does not persist a second search truth. It derives every - result from the loader's current in-memory canonical mission/node records and - only indexes fields that are already player-visible. Ground-truth answer, - grading, hint, feedback and rejected-answer fields are intentionally excluded. + Gradeable content remains owned exclusively by ``CanonicalContentLoader``. + A qualified D4 readable corpus may additionally be projected into this Library + view, but it is never inserted into the loader's gradeable mission/node maps. + The index is derived on demand and persists no second truth store. """ def __init__(self, loader: CanonicalContentLoader): @@ -51,6 +59,32 @@ def _unique(values: list[str]) -> list[str]: out.append(value) return out + @staticmethod + def _load_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ContentLoadError(f"invalid qualified readable D4 JSON {path}: {exc}") from exc + + @classmethod + def _load_jsonl(cls, path: Path) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + try: + lines = path.read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeDecodeError) as exc: + raise ContentLoadError(f"cannot read qualified readable D4 JSONL {path}: {exc}") from exc + for line_number, line in enumerate(lines, 1): + if not line.strip(): + continue + try: + row = json.loads(line) + except json.JSONDecodeError as exc: + raise ContentLoadError(f"invalid qualified readable D4 JSONL {path}:{line_number}") from exc + if not isinstance(row, dict): + raise ContentLoadError(f"qualified readable D4 row must be object: {path}:{line_number}") + rows.append(row) + return rows + @classmethod def _mission_source_refs(cls, mission: dict[str, Any]) -> list[str]: return cls._unique( @@ -60,22 +94,171 @@ def _mission_source_refs(cls, mission: dict[str, Any]) -> list[str]: @classmethod def _node_source_refs(cls, node: dict[str, Any], mission: dict[str, Any]) -> list[str]: - # Only the player-visible scope plus mission-visible Scripture scope are - # searchable. required_evidence/grading truth may be locked answer data. + # Only player-visible source scope plus mission-visible Scripture scope are + # searchable. Answer/grading/evidence-unlock truth remains deliberately out. return cls._unique( cls._text_values(node.get("source_scope_visible_to_player")) + cls._mission_source_refs(mission) ) + def _qualified_d4_records( + self, + ) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: + root = self.loader.repo_root / _D4_RELATIVE_ROOT + if not root.exists(): + return [], {}, {} + if root.is_symlink() or not root.is_dir(): + raise ContentLoadError("qualified readable D4 root must be a real directory") + + metadata_path = root / "metadata" / "mission_index_metadata.json" + if metadata_path.is_symlink() or not metadata_path.is_file(): + raise ContentLoadError("qualified readable D4 mission metadata is missing or unsafe") + metadata = self._load_json(metadata_path) + if not isinstance(metadata, dict): + raise ContentLoadError("qualified readable D4 mission metadata must be object") + campaign = metadata.get("campaign") + counts = metadata.get("counts") + if not isinstance(campaign, dict) or not isinstance(counts, dict): + raise ContentLoadError("qualified readable D4 metadata is incomplete") + if campaign.get("campaign_id") != _D4_CAMPAIGN_ID: + raise ContentLoadError("qualified readable D4 campaign identity changed") + if campaign.get("editorial_status") != _D4_EDITORIAL_STATUS: + raise ContentLoadError("qualified readable D4 editorial/audit status changed") + if campaign.get("source_audit_status") != _D4_SOURCE_AUDIT_STATUS: + raise ContentLoadError("qualified readable D4 source-audit status changed") + if counts.get("missions") != _D4_MISSION_COUNT or counts.get("nodes") != _D4_NODE_COUNT: + raise ContentLoadError("qualified readable D4 mission/node counts changed") + sequence = campaign.get("mission_sequence") + if not isinstance(sequence, list) or len(sequence) != _D4_MISSION_COUNT or len(set(sequence)) != len(sequence): + raise ContentLoadError("qualified readable D4 mission sequence is invalid") + campaign_title = self._clean(campaign.get("title_ua")) or _D4_CAMPAIGN_ID + + mission_rows: list[dict[str, Any]] = [] + for path in sorted((root / "registries").glob("missions_*.jsonl")): + if path.is_symlink() or not path.is_file(): + raise ContentLoadError("qualified readable D4 mission registry contains unsafe path") + mission_rows.extend(self._load_jsonl(path)) + if len(mission_rows) != _D4_MISSION_COUNT: + raise ContentLoadError("qualified readable D4 mission registry count changed") + + missions: list[dict[str, Any]] = [] + missions_by_id: dict[str, dict[str, Any]] = {} + expected_nodes_by_mission: dict[str, set[str]] = {} + for raw in mission_rows: + mid = raw.get("mission_id") + cid = raw.get("campaign_id") + task_nodes = raw.get("task_nodes") + if not isinstance(mid, str) or mid not in sequence or mid in missions_by_id: + raise ContentLoadError(f"unexpected or duplicate qualified readable D4 mission: {mid}") + if cid != _D4_CAMPAIGN_ID: + raise ContentLoadError(f"qualified readable D4 mission campaign changed: {mid}") + if not isinstance(task_nodes, list) or not task_nodes or not all(isinstance(v, str) and v for v in task_nodes): + raise ContentLoadError(f"qualified readable D4 mission task_nodes invalid: {mid}") + if len(set(task_nodes)) != len(task_nodes): + raise ContentLoadError(f"qualified readable D4 mission task_nodes duplicate: {mid}") + entry = { + "mission_id": mid, + "campaign_id": cid, + "title": self._clean(raw.get("title")) or mid, + "difficulty": raw.get("difficulty"), + "entry_node": raw.get("entry_node"), + "node_count": len(task_nodes), + "primary_scripture": raw.get("primary_scripture", []), + "secondary_scripture": raw.get("secondary_scripture", "none"), + "canonical_status": _D4_EDITORIAL_STATUS, + "source_audit_status": _D4_SOURCE_AUDIT_STATUS, + "content_access": "READ_ONLY_LIBRARY", + "gradeable_runtime_eligible": False, + "_campaign_title": campaign_title, + } + missions.append(entry) + missions_by_id[mid] = entry + expected_nodes_by_mission[mid] = set(task_nodes) + if [item["mission_id"] for item in missions] != sequence: + # Registry shard order is itself qualified and must match metadata order. + raise ContentLoadError("qualified readable D4 mission registry order changed") + + nodes: dict[str, dict[str, Any]] = {} + mission_for_node: dict[str, dict[str, Any]] = {} + actual_nodes_by_mission: dict[str, set[str]] = {mid: set() for mid in missions_by_id} + for path in sorted((root / "nodes").glob("nodes_*.jsonl")): + if path.is_symlink() or not path.is_file(): + raise ContentLoadError("qualified readable D4 node registry contains unsafe path") + for node in self._load_jsonl(path): + nid = node.get("node_id") + mid = node.get("mission_id") + if not isinstance(nid, str) or not nid or nid in nodes: + raise ContentLoadError(f"duplicate/empty qualified readable D4 node: {nid!r}") + if mid not in missions_by_id or nid not in expected_nodes_by_mission[mid]: + raise ContentLoadError(f"qualified readable D4 node/mission binding changed: {nid}") + nodes[nid] = node + mission_for_node[nid] = missions_by_id[mid] + actual_nodes_by_mission[mid].add(nid) + if len(nodes) != _D4_NODE_COUNT: + raise ContentLoadError("qualified readable D4 node count changed") + for mid, expected in expected_nodes_by_mission.items(): + if actual_nodes_by_mission[mid] != expected: + raise ContentLoadError(f"qualified readable D4 mission node set changed: {mid}") + return missions, nodes, mission_for_node + def _records(self) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: - self.loader._ensure() # Same-package read-only view; no independent store. - missions = [dict(item) for item in (self.loader._missions or [])] + self.loader._ensure() # Same-package read-only view; no independent persistent store. + missions: list[dict[str, Any]] = [] + for item in self.loader._missions or []: + mission = dict(item) + mission["content_access"] = "GRADEABLE_RUNTIME" + mission["gradeable_runtime_eligible"] = True + mission["_campaign_title"] = {"LN": "Остання ніч", "PA": "Дорога Павла"}.get( + str(mission.get("campaign_id") or ""), str(mission.get("campaign_id") or "") + ) + missions.append(mission) nodes = {str(key): dict(value) for key, value in (self.loader._nodes or {}).items()} mission_for_node = { str(key): dict(value) for key, value in (self.loader._mission_for_node or {}).items() } + + d4_missions, d4_nodes, d4_mission_for_node = self._qualified_d4_records() + existing_missions = {str(item.get("mission_id") or "") for item in missions} + if existing_missions.intersection(str(item.get("mission_id") or "") for item in d4_missions): + raise ContentLoadError("qualified readable D4 mission collides with gradeable runtime mission") + if set(nodes).intersection(d4_nodes): + raise ContentLoadError("qualified readable D4 node collides with gradeable runtime node") + missions.extend(d4_missions) + nodes.update(d4_nodes) + mission_for_node.update(d4_mission_for_node) return missions, nodes, mission_for_node + @staticmethod + def _public_mission(mission: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in mission.items() if not key.startswith("_")} + + def list_campaigns(self) -> list[dict[str, Any]]: + missions, _, _ = self._records() + grouped: dict[str, dict[str, Any]] = {} + for mission in missions: + cid = str(mission.get("campaign_id") or "") + row = grouped.setdefault( + cid, + { + "campaign_id": cid, + "title": mission.get("_campaign_title") or cid, + "mission_count": 0, + "machine_node_count": 0, + "gradeable_runtime_eligible": True, + "content_access": "GRADEABLE_RUNTIME", + }, + ) + row["mission_count"] += 1 + row["machine_node_count"] += int(mission.get("node_count") or 0) + if mission.get("gradeable_runtime_eligible") is not True: + row["gradeable_runtime_eligible"] = False + row["content_access"] = "READ_ONLY_LIBRARY" + return sorted(grouped.values(), key=lambda item: item["campaign_id"]) + + def list_missions(self, campaign_id: str) -> list[dict[str, Any]]: + missions, _, _ = self._records() + return [self._public_mission(item) for item in missions if item.get("campaign_id") == campaign_id] + def catalog(self) -> dict[str, Any]: missions, nodes, _ = self._records() mission_rows = [] @@ -92,19 +275,25 @@ def catalog(self) -> dict[str, Any]: "primary_scripture": list(self._text_values(mission.get("primary_scripture"))), "secondary_scripture": list(self._text_values(mission.get("secondary_scripture"))), "canonical_status": mission.get("canonical_status"), + "source_audit_status": mission.get("source_audit_status"), "node_count": int(mission.get("node_count") or 0), + "content_access": mission.get("content_access"), + "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, } ) for node_id, node in sorted(nodes.items()): - mission = (self.loader._mission_for_node or {}).get(node_id) or {} + mission = (dict((self.loader._mission_for_node or {}).get(node_id) or {})) + if not mission: + mission = next((item for item in missions if item.get("mission_id") == node.get("mission_id")), {}) passage_refs.extend(self._node_source_refs(node, mission)) return { "schema": CATALOG_SCHEMA, "source_of_truth": "CanonicalContentLoader", "derived_index": True, + "read_only_qualified_sources": [_D4_CAMPAIGN_ID] if any(m.get("campaign_id") == _D4_CAMPAIGN_ID for m in missions) else [], "bundled_full_bible_text": False, "text_provider_available": False, - "campaigns": self.loader.list_campaigns(), + "campaigns": self.list_campaigns(), "missions": mission_rows, "source_references": self._unique(passage_refs), "machine_node_count": len(nodes), @@ -178,6 +367,8 @@ def search( "title": self._clean(mission.get("title")) or mid, "snippet": refs[0] if refs else self._clean(mission.get("title")), "source_references": refs, + "content_access": mission.get("content_access"), + "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, "score": score, } ) @@ -207,6 +398,8 @@ def search( "task_family": task_family or None, "difficulty": node.get("difficulty"), "source_references": refs, + "content_access": mission.get("content_access"), + "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, "score": score, } ) From 59efc1b93491f27846dd9c82ff3e60355c3a4cdd Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:20:02 +0200 Subject: [PATCH 070/125] R06: prove D4 readable Library/runtime eligibility boundary --- .../test_d4_readable_library_consumption.py | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py new file mode 100644 index 000000000..647960f2e --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -0,0 +1,116 @@ +import json +import tempfile +import unittest +from pathlib import Path + +from scripture_archive_platform.content.library import CanonicalLibraryIndex +from scripture_archive_platform.content.loader import CanonicalContentLoader, ContentLoadError + + +D4_CAMPAIGN = "OT-R06-D4" +D4_FIRST_NODE = "OTAB01-N001" +D4_PRIVATE_ANSWER = "Yahweh tells Abram to leave his country, relatives, and father's house for a land Yahweh will show him." + + +def repository_root() -> Path: + candidates = [Path.cwd().resolve(), *Path.cwd().resolve().parents, *Path(__file__).resolve().parents] + for root in candidates: + if (root / "docs" / "campaigns" / "OT" / "R06_D4_STAGE05_READABLE").is_dir(): + return root + raise RuntimeError("qualified readable D4 repository root not found") + + +class D4ReadableLibraryConsumptionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.repo = repository_root() + cls.loader = CanonicalContentLoader(cls.repo) + cls.library = CanonicalLibraryIndex(cls.loader) + + def test_qualified_d4_is_visible_read_only_with_exact_mission_node_counts(self): + campaigns = {row["campaign_id"]: row for row in self.library.list_campaigns()} + self.assertIn(D4_CAMPAIGN, campaigns) + d4 = campaigns[D4_CAMPAIGN] + self.assertEqual(15, d4["mission_count"]) + self.assertEqual(450, d4["machine_node_count"]) + self.assertEqual("READ_ONLY_LIBRARY", d4["content_access"]) + self.assertFalse(d4["gradeable_runtime_eligible"]) + + missions = self.library.list_missions(D4_CAMPAIGN) + self.assertEqual(15, len(missions)) + self.assertEqual(450, sum(int(row["node_count"]) for row in missions)) + self.assertTrue(all(row["content_access"] == "READ_ONLY_LIBRARY" for row in missions)) + self.assertTrue(all(row["gradeable_runtime_eligible"] is False for row in missions)) + self.assertTrue(all("INDEPENDENT_AUDIT_PENDING" in row["canonical_status"] for row in missions)) + + def test_library_search_finds_real_d4_source_scope_without_private_answer_truth(self): + found = self.library.search("Genesis 12:1", campaign_id=D4_CAMPAIGN, limit=100) + task_ids = {row["id"] for row in found["results"] if row["kind"] == "task"} + self.assertIn(D4_FIRST_NODE, task_ids) + d4_rows = [row for row in found["results"] if row["campaign_id"] == D4_CAMPAIGN] + self.assertTrue(d4_rows) + self.assertTrue(all(row["content_access"] == "READ_ONLY_LIBRARY" for row in d4_rows)) + self.assertTrue(all(row["gradeable_runtime_eligible"] is False for row in d4_rows)) + + private = self.library.search(D4_PRIVATE_ANSWER, campaign_id=D4_CAMPAIGN, limit=100) + self.assertEqual(0, private["total"]) + serialized = json.dumps(found, ensure_ascii=False) + for forbidden in ("accepted_answer", "accepted_variants", "grading", "hints", "required_evidence"): + self.assertNotIn(forbidden, serialized) + + def test_d4_filesystem_presence_does_not_make_node_gradeable(self): + with self.assertRaises(ContentLoadError): + self.loader.load_node(D4_FIRST_NODE) + gradeable_campaigns = {row["campaign_id"] for row in self.loader.list_campaigns()} + self.assertNotIn(D4_CAMPAIGN, gradeable_campaigns) + + def test_existing_gradeable_runtime_nodes_remain_loadable(self): + self.loader._ensure() + self.assertTrue(self.loader._nodes) + node_id = sorted(self.loader._nodes)[0] + loaded = self.loader.load_node(node_id) + self.assertEqual(node_id, loaded["node_id"]) + mission = self.loader.mission_for_node(node_id) + self.assertTrue(mission["mission_id"]) + + def test_unqualified_readable_canary_cannot_enter_gradeable_loader(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + mission_dir = root / "docs" / "campaigns" / "DEMO" / "M1" + mission_dir.mkdir(parents=True) + (mission_dir / "MISSION_INDEX.json").write_text( + json.dumps( + { + "mission": { + "mission_id": "DM-01", + "campaign_id": "DM", + "title": "Gradeable control", + "entry_node": "DM01-N01", + "primary_scripture": ["Luke 1:1"], + }, + "node_count": 1, + "node_files": ["nodes.json"], + "canonical_status": "SOURCE_AUDITED", + } + ), + encoding="utf-8", + ) + (mission_dir / "nodes.json").write_text( + json.dumps({"nodes": [{"node_id": "DM01-N01", "mission_id": "DM-01"}]}), + encoding="utf-8", + ) + readable = root / "docs" / "campaigns" / "OT" / "R06_D4_STAGE05_READABLE" / "nodes" + readable.mkdir(parents=True) + (readable / "nodes_canary.jsonl").write_text( + json.dumps({"node_id": "D4-CANARY-N01", "mission_id": "D4-CANARY", "accepted_answer": "SECRET"}) + "\n", + encoding="utf-8", + ) + + loader = CanonicalContentLoader(root) + self.assertEqual("DM01-N01", loader.load_node("DM01-N01")["node_id"]) + with self.assertRaises(ContentLoadError): + loader.load_node("D4-CANARY-N01") + + +if __name__ == "__main__": + unittest.main() From 6f4de1bdfaceacbf3ad9cbe707c21c9ca30c4f77 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:20:27 +0200 Subject: [PATCH 071/125] R06: qualify real D4 read-only Library consumption --- tools/verify_library_search_overlay.py | 32 ++++++++++++++++---------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 63b48954f..6b6993870 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -19,12 +19,17 @@ CANONICAL_DEV1_SOURCE_COMMIT = "90a13aca71d2a5f832846a84acbdf0f7c89f5da9" CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" -EXPECTED_REAL_TESTS = 6 +EXPECTED_REAL_TESTS = 11 OVERLAY_FIDELITY_PATHS = ( Path("scripture_archive_platform/content/library.py"), Path("scripture_archive_platform/application/service.py"), Path("scripture_archive_platform/transport/contracts.py"), Path("tests/test_library_search.py"), + Path("tests/test_d4_readable_library_consumption.py"), +) +REGRESSION_MODULES = ( + ("library_search_real_regression", Path("tests/test_library_search.py")), + ("d4_readable_library_consumption_real_regression", Path("tests/test_d4_readable_library_consumption.py")), ) @@ -150,7 +155,7 @@ def parse_real_paths(platform_root: Path) -> None: ) -def load_real_regression_module(platform_root: Path): +def _reset_platform_imports(platform_root: Path) -> None: for name in tuple(sys.modules): if name == "scripture_archive_platform" or name.startswith( "scripture_archive_platform." @@ -164,23 +169,26 @@ def load_real_regression_module(platform_root: Path): sys.path.remove(value) sys.path.insert(0, value) - module_path = platform_root / "tests" / "test_library_search.py" - spec = importlib.util.spec_from_file_location( - "library_search_real_regression", module_path - ) + +def load_real_regression_module(platform_root: Path, name: str, relative: Path): + _reset_platform_imports(platform_root) + module_path = platform_root / relative + spec = importlib.util.spec_from_file_location(name, module_path) if spec is None or spec.loader is None: - raise AssertionError("Unable to load real Library/Search regression module") + raise AssertionError(f"Unable to load real Library/Search regression module {relative}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def run_real_response_regressions(platform_root: Path) -> None: - module = load_real_regression_module(platform_root) - suite = unittest.defaultTestLoader.loadTestsFromModule(module) + suite = unittest.TestSuite() + for name, relative in REGRESSION_MODULES: + module = load_real_regression_module(platform_root, name, relative) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) if suite.countTestCases() != EXPECTED_REAL_TESTS: raise AssertionError( - f"Expected {EXPECTED_REAL_TESTS} Library/Search tests, got {suite.countTestCases()}" + f"Expected {EXPECTED_REAL_TESTS} Library/Search + D4 read-only tests, got {suite.countTestCases()}" ) result = unittest.TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): @@ -196,8 +204,8 @@ def main() -> None: run_real_response_regressions(platform_root) print( "Library/Search qualification PASS: exact candidate checkout, pinned canonical " - "FINALPREP02 DEV1 base hash/CRC, overlay fidelity, and six real response-level " - "regressions." + "FINALPREP02 DEV1 base hash/CRC, overlay fidelity, six legacy Library/Search " + "regressions, and five real qualified-D4 read-only/runtime-eligibility regressions." ) From 7d77025163eb705d495e2f5c3613160476202489 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:21:59 +0200 Subject: [PATCH 072/125] R06: bind Library qualification to readable D4 authority --- .github/workflows/r06-library-search-qualification.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/r06-library-search-qualification.yml b/.github/workflows/r06-library-search-qualification.yml index 42f851951..aaef3168d 100644 --- a/.github/workflows/r06-library-search-qualification.yml +++ b/.github/workflows/r06-library-search-qualification.yml @@ -7,11 +7,13 @@ on: - r06-converge-library-search-current-coord-0912-sol paths: - 'lanes/dev1/**' + - 'docs/campaigns/OT/R06_D4_STAGE05_READABLE/**' - 'tools/verify_library_search_overlay.py' - '.github/workflows/r06-library-search-qualification.yml' pull_request: paths: - 'lanes/dev1/**' + - 'docs/campaigns/OT/R06_D4_STAGE05_READABLE/**' - 'tools/verify_library_search_overlay.py' - '.github/workflows/r06-library-search-qualification.yml' From 49fcfee9f5454d9b3cbe2492ef9ac301acd3eb53 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:23:21 +0200 Subject: [PATCH 073/125] R06: preserve gradeable eligibility in Library node results --- .../content/library.py | 170 ++++++++---------- 1 file changed, 74 insertions(+), 96 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index c2e93be14..953df9084 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -19,12 +19,11 @@ class CanonicalLibraryIndex: - """Read-only search/catalog view over canonical and qualified readable content. + """Derived read-only catalog/search over gradeable plus qualified readable content. - Gradeable content remains owned exclusively by ``CanonicalContentLoader``. - A qualified D4 readable corpus may additionally be projected into this Library - view, but it is never inserted into the loader's gradeable mission/node maps. - The index is derived on demand and persists no second truth store. + ``CanonicalContentLoader`` remains the only gradeable mission/node authority. + Qualified D4 JSONL records are projected only into this Library view and never + inserted into the loader's gradeable maps or persisted as a second truth store. """ def __init__(self, loader: CanonicalContentLoader): @@ -59,6 +58,20 @@ def _unique(values: list[str]) -> list[str]: out.append(value) return out + @classmethod + def _mission_source_refs(cls, mission: dict[str, Any]) -> list[str]: + return cls._unique( + cls._text_values(mission.get("primary_scripture")) + + cls._text_values(mission.get("secondary_scripture")) + ) + + @classmethod + def _node_source_refs(cls, node: dict[str, Any], mission: dict[str, Any]) -> list[str]: + return cls._unique( + cls._text_values(node.get("source_scope_visible_to_player")) + + cls._mission_source_refs(mission) + ) + @staticmethod def _load_json(path: Path) -> Any: try: @@ -66,13 +79,13 @@ def _load_json(path: Path) -> Any: except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise ContentLoadError(f"invalid qualified readable D4 JSON {path}: {exc}") from exc - @classmethod - def _load_jsonl(cls, path: Path) -> list[dict[str, Any]]: - rows: list[dict[str, Any]] = [] + @staticmethod + def _load_jsonl(path: Path) -> list[dict[str, Any]]: try: lines = path.read_text(encoding="utf-8").splitlines() except (OSError, UnicodeDecodeError) as exc: raise ContentLoadError(f"cannot read qualified readable D4 JSONL {path}: {exc}") from exc + rows: list[dict[str, Any]] = [] for line_number, line in enumerate(lines, 1): if not line.strip(): continue @@ -85,21 +98,10 @@ def _load_jsonl(cls, path: Path) -> list[dict[str, Any]]: rows.append(row) return rows - @classmethod - def _mission_source_refs(cls, mission: dict[str, Any]) -> list[str]: - return cls._unique( - cls._text_values(mission.get("primary_scripture")) - + cls._text_values(mission.get("secondary_scripture")) - ) - - @classmethod - def _node_source_refs(cls, node: dict[str, Any], mission: dict[str, Any]) -> list[str]: - # Only player-visible source scope plus mission-visible Scripture scope are - # searchable. Answer/grading/evidence-unlock truth remains deliberately out. - return cls._unique( - cls._text_values(node.get("source_scope_visible_to_player")) - + cls._mission_source_refs(mission) - ) + @staticmethod + def _require_real_dir(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_dir(): + raise ContentLoadError(f"qualified readable D4 {label} must be a real directory") def _qualified_d4_records( self, @@ -107,8 +109,10 @@ def _qualified_d4_records( root = self.loader.repo_root / _D4_RELATIVE_ROOT if not root.exists(): return [], {}, {} - if root.is_symlink() or not root.is_dir(): - raise ContentLoadError("qualified readable D4 root must be a real directory") + self._require_real_dir(root, "root") + self._require_real_dir(root / "metadata", "metadata directory") + self._require_real_dir(root / "registries", "registries directory") + self._require_real_dir(root / "nodes", "nodes directory") metadata_path = root / "metadata" / "mission_index_metadata.json" if metadata_path.is_symlink() or not metadata_path.is_file(): @@ -133,24 +137,25 @@ def _qualified_d4_records( raise ContentLoadError("qualified readable D4 mission sequence is invalid") campaign_title = self._clean(campaign.get("title_ua")) or _D4_CAMPAIGN_ID - mission_rows: list[dict[str, Any]] = [] + raw_by_id: dict[str, dict[str, Any]] = {} for path in sorted((root / "registries").glob("missions_*.jsonl")): if path.is_symlink() or not path.is_file(): raise ContentLoadError("qualified readable D4 mission registry contains unsafe path") - mission_rows.extend(self._load_jsonl(path)) - if len(mission_rows) != _D4_MISSION_COUNT: - raise ContentLoadError("qualified readable D4 mission registry count changed") + for raw in self._load_jsonl(path): + mid = raw.get("mission_id") + if not isinstance(mid, str) or mid not in sequence or mid in raw_by_id: + raise ContentLoadError(f"unexpected or duplicate qualified readable D4 mission: {mid}") + raw_by_id[mid] = raw + if set(raw_by_id) != set(sequence): + raise ContentLoadError("qualified readable D4 mission registry set changed") missions: list[dict[str, Any]] = [] missions_by_id: dict[str, dict[str, Any]] = {} - expected_nodes_by_mission: dict[str, set[str]] = {} - for raw in mission_rows: - mid = raw.get("mission_id") - cid = raw.get("campaign_id") + expected_nodes: dict[str, set[str]] = {} + for mid in sequence: + raw = raw_by_id[mid] task_nodes = raw.get("task_nodes") - if not isinstance(mid, str) or mid not in sequence or mid in missions_by_id: - raise ContentLoadError(f"unexpected or duplicate qualified readable D4 mission: {mid}") - if cid != _D4_CAMPAIGN_ID: + if raw.get("campaign_id") != _D4_CAMPAIGN_ID: raise ContentLoadError(f"qualified readable D4 mission campaign changed: {mid}") if not isinstance(task_nodes, list) or not task_nodes or not all(isinstance(v, str) and v for v in task_nodes): raise ContentLoadError(f"qualified readable D4 mission task_nodes invalid: {mid}") @@ -158,7 +163,7 @@ def _qualified_d4_records( raise ContentLoadError(f"qualified readable D4 mission task_nodes duplicate: {mid}") entry = { "mission_id": mid, - "campaign_id": cid, + "campaign_id": _D4_CAMPAIGN_ID, "title": self._clean(raw.get("title")) or mid, "difficulty": raw.get("difficulty"), "entry_node": raw.get("entry_node"), @@ -173,14 +178,11 @@ def _qualified_d4_records( } missions.append(entry) missions_by_id[mid] = entry - expected_nodes_by_mission[mid] = set(task_nodes) - if [item["mission_id"] for item in missions] != sequence: - # Registry shard order is itself qualified and must match metadata order. - raise ContentLoadError("qualified readable D4 mission registry order changed") + expected_nodes[mid] = set(task_nodes) nodes: dict[str, dict[str, Any]] = {} mission_for_node: dict[str, dict[str, Any]] = {} - actual_nodes_by_mission: dict[str, set[str]] = {mid: set() for mid in missions_by_id} + actual_nodes: dict[str, set[str]] = {mid: set() for mid in missions_by_id} for path in sorted((root / "nodes").glob("nodes_*.jsonl")): if path.is_symlink() or not path.is_file(): raise ContentLoadError("qualified readable D4 node registry contains unsafe path") @@ -189,37 +191,39 @@ def _qualified_d4_records( mid = node.get("mission_id") if not isinstance(nid, str) or not nid or nid in nodes: raise ContentLoadError(f"duplicate/empty qualified readable D4 node: {nid!r}") - if mid not in missions_by_id or nid not in expected_nodes_by_mission[mid]: + if mid not in missions_by_id or nid not in expected_nodes[mid]: raise ContentLoadError(f"qualified readable D4 node/mission binding changed: {nid}") nodes[nid] = node mission_for_node[nid] = missions_by_id[mid] - actual_nodes_by_mission[mid].add(nid) + actual_nodes[mid].add(nid) if len(nodes) != _D4_NODE_COUNT: raise ContentLoadError("qualified readable D4 node count changed") - for mid, expected in expected_nodes_by_mission.items(): - if actual_nodes_by_mission[mid] != expected: + for mid, expected in expected_nodes.items(): + if actual_nodes[mid] != expected: raise ContentLoadError(f"qualified readable D4 mission node set changed: {mid}") return missions, nodes, mission_for_node def _records(self) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: - self.loader._ensure() # Same-package read-only view; no independent persistent store. + self.loader._ensure() missions: list[dict[str, Any]] = [] - for item in self.loader._missions or []: - mission = dict(item) + gradeable_by_id: dict[str, dict[str, Any]] = {} + for raw in self.loader._missions or []: + mission = dict(raw) + cid = str(mission.get("campaign_id") or "") mission["content_access"] = "GRADEABLE_RUNTIME" mission["gradeable_runtime_eligible"] = True - mission["_campaign_title"] = {"LN": "Остання ніч", "PA": "Дорога Павла"}.get( - str(mission.get("campaign_id") or ""), str(mission.get("campaign_id") or "") - ) + mission["_campaign_title"] = {"LN": "Остання ніч", "PA": "Дорога Павла"}.get(cid, cid) missions.append(mission) + gradeable_by_id[str(mission.get("mission_id") or "")] = mission + nodes = {str(key): dict(value) for key, value in (self.loader._nodes or {}).items()} - mission_for_node = { - str(key): dict(value) for key, value in (self.loader._mission_for_node or {}).items() - } + mission_for_node: dict[str, dict[str, Any]] = {} + for key, raw in (self.loader._mission_for_node or {}).items(): + mid = str(raw.get("mission_id") or "") + mission_for_node[str(key)] = dict(gradeable_by_id.get(mid) or raw) d4_missions, d4_nodes, d4_mission_for_node = self._qualified_d4_records() - existing_missions = {str(item.get("mission_id") or "") for item in missions} - if existing_missions.intersection(str(item.get("mission_id") or "") for item in d4_missions): + if set(gradeable_by_id).intersection(str(item.get("mission_id") or "") for item in d4_missions): raise ContentLoadError("qualified readable D4 mission collides with gradeable runtime mission") if set(nodes).intersection(d4_nodes): raise ContentLoadError("qualified readable D4 node collides with gradeable runtime node") @@ -260,8 +264,8 @@ def list_missions(self, campaign_id: str) -> list[dict[str, Any]]: return [self._public_mission(item) for item in missions if item.get("campaign_id") == campaign_id] def catalog(self) -> dict[str, Any]: - missions, nodes, _ = self._records() - mission_rows = [] + missions, nodes, mission_for_node = self._records() + mission_rows: list[dict[str, Any]] = [] passage_refs: list[str] = [] for mission in sorted(missions, key=lambda item: (str(item.get("campaign_id")), str(item.get("mission_id")))): refs = self._mission_source_refs(mission) @@ -282,10 +286,7 @@ def catalog(self) -> dict[str, Any]: } ) for node_id, node in sorted(nodes.items()): - mission = (dict((self.loader._mission_for_node or {}).get(node_id) or {})) - if not mission: - mission = next((item for item in missions if item.get("mission_id") == node.get("mission_id")), {}) - passage_refs.extend(self._node_source_refs(node, mission)) + passage_refs.extend(self._node_source_refs(node, mission_for_node.get(node_id) or {})) return { "schema": CATALOG_SCHEMA, "source_of_truth": "CanonicalContentLoader", @@ -326,14 +327,7 @@ def _optional_id(value: Any, name: str) -> str | None: raise ValueError(f"invalid {name}") return value - def search( - self, - query: Any, - *, - campaign_id: Any = None, - mission_id: Any = None, - limit: Any = 25, - ) -> dict[str, Any]: + def search(self, query: Any, *, campaign_id: Any = None, mission_id: Any = None, limit: Any = 25) -> dict[str, Any]: if not isinstance(query, str): raise ValueError("query must be string") query = self._clean(query) @@ -346,24 +340,17 @@ def search( missions, nodes, mission_for_node = self._records() results: list[dict[str, Any]] = [] - for mission in missions: cid = str(mission.get("campaign_id") or "") mid = str(mission.get("mission_id") or "") - if campaign_filter and cid != campaign_filter: - continue - if mission_filter and mid != mission_filter: + if (campaign_filter and cid != campaign_filter) or (mission_filter and mid != mission_filter): continue refs = self._mission_source_refs(mission) - fields = [cid, mid, self._clean(mission.get("title")), *refs] - score = self._score(query, fields) + score = self._score(query, [cid, mid, self._clean(mission.get("title")), *refs]) if score: results.append( { - "kind": "mission", - "id": mid, - "campaign_id": cid, - "mission_id": mid, + "kind": "mission", "id": mid, "campaign_id": cid, "mission_id": mid, "title": self._clean(mission.get("title")) or mid, "snippet": refs[0] if refs else self._clean(mission.get("title")), "source_references": refs, @@ -377,26 +364,18 @@ def search( mission = mission_for_node.get(node_id) or {} cid = str(mission.get("campaign_id") or node.get("campaign_id") or "") mid = str(node.get("mission_id") or mission.get("mission_id") or "") - if campaign_filter and cid != campaign_filter: - continue - if mission_filter and mid != mission_filter: + if (campaign_filter and cid != campaign_filter) or (mission_filter and mid != mission_filter): continue refs = self._node_source_refs(node, mission) prompt = self._clean(node.get("player_prompt")) task_family = self._clean(node.get("task_family")) - fields = [node_id, cid, mid, prompt, task_family, *refs] - score = self._score(query, fields) + score = self._score(query, [node_id, cid, mid, prompt, task_family, *refs]) if score: results.append( { - "kind": "task", - "id": node_id, - "campaign_id": cid, - "mission_id": mid, - "title": prompt or node_id, - "snippet": prompt, - "task_family": task_family or None, - "difficulty": node.get("difficulty"), + "kind": "task", "id": node_id, "campaign_id": cid, "mission_id": mid, + "title": prompt or node_id, "snippet": prompt, + "task_family": task_family or None, "difficulty": node.get("difficulty"), "source_references": refs, "content_access": mission.get("content_access"), "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, @@ -405,12 +384,11 @@ def search( ) results.sort(key=lambda item: (-int(item["score"]), item["kind"], item["id"])) - total = len(results) return { "schema": SEARCH_SCHEMA, "query": query, "filters": {"campaign_id": campaign_filter, "mission_id": mission_filter}, - "total": total, + "total": len(results), "results": results[:limit], "source_of_truth": "CanonicalContentLoader", "derived_index": True, From 4c650ace9cb2b530b99ac6af9bcbcd5972a44794 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:23:49 +0200 Subject: [PATCH 074/125] R06: assert existing gradeable Library eligibility remains true --- .../tests/test_d4_readable_library_consumption.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index 647960f2e..c14d9d0ba 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -64,7 +64,7 @@ def test_d4_filesystem_presence_does_not_make_node_gradeable(self): gradeable_campaigns = {row["campaign_id"] for row in self.loader.list_campaigns()} self.assertNotIn(D4_CAMPAIGN, gradeable_campaigns) - def test_existing_gradeable_runtime_nodes_remain_loadable(self): + def test_existing_gradeable_runtime_nodes_remain_loadable_and_marked_eligible(self): self.loader._ensure() self.assertTrue(self.loader._nodes) node_id = sorted(self.loader._nodes)[0] @@ -73,6 +73,12 @@ def test_existing_gradeable_runtime_nodes_remain_loadable(self): mission = self.loader.mission_for_node(node_id) self.assertTrue(mission["mission_id"]) + result = self.library.search(node_id, limit=100) + rows = [row for row in result["results"] if row["kind"] == "task" and row["id"] == node_id] + self.assertEqual(1, len(rows)) + self.assertEqual("GRADEABLE_RUNTIME", rows[0]["content_access"]) + self.assertTrue(rows[0]["gradeable_runtime_eligible"]) + def test_unqualified_readable_canary_cannot_enter_gradeable_loader(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From 44c314263f4ce48a3944859ef4645eaa420a9748 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:24:39 +0200 Subject: [PATCH 075/125] R06: prove D4 read-only boundary through packaged application transport --- .../test_d4_readable_library_consumption.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index c14d9d0ba..c93c71c90 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -3,8 +3,10 @@ import unittest from pathlib import Path +from scripture_archive_platform.application.service import PlatformApplication from scripture_archive_platform.content.library import CanonicalLibraryIndex from scripture_archive_platform.content.loader import CanonicalContentLoader, ContentLoadError +from scripture_archive_platform.persistence.store import JsonFileStore D4_CAMPAIGN = "OT-R06-D4" @@ -20,6 +22,15 @@ def repository_root() -> Path: raise RuntimeError("qualified readable D4 repository root not found") +def request(command: str, payload=None) -> dict: + return { + "api_version": "scripture.transport.v1", + "request_id": "d4-readable-library-test", + "command": command, + "payload": {} if payload is None else payload, + } + + class D4ReadableLibraryConsumptionTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -79,6 +90,23 @@ def test_existing_gradeable_runtime_nodes_remain_loadable_and_marked_eligible(se self.assertEqual("GRADEABLE_RUNTIME", rows[0]["content_access"]) self.assertTrue(rows[0]["gradeable_runtime_eligible"]) + def test_packaged_application_exposes_d4_only_through_read_only_library(self): + with tempfile.TemporaryDirectory() as tmp: + app = PlatformApplication(self.repo, store=JsonFileStore(Path(tmp) / "store")) + catalog = app.handle(request("library.catalog")) + self.assertTrue(catalog["ok"]) + campaigns = {row["campaign_id"]: row for row in catalog["data"]["campaigns"]} + self.assertEqual("READ_ONLY_LIBRARY", campaigns[D4_CAMPAIGN]["content_access"]) + self.assertFalse(campaigns[D4_CAMPAIGN]["gradeable_runtime_eligible"]) + + search = app.handle(request("library.search", {"query": "Genesis 12:1", "campaign_id": D4_CAMPAIGN, "limit": 100})) + self.assertTrue(search["ok"]) + self.assertIn(D4_FIRST_NODE, {row["id"] for row in search["data"]["results"]}) + + player = app.handle(request("player.load_node", {"node_id": D4_FIRST_NODE})) + self.assertFalse(player["ok"]) + self.assertEqual("VALIDATION_ERROR", player["error"]["code"]) + def test_unqualified_readable_canary_cannot_enter_gradeable_loader(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From 70174dd8f7b020c36d47fe1dc4a6dd90c63f0386 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 27 Sep 2026 22:25:06 +0200 Subject: [PATCH 076/125] R06: include packaged D4 transport boundary regression --- tools/verify_library_search_overlay.py | 99 ++++++-------------------- 1 file changed, 23 insertions(+), 76 deletions(-) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 6b6993870..21d11b0f6 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -19,7 +19,7 @@ CANONICAL_DEV1_SOURCE_COMMIT = "90a13aca71d2a5f832846a84acbdf0f7c89f5da9" CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" -EXPECTED_REAL_TESTS = 11 +EXPECTED_REAL_TESTS = 12 OVERLAY_FIDELITY_PATHS = ( Path("scripture_archive_platform/content/library.py"), Path("scripture_archive_platform/application/service.py"), @@ -37,9 +37,7 @@ def verify_exact_checkout() -> None: expected = os.environ.get("LIBRARY_SOURCE_SHA", "").strip() if not expected: raise AssertionError("LIBRARY_SOURCE_SHA is required") - actual = subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True - ).strip() + actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() if actual != expected: raise AssertionError(f"Expected exact source checkout {expected}, got {actual}") @@ -55,66 +53,33 @@ def _safe_extract(archive: zipfile.ZipFile, destination: Path) -> None: def _read_canonical_archive() -> bytes: fetch = subprocess.run( - [ - "git", - "fetch", - "--no-tags", - "--no-recurse-submodules", - "--depth=1", - "origin", - CANONICAL_DEV1_SOURCE_COMMIT, - ], + ["git", "fetch", "--no-tags", "--no-recurse-submodules", "--depth=1", "origin", CANONICAL_DEV1_SOURCE_COMMIT], cwd=ROOT, text=True, capture_output=True, ) if fetch.returncode != 0: detail = (fetch.stderr or fetch.stdout).strip() - raise AssertionError( - "Unable to fetch pinned canonical DEV1 source donor " - f"{CANONICAL_DEV1_SOURCE_COMMIT}: {detail}" - ) - fetched = subprocess.check_output( - ["git", "rev-parse", "FETCH_HEAD"], cwd=ROOT, text=True - ).strip() + raise AssertionError(f"Unable to fetch pinned canonical DEV1 source donor {CANONICAL_DEV1_SOURCE_COMMIT}: {detail}") + fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], cwd=ROOT, text=True).strip() if fetched != CANONICAL_DEV1_SOURCE_COMMIT: - raise AssertionError( - f"Expected pinned DEV1 donor {CANONICAL_DEV1_SOURCE_COMMIT}, got {fetched}" - ) + raise AssertionError(f"Expected pinned DEV1 donor {CANONICAL_DEV1_SOURCE_COMMIT}, got {fetched}") listing = subprocess.check_output( - [ - "git", - "ls-tree", - "-r", - "--name-only", - CANONICAL_DEV1_SOURCE_COMMIT, - "--", - CANONICAL_SOURCE_PREFIX, - ], + ["git", "ls-tree", "-r", "--name-only", CANONICAL_DEV1_SOURCE_COMMIT, "--", CANONICAL_SOURCE_PREFIX], cwd=ROOT, text=True, ) parts = sorted( - path.strip() - for path in listing.splitlines() - if Path(path.strip()).name.startswith("part-") - and path.strip().endswith(".b64") + path.strip() for path in listing.splitlines() + if Path(path.strip()).name.startswith("part-") and path.strip().endswith(".b64") ) if not parts: - raise AssertionError( - "Pinned canonical FINALPREP02 DEV1 source parts are missing" - ) - - encoded_chunks: list[str] = [] - for path in parts: - text = subprocess.check_output( - ["git", "show", f"{CANONICAL_DEV1_SOURCE_COMMIT}:{path}"], - cwd=ROOT, - text=True, - ) - encoded_chunks.append("".join(text.split())) - + raise AssertionError("Pinned canonical FINALPREP02 DEV1 source parts are missing") + encoded_chunks = [ + "".join(subprocess.check_output(["git", "show", f"{CANONICAL_DEV1_SOURCE_COMMIT}:{path}"], cwd=ROOT, text=True).split()) + for path in parts + ] return base64.b64decode("".join(encoded_chunks), validate=True) @@ -122,10 +87,7 @@ def compose_real_platform(temp_root: Path) -> Path: archive_bytes = _read_canonical_archive() digest = hashlib.sha256(archive_bytes).hexdigest() if digest != EXPECTED_BASE_SHA256: - raise AssertionError( - f"DEV1 base archive hash mismatch: expected {EXPECTED_BASE_SHA256}, got {digest}" - ) - + raise AssertionError(f"DEV1 base archive hash mismatch: expected {EXPECTED_BASE_SHA256}, got {digest}") archive_path = temp_root / "DEV1_R06_PLATFORM_SOURCE.zip" archive_path.write_bytes(archive_bytes) with zipfile.ZipFile(archive_path) as archive: @@ -133,37 +95,26 @@ def compose_real_platform(temp_root: Path) -> Path: if bad_member is not None: raise AssertionError(f"DEV1 base archive CRC failure: {bad_member}") _safe_extract(archive, temp_root) - platform_root = temp_root / "r06_platform" if not platform_root.is_dir(): raise AssertionError("DEV1 base archive did not produce r06_platform") shutil.copytree(OVERLAY, platform_root, dirs_exist_ok=True) - for relative in OVERLAY_FIDELITY_PATHS: - overlay_bytes = (OVERLAY / relative).read_bytes() - composed_bytes = (platform_root / relative).read_bytes() - if composed_bytes != overlay_bytes: + if (platform_root / relative).read_bytes() != (OVERLAY / relative).read_bytes(): raise AssertionError(f"Overlay fidelity mismatch: {relative.as_posix()}") return platform_root def parse_real_paths(platform_root: Path) -> None: for relative in OVERLAY_FIDELITY_PATHS: - ast.parse( - (platform_root / relative).read_text(encoding="utf-8"), - filename=relative.as_posix(), - ) + ast.parse((platform_root / relative).read_text(encoding="utf-8"), filename=relative.as_posix()) def _reset_platform_imports(platform_root: Path) -> None: for name in tuple(sys.modules): - if name == "scripture_archive_platform" or name.startswith( - "scripture_archive_platform." - ): + if name == "scripture_archive_platform" or name.startswith("scripture_archive_platform."): del sys.modules[name] - - ordered_paths = (platform_root, RUNTIME_ENGINE, ROOT) - for entry in reversed(ordered_paths): + for entry in reversed((platform_root, RUNTIME_ENGINE, ROOT)): value = str(entry) while value in sys.path: sys.path.remove(value) @@ -184,12 +135,9 @@ def load_real_regression_module(platform_root: Path, name: str, relative: Path): def run_real_response_regressions(platform_root: Path) -> None: suite = unittest.TestSuite() for name, relative in REGRESSION_MODULES: - module = load_real_regression_module(platform_root, name, relative) - suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(load_real_regression_module(platform_root, name, relative))) if suite.countTestCases() != EXPECTED_REAL_TESTS: - raise AssertionError( - f"Expected {EXPECTED_REAL_TESTS} Library/Search + D4 read-only tests, got {suite.countTestCases()}" - ) + raise AssertionError(f"Expected {EXPECTED_REAL_TESTS} Library/Search + D4 read-only tests, got {suite.countTestCases()}") result = unittest.TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): raise SystemExit(1) @@ -203,9 +151,8 @@ def main() -> None: parse_real_paths(platform_root) run_real_response_regressions(platform_root) print( - "Library/Search qualification PASS: exact candidate checkout, pinned canonical " - "FINALPREP02 DEV1 base hash/CRC, overlay fidelity, six legacy Library/Search " - "regressions, and five real qualified-D4 read-only/runtime-eligibility regressions." + "Library/Search qualification PASS: exact candidate checkout, pinned canonical FINALPREP02 DEV1 base hash/CRC, " + "overlay fidelity, six legacy Library/Search regressions, and six real qualified-D4 read-only/runtime-eligibility regressions." ) From a5f600ed013c45d70a8c5bdcc03d9101a25773ed Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:38:30 +0200 Subject: [PATCH 077/125] R06: surface D4 read-only eligibility in Library UI --- .../repair_overlay/frontend/library-ui.js | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/library-ui.js b/lanes/dev1/repair_overlay/frontend/library-ui.js index 83469f5c5..4417effcb 100644 --- a/lanes/dev1/repair_overlay/frontend/library-ui.js +++ b/lanes/dev1/repair_overlay/frontend/library-ui.js @@ -74,6 +74,13 @@ function requireBoolean(value, name) { return value; } +function requireContentAccess(value, name) { + if (value !== 'GRADEABLE_RUNTIME' && value !== 'READ_ONLY_LIBRARY') { + throw new Error(`${name} is invalid`); + } + return value; +} + function requireStringArray(value, name, {maxLength = MAX_TEXT_LENGTH} = {}) { if (!Array.isArray(value)) throw new Error(`${name} must be array`); for (let index = 0; index < value.length; index += 1) { @@ -88,6 +95,8 @@ function validateCampaign(row, index) { requireText(row.title, `campaigns[${index}].title`); requireNonNegativeInteger(row.mission_count, `campaigns[${index}].mission_count`); requireNonNegativeInteger(row.machine_node_count, `campaigns[${index}].machine_node_count`); + requireContentAccess(row.content_access, `campaigns[${index}].content_access`); + requireBoolean(row.gradeable_runtime_eligible, `campaigns[${index}].gradeable_runtime_eligible`); return row; } @@ -96,6 +105,8 @@ function validateMission(row, index) { requireText(row.campaign_id, `missions[${index}].campaign_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.mission_id, `missions[${index}].mission_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.title, `missions[${index}].title`); + requireContentAccess(row.content_access, `missions[${index}].content_access`); + requireBoolean(row.gradeable_runtime_eligible, `missions[${index}].gradeable_runtime_eligible`); return row; } @@ -108,6 +119,8 @@ function validateResult(row, index) { requireText(row.title, `results[${index}].title`); requireText(row.snippet, `results[${index}].snippet`, {allowEmpty: true}); requireStringArray(row.source_references, `results[${index}].source_references`, {maxLength: MAX_SOURCE_REF_LENGTH}); + requireContentAccess(row.content_access, `results[${index}].content_access`); + requireBoolean(row.gradeable_runtime_eligible, `results[${index}].gradeable_runtime_eligible`); return row; } @@ -119,6 +132,7 @@ export function validateCatalogResponse(data) { requireBoolean(data.bundled_full_bible_text, 'bundled_full_bible_text'); requireBoolean(data.text_provider_available, 'text_provider_available'); requireNonNegativeInteger(data.machine_node_count, 'machine_node_count'); + requireStringArray(data.read_only_qualified_sources, 'read_only_qualified_sources', {maxLength: MAX_ID_LENGTH}); if (!Array.isArray(data.campaigns)) throw new Error('campaigns must be array'); if (!Array.isArray(data.missions)) throw new Error('missions must be array'); requireStringArray(data.source_references, 'source_references', {maxLength: MAX_SOURCE_REF_LENGTH}); @@ -165,7 +179,7 @@ function updateMissionFilter() { 'Усі місії', missions, 'mission_id', - row => `${row.mission_id} — ${row.title || row.mission_id}` + row => `${row.mission_id} — ${row.title || row.mission_id}${row.gradeable_runtime_eligible ? '' : ' — лише Library, без player/grading'}` ); } @@ -180,7 +194,8 @@ function renderCatalog(data) { ['Місій', missions.length], ['Machine-readable вузлів', data.machine_node_count], ['Видимих source references', sourceReferences.length], - ['Джерело індексу', data.source_of_truth] + ['Gradeable authority', data.source_of_truth], + ['Qualified read-only sources', data.read_only_qualified_sources.length ? data.read_only_qualified_sources.join(', ') : 'немає'] ]; for (const [name, value] of rows) { const wrapper = element('div'); @@ -190,7 +205,10 @@ function renderCatalog(data) { const notice = byId('library-corpus-notice'); if (data.bundled_full_bible_text === false || data.text_provider_available === false) { - notice.textContent = 'Повний біблійний текст не входить до цього пакета і активний text provider не підтверджений. Пошук охоплює лише player-visible canonical metadata та source references, які вже надає CanonicalContentLoader; відсутній текст не вигадується.'; + const readOnly = data.read_only_qualified_sources.length + ? ` Окремо доступні qualified read-only джерела: ${data.read_only_qualified_sources.join(', ')}. Вони не є player/grading authority.` + : ''; + notice.textContent = `Повний біблійний текст не входить до цього пакета і активний text provider не підтверджений. Gradeable runtime authority залишається CanonicalContentLoader; Library також може показувати явно позначені qualified read-only джерела. Відсутній текст не вигадується.${readOnly}`; } else { notice.textContent = 'Статус повного біблійного тексту або text provider не підтверджено цим catalog response.'; } @@ -200,7 +218,7 @@ function renderCatalog(data) { 'Усі кампанії', campaigns, 'campaign_id', - row => `${row.campaign_id} — ${row.title || row.campaign_id}` + row => `${row.campaign_id} — ${row.title || row.campaign_id}${row.gradeable_runtime_eligible ? '' : ' — лише Library, без player/grading'}` ); updateMissionFilter(); } @@ -221,7 +239,10 @@ function renderResults(data) { const snippet = element('p', row.snippet || 'Без додаткового player-visible фрагмента.'); const refs = row.source_references.slice(0, MAX_RESULT_REFS); const source = element('p', refs.length ? `Джерела: ${refs.join('; ')}` : 'Джерела: не вказано у видимому індексі.'); - article.append(heading, identity, snippet, source); + const access = row.gradeable_runtime_eligible + ? element('p', 'Доступ: gradeable runtime — запис належить player/grading authority.') + : element('p', 'Доступ: лише Library — цей запис не є доступним для player або grading.'); + article.append(heading, identity, access, snippet, source); host.append(article); } } From 011e3d1b913a4e57a0948bf7efe6c10c65e1eb8a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:38:47 +0200 Subject: [PATCH 078/125] R06: qualify read-only Library eligibility presentation --- .../test_packaged_library_current_shell.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 0f77999f5..0a894b74e 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -5,7 +5,7 @@ import unittest ROOT = Path(__file__).resolve().parents[1] / "frontend" -EXPECTED_LIBRARY_UI_BLOB = "83469f5c54df4a78d6a45331c17e9bfe07bc0e9c" +EXPECTED_LIBRARY_UI_BLOB = "4417effcbfc08f674b3ecb200187ad830f9a4257" def git_blob_sha(data: bytes) -> str: @@ -81,6 +81,22 @@ def test_library_source_truth_and_absent_full_text_are_explicit(self): ): self.assertIn(token, self.library) + def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): + for token in ( + "requireContentAccess", + "read_only_qualified_sources", + "content_access", + "gradeable_runtime_eligible", + "Gradeable authority", + "Qualified read-only sources", + "лише Library, без player/grading", + "Library також може показувати явно позначені qualified read-only джерела", + "цей запис не є доступним для player або grading", + ): + self.assertIn(token, self.library) + self.assertIn("row.gradeable_runtime_eligible", self.library) + self.assertIn("data.read_only_qualified_sources.length", self.library) + def test_dynamic_content_remains_inert_and_bounded(self): self.assertNotIn("innerHTML", self.library) self.assertNotIn("insertAdjacentHTML", self.library) From 43571331027fb8c01aac415c90e310f31103888c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:38:59 +0200 Subject: [PATCH 079/125] R06: allowlist native trusted update staging command --- .../scripture_archive_platform/transport/contracts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 fb97fb268..ac8e0ebcd 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -21,7 +21,7 @@ "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", - "speech.status","speech.synthesize_prompt","application_update.select_verify","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) From e6cf938c9aa4851362987f8fbf75f69c9961e0d2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:43:13 +0200 Subject: [PATCH 080/125] R06: bind Library D4 nodes to qualified hash authority --- .../content/library.py | 48 ++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index 953df9084..1634a9c0a 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import re from pathlib import Path @@ -16,6 +17,7 @@ _D4_SOURCE_AUDIT_STATUS = "DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING" _D4_MISSION_COUNT = 15 _D4_NODE_COUNT = 450 +_D4_NODE_RECORD_AGGREGATE_SHA256 = "9fd8f668868e267e97b718a1de3025ad47577748e1054e146b6279da585e2ef7" class CanonicalLibraryIndex: @@ -103,6 +105,45 @@ def _require_real_dir(path: Path, label: str) -> None: if path.is_symlink() or not path.is_dir(): raise ContentLoadError(f"qualified readable D4 {label} must be a real directory") + @staticmethod + def _canonical_record_sha256(record: dict[str, Any]) -> str: + encoded = json.dumps( + record, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + def _qualified_d4_node_hashes(self, root: Path) -> dict[str, str]: + hash_root = root / "record_hashes" + self._require_real_dir(hash_root, "record-hash directory") + expected: dict[str, str] = {} + for path in sorted(hash_root.glob("nodes_*.sha256.json")): + if path.is_symlink() or not path.is_file(): + raise ContentLoadError("qualified readable D4 node-hash registry contains unsafe path") + payload = self._load_json(path) + if not isinstance(payload, dict): + raise ContentLoadError(f"qualified readable D4 node-hash registry must be object: {path}") + for node_id, digest in payload.items(): + if ( + not isinstance(node_id, str) + or not node_id + or node_id in expected + or not isinstance(digest, str) + or not re.fullmatch(r"[0-9a-f]{64}", digest) + ): + raise ContentLoadError(f"invalid/duplicate qualified readable D4 node hash: {node_id!r}") + expected[node_id] = digest + if len(expected) != _D4_NODE_COUNT: + raise ContentLoadError("qualified readable D4 node-hash count changed") + aggregate = hashlib.sha256( + "".join(expected[node_id] for node_id in sorted(expected)).encode("ascii") + ).hexdigest() + if aggregate != _D4_NODE_RECORD_AGGREGATE_SHA256: + raise ContentLoadError("qualified readable D4 node-hash aggregate changed") + return expected + def _qualified_d4_records( self, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: @@ -113,6 +154,7 @@ def _qualified_d4_records( self._require_real_dir(root / "metadata", "metadata directory") self._require_real_dir(root / "registries", "registries directory") self._require_real_dir(root / "nodes", "nodes directory") + expected_node_hashes = self._qualified_d4_node_hashes(root) metadata_path = root / "metadata" / "mission_index_metadata.json" if metadata_path.is_symlink() or not metadata_path.is_file(): @@ -193,11 +235,13 @@ def _qualified_d4_records( raise ContentLoadError(f"duplicate/empty qualified readable D4 node: {nid!r}") if mid not in missions_by_id or nid not in expected_nodes[mid]: raise ContentLoadError(f"qualified readable D4 node/mission binding changed: {nid}") + if self._canonical_record_sha256(node) != expected_node_hashes.get(nid): + raise ContentLoadError(f"qualified readable D4 node hash changed: {nid}") nodes[nid] = node mission_for_node[nid] = missions_by_id[mid] actual_nodes[mid].add(nid) - if len(nodes) != _D4_NODE_COUNT: - raise ContentLoadError("qualified readable D4 node count changed") + if len(nodes) != _D4_NODE_COUNT or set(nodes) != set(expected_node_hashes): + raise ContentLoadError("qualified readable D4 node/hash identity set changed") for mid, expected in expected_nodes.items(): if actual_nodes[mid] != expected: raise ContentLoadError(f"qualified readable D4 mission node set changed: {mid}") From 7328c868e7c3992c480a025172a00fc45cb95781 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:43:39 +0200 Subject: [PATCH 081/125] R06: regress D4 readable hash tampering --- .../test_d4_readable_library_consumption.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index c93c71c90..17361e3da 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -1,4 +1,5 @@ import json +import shutil import tempfile import unittest from pathlib import Path @@ -69,6 +70,44 @@ def test_library_search_finds_real_d4_source_scope_without_private_answer_truth( for forbidden in ("accepted_answer", "accepted_variants", "grading", "hints", "required_evidence"): self.assertNotIn(forbidden, serialized) + def _copied_d4_root(self, temp_root: Path) -> Path: + source = self.repo / "docs" / "campaigns" / "OT" / "R06_D4_STAGE05_READABLE" + destination = temp_root / "docs" / "campaigns" / "OT" / "R06_D4_STAGE05_READABLE" + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copytree(source, destination) + return destination + + def test_d4_node_tampering_fails_closed_against_qualified_hash_authority(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + node_path = d4_root / "nodes" / "nodes_001_002.jsonl" + lines = node_path.read_text(encoding="utf-8").splitlines() + first = json.loads(lines[0]) + first["player_prompt"] = str(first.get("player_prompt") or "") + " TAMPERED" + lines[0] = json.dumps(first, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + node_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + + def test_d4_hash_registry_tampering_fails_closed_against_pinned_aggregate(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + hash_path = d4_root / "record_hashes" / "nodes_001_090.sha256.json" + hashes = json.loads(hash_path.read_text(encoding="utf-8")) + hashes[D4_FIRST_NODE] = "0" * 64 + hash_path.write_text( + json.dumps(hashes, ensure_ascii=False, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + def test_d4_filesystem_presence_does_not_make_node_gradeable(self): with self.assertRaises(ContentLoadError): self.loader.load_node(D4_FIRST_NODE) From a8959429fe6b0623d3a0ebbe62818edc39065009 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:43:54 +0200 Subject: [PATCH 082/125] R06: qualify D4 hash-authority regressions --- tools/verify_library_search_overlay.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 21d11b0f6..ef5f58409 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -19,7 +19,7 @@ CANONICAL_DEV1_SOURCE_COMMIT = "90a13aca71d2a5f832846a84acbdf0f7c89f5da9" CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" -EXPECTED_REAL_TESTS = 12 +EXPECTED_REAL_TESTS = 14 OVERLAY_FIDELITY_PATHS = ( Path("scripture_archive_platform/content/library.py"), Path("scripture_archive_platform/application/service.py"), @@ -152,7 +152,7 @@ def main() -> None: run_real_response_regressions(platform_root) print( "Library/Search qualification PASS: exact candidate checkout, pinned canonical FINALPREP02 DEV1 base hash/CRC, " - "overlay fidelity, six legacy Library/Search regressions, and six real qualified-D4 read-only/runtime-eligibility regressions." + "overlay fidelity, six legacy Library/Search regressions, and eight real qualified-D4 read-only/runtime-eligibility/hash-authority regressions." ) From 65457021d3ff31e6e5d2b381a220c5bf3a583441 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:44:17 +0200 Subject: [PATCH 083/125] R06 Library: expose read-only source audit status honestly --- lanes/dev1/repair_overlay/frontend/library-ui.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/library-ui.js b/lanes/dev1/repair_overlay/frontend/library-ui.js index 4417effcb..942227f05 100644 --- a/lanes/dev1/repair_overlay/frontend/library-ui.js +++ b/lanes/dev1/repair_overlay/frontend/library-ui.js @@ -105,6 +105,9 @@ function validateMission(row, index) { requireText(row.campaign_id, `missions[${index}].campaign_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.mission_id, `missions[${index}].mission_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.title, `missions[${index}].title`); + if (row.source_audit_status !== null && row.source_audit_status !== undefined) { + requireText(row.source_audit_status, `missions[${index}].source_audit_status`); + } requireContentAccess(row.content_access, `missions[${index}].content_access`); requireBoolean(row.gradeable_runtime_eligible, `missions[${index}].gradeable_runtime_eligible`); return row; @@ -179,7 +182,7 @@ function updateMissionFilter() { 'Усі місії', missions, 'mission_id', - row => `${row.mission_id} — ${row.title || row.mission_id}${row.gradeable_runtime_eligible ? '' : ' — лише Library, без player/grading'}` + row => `${row.mission_id} — ${row.title || row.mission_id}${row.gradeable_runtime_eligible ? '' : ` — лише Library, без player/grading — source audit: ${row.source_audit_status || 'статус не надано'}`}` ); } @@ -195,7 +198,7 @@ function renderCatalog(data) { ['Machine-readable вузлів', data.machine_node_count], ['Видимих source references', sourceReferences.length], ['Gradeable authority', data.source_of_truth], - ['Qualified read-only sources', data.read_only_qualified_sources.length ? data.read_only_qualified_sources.join(', ') : 'немає'] + ['Library-qualified read-only sources', data.read_only_qualified_sources.length ? data.read_only_qualified_sources.join(', ') : 'немає'] ]; for (const [name, value] of rows) { const wrapper = element('div'); @@ -206,9 +209,9 @@ function renderCatalog(data) { const notice = byId('library-corpus-notice'); if (data.bundled_full_bible_text === false || data.text_provider_available === false) { const readOnly = data.read_only_qualified_sources.length - ? ` Окремо доступні qualified read-only джерела: ${data.read_only_qualified_sources.join(', ')}. Вони не є player/grading authority.` + ? ` Окремо доступні Library-qualified read-only джерела: ${data.read_only_qualified_sources.join(', ')}. Library eligibility не означає завершений independent source audit; точний source audit status показується для місії, коли backend його надає. Вони не є player/grading authority.` : ''; - notice.textContent = `Повний біблійний текст не входить до цього пакета і активний text provider не підтверджений. Gradeable runtime authority залишається CanonicalContentLoader; Library також може показувати явно позначені qualified read-only джерела. Відсутній текст не вигадується.${readOnly}`; + notice.textContent = `Повний біблійний текст не входить до цього пакета і активний text provider не підтверджений. Gradeable runtime authority залишається CanonicalContentLoader; Library також може показувати явно позначені Library-qualified read-only джерела. Відсутній текст не вигадується.${readOnly}`; } else { notice.textContent = 'Статус повного біблійного тексту або text provider не підтверджено цим catalog response.'; } From f5d5d461331f63cd9b126a07f384364d7d8afd26 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:44:19 +0200 Subject: [PATCH 084/125] R06 Library: qualify audit-status presentation regression --- .../tests/test_packaged_library_current_shell.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 0a894b74e..754ebb1fd 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -5,7 +5,7 @@ import unittest ROOT = Path(__file__).resolve().parents[1] / "frontend" -EXPECTED_LIBRARY_UI_BLOB = "4417effcbfc08f674b3ecb200187ad830f9a4257" +EXPECTED_LIBRARY_UI_BLOB = "942227f0540812f067cf5e2b205ac7ad828cae37" def git_blob_sha(data: bytes) -> str: @@ -88,9 +88,12 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): "content_access", "gradeable_runtime_eligible", "Gradeable authority", - "Qualified read-only sources", + "Library-qualified read-only sources", "лише Library, без player/grading", - "Library також може показувати явно позначені qualified read-only джерела", + "Library також може показувати явно позначені Library-qualified read-only джерела", + "source_audit_status", + "Library eligibility не означає завершений independent source audit", + "source audit: ${row.source_audit_status || 'статус не надано'}", "цей запис не є доступним для player або grading", ): self.assertIn(token, self.library) From 778d9ff34c21e1ff293e11c85735947598853221 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:48:30 +0200 Subject: [PATCH 085/125] R06 Library: carry source audit status in search DTO --- .../scripture_archive_platform/content/library.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index 1634a9c0a..5ad6f647c 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -400,6 +400,7 @@ def search(self, query: Any, *, campaign_id: Any = None, mission_id: Any = None, "source_references": refs, "content_access": mission.get("content_access"), "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, + "source_audit_status": mission.get("source_audit_status"), "score": score, } ) @@ -423,6 +424,7 @@ def search(self, query: Any, *, campaign_id: Any = None, mission_id: Any = None, "source_references": refs, "content_access": mission.get("content_access"), "gradeable_runtime_eligible": mission.get("gradeable_runtime_eligible") is True, + "source_audit_status": mission.get("source_audit_status"), "score": score, } ) From 3b0f7ed48fe39e7fb68005dabb08ec2b2a9d4729 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:48:41 +0200 Subject: [PATCH 086/125] R06 Library: announce read-only audit status per result --- lanes/dev1/repair_overlay/frontend/library-ui.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/frontend/library-ui.js b/lanes/dev1/repair_overlay/frontend/library-ui.js index 942227f05..b68ce0725 100644 --- a/lanes/dev1/repair_overlay/frontend/library-ui.js +++ b/lanes/dev1/repair_overlay/frontend/library-ui.js @@ -122,6 +122,9 @@ function validateResult(row, index) { requireText(row.title, `results[${index}].title`); requireText(row.snippet, `results[${index}].snippet`, {allowEmpty: true}); requireStringArray(row.source_references, `results[${index}].source_references`, {maxLength: MAX_SOURCE_REF_LENGTH}); + if (row.source_audit_status !== null && row.source_audit_status !== undefined) { + requireText(row.source_audit_status, `results[${index}].source_audit_status`); + } requireContentAccess(row.content_access, `results[${index}].content_access`); requireBoolean(row.gradeable_runtime_eligible, `results[${index}].gradeable_runtime_eligible`); return row; @@ -245,7 +248,12 @@ function renderResults(data) { const access = row.gradeable_runtime_eligible ? element('p', 'Доступ: gradeable runtime — запис належить player/grading authority.') : element('p', 'Доступ: лише Library — цей запис не є доступним для player або grading.'); - article.append(heading, identity, access, snippet, source); + const audit = row.gradeable_runtime_eligible + ? null + : element('p', `Source audit: ${row.source_audit_status || 'статус не надано'}.`); + article.append(heading, identity, access); + if (audit) article.append(audit); + article.append(snippet, source); host.append(article); } } From 4eda4a75e3e4152fea139723b723beae3a13751b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:48:52 +0200 Subject: [PATCH 087/125] R06 Library: regress D4 audit status in search transport --- .../tests/test_d4_readable_library_consumption.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index 17361e3da..8f95f712a 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -63,6 +63,13 @@ def test_library_search_finds_real_d4_source_scope_without_private_answer_truth( self.assertTrue(d4_rows) self.assertTrue(all(row["content_access"] == "READ_ONLY_LIBRARY" for row in d4_rows)) self.assertTrue(all(row["gradeable_runtime_eligible"] is False for row in d4_rows)) + self.assertTrue( + all( + isinstance(row.get("source_audit_status"), str) + and "INDEPENDENT_AUDIT_PENDING" in row["source_audit_status"] + for row in d4_rows + ) + ) private = self.library.search(D4_PRIVATE_ANSWER, campaign_id=D4_CAMPAIGN, limit=100) self.assertEqual(0, private["total"]) @@ -141,6 +148,13 @@ def test_packaged_application_exposes_d4_only_through_read_only_library(self): search = app.handle(request("library.search", {"query": "Genesis 12:1", "campaign_id": D4_CAMPAIGN, "limit": 100})) self.assertTrue(search["ok"]) self.assertIn(D4_FIRST_NODE, {row["id"] for row in search["data"]["results"]}) + self.assertTrue( + all( + isinstance(row.get("source_audit_status"), str) + and "INDEPENDENT_AUDIT_PENDING" in row["source_audit_status"] + for row in search["data"]["results"] + ) + ) player = app.handle(request("player.load_node", {"node_id": D4_FIRST_NODE})) self.assertFalse(player["ok"]) From 06de9b7868accb37509fe7a2ccd9036d2de2f040 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:49:02 +0200 Subject: [PATCH 088/125] R06 Library: qualify per-result audit status presentation --- .../tests/test_packaged_library_current_shell.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 754ebb1fd..0908f0ce0 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -5,7 +5,7 @@ import unittest ROOT = Path(__file__).resolve().parents[1] / "frontend" -EXPECTED_LIBRARY_UI_BLOB = "942227f0540812f067cf5e2b205ac7ad828cae37" +EXPECTED_LIBRARY_UI_BLOB = "b68ce072597749a81fdafcfb8591c6e24c6d21b7" def git_blob_sha(data: bytes) -> str: @@ -94,6 +94,8 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): "source_audit_status", "Library eligibility не означає завершений independent source audit", "source audit: ${row.source_audit_status || 'статус не надано'}", + "results[${index}].source_audit_status", + "Source audit: ${row.source_audit_status || 'статус не надано'}", "цей запис не є доступним для player або grading", ): self.assertIn(token, self.library) From d4dde5de1820077d1543857448f99adfa47ba1ef Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 19:56:58 +0200 Subject: [PATCH 089/125] R06 Library: bind qualified D4 mission authority bytes --- .../content/library.py | 49 ++++++++++++++++--- .../test_d4_readable_library_consumption.py | 41 ++++++++++++++++ tools/verify_library_search_overlay.py | 4 +- 3 files changed, 85 insertions(+), 9 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index 5ad6f647c..139b4f7af 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -19,6 +19,16 @@ _D4_NODE_COUNT = 450 _D4_NODE_RECORD_AGGREGATE_SHA256 = "9fd8f668868e267e97b718a1de3025ad47577748e1054e146b6279da585e2ef7" +_D4_PUBLIC_AUTHORITY_SHA256 = { + "metadata/mission_index_metadata.json": "cfc13e369006522f6ad450863888f3603f395d4d0168f7f498e5ebf7ed6e0192", + "registries/missions_001_005.jsonl": "756b265b32b011b7a875872e140d54095f979391de4bd0c22029141d7a75aaa8", + "registries/missions_006_008.jsonl": "ed7e3078ddeff1cbbdbbc46014fdf25cb9b73657f8d87246917507be1add8f95", + "registries/missions_009_010.jsonl": "dfba7785e7c55d79692f30ff8e7ec165c5b9717b22fb472f4111dcc701ada76c", + "registries/missions_011_012.jsonl": "0a701f11b1ca0c1420443caf46b6424855300a73e8b6355ef9749b905cc39256", + "registries/missions_013_013.jsonl": "e20ceca46f0242d2670bacbf305ab35fb01c11918664b5d040ce158bcc1e8c54", + "registries/missions_014_015.jsonl": "9fe7b601e514ee384e23548d19990c9d7efb7a0586efb02e4d4bc161995356f3", +} + class CanonicalLibraryIndex: """Derived read-only catalog/search over gradeable plus qualified readable content. @@ -75,16 +85,26 @@ def _node_source_refs(cls, node: dict[str, Any], mission: dict[str, Any]) -> lis ) @staticmethod - def _load_json(path: Path) -> Any: + def _load_json(path: Path, *, expected_sha256: str | None = None) -> Any: try: - return json.loads(path.read_text(encoding="utf-8")) + raw = path.read_bytes() + if expected_sha256 is not None and hashlib.sha256(raw).hexdigest() != expected_sha256: + raise ContentLoadError(f"qualified readable D4 authority bytes changed: {path}") + return json.loads(raw.decode("utf-8")) + except ContentLoadError: + raise except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise ContentLoadError(f"invalid qualified readable D4 JSON {path}: {exc}") from exc @staticmethod - def _load_jsonl(path: Path) -> list[dict[str, Any]]: + def _load_jsonl(path: Path, *, expected_sha256: str | None = None) -> list[dict[str, Any]]: try: - lines = path.read_text(encoding="utf-8").splitlines() + raw = path.read_bytes() + if expected_sha256 is not None and hashlib.sha256(raw).hexdigest() != expected_sha256: + raise ContentLoadError(f"qualified readable D4 authority bytes changed: {path}") + lines = raw.decode("utf-8").splitlines() + except ContentLoadError: + raise except (OSError, UnicodeDecodeError) as exc: raise ContentLoadError(f"cannot read qualified readable D4 JSONL {path}: {exc}") from exc rows: list[dict[str, Any]] = [] @@ -159,7 +179,10 @@ def _qualified_d4_records( metadata_path = root / "metadata" / "mission_index_metadata.json" if metadata_path.is_symlink() or not metadata_path.is_file(): raise ContentLoadError("qualified readable D4 mission metadata is missing or unsafe") - metadata = self._load_json(metadata_path) + metadata = self._load_json( + metadata_path, + expected_sha256=_D4_PUBLIC_AUTHORITY_SHA256["metadata/mission_index_metadata.json"], + ) if not isinstance(metadata, dict): raise ContentLoadError("qualified readable D4 mission metadata must be object") campaign = metadata.get("campaign") @@ -180,10 +203,22 @@ def _qualified_d4_records( campaign_title = self._clean(campaign.get("title_ua")) or _D4_CAMPAIGN_ID raw_by_id: dict[str, dict[str, Any]] = {} - for path in sorted((root / "registries").glob("missions_*.jsonl")): + registry_root = root / "registries" + registry_paths = sorted(registry_root.glob("missions_*.jsonl")) + expected_registry_names = sorted( + Path(relative).name + for relative in _D4_PUBLIC_AUTHORITY_SHA256 + if relative.startswith("registries/") + ) + if [path.name for path in registry_paths] != expected_registry_names: + raise ContentLoadError("qualified readable D4 mission registry file set changed") + for path in registry_paths: if path.is_symlink() or not path.is_file(): raise ContentLoadError("qualified readable D4 mission registry contains unsafe path") - for raw in self._load_jsonl(path): + for raw in self._load_jsonl( + path, + expected_sha256=_D4_PUBLIC_AUTHORITY_SHA256[f"registries/{path.name}"], + ): mid = raw.get("mission_id") if not isinstance(mid, str) or mid not in sequence or mid in raw_by_id: raise ContentLoadError(f"unexpected or duplicate qualified readable D4 mission: {mid}") diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index 8f95f712a..f111d2011 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -115,6 +115,47 @@ def test_d4_hash_registry_tampering_fails_closed_against_pinned_aggregate(self): with self.assertRaises(ContentLoadError): library.catalog() + def test_d4_mission_registry_tampering_fails_closed_against_qualified_bytes(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + mission_path = d4_root / "registries" / "missions_001_005.jsonl" + lines = mission_path.read_text(encoding="utf-8").splitlines() + first = json.loads(lines[0]) + first["title"] = str(first.get("title") or "") + " TAMPERED" + lines[0] = json.dumps(first, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + mission_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + + def test_d4_mission_metadata_tampering_fails_closed_against_qualified_bytes(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + metadata_path = d4_root / "metadata" / "mission_index_metadata.json" + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + metadata["campaign"]["title_ua"] = str(metadata["campaign"].get("title_ua") or "") + " TAMPERED" + metadata_path.write_text( + json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + + def test_d4_unexpected_mission_registry_file_fails_closed(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + (d4_root / "registries" / "missions_999_999.jsonl").write_text("", encoding="utf-8") + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + def test_d4_filesystem_presence_does_not_make_node_gradeable(self): with self.assertRaises(ContentLoadError): self.loader.load_node(D4_FIRST_NODE) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index ef5f58409..9107d8090 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -19,7 +19,7 @@ CANONICAL_DEV1_SOURCE_COMMIT = "90a13aca71d2a5f832846a84acbdf0f7c89f5da9" CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" -EXPECTED_REAL_TESTS = 14 +EXPECTED_REAL_TESTS = 17 OVERLAY_FIDELITY_PATHS = ( Path("scripture_archive_platform/content/library.py"), Path("scripture_archive_platform/application/service.py"), @@ -152,7 +152,7 @@ def main() -> None: run_real_response_regressions(platform_root) print( "Library/Search qualification PASS: exact candidate checkout, pinned canonical FINALPREP02 DEV1 base hash/CRC, " - "overlay fidelity, six legacy Library/Search regressions, and eight real qualified-D4 read-only/runtime-eligibility/hash-authority regressions." + "overlay fidelity, six legacy Library/Search regressions, and eleven real qualified-D4 read-only/runtime-eligibility/hash/mission-authority regressions." ) From ee9c0a6d5e23008bef49fac47e6a2a7de8464bdb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:25:31 +0200 Subject: [PATCH 090/125] R06 Library: normalize CRLF for qualified D4 text authority --- .../content/library.py | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py index 139b4f7af..919daed06 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/content/library.py @@ -85,24 +85,35 @@ def _node_source_refs(cls, node: dict[str, Any], mission: dict[str, Any]) -> lis ) @staticmethod - def _load_json(path: Path, *, expected_sha256: str | None = None) -> Any: + def _qualified_text_bytes(raw: bytes, path: Path) -> bytes: + if b"\r" not in raw: + return raw + normalized = raw.replace(b"\r\n", b"\n") + if b"\r" in normalized: + raise ContentLoadError(f"qualified readable D4 authority has unsupported line endings: {path}") + return normalized + + @classmethod + def _load_json(cls, path: Path, *, expected_sha256: str | None = None) -> Any: try: raw = path.read_bytes() - if expected_sha256 is not None and hashlib.sha256(raw).hexdigest() != expected_sha256: + verified = cls._qualified_text_bytes(raw, path) if expected_sha256 is not None else raw + if expected_sha256 is not None and hashlib.sha256(verified).hexdigest() != expected_sha256: raise ContentLoadError(f"qualified readable D4 authority bytes changed: {path}") - return json.loads(raw.decode("utf-8")) + return json.loads(verified.decode("utf-8")) except ContentLoadError: raise except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise ContentLoadError(f"invalid qualified readable D4 JSON {path}: {exc}") from exc - @staticmethod - def _load_jsonl(path: Path, *, expected_sha256: str | None = None) -> list[dict[str, Any]]: + @classmethod + def _load_jsonl(cls, path: Path, *, expected_sha256: str | None = None) -> list[dict[str, Any]]: try: raw = path.read_bytes() - if expected_sha256 is not None and hashlib.sha256(raw).hexdigest() != expected_sha256: + verified = cls._qualified_text_bytes(raw, path) if expected_sha256 is not None else raw + if expected_sha256 is not None and hashlib.sha256(verified).hexdigest() != expected_sha256: raise ContentLoadError(f"qualified readable D4 authority bytes changed: {path}") - lines = raw.decode("utf-8").splitlines() + lines = verified.decode("utf-8").splitlines() except ContentLoadError: raise except (OSError, UnicodeDecodeError) as exc: From 43b901a567ec049386d81de607f8a9246101b1ed Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:25:58 +0200 Subject: [PATCH 091/125] R06 Library: regress cross-platform D4 authority EOL policy --- .../test_d4_readable_library_consumption.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py index f111d2011..bcf7a226a 100644 --- a/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py +++ b/lanes/dev1/repair_overlay/tests/test_d4_readable_library_consumption.py @@ -84,6 +84,36 @@ def _copied_d4_root(self, temp_root: Path) -> Path: shutil.copytree(source, destination) return destination + def test_d4_public_authority_accepts_crlf_equivalent_checkout_bytes(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + paths = [ + d4_root / "metadata" / "mission_index_metadata.json", + d4_root / "registries" / "missions_001_005.jsonl", + ] + for path in paths: + raw = path.read_bytes().replace(b"\r\n", b"\n") + path.write_bytes(raw.replace(b"\n", b"\r\n")) + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + campaigns = {row["campaign_id"]: row for row in library.list_campaigns()} + self.assertIn(D4_CAMPAIGN, campaigns) + self.assertEqual(15, campaigns[D4_CAMPAIGN]["mission_count"]) + + def test_d4_public_authority_rejects_lone_cr_line_endings(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + d4_root = self._copied_d4_root(root) + metadata_path = d4_root / "metadata" / "mission_index_metadata.json" + raw = metadata_path.read_bytes().replace(b"\r\n", b"\n") + self.assertIn(b"\n", raw) + metadata_path.write_bytes(raw.replace(b"\n", b"\r", 1)) + + library = CanonicalLibraryIndex(CanonicalContentLoader(root)) + with self.assertRaises(ContentLoadError): + library.catalog() + def test_d4_node_tampering_fails_closed_against_qualified_hash_authority(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From 833ab9f6a71c9fc2a8c24d8d318b3f1a2604fca1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:26:06 +0200 Subject: [PATCH 092/125] R06 Library: qualify D4 EOL policy regressions --- tools/verify_library_search_overlay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 9107d8090..2b53c8215 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -19,7 +19,7 @@ CANONICAL_DEV1_SOURCE_COMMIT = "90a13aca71d2a5f832846a84acbdf0f7c89f5da9" CANONICAL_SOURCE_PREFIX = "release_inputs/dev1_finalprep02" EXPECTED_BASE_SHA256 = "10fbd546ff4d985465b85b99f4f64bff95d9ec8b1f27132c6d21b4930c344c35" -EXPECTED_REAL_TESTS = 17 +EXPECTED_REAL_TESTS = 19 OVERLAY_FIDELITY_PATHS = ( Path("scripture_archive_platform/content/library.py"), Path("scripture_archive_platform/application/service.py"), From b9b1cf4104f42bb507211cb1c2303c3b3f81a05d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:26:14 +0200 Subject: [PATCH 093/125] R06 Library: align absent-text UI regression with current copy --- .../repair_overlay/tests/test_packaged_library_current_shell.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 0908f0ce0..f61fc7de9 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -77,7 +77,7 @@ def test_library_source_truth_and_absent_full_text_are_explicit(self): "bundled_full_bible_text", "text_provider_available", "Результати не додають нових source claims", - "відсутній текст не вигадується", + "Відсутній текст не вигадується", ): self.assertIn(token, self.library) From f3a28f36b58c8615c5cf33faa2b2728813e6371e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:31:05 +0200 Subject: [PATCH 094/125] R06 Library: fail closed on access/audit truth mismatches --- .../repair_overlay/frontend/library-ui.js | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/library-ui.js b/lanes/dev1/repair_overlay/frontend/library-ui.js index b68ce0725..471991931 100644 --- a/lanes/dev1/repair_overlay/frontend/library-ui.js +++ b/lanes/dev1/repair_overlay/frontend/library-ui.js @@ -81,6 +81,21 @@ function requireContentAccess(value, name) { return value; } +function requireAccessTruth(row, name, {requireReadOnlyAudit = false} = {}) { + const access = requireContentAccess(row.content_access, `${name}.content_access`); + const gradeable = requireBoolean(row.gradeable_runtime_eligible, `${name}.gradeable_runtime_eligible`); + if ((access === 'GRADEABLE_RUNTIME') !== gradeable) { + throw new Error(`${name} content_access/gradeable_runtime_eligible mismatch`); + } + const audit = row.source_audit_status; + if (!gradeable && requireReadOnlyAudit) { + requireText(audit, `${name}.source_audit_status`); + } else if (audit !== null && audit !== undefined) { + requireText(audit, `${name}.source_audit_status`); + } + return row; +} + function requireStringArray(value, name, {maxLength = MAX_TEXT_LENGTH} = {}) { if (!Array.isArray(value)) throw new Error(`${name} must be array`); for (let index = 0; index < value.length; index += 1) { @@ -95,8 +110,7 @@ function validateCampaign(row, index) { requireText(row.title, `campaigns[${index}].title`); requireNonNegativeInteger(row.mission_count, `campaigns[${index}].mission_count`); requireNonNegativeInteger(row.machine_node_count, `campaigns[${index}].machine_node_count`); - requireContentAccess(row.content_access, `campaigns[${index}].content_access`); - requireBoolean(row.gradeable_runtime_eligible, `campaigns[${index}].gradeable_runtime_eligible`); + requireAccessTruth(row, `campaigns[${index}]`); return row; } @@ -105,11 +119,7 @@ function validateMission(row, index) { requireText(row.campaign_id, `missions[${index}].campaign_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.mission_id, `missions[${index}].mission_id`, {maxLength: MAX_ID_LENGTH}); requireText(row.title, `missions[${index}].title`); - if (row.source_audit_status !== null && row.source_audit_status !== undefined) { - requireText(row.source_audit_status, `missions[${index}].source_audit_status`); - } - requireContentAccess(row.content_access, `missions[${index}].content_access`); - requireBoolean(row.gradeable_runtime_eligible, `missions[${index}].gradeable_runtime_eligible`); + requireAccessTruth(row, `missions[${index}]`, {requireReadOnlyAudit: true}); return row; } @@ -122,11 +132,7 @@ function validateResult(row, index) { requireText(row.title, `results[${index}].title`); requireText(row.snippet, `results[${index}].snippet`, {allowEmpty: true}); requireStringArray(row.source_references, `results[${index}].source_references`, {maxLength: MAX_SOURCE_REF_LENGTH}); - if (row.source_audit_status !== null && row.source_audit_status !== undefined) { - requireText(row.source_audit_status, `results[${index}].source_audit_status`); - } - requireContentAccess(row.content_access, `results[${index}].content_access`); - requireBoolean(row.gradeable_runtime_eligible, `results[${index}].gradeable_runtime_eligible`); + requireAccessTruth(row, `results[${index}]`, {requireReadOnlyAudit: true}); return row; } From d472c0d96f83dc5c432960c7a7a318b6106df922 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:31:20 +0200 Subject: [PATCH 095/125] R06 Library: lock access/audit truth validation contract --- .../tests/test_packaged_library_current_shell.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index f61fc7de9..69c96f565 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -5,7 +5,7 @@ import unittest ROOT = Path(__file__).resolve().parents[1] / "frontend" -EXPECTED_LIBRARY_UI_BLOB = "b68ce072597749a81fdafcfb8591c6e24c6d21b7" +EXPECTED_LIBRARY_UI_BLOB = "471991931544e3c83baaed34cdbfa6806d85bb69" def git_blob_sha(data: bytes) -> str: @@ -101,6 +101,10 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): self.assertIn(token, self.library) self.assertIn("row.gradeable_runtime_eligible", self.library) self.assertIn("data.read_only_qualified_sources.length", self.library) + self.assertIn("function requireAccessTruth", self.library) + self.assertIn("content_access/gradeable_runtime_eligible mismatch", self.library) + self.assertIn("requireReadOnlyAudit: true", self.library) + self.assertEqual(self.library.count("requireAccessTruth(row,"), 3) def test_dynamic_content_remains_inert_and_bounded(self): self.assertNotIn("innerHTML", self.library) From d9aa4ba358c3d6686a030209c92338712c1571c2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:31:45 +0200 Subject: [PATCH 096/125] R06 Library: count access-truth call sites precisely --- .../repair_overlay/tests/test_packaged_library_current_shell.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 69c96f565..3a7db2312 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -104,7 +104,7 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): self.assertIn("function requireAccessTruth", self.library) self.assertIn("content_access/gradeable_runtime_eligible mismatch", self.library) self.assertIn("requireReadOnlyAudit: true", self.library) - self.assertEqual(self.library.count("requireAccessTruth(row,"), 3) + self.assertEqual(self.library.count(" requireAccessTruth(row,"), 3) def test_dynamic_content_remains_inert_and_bounded(self): self.assertNotIn("innerHTML", self.library) From 4591f94e53dd53e54fa89d76f8c86bad815e3d49 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:36:04 +0200 Subject: [PATCH 097/125] R06 Library: execute access-truth validator regressions --- .../test_packaged_library_current_shell.py | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 3a7db2312..757d0a4db 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -2,6 +2,7 @@ import hashlib import re import subprocess +import tempfile import unittest ROOT = Path(__file__).resolve().parents[1] / "frontend" @@ -106,6 +107,113 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): self.assertIn("requireReadOnlyAudit: true", self.library) self.assertEqual(self.library.count(" requireAccessTruth(row,"), 3) + def test_access_truth_validators_execute_fail_closed(self): + runner = r""" +import assert from 'node:assert/strict'; +import fs from 'node:fs'; + +const libraryPath = process.argv[2]; +let source = fs.readFileSync(libraryPath, 'utf8'); +const transportImport = "import {chooseTransport, unwrap} from './transport.js';"; +assert.ok(source.startsWith(transportImport), 'unexpected library-ui import boundary'); +source = source.slice(transportImport.length); + +const moduleUrl = 'data:text/javascript;base64,' + Buffer.from(source, 'utf8').toString('base64'); +const {validateCatalogResponse, validateSearchResponse} = await import(moduleUrl); + +const readOnlyMission = { + campaign_id: 'OT-R06-D4', + mission_id: 'OT-AB-01', + title: 'Read-only mission', + source_audit_status: 'DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING', + content_access: 'READ_ONLY_LIBRARY', + gradeable_runtime_eligible: false, +}; +const readOnlyCampaign = { + campaign_id: 'OT-R06-D4', + title: 'Read-only campaign', + mission_count: 1, + machine_node_count: 1, + content_access: 'READ_ONLY_LIBRARY', + gradeable_runtime_eligible: false, +}; +const validCatalog = { + schema: 'scripture.library.catalog.v1', + source_of_truth: 'CanonicalContentLoader', + derived_index: true, + bundled_full_bible_text: false, + text_provider_available: false, + machine_node_count: 1, + read_only_qualified_sources: ['OT-R06-D4'], + campaigns: [readOnlyCampaign], + missions: [readOnlyMission], + source_references: ['Genesis 12:1'], +}; +assert.equal(validateCatalogResponse(validCatalog), validCatalog); +assert.throws( + () => validateCatalogResponse({...validCatalog, campaigns: [{...readOnlyCampaign, gradeable_runtime_eligible: true}]}), + /content_access\/gradeable_runtime_eligible mismatch/ +); +assert.throws( + () => validateCatalogResponse({...validCatalog, missions: [{...readOnlyMission, source_audit_status: null}]}), + /source_audit_status/ +); + +const readOnlyResult = { + kind: 'task', + id: 'OTAB01-N001', + campaign_id: 'OT-R06-D4', + mission_id: 'OT-AB-01', + title: 'Read-only task', + snippet: 'Genesis 12:1', + source_references: ['Genesis 12:1'], + source_audit_status: 'DEVELOPER_SOURCE_AUDITED / INDEPENDENT_AUDIT_PENDING', + content_access: 'READ_ONLY_LIBRARY', + gradeable_runtime_eligible: false, +}; +const validSearch = { + schema: 'scripture.library.search.v1', + source_of_truth: 'CanonicalContentLoader', + derived_index: true, + bundled_full_bible_text: false, + query: 'Genesis 12:1', + filters: {campaign_id: 'OT-R06-D4', mission_id: null}, + total: 1, + results: [readOnlyResult], +}; +assert.equal(validateSearchResponse(validSearch), validSearch); +assert.throws( + () => validateSearchResponse({...validSearch, results: [{...readOnlyResult, content_access: 'GRADEABLE_RUNTIME'}]}), + /content_access\/gradeable_runtime_eligible mismatch/ +); +assert.throws( + () => validateSearchResponse({...validSearch, results: [{...readOnlyResult, source_audit_status: undefined}]}), + /source_audit_status/ +); +assert.equal( + validateSearchResponse({ + ...validSearch, + results: [{ + ...readOnlyResult, + content_access: 'GRADEABLE_RUNTIME', + gradeable_runtime_eligible: true, + source_audit_status: null, + }], + }).results[0].gradeable_runtime_eligible, + true +); +""" + with tempfile.TemporaryDirectory() as tmp: + runner_path = Path(tmp) / "validate-library-access.mjs" + runner_path.write_text(runner, encoding="utf-8") + completed = subprocess.run( + ["node", str(runner_path), str(ROOT / "library-ui.js")], + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) + def test_dynamic_content_remains_inert_and_bounded(self): self.assertNotIn("innerHTML", self.library) self.assertNotIn("insertAdjacentHTML", self.library) From b0154847051f9e7168613aac2bf8c4484ce0024a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:47:37 +0200 Subject: [PATCH 098/125] R06: add read-only corrected D2 runtime preintegration gate --- ...06-d2-corrected-runtime-preintegration.yml | 129 +++++ ..._validate_dev2_corrected_runtime_compat.py | 65 +++ .../validate_dev2_corrected_runtime_compat.py | 461 ++++++++++++++++++ 3 files changed, 655 insertions(+) create mode 100644 .github/workflows/r06-d2-corrected-runtime-preintegration.yml create mode 100644 tools/test_validate_dev2_corrected_runtime_compat.py create mode 100755 tools/validate_dev2_corrected_runtime_compat.py diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml new file mode 100644 index 000000000..33b200d42 --- /dev/null +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -0,0 +1,129 @@ +name: R06 D2 corrected runtime preintegration + +on: + push: + branches: + - r06-d2-corrected-runtime-preintegration-0928-sol + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + pull_request: + paths: + - 'tools/validate_dev2_corrected_runtime_compat.py' + - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-d2-corrected-runtime-preintegration + cancel-in-progress: false + +jobs: + compatibility: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + PACKAGE_BASE_SHA: a8f032c401803827300e0b7f2f1588bdfaec3f05 + D2_AUTHORITY_SHA: 5b367fb567eec6312a149ef23075a0e3d48c054f + D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 + steps: + - name: Resolve expected head + id: head + shell: bash + env: + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EVENT_SHA: ${{ github.sha }} + run: | + set -euo pipefail + expected="${PR_HEAD_SHA:-$EVENT_SHA}" + test -n "$expected" + echo "sha=$expected" >> "$GITHUB_OUTPUT" + + - name: Checkout exact current-package candidate + uses: actions/checkout@v4 + with: + ref: ${{ steps.head.outputs.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Prove package lineage and exact checkout + shell: bash + env: + EXPECTED_HEAD: ${{ steps.head.outputs.sha }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + git merge-base --is-ancestor "$PACKAGE_BASE_SHA" HEAD + test -z "$(git status --porcelain)" + echo "D2_RUNTIME_PREINTEGRATION_PACKAGE_HEAD=$EXPECTED_HEAD" + + - name: Extract exact D2 authority read-only + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority" + rm -rf "$authority" + mkdir -p "$authority" + git fetch --no-tags origin "$D2_AUTHORITY_SHA" + test "$(git cat-file -t "$D2_AUTHORITY_SHA")" = "commit" + git archive "$D2_AUTHORITY_SHA" "$D2_AUTHORITY_REL" | tar -x -C "$authority" + root="$authority/$D2_AUTHORITY_REL" + test -f "$root/D2_CORRECTED_NODE_HASH_INDEX.json" + test -f "$root/D2_FULL_CORRECTED_AGGREGATION_MANIFEST.json" + test -f "$root/evidence_hash_index.json" + echo "D2_RUNTIME_PREINTEGRATION_AUTHORITY=$D2_AUTHORITY_SHA" + + - name: Run compatibility-tool regressions + shell: bash + run: | + set -euo pipefail + python -m py_compile tools/validate_dev2_corrected_runtime_compat.py + python -m unittest tools/test_validate_dev2_corrected_runtime_compat.py -v + + - name: Run exact D2 through current-package runtime + shell: bash + run: | + set -euo pipefail + authority="$RUNNER_TEMP/d2-authority/$D2_AUTHORITY_REL" + pack="$RUNNER_TEMP/R06_D2_PREINTEGRATION_ONLY.zip" + report="$RUNNER_TEMP/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json" + python tools/validate_dev2_corrected_runtime_compat.py --authority-root "$authority" --pack-out "$pack" --report "$report" + python - "$report" <<'PY' + import json + import pathlib + import sys + report = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) + assert report["status"] == "COMPATIBILITY_PASS / PROMOTION_BLOCKED", report + assert report["authority"]["node_count"] == 386, report + assert report["authority"]["evidence_count"] == 184, report + assert report["authority"]["independent_audit"] == "PENDING", report + runtime = report["current_package_runtime"] + assert runtime["repository_nodes"] == 386, runtime + assert runtime["self_grade_correct"] == 386, runtime + assert runtime["runtime_load_pass"] == 386, runtime + pack = report["preintegration_content_pack"] + assert pack["node_count"] == 386, pack + assert report["promotion_allowed"] is False, report + print("D2_RUNTIME_PREINTEGRATION_PASS nodes=386 self_grade=386 runtime_load=386") + PY + + - name: Prove worktree stayed immutable + shell: bash + run: | + set -euo pipefail + test -z "$(git status --porcelain)" + echo "D2_RUNTIME_PREINTEGRATION_READ_ONLY_PASS" + + - name: Upload read-only compatibility evidence + uses: actions/upload-artifact@v4 + with: + name: r06-d2-runtime-preintegration-${{ steps.head.outputs.sha }} + path: | + ${{ runner.temp }}/R06_D2_PREINTEGRATION_ONLY.zip + ${{ runner.temp }}/R06_D2_RUNTIME_PREINTEGRATION_REPORT.json + if-no-files-found: error + retention-days: 30 diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py new file mode 100644 index 000000000..b6f24c4cf --- /dev/null +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import copy +import json +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +for entry in ( + REPO_ROOT / "runtime_engine", + REPO_ROOT / "runtime_engine" / "tests", + REPO_ROOT / "tools", +): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from fixtures import LN01_N03 +from scripture_archive_runtime.content_packs import ContentPackStore, inspect_content_pack +from validate_dev2_corrected_runtime_compat import ( + PACK_ID, + PACK_VERSION, + _runtime_compatibility, + write_preintegration_pack, +) + + +class D2CorrectedRuntimeCompatibilityTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_pack_writer_is_deterministic_and_installable(self) -> None: + node = copy.deepcopy(LN01_N03) + first = self.root / "first.zip" + second = self.root / "second.zip" + a = write_preintegration_pack([node] * 0 + [node], first) + b = write_preintegration_pack([copy.deepcopy(node)], second) + self.assertEqual(first.read_bytes(), second.read_bytes()) + self.assertEqual(a["archive_sha256"], b["archive_sha256"]) + inspected = inspect_content_pack(first) + self.assertEqual(PACK_ID, inspected.manifest.pack_id) + self.assertEqual(PACK_VERSION, inspected.manifest.version) + self.assertEqual(1, inspected.node_count) + + def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self) -> None: + node = copy.deepcopy(LN01_N03) + # The production helper is cardinality-pinned to D2, so exercise the same + # runtime primitives here through a one-record content pack round trip. + archive = self.root / "fixture.zip" + write_preintegration_pack([node], archive) + store = ContentPackStore(self.root / "store") + inspected = store.install(archive) + self.assertEqual(1, inspected.node_count) + store.activate(PACK_ID, PACK_VERSION) + self.assertEqual({PACK_ID: PACK_VERSION}, store.active_versions()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py new file mode 100755 index 000000000..bf1739c03 --- /dev/null +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +"""Read-only compatibility gate for the corrected R06 D2 Paul/Acts authority. + +This gate never promotes the D2 corpus and never mutates the packaged-app content +surface. It consumes an exact external authority snapshot, proves its corrected +hash/index/evidence bindings, then runs all 386 nodes through the current-package +runtime and a deterministic preintegration content-pack round trip. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import stat +import sys +import tempfile +import zipfile +from collections import Counter +from pathlib import Path +from typing import Any, Iterable, Mapping + +REPO_ROOT = Path(__file__).resolve().parents[1] +RUNTIME_ROOT = REPO_ROOT / "runtime_engine" +TOOLS_ROOT = REPO_ROOT / "tools" +for entry in (RUNTIME_ROOT, TOOLS_ROOT): + if str(entry) not in sys.path: + sys.path.insert(0, str(entry)) + +from scripture_archive_runtime.application import RuntimeApplication +from scripture_archive_runtime.content import ContentRepository +from scripture_archive_runtime.content_packs import ( + CONTENT_PACK_SCHEMA, + CONTENT_SCHEMA_VERSION, + MANIFEST_NAME, + ContentPackStore, + inspect_content_pack, +) +from scripture_archive_runtime.grading import GraderRegistry +from scripture_archive_runtime.models import Correctness +from scripture_archive_runtime.provenance import canonical_answer_dto, classify_provenance +from scripture_archive_runtime.security import ValidationError +from validate_dev2_evidence_bundle import validate_bundle as validate_composed_evidence + +SCHEMA = "R06_D2_CORRECTED_RUNTIME_PREINTEGRATION_v1" +AUTHORITY_SCHEMA = "R06_D2_CORRECTED_NODE_HASH_INDEX_v1" +EXPECTED_NODE_COUNT = 386 +EXPECTED_EVIDENCE_COUNT = 184 +EXPECTED_NODE_AGGREGATE = "b096d316e07b2b64ac79dfb2c4a3a328e390520fba8ab021c13f7c6f9dbb38d2" +EXPECTED_EVIDENCE_AGGREGATE = "88e197fd1c91b7787040e81bdd066d959d42b8ba64ac01acac667ffd8ad346ba" +EXPECTED_STAGING_ZIP = "b681ea26d985eb754bde02a77254d40ab0920061edb9226fae7921a6740a06c0" +EXPECTED_MISSION_COUNTS = { + "PA-03": 53, + "PA-04": 63, + "PA-05": 61, + "PA-06": 43, + "PA-07": 61, + "PA-08": 105, +} +EXPECTED_PARTS = tuple(f"nodes/part_{index:03d}.jsonl" for index in range(1, 27)) +PACKAGE_EVIDENCE_REL = ( + "evidence/part_001.jsonl", + "evidence/part_002.jsonl", + "evidence/part_003.jsonl", + "evidence_hash_index.json", + "mission_metadata.json", +) +PACK_ID = "r06-d2-paul-acts-preintegration" +PACK_VERSION = "0.6.0-d2pre.1" + + +class CompatibilityError(ValueError): + pass + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _canonical_bytes(value: Any) -> bytes: + return json.dumps( + value, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + +def _load_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise CompatibilityError(f"cannot load JSON {path}: {exc}") from exc + + +def _require_regular(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_file(): + raise CompatibilityError(f"missing or unsafe regular file: {label}") + + +def _reject_symlinks(root: Path) -> None: + if root.is_symlink() or not root.is_dir(): + raise CompatibilityError(f"missing or unsafe authority root: {root}") + for path in root.rglob("*"): + if path.is_symlink(): + raise CompatibilityError( + f"symlink forbidden in authority snapshot: {path.relative_to(root)}" + ) + + +def _load_evidence_ids(authority_root: Path) -> set[str]: + index = _load_json(authority_root / "evidence_hash_index.json") + if not isinstance(index, Mapping): + raise CompatibilityError("evidence_hash_index.json must be an object") + if index.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence record_count changed") + if index.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("evidence aggregate changed") + records = index.get("records") + if not isinstance(records, list): + raise CompatibilityError("evidence index records must be a list") + ids: set[str] = set() + for row in records: + if not isinstance(row, Mapping): + raise CompatibilityError("evidence index row must be an object") + evidence_id = row.get("id") + digest = row.get("sha256") + if not isinstance(evidence_id, str) or not evidence_id: + raise CompatibilityError("invalid evidence id") + if evidence_id in ids: + raise CompatibilityError(f"duplicate evidence id: {evidence_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid evidence SHA256: {evidence_id}") + ids.add(evidence_id) + if len(ids) != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("evidence ID cardinality changed") + return ids + + +def load_corrected_nodes(authority_root: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]: + _reject_symlinks(authority_root) + index = _load_json(authority_root / "D2_CORRECTED_NODE_HASH_INDEX.json") + if not isinstance(index, Mapping): + raise CompatibilityError("corrected node hash index must be an object") + if index.get("schema") != AUTHORITY_SCHEMA: + raise CompatibilityError("unexpected corrected node hash-index schema") + if index.get("record_count") != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected node record_count changed") + if index.get("aggregate_sha256") != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError("corrected node aggregate changed") + if index.get("historical_staging_zip_sha256") != EXPECTED_STAGING_ZIP: + raise CompatibilityError("historical staging provenance pin changed") + if index.get("source_truth_changed") is not False: + raise CompatibilityError("corrected authority claims source-truth mutation") + if "INDEPENDENT_AUDIT_PENDING" not in str(index.get("status", "")): + raise CompatibilityError("corrected authority improperly promotes audit status") + + rows = index.get("records") + if not isinstance(rows, list): + raise CompatibilityError("corrected index records must be a list") + + expected: dict[str, tuple[str, str]] = {} + indexed_parts: set[str] = set() + for row in rows: + if not isinstance(row, Mapping): + raise CompatibilityError("corrected index row must be an object") + node_id = row.get("id") + digest = row.get("sha256") + part = row.get("part") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError("corrected index row has invalid id") + if node_id in expected: + raise CompatibilityError(f"duplicate corrected index node: {node_id}") + if not isinstance(digest, str) or len(digest) != 64: + raise CompatibilityError(f"invalid corrected SHA256: {node_id}") + if part not in EXPECTED_PARTS: + raise CompatibilityError(f"unexpected corrected part for {node_id}: {part}") + expected[node_id] = (digest.casefold(), str(part)) + indexed_parts.add(str(part)) + + if len(expected) != EXPECTED_NODE_COUNT: + raise CompatibilityError("corrected index unique-node count changed") + if indexed_parts != set(EXPECTED_PARTS): + raise CompatibilityError("corrected index does not cover all 26 canonical parts") + + nodes: dict[str, dict[str, Any]] = {} + mission_counts: Counter[str] = Counter() + for part in EXPECTED_PARTS: + path = authority_root / part + _require_regular(path, part) + for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + try: + node = json.loads(line) + except json.JSONDecodeError as exc: + raise CompatibilityError(f"invalid node JSONL at {part}:{line_number}") from exc + if not isinstance(node, dict): + raise CompatibilityError(f"node at {part}:{line_number} must be an object") + node_id = node.get("node_id") + if not isinstance(node_id, str) or not node_id: + raise CompatibilityError(f"node at {part}:{line_number} has invalid node_id") + if node_id in nodes: + raise CompatibilityError(f"duplicate corrected node_id: {node_id}") + indexed = expected.get(node_id) + if indexed is None: + raise CompatibilityError(f"unindexed corrected node: {node_id}") + digest = _sha256_bytes(_canonical_bytes(node)) + if digest != indexed[0]: + raise CompatibilityError(f"corrected record SHA256 mismatch: {node_id}") + if indexed[1] != part: + raise CompatibilityError(f"corrected part mismatch: {node_id}") + mission_id = node.get("mission_id") + if mission_id not in EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"unexpected D2 mission_id: {mission_id}") + mission_counts[str(mission_id)] += 1 + nodes[node_id] = node + + if set(nodes) != set(expected): + missing = sorted(set(expected) - set(nodes)) + extra = sorted(set(nodes) - set(expected)) + raise CompatibilityError( + f"corrected node ID set mismatch missing={missing[:5]} extra={extra[:5]}" + ) + if dict(sorted(mission_counts.items())) != EXPECTED_MISSION_COUNTS: + raise CompatibilityError(f"mission node counts changed: {dict(mission_counts)}") + + aggregate = _sha256_bytes( + "".join( + f"{node_id}\t{_sha256_bytes(_canonical_bytes(nodes[node_id]))}\n" + for node_id in sorted(nodes) + ).encode("utf-8") + ) + if aggregate != EXPECTED_NODE_AGGREGATE: + raise CompatibilityError(f"recomputed corrected aggregate mismatch: {aggregate}") + + return [nodes[node_id] for node_id in sorted(nodes)], dict(index) + + +def _verify_evidence_binding( + nodes: Iterable[Mapping[str, Any]], + *, + authority_root: Path, + repo_root: Path, +) -> tuple[int, dict[str, Any]]: + evidence_ids = _load_evidence_ids(authority_root) + missing: list[tuple[str, str]] = [] + for node in nodes: + required = node.get("required_evidence") + if not isinstance(required, list) or not all(isinstance(value, str) for value in required): + raise CompatibilityError(f"{node.get('node_id')}: invalid required_evidence") + for evidence_id in required: + if evidence_id not in evidence_ids: + missing.append((str(node.get("node_id")), evidence_id)) + if missing: + raise CompatibilityError(f"nodes reference unknown evidence IDs: {missing[:10]}") + + package_root = repo_root / "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05" + for rel in PACKAGE_EVIDENCE_REL: + authority_path = authority_root / rel + package_path = package_root / rel + _require_regular(authority_path, f"authority/{rel}") + _require_regular(package_path, f"package/{rel}") + if authority_path.read_bytes() != package_path.read_bytes(): + raise CompatibilityError(f"current-package evidence drift: {rel}") + + evidence_report = validate_composed_evidence(repo_root) + if evidence_report.get("status") != "PASS": + raise CompatibilityError("current-package D2 evidence validator did not PASS") + if evidence_report.get("record_count") != EXPECTED_EVIDENCE_COUNT: + raise CompatibilityError("current-package evidence count changed") + if evidence_report.get("aggregate_sha256") != EXPECTED_EVIDENCE_AGGREGATE: + raise CompatibilityError("current-package evidence aggregate changed") + if evidence_report.get("independent_audit") != "PENDING": + raise CompatibilityError("current-package evidence audit status was promoted") + return len(evidence_ids), evidence_report + + +def _runtime_compatibility(nodes: list[dict[str, Any]]) -> dict[str, Any]: + try: + repository = ContentRepository(nodes, adapt_legacy=True, lane="D2") + except (ValidationError, ValueError, TypeError) as exc: + raise CompatibilityError(f"current runtime rejected corrected D2 corpus: {exc}") from exc + tasks = repository.all() + if len(tasks) != EXPECTED_NODE_COUNT: + raise CompatibilityError("runtime repository did not retain all corrected nodes") + + grader = GraderRegistry() + app = RuntimeApplication(repository) + provenance_counts: Counter[str] = Counter() + self_grade_failures: list[str] = [] + runtime_load_failures: list[str] = [] + + for node_id in sorted(tasks): + task = tasks[node_id] + decision = classify_provenance(task.raw) + provenance_counts[decision.provenance_class] += 1 + if not decision.release_pass: + raise CompatibilityError( + f"{node_id}: current runtime provenance rejects corrected node: {decision.reason}" + ) + try: + answer = canonical_answer_dto(task.raw) + result = grader.grade(task, answer) + except Exception as exc: + raise CompatibilityError(f"{node_id}: self-grade raised {type(exc).__name__}: {exc}") from exc + if result.correctness is not Correctness.CORRECT or result.score != 1.0: + self_grade_failures.append(node_id) + try: + response = app.load_task(node_id) + rendered = response.get("task", {}) + if rendered.get("node_id") != node_id: + runtime_load_failures.append(node_id) + if not str(rendered.get("functional_nonvisual_equivalent", "")).strip(): + runtime_load_failures.append(node_id) + except Exception as exc: + raise CompatibilityError(f"{node_id}: runtime load raised {type(exc).__name__}: {exc}") from exc + + if self_grade_failures: + raise CompatibilityError(f"runtime self-grade failed: {self_grade_failures[:10]}") + if runtime_load_failures: + raise CompatibilityError(f"runtime task render failed: {runtime_load_failures[:10]}") + + return { + "repository_nodes": len(tasks), + "self_grade_correct": EXPECTED_NODE_COUNT, + "runtime_load_pass": EXPECTED_NODE_COUNT, + "provenance_classes": dict(sorted(provenance_counts.items())), + } + + +def _json_bytes(value: Any) -> bytes: + return ( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" + ).encode("utf-8") + + +def write_preintegration_pack(nodes: list[dict[str, Any]], destination: Path) -> dict[str, Any]: + destination = destination.expanduser().resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + payload = _json_bytes({"nodes": nodes}) + payload_name = "content/nodes.json" + manifest = { + "schema": CONTENT_PACK_SCHEMA, + "pack_id": PACK_ID, + "version": PACK_VERSION, + "content_schema_version": CONTENT_SCHEMA_VERSION, + "entry_points": [payload_name], + "files": {payload_name: _sha256_bytes(payload)}, + } + manifest_bytes = _json_bytes(manifest) + with zipfile.ZipFile( + destination, + "w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=9, + ) as archive: + for name, data in ((MANIFEST_NAME, manifest_bytes), (payload_name, payload)): + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = (stat.S_IFREG | 0o644) << 16 + archive.writestr(info, data) + + inspection = inspect_content_pack(destination) + if inspection.node_count != EXPECTED_NODE_COUNT: + raise CompatibilityError("content-pack inspector did not see all corrected nodes") + if inspection.manifest.pack_id != PACK_ID or inspection.manifest.version != PACK_VERSION: + raise CompatibilityError("content-pack identity drifted") + + with tempfile.TemporaryDirectory() as temp: + store = ContentPackStore(Path(temp) / "store") + installed = store.install(destination) + if installed.node_count != EXPECTED_NODE_COUNT: + raise CompatibilityError("content-pack store install lost corrected nodes") + store.activate(PACK_ID, PACK_VERSION) + if store.active_versions().get(PACK_ID) != PACK_VERSION: + raise CompatibilityError("content-pack activation did not select D2 preintegration pack") + installed_payload = ( + Path(temp) + / "store" + / "packs" + / PACK_ID + / PACK_VERSION + / payload_name + ) + roundtrip = ContentRepository.from_json_files( + [installed_payload], + adapt_legacy=True, + lane="D2", + ) + if len(roundtrip.all()) != EXPECTED_NODE_COUNT: + raise CompatibilityError("installed content pack runtime reload lost corrected nodes") + + return { + "pack_id": PACK_ID, + "version": PACK_VERSION, + "archive_sha256": _sha256_bytes(destination.read_bytes()), + "payload_sha256": manifest["files"][payload_name], + "node_count": inspection.node_count, + "file_count": inspection.file_count, + } + + +def run(authority_root: Path, pack_out: Path) -> dict[str, Any]: + authority_root = authority_root.expanduser().resolve() + nodes, index = load_corrected_nodes(authority_root) + evidence_count, evidence_report = _verify_evidence_binding( + nodes, + authority_root=authority_root, + repo_root=REPO_ROOT, + ) + runtime_report = _runtime_compatibility(nodes) + pack_report = write_preintegration_pack(nodes, pack_out) + return { + "schema": SCHEMA, + "status": "COMPATIBILITY_PASS / PROMOTION_BLOCKED", + "authority": { + "node_count": len(nodes), + "corrected_node_aggregate_sha256": index["aggregate_sha256"], + "evidence_count": evidence_count, + "evidence_aggregate_sha256": evidence_report["aggregate_sha256"], + "historical_staging_zip_sha256": EXPECTED_STAGING_ZIP, + "source_truth_changed": False, + "independent_audit": "PENDING", + }, + "current_package_runtime": runtime_report, + "preintegration_content_pack": pack_report, + "promotion_allowed": False, + "promotion_blockers": [ + "final-head D2 hosted qualification must be terminal green", + "independent D2 QA verdict must be recorded", + "current-package composition must occur on its canonical lineage after those gates", + ], + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--authority-root", type=Path, required=True) + parser.add_argument("--pack-out", type=Path, required=True) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + try: + report = run(args.authority_root, args.pack_out) + except (CompatibilityError, ValidationError) as exc: + failure = {"schema": SCHEMA, "status": "FAIL", "error": str(exc)} + payload = json.dumps(failure, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="", file=sys.stderr) + return 1 + payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n" + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(payload, encoding="utf-8") + print(payload, end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From d58ecca7646da50df7b465e65ebf8747c9a959dc Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:47:54 +0200 Subject: [PATCH 099/125] R06 Cross-Testament: bind linear view to structured provenance --- .../frontend/cross-testament-ui.js | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js b/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js index 4125f6e20..0c370d0ae 100644 --- a/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js +++ b/lanes/dev1/repair_overlay/frontend/cross-testament-ui.js @@ -48,12 +48,32 @@ function validateEndpoint(endpoint, testament, field) { boundedText(endpoint.book, `${field}.book`); positiveInt(endpoint.chapter, `${field}.chapter`); positiveInt(endpoint.verse_start, `${field}.verse_start`); - if (endpoint.verse_end !== null) positiveInt(endpoint.verse_end, `${field}.verse_end`); + if (endpoint.verse_end !== null) { + positiveInt(endpoint.verse_end, `${field}.verse_end`); + if (endpoint.verse_end < endpoint.verse_start) throw new Error(`${field}.verse_end precedes verse_start`); + } boundedText(endpoint.witness, `${field}.witness`, {nullable: true}); if (!Array.isArray(endpoint.evidence) || endpoint.evidence.length > MAX_EVIDENCE) throw new Error(`${field}.evidence is invalid`); endpoint.evidence.forEach((item, index) => validateEvidence(item, `${field}.evidence[${index}]`)); } +function canonicalLinearFromLinks(links) { + if (!links.length) return ['Not stated in cited text']; + const lines = []; + for (const link of links) { + lines.push(`Relation ${link.relation_id} [${link.relation_type}]: OT ${passage(link.ot)} ↔ NT ${passage(link.nt)}`); + if (link.relation_witness) lines.push(`Relation witness: ${link.relation_witness}`); + for (const [label, endpoint] of [['OT', link.ot], ['NT', link.nt]]) { + lines.push(`${label} passage: ${passage(endpoint)}; witness=${endpoint.witness || 'not stated'}`); + for (const item of endpoint.evidence) { + const tx = item.tx1 ? '; TX1' : ''; + lines.push(`${label} evidence ${item.evidence_id}: confidence=${item.confidence}${tx}; witness=${item.witness || 'not stated'}`); + } + } + } + return lines; +} + export function validateCrossTestamentResponse(data) { if (!record(data) || data.schema !== 'scripture.research.cross-testament.v1') throw new Error('Некоректний OT↔NT contract'); if (data.projection_schema !== 'CROSS_TESTAMENT_v1') throw new Error('Некоректна canonical OT↔NT projection'); @@ -76,6 +96,13 @@ export function validateCrossTestamentResponse(data) { data.linear.forEach((line, index) => boundedText(line, `linear[${index}]`)); if (data.status === 'NOT_STATED_IN_CITED_TEXT' && data.links.length !== 0) throw new Error('Empty-state status conflicts with links'); if (data.status === 'LINKS' && data.links.length === 0) throw new Error('Link status requires links'); + const expectedLinear = canonicalLinearFromLinks(data.links); + if ( + data.linear.length !== expectedLinear.length + || data.linear.some((line, index) => line !== expectedLinear[index]) + ) { + throw new Error('OT↔NT linear equivalent conflicts with structured links'); + } return data; } From 0e42a79b5f4038626d633dd5cfcee8a10c0e4513 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:48:15 +0200 Subject: [PATCH 100/125] R06 Cross-Testament: regress accessible linear provenance equality --- .../test_packaged_cross_testament_contract.py | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py index 8925bd3f7..b9ba91393 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_cross_testament_contract.py @@ -1,4 +1,6 @@ import ast +import subprocess +import textwrap import unittest from pathlib import Path from tempfile import TemporaryDirectory @@ -220,6 +222,84 @@ def test_runtime_gateway_holds_projection_under_runtime_lock(self): self.assertIn("project_packaged_cross_testament(self._runtime_application.evidence)", locked_source) self.assertNotIn("include_locked", locked_source) + def test_frontend_linear_equivalent_executes_fail_closed(self): + frontend = Path(__file__).resolve().parents[1] / "frontend" + ui_path = frontend / "cross-testament-ui.js" + script = textwrap.dedent( + r""" + import {readFileSync} from 'node:fs'; + let source = readFileSync(process.argv[1], 'utf8'); + source = source.replace( + "import {chooseTransport, unwrap} from './transport.js';", + "const chooseTransport=()=>null; const unwrap=async()=>({});" + ); + const mod = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')); + const reject = (fn, label) => { + let failed = false; + try { fn(); } catch (_) { failed = true; } + if (!failed) throw new Error('expected rejection: ' + label); + }; + const endpoint = (testament, passage_id, book, chapter, verse, evidence_id, confidence, tx1, witness) => ({ + passage_id, testament, book, chapter, verse_start:verse, verse_end:null, witness, + evidence:[{evidence_id, confidence, tx1, witness}] + }); + const ot = endpoint('OT', 'ISA7:14', 'Isaiah', 7, 14, 'EV-OT', 'T1', false, 'Isaiah'); + const nt = endpoint('NT', 'MT1:23', 'Matthew', 1, 23, 'EV-NT', 'T2', true, 'Matthew'); + const link = { + relation_id:'REL-X', + relation_type:'explicit_cross_reference', + relation_witness:null, + ot, nt + }; + const valid = { + schema:'scripture.research.cross-testament.v1', + projection_schema:'CROSS_TESTAMENT_v1', + status:'LINKS', + links:[link], + linear:[ + 'Relation REL-X [explicit_cross_reference]: OT Isaiah 7:14 (ISA7:14) ↔ NT Matthew 1:23 (MT1:23)', + 'OT passage: Isaiah 7:14 (ISA7:14); witness=Isaiah', + 'OT evidence EV-OT: confidence=T1; witness=Isaiah', + 'NT passage: Matthew 1:23 (MT1:23); witness=Matthew', + 'NT evidence EV-NT: confidence=T2; TX1; witness=Matthew' + ], + read_only:true, + evidence_scope:'unlocked_only', + truth_owner:'D5/runtime' + }; + mod.validateCrossTestamentResponse(valid); + reject( + () => mod.validateCrossTestamentResponse({...valid, linear:[...valid.linear.slice(0, -1), 'Contradictory accessible text']}), + 'linear mismatch' + ); + reject( + () => mod.validateCrossTestamentResponse({ + ...valid, + links:[{...link, ot:{...ot, verse_end:13}}] + }), + 'reversed verse range' + ); + const empty = { + ...valid, + status:'NOT_STATED_IN_CITED_TEXT', + links:[], + linear:['Not stated in cited text'] + }; + mod.validateCrossTestamentResponse(empty); + reject( + () => mod.validateCrossTestamentResponse({...empty, linear:['No relations exist anywhere']}), + 'dishonest empty-state linear text' + ); + """ + ) + result = subprocess.run( + ["node", "--input-type=module", "-e", script, str(ui_path)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, result.returncode, result.stderr or result.stdout) + def test_frontend_is_semantic_text_first_and_linear_equivalent(self): frontend = Path(__file__).resolve().parents[1] / "frontend" ui = (frontend / "cross-testament-ui.js").read_text(encoding="utf-8") @@ -228,6 +308,8 @@ def test_frontend_is_semantic_text_first_and_linear_equivalent(self): self.assertIn("document.createElement('table')", ui) self.assertIn("Повний лінійний еквівалент", ui) self.assertIn("Not stated in cited text", ui) + self.assertIn("canonicalLinearFromLinks", ui) + self.assertIn("linear equivalent conflicts with structured links", ui) self.assertIn("aria-live", ui) self.assertNotIn("innerHTML", ui) self.assertIn("cross-testament-ui.js", transport) From 9e2069c6bbdcdf5b2a5ce97f9f45363bad7fcb06 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:48:16 +0200 Subject: [PATCH 101/125] R06: make preintegration pack helper fixture-safe --- tools/test_validate_dev2_corrected_runtime_compat.py | 2 +- tools/validate_dev2_corrected_runtime_compat.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index b6f24c4cf..a720501c7 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -53,7 +53,7 @@ def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self # The production helper is cardinality-pinned to D2, so exercise the same # runtime primitives here through a one-record content pack round trip. archive = self.root / "fixture.zip" - write_preintegration_pack([node], archive) + write_preintegration_pack([node], archive, expected_node_count=1) store = ContentPackStore(self.root / "store") inspected = store.install(archive) self.assertEqual(1, inspected.node_count) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index bf1739c03..881faf372 100755 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -334,7 +334,7 @@ def _json_bytes(value: Any) -> bytes: ).encode("utf-8") -def write_preintegration_pack(nodes: list[dict[str, Any]], destination: Path) -> dict[str, Any]: +def write_preintegration_pack(\n nodes: list[dict[str, Any]],\n destination: Path,\n *,\n expected_node_count: int = EXPECTED_NODE_COUNT,\n) -> dict[str, Any]: destination = destination.expanduser().resolve() destination.parent.mkdir(parents=True, exist_ok=True) payload = _json_bytes({"nodes": nodes}) From 606c5486e774e1bc7a00aea2ccfdbc41d871a534 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:50:41 +0200 Subject: [PATCH 102/125] R06: repair preintegration pack helper syntax and cardinality --- .../validate_dev2_corrected_runtime_compat.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index 881faf372..a11c22355 100755 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -334,7 +334,12 @@ def _json_bytes(value: Any) -> bytes: ).encode("utf-8") -def write_preintegration_pack(\n nodes: list[dict[str, Any]],\n destination: Path,\n *,\n expected_node_count: int = EXPECTED_NODE_COUNT,\n) -> dict[str, Any]: +def write_preintegration_pack( + nodes: list[dict[str, Any]], + destination: Path, + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: destination = destination.expanduser().resolve() destination.parent.mkdir(parents=True, exist_ok=True) payload = _json_bytes({"nodes": nodes}) @@ -361,16 +366,16 @@ def write_preintegration_pack(\n nodes: list[dict[str, Any]],\n destinatio archive.writestr(info, data) inspection = inspect_content_pack(destination) - if inspection.node_count != EXPECTED_NODE_COUNT: - raise CompatibilityError("content-pack inspector did not see all corrected nodes") + if inspection.node_count != expected_node_count: + raise CompatibilityError("content-pack inspector did not see expected nodes") if inspection.manifest.pack_id != PACK_ID or inspection.manifest.version != PACK_VERSION: raise CompatibilityError("content-pack identity drifted") with tempfile.TemporaryDirectory() as temp: store = ContentPackStore(Path(temp) / "store") installed = store.install(destination) - if installed.node_count != EXPECTED_NODE_COUNT: - raise CompatibilityError("content-pack store install lost corrected nodes") + if installed.node_count != expected_node_count: + raise CompatibilityError("content-pack store install lost expected nodes") store.activate(PACK_ID, PACK_VERSION) if store.active_versions().get(PACK_ID) != PACK_VERSION: raise CompatibilityError("content-pack activation did not select D2 preintegration pack") @@ -387,8 +392,8 @@ def write_preintegration_pack(\n nodes: list[dict[str, Any]],\n destinatio adapt_legacy=True, lane="D2", ) - if len(roundtrip.all()) != EXPECTED_NODE_COUNT: - raise CompatibilityError("installed content pack runtime reload lost corrected nodes") + if len(roundtrip.all()) != expected_node_count: + raise CompatibilityError("installed content pack runtime reload lost expected nodes") return { "pack_id": PACK_ID, From c65e2129e239cb9b5afe1ef15f9b5b7df08411db Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:50:55 +0200 Subject: [PATCH 103/125] R06: fix preintegration fixture cardinality --- tools/test_validate_dev2_corrected_runtime_compat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index a720501c7..7b68adee4 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -39,7 +39,7 @@ def test_pack_writer_is_deterministic_and_installable(self) -> None: node = copy.deepcopy(LN01_N03) first = self.root / "first.zip" second = self.root / "second.zip" - a = write_preintegration_pack([node] * 0 + [node], first) + a = write_preintegration_pack([node], first, expected_node_count=1) b = write_preintegration_pack([copy.deepcopy(node)], second) self.assertEqual(first.read_bytes(), second.read_bytes()) self.assertEqual(a["archive_sha256"], b["archive_sha256"]) From 8731353fbf05538d62cbc58a2e715e5c31b3749b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:51:21 +0200 Subject: [PATCH 104/125] R06: make runtime compatibility helper regression-testable --- tools/validate_dev2_corrected_runtime_compat.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index a11c22355..552e2de4a 100755 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -275,14 +275,18 @@ def _verify_evidence_binding( return len(evidence_ids), evidence_report -def _runtime_compatibility(nodes: list[dict[str, Any]]) -> dict[str, Any]: +def _runtime_compatibility( + nodes: list[dict[str, Any]], + *, + expected_node_count: int = EXPECTED_NODE_COUNT, +) -> dict[str, Any]: try: repository = ContentRepository(nodes, adapt_legacy=True, lane="D2") except (ValidationError, ValueError, TypeError) as exc: raise CompatibilityError(f"current runtime rejected corrected D2 corpus: {exc}") from exc tasks = repository.all() - if len(tasks) != EXPECTED_NODE_COUNT: - raise CompatibilityError("runtime repository did not retain all corrected nodes") + if len(tasks) != expected_node_count: + raise CompatibilityError("runtime repository did not retain expected nodes") grader = GraderRegistry() app = RuntimeApplication(repository) @@ -322,8 +326,8 @@ def _runtime_compatibility(nodes: list[dict[str, Any]]) -> dict[str, Any]: return { "repository_nodes": len(tasks), - "self_grade_correct": EXPECTED_NODE_COUNT, - "runtime_load_pass": EXPECTED_NODE_COUNT, + "self_grade_correct": expected_node_count, + "runtime_load_pass": expected_node_count, "provenance_classes": dict(sorted(provenance_counts.items())), } From fb0e49e4bfacd8d8eb827859b97630f4ffc78472 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:51:34 +0200 Subject: [PATCH 105/125] R06: cover runtime provenance grade and load in preintegration test --- tools/test_validate_dev2_corrected_runtime_compat.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index 7b68adee4..3e3a7f885 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -50,8 +50,11 @@ def test_pack_writer_is_deterministic_and_installable(self) -> None: def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self) -> None: node = copy.deepcopy(LN01_N03) - # The production helper is cardinality-pinned to D2, so exercise the same - # runtime primitives here through a one-record content pack round trip. + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["repository_nodes"]) + self.assertEqual(1, runtime["self_grade_correct"]) + self.assertEqual(1, runtime["runtime_load_pass"]) + archive = self.root / "fixture.zip" write_preintegration_pack([node], archive, expected_node_count=1) store = ContentPackStore(self.root / "store") From 0d4f5473c968feac364a038669791ee555c68e15 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:52:27 +0200 Subject: [PATCH 106/125] R06: fix second deterministic pack fixture cardinality --- tools/test_validate_dev2_corrected_runtime_compat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index 3e3a7f885..0f48a8609 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -40,7 +40,7 @@ def test_pack_writer_is_deterministic_and_installable(self) -> None: first = self.root / "first.zip" second = self.root / "second.zip" a = write_preintegration_pack([node], first, expected_node_count=1) - b = write_preintegration_pack([copy.deepcopy(node)], second) + b = write_preintegration_pack([copy.deepcopy(node)], second, expected_node_count=1) self.assertEqual(first.read_bytes(), second.read_bytes()) self.assertEqual(a["archive_sha256"], b["archive_sha256"]) inspected = inspect_content_pack(first) From c8b2723e5197cfd9f42ec2a63e4892a369a71970 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:54:29 +0200 Subject: [PATCH 107/125] R06: add fail-closed runtime preintegration regressions --- ..._validate_dev2_corrected_runtime_compat.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index 0f48a8609..0668a090f 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -22,6 +22,7 @@ from validate_dev2_corrected_runtime_compat import ( PACK_ID, PACK_VERSION, + CompatibilityError, _runtime_compatibility, write_preintegration_pack, ) @@ -63,6 +64,24 @@ def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self store.activate(PACK_ID, PACK_VERSION) self.assertEqual({PACK_ID: PACK_VERSION}, store.active_versions()) + def test_conflicting_explicit_grading_truth_fails_closed(self) -> None: + node = copy.deepcopy(LN01_N03) + node["grading"] = {"accepted_choice": "CONTRADICTS CANONICAL ANSWER"} + with self.assertRaisesRegex( + CompatibilityError, + "provenance rejects corrected node", + ): + _runtime_compatibility([node], expected_node_count=1) + + def test_missing_nonvisual_equivalent_fails_before_runtime_promotion(self) -> None: + node = copy.deepcopy(LN01_N03) + node["functional_nonvisual_equivalent"] = "" + with self.assertRaisesRegex( + CompatibilityError, + "current runtime rejected corrected D2 corpus", + ): + _runtime_compatibility([node], expected_node_count=1) + if __name__ == "__main__": unittest.main() From 71bcc59b52489b108e1e16be3544ec6b0a7f30bb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 21:54:59 +0200 Subject: [PATCH 108/125] R06: pin final D2 head and cancel stale preintegration runs --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 33b200d42..166bd3189 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -20,7 +20,7 @@ permissions: concurrency: group: r06-d2-corrected-runtime-preintegration - cancel-in-progress: false + cancel-in-progress: true jobs: compatibility: @@ -28,7 +28,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: a8f032c401803827300e0b7f2f1588bdfaec3f05 - D2_AUTHORITY_SHA: 5b367fb567eec6312a149ef23075a0e3d48c054f + D2_AUTHORITY_SHA: 9fc42ffb65f5168801680132127b97ae398212ac D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From a594a293e9c2d40fe128cd02214ecc51123faadb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:12:36 +0200 Subject: [PATCH 109/125] R06 Library: align static audit assertion with shared validator --- .../repair_overlay/tests/test_packaged_library_current_shell.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py index 757d0a4db..85430e54b 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_library_current_shell.py @@ -95,7 +95,7 @@ def test_read_only_library_eligibility_is_fail_closed_and_user_visible(self): "source_audit_status", "Library eligibility не означає завершений independent source audit", "source audit: ${row.source_audit_status || 'статус не надано'}", - "results[${index}].source_audit_status", + "${name}.source_audit_status", "Source audit: ${row.source_audit_status || 'статус не надано'}", "цей запис не є доступним для player або grading", ): From 4b8ce9042dc2d5871c4ce63a6a779247c6c813b3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:16:46 +0200 Subject: [PATCH 110/125] R06 D2: bind runtime proof to trusted-staging package --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 166bd3189..1c3dca784 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -27,7 +27,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 env: - PACKAGE_BASE_SHA: a8f032c401803827300e0b7f2f1588bdfaec3f05 + PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 D2_AUTHORITY_SHA: 9fc42ffb65f5168801680132127b97ae398212ac D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: @@ -58,6 +58,7 @@ jobs: set -euo pipefail test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" git merge-base --is-ancestor "$PACKAGE_BASE_SHA" HEAD + test "$(git merge-base "$PACKAGE_BASE_SHA" HEAD)" = "$PACKAGE_BASE_SHA" test -z "$(git status --porcelain)" echo "D2_RUNTIME_PREINTEGRATION_PACKAGE_HEAD=$EXPECTED_HEAD" From b30b364a57d9be9c7605c8e48569a6c52579cc78 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:19:04 +0200 Subject: [PATCH 111/125] R06 D2: bind runtime proof to hardened authority head --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 1c3dca784..6fc4075a0 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -28,7 +28,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: 9fc42ffb65f5168801680132127b97ae398212ac + D2_AUTHORITY_SHA: 5d4b11c5cc45e06cb7d99d69621c74ccab8203b2 D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From 506c12ecb11d779ed2b36a0c9413a273f1f7e35f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:24:04 +0200 Subject: [PATCH 112/125] R06 D2: bind runtime proof to semantic-anchor hardened authority --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 6fc4075a0..4207693b3 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -28,7 +28,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: 5d4b11c5cc45e06cb7d99d69621c74ccab8203b2 + D2_AUTHORITY_SHA: 5dc6ad7e853c1f4be97f4179c43e90c4454edf8e D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From 944bf63d8a2601f99ab1f3948078c04456afb791 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:34:02 +0200 Subject: [PATCH 113/125] R06 D2: requalify on runtime and package changes --- .../r06-d2-corrected-runtime-preintegration.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 4207693b3..895610393 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -7,11 +7,21 @@ on: paths: - 'tools/validate_dev2_corrected_runtime_compat.py' - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' pull_request: paths: - 'tools/validate_dev2_corrected_runtime_compat.py' - 'tools/test_validate_dev2_corrected_runtime_compat.py' + - 'tools/validate_dev2_evidence_bundle.py' + - 'runtime_engine/scripture_archive_runtime/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/**' + - 'lanes/dev1/repair_overlay/frontend/**' + - 'docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**' - '.github/workflows/r06-d2-corrected-runtime-preintegration.yml' workflow_dispatch: From f6f1d58d89fd107e50f5ed92ad0d57c210026df1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:34:19 +0200 Subject: [PATCH 114/125] R06 D2: guard compatibility trigger coverage --- ..._validate_dev2_corrected_runtime_compat.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index 0668a090f..71920db45 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -82,6 +82,29 @@ def test_missing_nonvisual_equivalent_fails_before_runtime_promotion(self) -> No ): _runtime_compatibility([node], expected_node_count=1) + def test_workflow_requalifies_when_runtime_or_bound_package_changes(self) -> None: + workflow = ( + REPO_ROOT + / ".github" + / "workflows" + / "r06-d2-corrected-runtime-preintegration.yml" + ).read_text(encoding="utf-8") + required_trigger_surfaces = ( + "tools/validate_dev2_corrected_runtime_compat.py", + "tools/test_validate_dev2_corrected_runtime_compat.py", + "tools/validate_dev2_evidence_bundle.py", + "runtime_engine/scripture_archive_runtime/**", + "lanes/dev1/repair_overlay/scripture_archive_platform/**", + "lanes/dev1/repair_overlay/frontend/**", + "docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05/**", + ) + for trigger in required_trigger_surfaces: + self.assertGreaterEqual( + workflow.count(f" - '{trigger}'"), + 2, + f"push and pull_request must both requalify on {trigger}", + ) + if __name__ == "__main__": unittest.main() From f2b6c156f0a89ba46a3865de6cc79bef6899d79f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:38:05 +0200 Subject: [PATCH 115/125] R06 D2: bind runtime proof to localized authority --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 895610393..ef6f3ab9a 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -38,7 +38,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: 5dc6ad7e853c1f4be97f4179c43e90c4454edf8e + D2_AUTHORITY_SHA: 17a1e8b4c2f2328f78fe874cd155d038eaafa8be D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From 489f32a157f9b3253b9f4ca7224c428ffccc5405 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:38:08 +0200 Subject: [PATCH 116/125] R06 D2: qualify localized corrected aggregate --- tools/validate_dev2_corrected_runtime_compat.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index 552e2de4a..0515496b8 100644 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -45,7 +45,7 @@ AUTHORITY_SCHEMA = "R06_D2_CORRECTED_NODE_HASH_INDEX_v1" EXPECTED_NODE_COUNT = 386 EXPECTED_EVIDENCE_COUNT = 184 -EXPECTED_NODE_AGGREGATE = "b096d316e07b2b64ac79dfb2c4a3a328e390520fba8ab021c13f7c6f9dbb38d2" +EXPECTED_NODE_AGGREGATE = "ef77ae5d822e105050dedfa9a460325259fe079701ca69f385693aabcad0e661" EXPECTED_EVIDENCE_AGGREGATE = "88e197fd1c91b7787040e81bdd066d959d42b8ba64ac01acac667ffd8ad346ba" EXPECTED_STAGING_ZIP = "b681ea26d985eb754bde02a77254d40ab0920061edb9226fae7921a6740a06c0" EXPECTED_MISSION_COUNTS = { From f8c8d1df85cdfdcdd3610f09f501a760050299c0 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:39:17 +0200 Subject: [PATCH 117/125] R06 D2: bind runtime proof to authority mission IDs --- tools/validate_dev2_corrected_runtime_compat.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index 0515496b8..4369cac30 100644 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -153,6 +153,10 @@ def load_corrected_nodes(authority_root: Path) -> tuple[list[dict[str, Any]], di raise CompatibilityError("corrected authority claims source-truth mutation") if "INDEPENDENT_AUDIT_PENDING" not in str(index.get("status", "")): raise CompatibilityError("corrected authority improperly promotes audit status") + if index.get("mission_counts") != EXPECTED_MISSION_COUNTS: + raise CompatibilityError( + f"corrected authority mission_counts changed: {index.get('mission_counts')}" + ) rows = index.get("records") if not isinstance(rows, list): From 54bfbd88dd464af661191d3ed237084723853431 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:39:24 +0200 Subject: [PATCH 118/125] R06 D2: pin runtime proof to corrected authority metadata --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index ef6f3ab9a..c0be0ff7b 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -38,7 +38,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: 17a1e8b4c2f2328f78fe874cd155d038eaafa8be + D2_AUTHORITY_SHA: c9b7afef9f1cac7868d446d0e903e049c174667b D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From 7cdd8f096c6ba1ea062dbdffb696cc68d99c0c2a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:39:37 +0200 Subject: [PATCH 119/125] R06 D2: pin runtime proof to fully qualified localization authority --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index c0be0ff7b..3e53ced7c 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -38,7 +38,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: c9b7afef9f1cac7868d446d0e903e049c174667b + D2_AUTHORITY_SHA: ccbb77cbf2c52432c22430d13d6a84f965d9eaed D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From 8bb4cddc3cee6d12506c647a334a98fdd2c7c984 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Mon, 28 Sep 2026 23:41:20 +0200 Subject: [PATCH 120/125] R06 D2: follow localized authority qualification repair --- .github/workflows/r06-d2-corrected-runtime-preintegration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml index 3e53ced7c..9966a2a08 100644 --- a/.github/workflows/r06-d2-corrected-runtime-preintegration.yml +++ b/.github/workflows/r06-d2-corrected-runtime-preintegration.yml @@ -38,7 +38,7 @@ jobs: timeout-minutes: 20 env: PACKAGE_BASE_SHA: 84933e28992ee5284b0cab20b0be61ac2e8f7a50 - D2_AUTHORITY_SHA: ccbb77cbf2c52432c22430d13d6a84f965d9eaed + D2_AUTHORITY_SHA: f4d3bc6c918e9091a1e963029ccf3cf74558cfba D2_AUTHORITY_REL: docs/campaigns/PA/R06_DEV2_MATERIALIZATION_05 steps: - name: Resolve expected head From c80bc4a6af44f2a1c03b8b2a436f19ba80ab8e25 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:40:18 +0200 Subject: [PATCH 121/125] R06: make Authenticode host probe runner-agnostic --- .../tests/test_packaged_application_update.py | 44 ++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py index 83e2d9d98..0deb8becc 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py @@ -1,6 +1,7 @@ import hashlib import json import os +import subprocess import tempfile import unittest from pathlib import Path @@ -305,12 +306,51 @@ def test_windows_verifier_uses_native_system_directory_not_hostile_environment(s ) @unittest.skipUnless(os.name == "nt", "Windows Authenticode integration only") - def test_windows_verifier_executes_real_system_authenticode_command(self): + def test_windows_verifier_matches_real_system_authenticode_state(self): system_directory = _windows_system_directory() self.assertIsInstance(system_directory, Path) powershell = system_directory / "WindowsPowerShell" / "v1.0" / "powershell.exe" self.assertTrue(powershell.is_file()) - self.assertTrue(verify_same_publisher_authenticode(powershell, powershell)) + + probe_script = r""" +$s = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $env:SCRIPTURE_AUTH_PROBE +[pscustomobject]@{ + status = [string]$s.Status + thumbprint = if ($null -eq $s.SignerCertificate) { $null } else { [string]$s.SignerCertificate.Thumbprint } +} | ConvertTo-Json -Compress +""".strip() + environment = os.environ.copy() + environment["SCRIPTURE_AUTH_PROBE"] = str(powershell) + completed = subprocess.run( + [ + str(powershell), + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-Command", + probe_script, + ], + env=environment, + capture_output=True, + text=True, + encoding="utf-8", + errors="strict", + timeout=10, + check=False, + ) + self.assertEqual(0, completed.returncode, completed.stderr) + payload = json.loads(completed.stdout) + thumbprint = payload.get("thumbprint") + expected = ( + payload.get("status") == "Valid" + and isinstance(thumbprint, str) + and len(thumbprint.strip()) == 40 + and all(char in "0123456789ABCDEF" for char in thumbprint.strip().upper()) + ) + self.assertEqual( + expected, + verify_same_publisher_authenticode(powershell, powershell), + ) class NativeUpdateFileSelectorTests(unittest.TestCase): From 7de9d5dba17e5ab0acf05e384e1310652054f364 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:41:38 +0200 Subject: [PATCH 122/125] R06: keep D4 Library candidate scoped after package-wide CI diagnosis --- .../tests/test_packaged_application_update.py | 44 +------------------ 1 file changed, 2 insertions(+), 42 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py index 0deb8becc..83e2d9d98 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update.py @@ -1,7 +1,6 @@ import hashlib import json import os -import subprocess import tempfile import unittest from pathlib import Path @@ -306,51 +305,12 @@ def test_windows_verifier_uses_native_system_directory_not_hostile_environment(s ) @unittest.skipUnless(os.name == "nt", "Windows Authenticode integration only") - def test_windows_verifier_matches_real_system_authenticode_state(self): + def test_windows_verifier_executes_real_system_authenticode_command(self): system_directory = _windows_system_directory() self.assertIsInstance(system_directory, Path) powershell = system_directory / "WindowsPowerShell" / "v1.0" / "powershell.exe" self.assertTrue(powershell.is_file()) - - probe_script = r""" -$s = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $env:SCRIPTURE_AUTH_PROBE -[pscustomobject]@{ - status = [string]$s.Status - thumbprint = if ($null -eq $s.SignerCertificate) { $null } else { [string]$s.SignerCertificate.Thumbprint } -} | ConvertTo-Json -Compress -""".strip() - environment = os.environ.copy() - environment["SCRIPTURE_AUTH_PROBE"] = str(powershell) - completed = subprocess.run( - [ - str(powershell), - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-Command", - probe_script, - ], - env=environment, - capture_output=True, - text=True, - encoding="utf-8", - errors="strict", - timeout=10, - check=False, - ) - self.assertEqual(0, completed.returncode, completed.stderr) - payload = json.loads(completed.stdout) - thumbprint = payload.get("thumbprint") - expected = ( - payload.get("status") == "Valid" - and isinstance(thumbprint, str) - and len(thumbprint.strip()) == 40 - and all(char in "0123456789ABCDEF" for char in thumbprint.strip().upper()) - ) - self.assertEqual( - expected, - verify_same_publisher_authenticode(powershell, powershell), - ) + self.assertTrue(verify_same_publisher_authenticode(powershell, powershell)) class NativeUpdateFileSelectorTests(unittest.TestCase): From 47841f93c678c7db69254da1c1f7952da15d20fa Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:57:00 +0200 Subject: [PATCH 123/125] R06: correct D4 qualification test-count evidence --- tools/verify_library_search_overlay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/verify_library_search_overlay.py b/tools/verify_library_search_overlay.py index 2b53c8215..52731e32b 100644 --- a/tools/verify_library_search_overlay.py +++ b/tools/verify_library_search_overlay.py @@ -152,7 +152,7 @@ def main() -> None: run_real_response_regressions(platform_root) print( "Library/Search qualification PASS: exact candidate checkout, pinned canonical FINALPREP02 DEV1 base hash/CRC, " - "overlay fidelity, six legacy Library/Search regressions, and eleven real qualified-D4 read-only/runtime-eligibility/hash/mission-authority regressions." + "overlay fidelity, six legacy Library/Search regressions, and thirteen real qualified-D4 read-only/runtime-eligibility/hash/mission-authority regressions." ) From f6bfd128cf3cc342dec6ee762cb5e689e09e6e5e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:22:59 +0200 Subject: [PATCH 124/125] R06 D2: apply explicit lossless runtime fallbacks in preintegration --- .../validate_dev2_corrected_runtime_compat.py | 104 +++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) diff --git a/tools/validate_dev2_corrected_runtime_compat.py b/tools/validate_dev2_corrected_runtime_compat.py index 4369cac30..3dac7a78b 100644 --- a/tools/validate_dev2_corrected_runtime_compat.py +++ b/tools/validate_dev2_corrected_runtime_compat.py @@ -9,6 +9,7 @@ from __future__ import annotations import argparse +import copy import hashlib import json import stat @@ -66,6 +67,11 @@ ) PACK_ID = "r06-d2-paul-acts-preintegration" PACK_VERSION = "0.6.0-d2pre.1" +EXPECTED_PARALLEL_WITNESS_FALLBACK_COUNT = 11 +PARALLEL_WITNESS_FALLBACK_REASON = ( + "DEV5 pre-integration runtime lacks PARALLEL_WITNESS_COMPARE grader; " + "preserve structured canonical comparison and use text fallback only for compatibility testing." +) class CompatibilityError(ValueError): @@ -279,13 +285,98 @@ def _verify_evidence_binding( return len(evidence_ids), evidence_report +def _project_nodes_for_current_runtime( + nodes: Iterable[Mapping[str, Any]], +) -> tuple[list[dict[str, Any]], list[str]]: + """Build a compatibility-only runtime projection without mutating source authority. + + The corrected D2 authority intentionally keeps PARALLEL_WITNESS_COMPARE as a + structured synthesis+witness object. The current DEV5 runtime has no grader + for that task type, so those exact authority records carry an explicit + runtime_fallback. Apply it only after authority hash/evidence verification, + and only when it is a lossless projection of accepted_answer.synthesis. + """ + projected: list[dict[str, Any]] = [] + fallback_node_ids: list[str] = [] + expected_fields = {"synthesis": "string", "witnesses": "array[passage]"} + allowed_contract_kinds = {"witness_compare", "parallel_witness_compare"} + + for source in nodes: + node = copy.deepcopy(dict(source)) + if str(node.get("task_type") or "") != "PARALLEL_WITNESS_COMPARE": + projected.append(node) + continue + + node_id = str(node.get("node_id") or "") + accepted = node.get("accepted_answer") + if not isinstance(accepted, Mapping) or set(accepted) != {"synthesis", "witnesses"}: + raise CompatibilityError( + f"{node_id}: PARALLEL_WITNESS_COMPARE requires structured synthesis+witnesses authority" + ) + synthesis = accepted.get("synthesis") + witnesses = accepted.get("witnesses") + if not isinstance(synthesis, str) or not synthesis.strip(): + raise CompatibilityError(f"{node_id}: structured synthesis must be non-empty string") + if ( + not isinstance(witnesses, list) + or not witnesses + or not all(isinstance(value, str) and value.strip() for value in witnesses) + ): + raise CompatibilityError(f"{node_id}: structured witnesses must be a non-empty string list") + + contract = node.get("response_contract") + dto = contract.get("answer_dto") if isinstance(contract, Mapping) else None + if ( + not isinstance(contract, Mapping) + or contract.get("kind") not in allowed_contract_kinds + or not isinstance(dto, Mapping) + or dto.get("shape") != "object" + or dto.get("fields") != expected_fields + ): + raise CompatibilityError(f"{node_id}: structured witness response_contract changed") + + variants = node.get("accepted_variants") + grading = node.get("grading") + if ( + not isinstance(variants, Mapping) + or variants.get("witnesses") != witnesses + or not isinstance(variants.get("synthesis_aliases"), list) + or synthesis not in variants.get("synthesis_aliases", []) + or not isinstance(grading, Mapping) + or grading.get("required_witnesses") != witnesses + ): + raise CompatibilityError(f"{node_id}: structured witness truth bindings changed") + + fallback = node.get("runtime_fallback") + if ( + not isinstance(fallback, Mapping) + or set(fallback) != {"accepted_answer", "reason", "task_type"} + or fallback.get("task_type") != "LONG_TEXT" + or fallback.get("accepted_answer") != synthesis + or fallback.get("reason") != PARALLEL_WITNESS_FALLBACK_REASON + ): + raise CompatibilityError(f"{node_id}: runtime_fallback is missing or not lossless") + + node["task_type"] = "LONG_TEXT" + node["accepted_answer"] = synthesis + projected.append(node) + fallback_node_ids.append(node_id) + + return projected, sorted(fallback_node_ids) + + def _runtime_compatibility( nodes: list[dict[str, Any]], *, expected_node_count: int = EXPECTED_NODE_COUNT, ) -> dict[str, Any]: + runtime_nodes, fallback_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(fallback_node_ids) != EXPECTED_PARALLEL_WITNESS_FALLBACK_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_PARALLEL_WITNESS_FALLBACK_COUNT} explicit parallel-witness fallbacks, got {len(fallback_node_ids)}" + ) try: - repository = ContentRepository(nodes, adapt_legacy=True, lane="D2") + repository = ContentRepository(runtime_nodes, adapt_legacy=True, lane="D2") except (ValidationError, ValueError, TypeError) as exc: raise CompatibilityError(f"current runtime rejected corrected D2 corpus: {exc}") from exc tasks = repository.all() @@ -333,6 +424,8 @@ def _runtime_compatibility( "self_grade_correct": expected_node_count, "runtime_load_pass": expected_node_count, "provenance_classes": dict(sorted(provenance_counts.items())), + "runtime_fallback_node_ids": fallback_node_ids, + "runtime_fallback_count": len(fallback_node_ids), } @@ -350,7 +443,12 @@ def write_preintegration_pack( ) -> dict[str, Any]: destination = destination.expanduser().resolve() destination.parent.mkdir(parents=True, exist_ok=True) - payload = _json_bytes({"nodes": nodes}) + runtime_nodes, fallback_node_ids = _project_nodes_for_current_runtime(nodes) + if expected_node_count == EXPECTED_NODE_COUNT and len(fallback_node_ids) != EXPECTED_PARALLEL_WITNESS_FALLBACK_COUNT: + raise CompatibilityError( + f"expected {EXPECTED_PARALLEL_WITNESS_FALLBACK_COUNT} explicit parallel-witness fallbacks, got {len(fallback_node_ids)}" + ) + payload = _json_bytes({"nodes": runtime_nodes}) payload_name = "content/nodes.json" manifest = { "schema": CONTENT_PACK_SCHEMA, @@ -410,6 +508,8 @@ def write_preintegration_pack( "payload_sha256": manifest["files"][payload_name], "node_count": inspection.node_count, "file_count": inspection.file_count, + "runtime_fallback_node_ids": fallback_node_ids, + "runtime_fallback_count": len(fallback_node_ids), } From 9c2f1b7e7c08843357c01d6f2b6e90df13715752 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:23:21 +0200 Subject: [PATCH 125/125] R06 D2: regress explicit witness fallback boundary --- ..._validate_dev2_corrected_runtime_compat.py | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tools/test_validate_dev2_corrected_runtime_compat.py b/tools/test_validate_dev2_corrected_runtime_compat.py index 71920db45..f63624be6 100644 --- a/tools/test_validate_dev2_corrected_runtime_compat.py +++ b/tools/test_validate_dev2_corrected_runtime_compat.py @@ -22,7 +22,9 @@ from validate_dev2_corrected_runtime_compat import ( PACK_ID, PACK_VERSION, + PARALLEL_WITNESS_FALLBACK_REASON, CompatibilityError, + _project_nodes_for_current_runtime, _runtime_compatibility, write_preintegration_pack, ) @@ -64,6 +66,65 @@ def test_generic_runtime_self_grade_and_load_path_accepts_canonical_fixture(self store.activate(PACK_ID, PACK_VERSION) self.assertEqual({PACK_ID: PACK_VERSION}, store.active_versions()) + def _parallel_witness_fixture(self): + node = copy.deepcopy(LN01_N03) + synthesis = "Witness-safe synthesis for current-runtime compatibility." + witnesses = ["Luke 22:8"] + node["task_type"] = "PARALLEL_WITNESS_COMPARE" + node["response_mode"] = "PARALLEL_WITNESS_COMPARE" + node["task_family"] = "parallel_witness_compare" + node["accepted_answer"] = {"synthesis": synthesis, "witnesses": witnesses} + node["accepted_variants"] = { + "synthesis_aliases": [synthesis], + "witnesses": witnesses, + } + node["grading"] = { + "accepted_propositions": [ + {"id": "P1", "required": True, "aliases": [synthesis]} + ], + "provenance_required": True, + "required_witnesses": witnesses, + } + node["response_contract"] = { + "kind": "witness_compare", + "answer_dto": { + "shape": "object", + "fields": {"synthesis": "string", "witnesses": "array[passage]"}, + }, + } + node["runtime_fallback"] = { + "task_type": "LONG_TEXT", + "accepted_answer": synthesis, + "reason": PARALLEL_WITNESS_FALLBACK_REASON, + } + return node + + def test_parallel_witness_runtime_fallback_is_lossless_and_source_immutable(self) -> None: + node = self._parallel_witness_fixture() + original = copy.deepcopy(node) + projected, fallback_ids = _project_nodes_for_current_runtime([node]) + self.assertEqual(original, node) + self.assertEqual([node["node_id"]], fallback_ids) + self.assertEqual("LONG_TEXT", projected[0]["task_type"]) + self.assertEqual(node["accepted_answer"]["synthesis"], projected[0]["accepted_answer"]) + self.assertEqual(node["accepted_answer"], original["accepted_answer"]) + + runtime = _runtime_compatibility([node], expected_node_count=1) + self.assertEqual(1, runtime["runtime_fallback_count"]) + self.assertEqual([node["node_id"]], runtime["runtime_fallback_node_ids"]) + + def test_parallel_witness_runtime_fallback_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["runtime_fallback"]["accepted_answer"] = "Different synthesis" + with self.assertRaisesRegex(CompatibilityError, "runtime_fallback is missing or not lossless"): + _project_nodes_for_current_runtime([node]) + + def test_parallel_witness_truth_binding_mismatch_fails_closed(self) -> None: + node = self._parallel_witness_fixture() + node["grading"]["required_witnesses"] = ["Acts 1:1"] + with self.assertRaisesRegex(CompatibilityError, "structured witness truth bindings changed"): + _project_nodes_for_current_runtime([node]) + def test_conflicting_explicit_grading_truth_fails_closed(self) -> None: node = copy.deepcopy(LN01_N03) node["grading"] = {"accepted_choice": "CONTRADICTS CANONICAL ANSWER"}