From 780f8efb688b72f9aba100d6ad1734b0a55c6976 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:51:37 +0200 Subject: [PATCH 001/118] R06: add fail-closed pending update readback and disarm --- .../application_update_pending.py | 291 ++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_pending.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_pending.py b/runtime_engine/scripture_archive_runtime/application_update_pending.py new file mode 100644 index 000000000..136235e92 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_pending.py @@ -0,0 +1,291 @@ +"""Fail-closed readback and disarm semantics for a staged application update. + +This module deliberately does not install, execute, replace, restart, or roll back +application code. It gives the packaged host a durable way to re-open the fixed +pending-update journal after restart, bind it back to exact staged bytes, and remove +only the journal authority when the user cancels a pending update. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +import os +from pathlib import Path +import stat +import threading +from typing import Any + +from .application_update import ( + ApplicationUpdateError, + ApplicationUpdateManifest, + verify_local_update, +) +from .application_update_staging import STAGING_JOURNAL_SCHEMA + + +_JOURNAL_NAME = "pending-update.json" +_PENDING_DIRECTORY = "pending" +_MAX_JOURNAL_BYTES = 16 * 1024 +_REQUIRED_KEYS = frozenset( + { + "schema", + "status", + "product_id", + "target_platform", + "current_version", + "target_version", + "source_head", + "artifact_name", + "artifact_size", + "artifact_sha256", + "authenticity", + } +) +_STATE_LOCKS_GUARD = threading.Lock() +_STATE_LOCKS: dict[str, threading.RLock] = {} + + +@dataclass(frozen=True) +class PendingApplicationUpdate: + 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 inspect_pending_update( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate | None: + """Re-open a fixed pending journal and re-verify its exact staged bytes. + + ``None`` means there is no pending journal. Any present but malformed, stale, + redirected, or byte-mismatched state raises ``ApplicationUpdateError`` rather + than being presented as an installable update. + """ + + root = Path(staging_root) + lock = _state_lock_for_root(root) + with lock: + if not root.exists(): + return None + _require_real_directory(root, "update state root") + journal = root / _JOURNAL_NAME + payload = _read_fixed_journal(journal) + if payload is None: + return None + row = _parse_journal(payload) + if row["current_version"] != current_version: + raise ApplicationUpdateError( + "pending update was staged by a different current application version" + ) + + manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": row["product_id"], + "target_platform": row["target_platform"], + "target_version": row["target_version"], + "source_head": row["source_head"], + "artifact_name": row["artifact_name"], + "artifact_size": row["artifact_size"], + "artifact_sha256": row["artifact_sha256"], + } + ) + pending_root = root / _PENDING_DIRECTORY + digest_root = pending_root / manifest.artifact_sha256 + _require_real_directory(pending_root, "pending update directory") + _require_real_directory(digest_root, "pending digest directory") + artifact = digest_root / manifest.artifact_name + verified = verify_local_update( + manifest, + artifact, + current_version=current_version, + ) + return PendingApplicationUpdate( + product_id=verified.product_id, + target_platform=verified.target_platform, + current_version=verified.current_version, + target_version=verified.target_version, + source_head=verified.source_head, + artifact_name=verified.artifact_name, + artifact_size=verified.artifact_size, + artifact_sha256=verified.artifact_sha256, + ) + + +def staged_artifact_path( + staging_root: str | os.PathLike[str], + pending: PendingApplicationUpdate, +) -> Path: + """Reconstruct the host-private staged path from already-validated identity. + + Callers must never serialize this path into browser-visible transport data. + ``inspect_pending_update`` should be called again after any signature operation + to bind that result back to exact bytes. + """ + + if not isinstance(pending, PendingApplicationUpdate): + raise ApplicationUpdateError("pending update identity is invalid") + root = Path(staging_root) + _require_real_directory(root, "update state root") + pending_root = root / _PENDING_DIRECTORY + digest_root = pending_root / pending.artifact_sha256 + _require_real_directory(pending_root, "pending update directory") + _require_real_directory(digest_root, "pending digest directory") + return digest_root / pending.artifact_name + + +def discard_pending_update(staging_root: str | os.PathLike[str]) -> bool: + """Disarm pending authority without deleting staged executable bytes. + + Cancellation intentionally removes only the fixed journal. Staged bytes become + inert and may be overwritten by a later staging operation. This avoids turning + recovery into a recursive deletion primitive when journal contents are corrupt. + The fixed journal path may itself be a symlink; unlinking that symlink is safe and + does not touch its target. + """ + + root = Path(staging_root) + lock = _state_lock_for_root(root) + with lock: + if not root.exists(): + return False + _require_real_directory(root, "update state root") + journal = root / _JOURNAL_NAME + try: + metadata = journal.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("pending update journal is unavailable") from exc + if not (stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode)): + raise ApplicationUpdateError("pending update journal path is unsafe") + try: + journal.unlink() + _fsync_directory(root) + except OSError as exc: + raise ApplicationUpdateError("pending update could not be cancelled safely") from exc + return True + + +def _parse_journal(payload: bytes) -> dict[str, Any]: + try: + raw = json.loads(payload.decode("utf-8"), object_pairs_hook=_strict_json_object) + except ApplicationUpdateError: + raise + except (UnicodeDecodeError, TypeError, ValueError) as exc: + raise ApplicationUpdateError("pending update journal is not valid UTF-8 JSON") from exc + if not isinstance(raw, dict): + raise ApplicationUpdateError("pending update journal must be an object") + keys = frozenset(raw.keys()) + if keys != _REQUIRED_KEYS: + raise ApplicationUpdateError("pending update journal keys do not match the staging schema") + if raw["schema"] != STAGING_JOURNAL_SCHEMA: + raise ApplicationUpdateError("unsupported pending update journal schema") + if raw["status"] != "staged": + raise ApplicationUpdateError("pending update journal is not in staged state") + if raw["authenticity"] != "same_publisher_authenticode_verified": + raise ApplicationUpdateError("pending update journal lacks same-publisher authenticity") + current_version = raw["current_version"] + if not isinstance(current_version, str) or not current_version or len(current_version) > 128: + raise ApplicationUpdateError("pending update current_version is invalid") + return raw + + +def _read_fixed_journal(path: Path) -> bytes | None: + try: + before = path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("pending update journal is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("pending update journal must be a regular non-symlink file") + if before.st_size <= 0 or before.st_size > _MAX_JOURNAL_BYTES: + raise ApplicationUpdateError("pending update journal is empty or exceeds the size limit") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + 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 ApplicationUpdateError("pending update journal changed before readback") + payload = handle.read(_MAX_JOURNAL_BYTES + 1) + opened_after = os.fstat(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("pending update journal changed during readback") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("pending update journal could not be read safely") from exc + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if ( + after_identity != before_identity + or len(payload) != before.st_size + or len(payload) > _MAX_JOURNAL_BYTES + ): + raise ApplicationUpdateError("pending update journal changed during readback") + return payload + + +def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ApplicationUpdateError(f"pending update journal contains duplicate key: {key}") + out[key] = value + return out + + +def _require_real_directory(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a real directory") + + +def _state_lock_for_root(root: Path) -> threading.RLock: + key = os.path.normcase(str(root.absolute())) + with _STATE_LOCKS_GUARD: + lock = _STATE_LOCKS.get(key) + if lock is None: + lock = threading.RLock() + _STATE_LOCKS[key] = lock + return lock + + +def _fsync_directory(path: Path) -> None: + 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 0f895f3b9089de11ce409e2103c758cba092c96f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:52:00 +0200 Subject: [PATCH 002/118] R06: expose native pending-update recovery boundary --- .../desktop_host/pending_update.py | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py new file mode 100644 index 000000000..63c8b3be0 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +import sys +from pathlib import Path +from typing import Any, Callable + +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) +from scripture_archive_platform.transport.contracts import ( + error_response, + ok_response, + validate_request_shape, +) + + +PENDING_UPDATE_STATUS_COMMAND = "application_update.pending_status" +CANCEL_PENDING_UPDATE_COMMAND = "application_update.cancel_pending" + + +class NativePendingUpdateLayer: + """Expose fixed-path staged-update recovery without browser filesystem authority. + + Status re-opens the host-owned journal, re-verifies exact staged bytes, checks + same-publisher Authenticode again, then re-verifies exact bytes after that OS + signature inspection. Cancellation removes only the fixed journal authority; + staged executable bytes remain inert and are never recursively deleted here. + """ + + def __init__( + self, + app: Any, + repo_root: Path, + staging_root: Path, + *, + current_version: str, + authenticity_verifier: Callable[[Path], bool] | None = None, + ) -> None: + self._app = app + self._repo_root = Path(repo_root).resolve() + self._staging_root = Path(staging_root) + self._current_version = current_version + self._authenticity_verifier = ( + authenticity_verifier + if authenticity_verifier is not None + else self._default_authenticity_verifier + ) + + def handle(self, request: Any) -> dict[str, Any]: + if not isinstance(request, dict) or request.get("command") not in { + PENDING_UPDATE_STATUS_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + }: + return self._app.handle(request) + rid = str(request.get("request_id", "invalid")) + try: + rid, command, payload = validate_request_shape(request) + if command not in { + PENDING_UPDATE_STATUS_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } or payload: + raise ValueError("pending update recovery requires an empty payload") + inspect_pending_update, staged_artifact_path, discard_pending_update = ( + self._load_pending_core() + ) + + if command == CANCEL_PENDING_UPDATE_COMMAND: + removed = discard_pending_update(self._staging_root) + return ok_response( + rid, + { + "pending": False, + "status": "cancelled" if removed else "none", + "staged_bytes_removed": False, + "installation_performed": False, + }, + ) + + pending = inspect_pending_update( + self._staging_root, + current_version=self._current_version, + ) + if pending is None: + return ok_response( + rid, + { + "pending": False, + "status": "none", + "installation_performed": False, + }, + ) + + candidate = staged_artifact_path(self._staging_root, pending) + try: + authenticity_verified = bool(self._authenticity_verifier(candidate)) + except Exception: + authenticity_verified = False + if not authenticity_verified: + return error_response( + rid, + "UPDATE_PENDING_AUTHENTICITY_INVALID", + "Pending update no longer has valid same-publisher Authenticode.", + ) + + # Bind the positive OS signature result back to exact staged bytes. + pending = inspect_pending_update( + self._staging_root, + current_version=self._current_version, + ) + return ok_response( + rid, + { + "pending": True, + "status": pending.status, + "product_id": pending.product_id, + "target_platform": pending.target_platform, + "current_version": pending.current_version, + "target_version": pending.target_version, + "source_head": pending.source_head, + "artifact_name": pending.artifact_name, + "artifact_size": pending.artifact_size, + "artifact_sha256": pending.artifact_sha256, + "authenticity": pending.authenticity, + "installation_performed": False, + }, + ) + except ValueError: + return error_response( + rid, + "UPDATE_PENDING_INVALID", + "Pending application update state failed closed.", + ) + except OSError: + return error_response( + rid, + "UPDATE_PENDING_FILE_ERROR", + "Pending application update state could not be read safely.", + ) + except Exception: + return error_response( + rid, + "UPDATE_PENDING_FAILED", + "Pending application update recovery failed closed.", + ) + + def _default_authenticity_verifier(self, candidate: Path) -> bool: + return verify_same_publisher_authenticode(Path(sys.executable), candidate) + + def _load_pending_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) + from runtime_engine.scripture_archive_runtime.application_update_pending import ( + discard_pending_update, + inspect_pending_update, + staged_artifact_path, + ) + + return inspect_pending_update, staged_artifact_path, discard_pending_update From 82bdda0f721aefde89e09c0aa50299090407de4e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:52:18 +0200 Subject: [PATCH 003/118] R06: wire pending update recovery into packaged host --- .../scripture_archive_platform/desktop_host/main.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) 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 334870a1b..02308b0e6 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 @@ -7,6 +7,7 @@ from scripture_archive_platform.application.speech_application import build_default_application from scripture_archive_platform.desktop_host.bridge import DesktopBridge from scripture_archive_platform.desktop_host.diagnostics import NativeDiagnosticsLayer +from scripture_archive_platform.desktop_host.pending_update import NativePendingUpdateLayer from scripture_archive_platform.desktop_host.update_application import ( NativeApplicationUpdateLayer, NativeUpdateFileSelector, @@ -52,12 +53,19 @@ def main() -> int: selector = NativeUpdateFileSelector(webview) platform_app = build_default_application(root) + staging_root = Path(platform_app.store.root) / "application-updates" app = NativeApplicationUpdateLayer( platform_app, root, selector, current_version=CURRENT_APPLICATION_VERSION, - staging_root=Path(platform_app.store.root) / "application-updates", + staging_root=staging_root, + ) + app = NativePendingUpdateLayer( + app, + root, + staging_root, + current_version=CURRENT_APPLICATION_VERSION, ) app = NativeDiagnosticsLayer( app, From fc1a8eec7fd754c140e0b5c1aad9714569ef1bfa Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:53:03 +0200 Subject: [PATCH 004/118] R06: add accessible pending update recovery controls --- .../repair_overlay/frontend/pending-update.js | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/pending-update.js diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js new file mode 100644 index 000000000..9c33df920 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -0,0 +1,90 @@ +const API_VERSION='scripture.transport.v1'; +const STATUS_COMMAND='application_update.pending_status'; +const CANCEL_COMMAND='application_update.cancel_pending'; +const $=id=>document.getElementById(id); +let sequence=0; + +function announce(message){ + const global=$('global-status'); + if(global){global.textContent='';requestAnimationFrame(()=>{global.textContent=message})} + const local=$('pending-update-status'); + if(local)local.textContent=message; +} + +function element(tag,text){ + const node=document.createElement(tag); + if(text!==undefined)node.textContent=text; + return node; +} + +async function invoke(command){ + const invokeNative=window.pywebview?.api?.invoke; + if(typeof invokeNative!=='function')throw new Error('Ця дія доступна лише у packaged Windows application.'); + const response=await invokeNative({api_version:API_VERSION,request_id:`pending-${Date.now()}-${++sequence}`,command,payload:{}}); + if(!response?.ok)throw new Error(response?.error?.message||'Операція завершилась помилкою.'); + return response.data??{}; +} + +function setBusy(busy){ + for(const id of ['pending-update-check','pending-update-cancel']){ + const button=$(id);if(button)button.disabled=busy; + } +} + +function clearDetails(){$('pending-update-details')?.replaceChildren()} + +function renderPending(data){ + const host=$('pending-update-details'); + if(!host||data.pending!==true)return; + host.replaceChildren(); + const rows=[ + ['Статус','Підготовлено, але не встановлено'], + ['Продукт',data.product_id],['Платформа',data.target_platform], + ['Поточна версія',data.current_version],['Цільова версія',data.target_version], + ['Source head',data.source_head],['Файл пакета',data.artifact_name], + ['Розмір',Number.isFinite(Number(data.artifact_size))?`${data.artifact_size} байт`:'—'], + ['SHA-256',data.artifact_sha256],['Автентичність','Same-publisher Authenticode повторно підтверджено'] + ]; + for(const [label,value] of rows){host.append(element('dt',label),element('dd',value??'—'))} +} + +async function checkPending(){ + setBusy(true);clearDetails();announce('Повторно перевіряю підготовлене оновлення.'); + try{ + const data=await invoke(STATUS_COMMAND); + if(data.pending===true&&data.status==='staged'){ + renderPending(data); + announce(`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); + }else if(data.pending===false&&data.status==='none')announce('Підготовленого оновлення немає.'); + else throw new Error('Отримано неочікуваний стан.'); + }catch(error){clearDetails();announce(`Pending update не підтверджено: ${error?.message||'невідома помилка'}`)} + finally{setBusy(false)} +} + +async function cancelPending(){ + setBusy(true);clearDetails();announce('Скасовую підготовлений стан оновлення.'); + try{ + const data=await invoke(CANCEL_COMMAND); + if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ + announce(data.status==='cancelled'?'Підготовлене оновлення скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); + }else throw new Error('Скасування не підтверджено.'); + }catch(error){announce(`Не вдалося безпечно скасувати pending update: ${error?.message||'невідома помилка'}`)} + finally{setBusy(false)} +} + +function mount(){ + const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; + const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); + const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; + const help=element('p','Перевірка повторно звіряє приватний pending state програми. Скасування прибирає лише статус підготовленого оновлення; встановлення тут не виконується.'); + const actions=element('div');actions.className='action-row'; + const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; + const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; + actions.append(check,cancel); + const status=element('p','Стан pending update ще не перевірявся.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); + section.append(heading,help,actions,status,details);view.append(section); + check.addEventListener('click',checkPending);cancel.addEventListener('click',cancelPending); +} + +mount(); From 984721b2f44b3e690ce18eec9cec663427c4e62e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:53:30 +0200 Subject: [PATCH 005/118] R06: load pending update recovery surface --- lanes/dev1/repair_overlay/frontend/application-update.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lanes/dev1/repair_overlay/frontend/application-update.js b/lanes/dev1/repair_overlay/frontend/application-update.js index 42e0abd85..d6625b403 100644 --- a/lanes/dev1/repair_overlay/frontend/application-update.js +++ b/lanes/dev1/repair_overlay/frontend/application-update.js @@ -153,3 +153,4 @@ function mount(){ mount(); void import('./diagnostics-ui.js'); +void import('./pending-update.js'); From e6b90a96cfd6f5cdc4f636e424e9851e7beb2c3a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:54:11 +0200 Subject: [PATCH 006/118] R06: cover pending update restart recovery and cancel semantics --- ...est_packaged_application_update_pending.py | 270 ++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py new file mode 100644 index 000000000..5a87fb469 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py @@ -0,0 +1,270 @@ +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_pending import ( + discard_pending_update, + inspect_pending_update, + staged_artifact_path, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import ( + stage_local_update, +) +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +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 runtime not found") + + +def request(command, payload=None): + return { + "api_version": "scripture.transport.v1", + "request_id": "pending-update-test-1", + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def __init__(self): + self.calls = [] + + def handle(self, value): + self.calls.append(value) + return {"ok": True, "data": {"passthrough": True}} + + +class PendingUpdateRuntimeTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"pending-update-recovery-exact-bytes") + self.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": self.digest, + } + ) + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + return stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def test_restart_readback_reverifies_exact_staged_bytes(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + self.assertIsNotNone(pending) + self.assertEqual("staged", pending.status) + self.assertEqual("same_publisher_authenticode_verified", pending.authenticity) + self.assertEqual("0.6.1", pending.target_version) + self.assertEqual(self.digest, pending.artifact_sha256) + staged = staged_artifact_path(self.staging, pending) + self.assertEqual(self.artifact.read_bytes(), staged.read_bytes()) + self.assertNotIn("path", pending.__dict__) + + def test_missing_journal_means_no_pending_update(self): + self.assertIsNone(inspect_pending_update(self.staging, current_version=CURRENT_VERSION)) + self.assertFalse(discard_pending_update(self.staging)) + + def test_staged_byte_mutation_fails_closed(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + staged.write_bytes(b"x" * self.manifest.artifact_size) + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + + def test_journal_extra_field_and_version_mismatch_fail_closed(self): + self.stage() + journal_path = self.staging / "pending-update.json" + journal = json.loads(journal_path.read_text(encoding="utf-8")) + journal["unexpected"] = True + journal_path.write_text(json.dumps(journal), encoding="utf-8") + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + + self.stage() + with self.assertRaises(ApplicationUpdateError): + inspect_pending_update(self.staging, current_version="0.6.0-r06.3dev.b") + + def test_cancel_removes_only_pending_authority_and_keeps_staged_bytes_inert(self): + self.stage() + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + self.assertTrue(staged.is_file()) + self.assertTrue(discard_pending_update(self.staging)) + self.assertFalse((self.staging / "pending-update.json").exists()) + self.assertTrue(staged.is_file()) + self.assertIsNone(inspect_pending_update(self.staging, current_version=CURRENT_VERSION)) + + def test_corrupt_journal_can_be_disarmed_without_parsing_or_recursive_delete(self): + self.staging.mkdir(parents=True) + journal_path = self.staging / "pending-update.json" + journal_path.write_bytes(b"not-json") + inert = self.staging / "pending" / "untrusted" / "keep.bin" + inert.parent.mkdir(parents=True) + inert.write_bytes(b"inert") + self.assertTrue(discard_pending_update(self.staging)) + self.assertFalse(journal_path.exists()) + self.assertEqual(b"inert", inert.read_bytes()) + + +class PendingUpdateHostTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"host-pending-update-exact-bytes") + 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": "d" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": digest, + } + ) + self.base = FakeBaseApplication() + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def layer(self, verifier): + return NativePendingUpdateLayer( + self.base, + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=verifier, + ) + + def test_status_reverifies_signature_and_returns_no_local_paths(self): + self.stage() + calls = [] + + def verifier(candidate): + calls.append(candidate) + return True + + response = self.layer(verifier).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertTrue(response["ok"]) + data = response["data"] + self.assertTrue(data["pending"]) + self.assertEqual("staged", data["status"]) + self.assertEqual("same_publisher_authenticode_verified", data["authenticity"]) + self.assertFalse(data["installation_performed"]) + self.assertEqual(1, len(calls)) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("staged_path", serialized) + self.assertNotIn("source_path", serialized) + + def test_positive_signature_followed_by_mutated_bytes_fails_closed(self): + self.stage() + + def mutate_after_signature(candidate): + candidate.write_bytes(b"x" * self.manifest.artifact_size) + return True + + response = self.layer(mutate_after_signature).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + + def test_negative_signature_fails_closed_without_pending_claim(self): + self.stage() + response = self.layer(lambda candidate: False).handle(request(PENDING_UPDATE_STATUS_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_AUTHENTICITY_INVALID", response["error"]["code"]) + + def test_cancel_disarms_even_corrupt_journal_without_signature_execution(self): + self.staging.mkdir(parents=True) + (self.staging / "pending-update.json").write_text("corrupt", encoding="utf-8") + calls = [] + response = self.layer(lambda candidate: calls.append(candidate) or True).handle( + request(CANCEL_PENDING_UPDATE_COMMAND) + ) + self.assertTrue(response["ok"]) + self.assertEqual("cancelled", response["data"]["status"]) + self.assertFalse(response["data"]["pending"]) + self.assertFalse(response["data"]["staged_bytes_removed"]) + self.assertEqual([], calls) + self.assertFalse((self.staging / "pending-update.json").exists()) + + def test_browser_payload_cannot_supply_pending_state_or_path(self): + response = self.layer(lambda candidate: True).handle( + request(PENDING_UPDATE_STATUS_COMMAND, {"path": "C:\\Users\\attacker\\state.json"}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + self.assertEqual([], self.base.calls) + + def test_unrelated_commands_are_delegated(self): + original = request("system.bootstrap") + response = self.layer(lambda candidate: True).handle(original) + self.assertTrue(response["data"]["passthrough"]) + self.assertEqual([original], self.base.calls) + + def test_frontend_exposes_keyboard_native_status_and_cancel_without_html_injection(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + entry = (platform / "frontend" / "application-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.pending_status", script) + self.assertIn("application_update.cancel_pending", script) + self.assertIn("pending-update-check", script) + self.assertIn("pending-update-cancel", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertIn("./pending-update.js", entry) + + +if __name__ == "__main__": + unittest.main() From 3622c1693a1bad00340b3ee32a9577cd010c5bef Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:56:01 +0200 Subject: [PATCH 007/118] R06: align pending recovery validation transport semantics --- .../desktop_host/pending_update.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index 63c8b3be0..68d26c166 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -60,6 +60,10 @@ def handle(self, request: Any) -> dict[str, Any]: CANCEL_PENDING_UPDATE_COMMAND, } or payload: raise ValueError("pending update recovery requires an empty payload") + except ValueError as exc: + return error_response(rid, "VALIDATION_ERROR", str(exc)) + + try: inspect_pending_update, staged_artifact_path, discard_pending_update = ( self._load_pending_core() ) @@ -102,7 +106,8 @@ def handle(self, request: Any) -> dict[str, Any]: "Pending update no longer has valid same-publisher Authenticode.", ) - # Bind the positive OS signature result back to exact staged bytes. + # Bind the positive OS signature result back to bytes that still satisfy + # the fixed pending journal after OS signature inspection. pending = inspect_pending_update( self._staging_root, current_version=self._current_version, From 085427ab490daefa95241626496d6017de01dd91 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:56:37 +0200 Subject: [PATCH 008/118] R06: assert shared validation error contract for pending recovery --- .../tests/test_packaged_application_update_pending.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py index 5a87fb469..6e5df4bc8 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py @@ -243,7 +243,7 @@ def test_browser_payload_cannot_supply_pending_state_or_path(self): request(PENDING_UPDATE_STATUS_COMMAND, {"path": "C:\\Users\\attacker\\state.json"}) ) self.assertFalse(response["ok"]) - self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) self.assertEqual([], self.base.calls) def test_unrelated_commands_are_delegated(self): From a78b2ba599b1282b6aef2988d10b013d7a44db92 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 00:57:49 +0200 Subject: [PATCH 009/118] R06: allowlist pending update recovery commands --- .../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 755a8e081..eb5cda948 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,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","application_update.select_verify_stage","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.cancel_pending","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,6 +102,8 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') + if cmd in {'application_update.pending_status','application_update.cancel_pending'} and payload: + raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} unknown=set(payload)-allowed From cf214fbf4d5f7544a0be63c1b24da5087342361c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:03:02 +0200 Subject: [PATCH 010/118] R06: serialize staged update recovery commands --- .../desktop_host/pending_update.py | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index 68d26c166..29b13e907 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -1,6 +1,7 @@ from __future__ import annotations import sys +import threading from pathlib import Path from typing import Any, Callable @@ -16,6 +17,17 @@ PENDING_UPDATE_STATUS_COMMAND = "application_update.pending_status" CANCEL_PENDING_UPDATE_COMMAND = "application_update.cancel_pending" +_PENDING_COMMANDS = frozenset( + {PENDING_UPDATE_STATUS_COMMAND, CANCEL_PENDING_UPDATE_COMMAND} +) +_UPDATE_COMMAND_FAMILY = frozenset( + { + "application_update.select_verify", + "application_update.select_verify_stage", + PENDING_UPDATE_STATUS_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } +) class NativePendingUpdateLayer: @@ -25,6 +37,10 @@ class NativePendingUpdateLayer: same-publisher Authenticode again, then re-verifies exact bytes after that OS signature inspection. Cancellation removes only the fixed journal authority; staged executable bytes remain inert and are never recursively deleted here. + + This outer packaged-host layer also serializes the complete application-update + command family. In particular, a staging request cannot publish a fresh pending + journal after a concurrent cancellation has already reported success. """ def __init__( @@ -45,20 +61,24 @@ def __init__( if authenticity_verifier is not None else self._default_authenticity_verifier ) + self._operation_lock = threading.RLock() def handle(self, request: Any) -> dict[str, Any]: - if not isinstance(request, dict) or request.get("command") not in { - PENDING_UPDATE_STATUS_COMMAND, - CANCEL_PENDING_UPDATE_COMMAND, - }: + if not isinstance(request, dict): return self._app.handle(request) + command_name = request.get("command") + if command_name not in _UPDATE_COMMAND_FAMILY: + return self._app.handle(request) + with self._operation_lock: + if command_name not in _PENDING_COMMANDS: + return self._app.handle(request) + return self._handle_pending(request) + + def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: rid = str(request.get("request_id", "invalid")) try: rid, command, payload = validate_request_shape(request) - if command not in { - PENDING_UPDATE_STATUS_COMMAND, - CANCEL_PENDING_UPDATE_COMMAND, - } or payload: + if command not in _PENDING_COMMANDS or payload: raise ValueError("pending update recovery requires an empty payload") except ValueError as exc: return error_response(rid, "VALIDATION_ERROR", str(exc)) From fcdf14c0b07d9d20d257d0c13ab2eb1fb2803dd1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:03:52 +0200 Subject: [PATCH 011/118] R06: regress shared update operation lock --- ...est_packaged_application_update_pending.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py index 6e5df4bc8..d12e66040 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py @@ -51,6 +51,18 @@ def handle(self, value): return {"ok": True, "data": {"passthrough": True}} +class CountingContextLock: + def __init__(self): + self.entries = 0 + + def __enter__(self): + self.entries += 1 + return self + + def __exit__(self, exc_type, exc, tb): + return False + + class PendingUpdateRuntimeTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() @@ -238,6 +250,23 @@ def test_cancel_disarms_even_corrupt_journal_without_signature_execution(self): self.assertEqual([], calls) self.assertFalse((self.staging / "pending-update.json").exists()) + def test_update_command_family_shares_outer_operation_lock(self): + layer = self.layer(lambda candidate: True) + lock = CountingContextLock() + layer._operation_lock = lock + + stage_request = request("application_update.select_verify_stage") + stage_response = layer.handle(stage_request) + self.assertTrue(stage_response["ok"]) + self.assertTrue(stage_response["data"]["passthrough"]) + self.assertEqual([stage_request], self.base.calls) + self.assertEqual(1, lock.entries) + + cancel_response = layer.handle(request(CANCEL_PENDING_UPDATE_COMMAND)) + self.assertTrue(cancel_response["ok"]) + self.assertEqual("none", cancel_response["data"]["status"]) + self.assertEqual(2, lock.entries) + def test_browser_payload_cannot_supply_pending_state_or_path(self): response = self.layer(lambda candidate: True).handle( request(PENDING_UPDATE_STATUS_COMMAND, {"path": "C:\\Users\\attacker\\state.json"}) From e79293deb5d16b1efc925ae66cf0b56297d4b18b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:04:31 +0200 Subject: [PATCH 012/118] R06: serialize packaged update and recovery operations --- .../desktop_host/update_serialization.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py new file mode 100644 index 000000000..edc9c3085 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import threading +from typing import Any + +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, +) +from scripture_archive_platform.desktop_host.update_application import ( + STAGE_UPDATE_COMMAND, + UPDATE_COMMAND, +) + + +_UPDATE_COMMANDS = frozenset( + { + UPDATE_COMMAND, + STAGE_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } +) + + +class SerializedApplicationUpdateLayer: + """Serialize all packaged update/recovery commands in one host process. + + Staging and recovery share the same fixed pending journal. Without one outer + operation lock a cancel/status call could race a concurrent stage call and make + the UI report a state that was immediately overwritten. The lock is deliberately + host-local: filesystem and signature validation remain fail-closed authorities. + """ + + def __init__(self, app: Any) -> None: + self._app = app + self._lock = threading.RLock() + + def handle(self, request: Any) -> dict[str, Any]: + if not isinstance(request, dict) or request.get("command") not in _UPDATE_COMMANDS: + return self._app.handle(request) + with self._lock: + return self._app.handle(request) From aa1f744548b632a0bc78164ef538a53415817ce1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:04:38 +0200 Subject: [PATCH 013/118] R06: reconverge apply handoff core on latest recovery parent --- .../application_update_apply.py | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_apply.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_apply.py b/runtime_engine/scripture_archive_runtime/application_update_apply.py new file mode 100644 index 000000000..3923d7640 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_apply.py @@ -0,0 +1,215 @@ +"""Durable, fail-closed apply handoff for a verified staged application update. + +This module does not replace or execute application bytes. It creates a fixed, +host-owned apply intent that a future privileged/standalone updater can consume only +after independently re-verifying the same pending journal and exact staged bytes. +Browser code never receives filesystem paths from this module. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import stat +from typing import Any + +from .application_update import ApplicationUpdateError +from .application_update_pending import PendingApplicationUpdate, inspect_pending_update + + +APPLY_INTENT_SCHEMA = "scripture.application-update.apply-intent.v1" +_APPLY_INTENT_NAME = "apply-update.json" +_MAX_INTENT_BYTES = 16 * 1024 +_REQUIRED_KEYS = frozenset( + { + "schema", + "status", + "product_id", + "target_platform", + "current_version", + "target_version", + "source_head", + "artifact_name", + "artifact_size", + "artifact_sha256", + "authenticity", + } +) + + +def prepare_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate: + """Persist an idempotent apply intent bound to the current verified pending bytes. + + Existing intent is accepted only when it is a regular non-symlink file and its + complete semantic identity exactly matches the freshly re-verified pending + update. Any divergent/corrupt intent fails closed rather than being overwritten. + """ + + root = Path(staging_root) + pending = inspect_pending_update(root, current_version=current_version) + if pending is None: + raise ApplicationUpdateError("no pending update is available for apply handoff") + + payload = _intent_payload(pending) + encoded = (json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + if len(encoded) > _MAX_INTENT_BYTES: + raise ApplicationUpdateError("apply intent exceeds the size limit") + + intent = root / _APPLY_INTENT_NAME + existing = _read_existing_intent(intent) + if existing is not None: + if existing != payload: + raise ApplicationUpdateError("existing apply intent does not match verified pending update") + return pending + + temp = root / f".{_APPLY_INTENT_NAME}.{os.getpid()}.tmp" + try: + descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except OSError as exc: + raise ApplicationUpdateError("could not create apply intent safely") from exc + try: + with os.fdopen(descriptor, "wb", closefd=True) as handle: + handle.write(encoded) + handle.flush() + os.fsync(handle.fileno()) + # Re-verify pending bytes immediately before publication so the durable + # intent is never published from stale verification state. + rebound = inspect_pending_update(root, current_version=current_version) + if rebound != pending: + raise ApplicationUpdateError("pending update changed before apply handoff publication") + os.replace(temp, intent) + _fsync_directory(root) + except Exception: + try: + temp.unlink() + except OSError: + pass + raise + + readback = _read_existing_intent(intent) + if readback != payload: + raise ApplicationUpdateError("apply intent readback does not match verified pending update") + return pending + + +def inspect_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, +) -> PendingApplicationUpdate | None: + """Return the verified pending identity only when the fixed apply intent matches it.""" + + root = Path(staging_root) + payload = _read_existing_intent(root / _APPLY_INTENT_NAME) + if payload is None: + return None + pending = inspect_pending_update(root, current_version=current_version) + if pending is None or payload != _intent_payload(pending): + raise ApplicationUpdateError("apply intent is detached from current pending update") + return pending + + +def discard_apply_handoff(staging_root: str | os.PathLike[str]) -> bool: + """Remove only the fixed apply-intent authority; never delete staged bytes.""" + + path = Path(staging_root) / _APPLY_INTENT_NAME + try: + metadata = path.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("apply intent is unavailable") from exc + if not (stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode)): + raise ApplicationUpdateError("apply intent path is unsafe") + try: + path.unlink() + _fsync_directory(path.parent) + except OSError as exc: + raise ApplicationUpdateError("apply intent could not be discarded safely") from exc + return True + + +def _intent_payload(pending: PendingApplicationUpdate) -> dict[str, Any]: + if not isinstance(pending, PendingApplicationUpdate): + raise ApplicationUpdateError("pending update identity is invalid") + return { + "schema": APPLY_INTENT_SCHEMA, + "status": "ready", + "product_id": pending.product_id, + "target_platform": pending.target_platform, + "current_version": pending.current_version, + "target_version": pending.target_version, + "source_head": pending.source_head, + "artifact_name": pending.artifact_name, + "artifact_size": pending.artifact_size, + "artifact_sha256": pending.artifact_sha256, + "authenticity": pending.authenticity, + } + + +def _read_existing_intent(path: Path) -> dict[str, Any] | None: + try: + before = path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("apply intent is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("apply intent must be a regular non-symlink file") + if before.st_size <= 0 or before.st_size > _MAX_INTENT_BYTES: + raise ApplicationUpdateError("apply intent is empty or exceeds the size limit") + identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + if (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns) != identity: + raise ApplicationUpdateError("apply intent changed before readback") + raw = handle.read(_MAX_INTENT_BYTES + 1) + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("apply intent could not be read safely") from exc + if (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) != identity or len(raw) != before.st_size: + raise ApplicationUpdateError("apply intent changed during readback") + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_strict_json_object) + except ApplicationUpdateError: + raise + except (UnicodeDecodeError, TypeError, ValueError) as exc: + raise ApplicationUpdateError("apply intent is not valid UTF-8 JSON") from exc + if not isinstance(value, dict) or frozenset(value) != _REQUIRED_KEYS: + raise ApplicationUpdateError("apply intent keys do not match schema") + if value["schema"] != APPLY_INTENT_SCHEMA or value["status"] != "ready": + raise ApplicationUpdateError("apply intent schema or status is invalid") + if value["authenticity"] != "same_publisher_authenticode_verified": + raise ApplicationUpdateError("apply intent lacks same-publisher authenticity") + return value + + +def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ApplicationUpdateError(f"apply intent contains duplicate key: {key}") + out[key] = value + return out + + +def _fsync_directory(path: Path) -> None: + 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 72292251666c2d9f7e4c76bd23eee45474ee0391 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:04:48 +0200 Subject: [PATCH 014/118] R06: serialize pending journal update operations in host --- .../scripture_archive_platform/desktop_host/main.py | 8 ++++++++ 1 file changed, 8 insertions(+) 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 02308b0e6..94c4a09ea 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 @@ -12,6 +12,9 @@ NativeApplicationUpdateLayer, NativeUpdateFileSelector, ) +from scripture_archive_platform.desktop_host.update_serialization import ( + SerializedApplicationUpdateLayer, +) # Semantic compatibility version for the current R06-3DEV-A packaged lineage. # It is deliberately host-owned rather than supplied by an update manifest/web payload. @@ -67,6 +70,11 @@ def main() -> int: staging_root, current_version=CURRENT_APPLICATION_VERSION, ) + # All update/stage/status/cancel commands share one outer process lock so the + # fixed pending journal cannot be concurrently overwritten while another update + # operation reports status or cancellation. Ordinary application commands remain + # unaffected and continue directly through the wrapped application. + app = SerializedApplicationUpdateLayer(app) app = NativeDiagnosticsLayer( app, root, From 928a818e611d39944fd0d58e45a1af834bb48b4f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:04:59 +0200 Subject: [PATCH 015/118] R06: reconverge apply handoff with serialized update-family lock --- .../desktop_host/pending_update.py | 67 +++++++++++++++---- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index 29b13e907..384a29015 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -16,31 +16,29 @@ PENDING_UPDATE_STATUS_COMMAND = "application_update.pending_status" +PREPARE_APPLY_COMMAND = "application_update.prepare_apply" CANCEL_PENDING_UPDATE_COMMAND = "application_update.cancel_pending" _PENDING_COMMANDS = frozenset( - {PENDING_UPDATE_STATUS_COMMAND, CANCEL_PENDING_UPDATE_COMMAND} + {PENDING_UPDATE_STATUS_COMMAND, PREPARE_APPLY_COMMAND, CANCEL_PENDING_UPDATE_COMMAND} ) _UPDATE_COMMAND_FAMILY = frozenset( { "application_update.select_verify", "application_update.select_verify_stage", PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, CANCEL_PENDING_UPDATE_COMMAND, } ) class NativePendingUpdateLayer: - """Expose fixed-path staged-update recovery without browser filesystem authority. + """Expose serialized fixed-path staged-update recovery and apply handoff. - Status re-opens the host-owned journal, re-verifies exact staged bytes, checks - same-publisher Authenticode again, then re-verifies exact bytes after that OS - signature inspection. Cancellation removes only the fixed journal authority; - staged executable bytes remain inert and are never recursively deleted here. - - This outer packaged-host layer also serializes the complete application-update - command family. In particular, a staging request cannot publish a fresh pending - journal after a concurrent cancellation has already reported success. + The outer packaged-host lock serializes the complete application-update command + family so staging, status, prepare-apply and cancellation cannot publish + contradictory durable state. Prepare-apply only creates a host-owned intent; it + does not replace, execute, install or restart application bytes. """ def __init__( @@ -87,14 +85,17 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: inspect_pending_update, staged_artifact_path, discard_pending_update = ( self._load_pending_core() ) + prepare_apply_handoff, discard_apply_handoff = self._load_apply_core() if command == CANCEL_PENDING_UPDATE_COMMAND: + apply_removed = discard_apply_handoff(self._staging_root) removed = discard_pending_update(self._staging_root) return ok_response( rid, { "pending": False, - "status": "cancelled" if removed else "none", + "status": "cancelled" if removed or apply_removed else "none", + "apply_handoff_removed": apply_removed, "staged_bytes_removed": False, "installation_performed": False, }, @@ -126,12 +127,41 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: "Pending update no longer has valid same-publisher Authenticode.", ) - # Bind the positive OS signature result back to bytes that still satisfy - # the fixed pending journal after OS signature inspection. pending = inspect_pending_update( self._staging_root, current_version=self._current_version, ) + + if command == PREPARE_APPLY_COMMAND: + rebound = prepare_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if rebound != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_INVALID", + "Apply handoff did not remain bound to the verified pending update.", + ) + return ok_response( + rid, + { + "pending": True, + "status": "apply_ready", + "product_id": rebound.product_id, + "target_platform": rebound.target_platform, + "current_version": rebound.current_version, + "target_version": rebound.target_version, + "source_head": rebound.source_head, + "artifact_name": rebound.artifact_name, + "artifact_size": rebound.artifact_size, + "artifact_sha256": rebound.artifact_sha256, + "authenticity": rebound.authenticity, + "installation_performed": False, + "restart_performed": False, + }, + ) + return ok_response( rid, { @@ -182,3 +212,14 @@ def _load_pending_core(self) -> tuple[Any, Any, Any]: ) return inspect_pending_update, staged_artifact_path, discard_pending_update + + def _load_apply_core(self) -> tuple[Any, Any]: + root_text = str(self._repo_root) + if root_text not in sys.path: + sys.path.insert(0, root_text) + from runtime_engine.scripture_archive_runtime.application_update_apply import ( + discard_apply_handoff, + prepare_apply_handoff, + ) + + return prepare_apply_handoff, discard_apply_handoff From 7320c9e9fbb55d603766d7485dc3e12a4f85082a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:05:19 +0200 Subject: [PATCH 016/118] R06: regress concurrent staging and pending cancellation --- ...ckaged_application_update_serialization.py | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py new file mode 100644 index 000000000..68a39b893 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py @@ -0,0 +1,139 @@ +import threading +import unittest + +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, +) +from scripture_archive_platform.desktop_host.update_application import ( + STAGE_UPDATE_COMMAND, + UPDATE_COMMAND, +) +from scripture_archive_platform.desktop_host.update_serialization import ( + SerializedApplicationUpdateLayer, +) + + +class BlockingUpdateApplication: + def __init__(self): + self.first_entered = threading.Event() + self.second_attempted = threading.Event() + self.second_entered = threading.Event() + self.release_first = threading.Event() + self.state_lock = threading.Lock() + self.active = 0 + self.max_active = 0 + self.order = [] + + def handle(self, request): + request_id = request.get("request_id") if isinstance(request, dict) else None + with self.state_lock: + self.active += 1 + self.max_active = max(self.max_active, self.active) + self.order.append(("enter", request_id)) + try: + if request_id == "first": + self.first_entered.set() + if not self.release_first.wait(timeout=5): + raise AssertionError("test did not release first update operation") + elif request_id == "second": + self.second_entered.set() + return {"ok": True, "request_id": request_id} + finally: + with self.state_lock: + self.order.append(("exit", request_id)) + self.active -= 1 + + +class SerializedApplicationUpdateLayerTests(unittest.TestCase): + @staticmethod + def request(command, request_id): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {}, + } + + def test_stage_and_cancel_cannot_overlap_same_host_process(self): + app = BlockingUpdateApplication() + layer = SerializedApplicationUpdateLayer(app) + results = [] + + first = threading.Thread( + target=lambda: results.append( + layer.handle(self.request(STAGE_UPDATE_COMMAND, "first")) + ) + ) + + def run_second(): + app.second_attempted.set() + results.append(layer.handle(self.request(CANCEL_PENDING_UPDATE_COMMAND, "second"))) + + second = threading.Thread(target=run_second) + first.start() + self.assertTrue(app.first_entered.wait(timeout=2)) + second.start() + self.assertTrue(app.second_attempted.wait(timeout=2)) + + # The first operation deliberately stays inside the wrapped application. + # A broken/no outer lock would allow the second call to enter immediately. + self.assertFalse(app.second_entered.wait(timeout=0.1)) + self.assertEqual(1, app.max_active) + + app.release_first.set() + first.join(timeout=2) + second.join(timeout=2) + self.assertFalse(first.is_alive()) + self.assertFalse(second.is_alive()) + self.assertTrue(app.second_entered.is_set()) + self.assertEqual(1, app.max_active) + self.assertEqual( + [ + ("enter", "first"), + ("exit", "first"), + ("enter", "second"), + ("exit", "second"), + ], + app.order, + ) + self.assertEqual(2, len(results)) + + def test_all_four_update_commands_share_the_serialized_boundary(self): + class RecordingApplication: + def __init__(self): + self.commands = [] + + def handle(self, request): + self.commands.append(request.get("command")) + return {"ok": True} + + app = RecordingApplication() + layer = SerializedApplicationUpdateLayer(app) + commands = ( + UPDATE_COMMAND, + STAGE_UPDATE_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + ) + for index, command in enumerate(commands): + self.assertTrue(layer.handle(self.request(command, f"serial-{index}"))["ok"]) + self.assertEqual(list(commands), app.commands) + + def test_unrelated_command_delegates_without_rewriting_request(self): + seen = [] + + class RecordingApplication: + def handle(self, request): + seen.append(request) + return {"ok": True, "data": {"passthrough": True}} + + layer = SerializedApplicationUpdateLayer(RecordingApplication()) + request = self.request("system.bootstrap", "bootstrap-1") + response = layer.handle(request) + self.assertTrue(response["data"]["passthrough"]) + self.assertEqual([request], seen) + + +if __name__ == "__main__": + unittest.main() From 806dfde78e7320b3fdda300323c179d5804b2602 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:05:24 +0200 Subject: [PATCH 017/118] R06: reconverge apply transport command on latest parent --- .../scripture_archive_platform/transport/contracts.py | 4 ++-- 1 file changed, 2 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 eb5cda948..95fdbc006 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,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","application_update.select_verify_stage","application_update.pending_status","application_update.cancel_pending","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.cancel_pending","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,7 +102,7 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') - if cmd in {'application_update.pending_status','application_update.cancel_pending'} and payload: + if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.cancel_pending'} and payload: raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} From c3aaa27043e0b83dbda67180c0ba47b86b4a28bb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:05:44 +0200 Subject: [PATCH 018/118] R06: reconverge accessible apply handoff control --- .../repair_overlay/frontend/pending-update.js | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js index 9c33df920..3fedcbe84 100644 --- a/lanes/dev1/repair_overlay/frontend/pending-update.js +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -1,5 +1,6 @@ const API_VERSION='scripture.transport.v1'; const STATUS_COMMAND='application_update.pending_status'; +const PREPARE_APPLY_COMMAND='application_update.prepare_apply'; const CANCEL_COMMAND='application_update.cancel_pending'; const $=id=>document.getElementById(id); let sequence=0; @@ -26,7 +27,7 @@ async function invoke(command){ } function setBusy(busy){ - for(const id of ['pending-update-check','pending-update-cancel']){ + for(const id of ['pending-update-check','pending-update-prepare-apply','pending-update-cancel']){ const button=$(id);if(button)button.disabled=busy; } } @@ -38,7 +39,7 @@ function renderPending(data){ if(!host||data.pending!==true)return; host.replaceChildren(); const rows=[ - ['Статус','Підготовлено, але не встановлено'], + ['Статус',data.status==='apply_ready'?'Намір встановлення підготовлено; заміна ще не виконана':'Підготовлено, але не встановлено'], ['Продукт',data.product_id],['Платформа',data.target_platform], ['Поточна версія',data.current_version],['Цільова версія',data.target_version], ['Source head',data.source_head],['Файл пакета',data.artifact_name], @@ -61,12 +62,24 @@ async function checkPending(){ finally{setBusy(false)} } +async function prepareApply(){ + setBusy(true);announce('Повторно перевіряю пакет і готую захищений намір встановлення.'); + try{ + const data=await invoke(PREPARE_APPLY_COMMAND); + if(data.pending===true&&data.status==='apply_ready'&&data.installation_performed===false){ + renderPending(data); + announce(`Намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} підготовлено. Файли програми ще не замінювались і перезапуск не виконувався.`); + }else throw new Error('Підготовку apply handoff не підтверджено.'); + }catch(error){announce(`Не вдалося безпечно підготувати встановлення: ${error?.message||'невідома помилка'}`)} + finally{setBusy(false)} +} + async function cancelPending(){ setBusy(true);clearDetails();announce('Скасовую підготовлений стан оновлення.'); try{ const data=await invoke(CANCEL_COMMAND); if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ - announce(data.status==='cancelled'?'Підготовлене оновлення скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); + announce(data.status==='cancelled'?'Підготовлене оновлення та його apply-наміри скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); }else throw new Error('Скасування не підтверджено.'); }catch(error){announce(`Не вдалося безпечно скасувати pending update: ${error?.message||'невідома помилка'}`)} finally{setBusy(false)} @@ -76,15 +89,16 @@ function mount(){ const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; - const help=element('p','Перевірка повторно звіряє приватний pending state програми. Скасування прибирає лише статус підготовленого оновлення; встановлення тут не виконується.'); + const help=element('p','Перевірка повторно звіряє приватний pending state програми. «Підготувати встановлення» створює лише захищений host-owned apply handoff для наступного окремого updater-кроку: воно не замінює файли і не перезапускає програму. Скасування прибирає pending/apply authority, але не виконує інсталяцію.'); const actions=element('div');actions.className='action-row'; const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; + const apply=element('button','Підготувати встановлення');apply.type='button';apply.id='pending-update-prepare-apply'; const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; - actions.append(check,cancel); + actions.append(check,apply,cancel); const status=element('p','Стан pending update ще не перевірявся.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); section.append(heading,help,actions,status,details);view.append(section); - check.addEventListener('click',checkPending);cancel.addEventListener('click',cancelPending); + check.addEventListener('click',checkPending);apply.addEventListener('click',prepareApply);cancel.addEventListener('click',cancelPending); } mount(); From 106a37831f8e7ccd71e035665f094070ac3f91bc Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:06:10 +0200 Subject: [PATCH 019/118] R06: reconverge apply handoff regressions on latest parent --- ...ckaged_application_update_apply_handoff.py | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py new file mode 100644 index 000000000..efa2db6fb --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_apply_handoff.py @@ -0,0 +1,221 @@ +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_apply import ( + APPLY_INTENT_SCHEMA, + discard_apply_handoff, + inspect_apply_handoff, + prepare_apply_handoff, +) +from runtime_engine.scripture_archive_runtime.application_update_pending import ( + inspect_pending_update, + staged_artifact_path, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + PREPARE_APPLY_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +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 runtime not found") + + +def request(command, payload=None): + return { + "api_version": "scripture.transport.v1", + "request_id": "apply-handoff-test-1", + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def handle(self, value): + return {"ok": True, "data": {"passthrough": value}} + + +class ApplyHandoffFixture(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"apply-handoff-exact-bytes") + self.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": "e" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": self.digest, + } + ) + + def tearDown(self): + self.temp.cleanup() + + def stage(self): + stage_local_update( + self.manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + +class ApplyHandoffRuntimeTests(ApplyHandoffFixture): + def test_prepare_writes_fixed_path_only_after_pending_reverification(self): + self.stage() + pending = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual(self.digest, pending.artifact_sha256) + intent_path = self.staging / "apply-update.json" + self.assertTrue(intent_path.is_file()) + payload = json.loads(intent_path.read_text(encoding="utf-8")) + self.assertEqual(APPLY_INTENT_SCHEMA, payload["schema"]) + self.assertEqual("ready", payload["status"]) + self.assertEqual(self.digest, payload["artifact_sha256"]) + self.assertNotIn("path", payload) + self.assertNotIn("source_path", payload) + self.assertNotIn("staged_path", payload) + self.assertEqual(pending, inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_prepare_is_idempotent_for_same_exact_identity(self): + self.stage() + first = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + before = (self.staging / "apply-update.json").read_bytes() + second = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual(first, second) + self.assertEqual(before, (self.staging / "apply-update.json").read_bytes()) + + def test_divergent_existing_intent_fails_closed_instead_of_overwrite(self): + self.stage() + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + path = self.staging / "apply-update.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["target_version"] = "9.9.9" + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaises(ApplicationUpdateError): + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + self.assertEqual("9.9.9", json.loads(path.read_text(encoding="utf-8"))["target_version"]) + + def test_staged_byte_mutation_detaches_and_blocks_apply_handoff(self): + self.stage() + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + pending = inspect_pending_update(self.staging, current_version=CURRENT_VERSION) + staged_artifact_path(self.staging, pending).write_bytes(b"x" * self.manifest.artifact_size) + with self.assertRaises(ApplicationUpdateError): + inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION) + + def test_discard_removes_only_apply_authority_and_keeps_pending_and_bytes(self): + self.stage() + pending = prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + staged = staged_artifact_path(self.staging, pending) + self.assertTrue(discard_apply_handoff(self.staging)) + self.assertFalse((self.staging / "apply-update.json").exists()) + self.assertTrue((self.staging / "pending-update.json").exists()) + self.assertTrue(staged.is_file()) + self.assertIsNone(inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_no_pending_update_means_no_apply_handoff(self): + with self.assertRaises(ApplicationUpdateError): + prepare_apply_handoff(self.staging, current_version=CURRENT_VERSION) + + +class ApplyHandoffHostTests(ApplyHandoffFixture): + def layer(self, verifier): + return NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=verifier, + ) + + def test_prepare_command_rechecks_authenticity_and_returns_no_paths(self): + self.stage() + calls = [] + response = self.layer(lambda candidate: calls.append(candidate) or True).handle( + request(PREPARE_APPLY_COMMAND) + ) + self.assertTrue(response["ok"]) + self.assertEqual("apply_ready", response["data"]["status"]) + self.assertFalse(response["data"]["installation_performed"]) + self.assertFalse(response["data"]["restart_performed"]) + self.assertEqual(1, len(calls)) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("path", serialized) + self.assertIsNotNone(inspect_apply_handoff(self.staging, current_version=CURRENT_VERSION)) + + def test_prepare_command_rejects_browser_payload_authority(self): + self.stage() + response = self.layer(lambda candidate: True).handle( + request(PREPARE_APPLY_COMMAND, {"path": "C:\\attacker.exe"}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_negative_authenticode_never_creates_apply_handoff(self): + self.stage() + response = self.layer(lambda candidate: False).handle(request(PREPARE_APPLY_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_AUTHENTICITY_INVALID", response["error"]["code"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_signature_then_byte_mutation_never_creates_apply_handoff(self): + self.stage() + + def verifier(candidate): + candidate.write_bytes(b"x" * self.manifest.artifact_size) + return True + + response = self.layer(verifier).handle(request(PREPARE_APPLY_COMMAND)) + self.assertFalse(response["ok"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + + def test_cancel_disarms_apply_intent_before_pending_authority(self): + self.stage() + self.assertTrue(self.layer(lambda candidate: True).handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = self.layer(lambda candidate: True).handle(request(CANCEL_PENDING_UPDATE_COMMAND)) + self.assertTrue(response["ok"]) + self.assertEqual("cancelled", response["data"]["status"]) + self.assertTrue(response["data"]["apply_handoff_removed"]) + self.assertFalse((self.staging / "apply-update.json").exists()) + self.assertFalse((self.staging / "pending-update.json").exists()) + + def test_frontend_is_keyboard_native_and_explicitly_denies_false_install_claim(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.prepare_apply", script) + self.assertIn("pending-update-prepare-apply", script) + self.assertIn("installation_performed===false", script) + self.assertIn("ще не замінювались", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() From d5392fe5c1aa0e4361dad8b8c83c82065a7a9d38 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:08:12 +0200 Subject: [PATCH 020/118] R06: detect pending update automatically after host startup --- .../repair_overlay/frontend/pending-update.js | 48 ++++++++++++------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js index 9c33df920..246cb630f 100644 --- a/lanes/dev1/repair_overlay/frontend/pending-update.js +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -3,10 +3,13 @@ const STATUS_COMMAND='application_update.pending_status'; const CANCEL_COMMAND='application_update.cancel_pending'; const $=id=>document.getElementById(id); let sequence=0; +let startupCheckStarted=false; -function announce(message){ - const global=$('global-status'); - if(global){global.textContent='';requestAnimationFrame(()=>{global.textContent=message})} +function setStatus(message,{global=true}={}){ + if(global){ + const live=$('global-status'); + if(live){live.textContent='';requestAnimationFrame(()=>{live.textContent=message})} + } const local=$('pending-update-status'); if(local)local.textContent=message; } @@ -48,43 +51,56 @@ function renderPending(data){ for(const [label,value] of rows){host.append(element('dt',label),element('dd',value??'—'))} } -async function checkPending(){ - setBusy(true);clearDetails();announce('Повторно перевіряю підготовлене оновлення.'); +async function checkPending({startup=false}={}){ + setBusy(true);clearDetails(); + if(!startup)setStatus('Повторно перевіряю підготовлене оновлення.'); try{ const data=await invoke(STATUS_COMMAND); if(data.pending===true&&data.status==='staged'){ renderPending(data); - announce(`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); - }else if(data.pending===false&&data.status==='none')announce('Підготовленого оновлення немає.'); - else throw new Error('Отримано неочікуваний стан.'); - }catch(error){clearDetails();announce(`Pending update не підтверджено: ${error?.message||'невідома помилка'}`)} - finally{setBusy(false)} + setStatus(`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); + }else if(data.pending===false&&data.status==='none'){ + setStatus('Підготовленого оновлення немає.',{global:!startup}); + }else throw new Error('Отримано неочікуваний стан.'); + }catch(error){ + clearDetails(); + setStatus(`Pending update не підтверджено: ${error?.message||'невідома помилка'}`); + }finally{setBusy(false)} } async function cancelPending(){ - setBusy(true);clearDetails();announce('Скасовую підготовлений стан оновлення.'); + setBusy(true);clearDetails();setStatus('Скасовую підготовлений стан оновлення.'); try{ const data=await invoke(CANCEL_COMMAND); if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ - announce(data.status==='cancelled'?'Підготовлене оновлення скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); + setStatus(data.status==='cancelled'?'Підготовлене оновлення скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); }else throw new Error('Скасування не підтверджено.'); - }catch(error){announce(`Не вдалося безпечно скасувати pending update: ${error?.message||'невідома помилка'}`)} + }catch(error){setStatus(`Не вдалося безпечно скасувати pending update: ${error?.message||'невідома помилка'}`)} finally{setBusy(false)} } +function startStartupCheck(){ + if(startupCheckStarted)return; + startupCheckStarted=true; + void checkPending({startup:true}); +} + function mount(){ const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; - const help=element('p','Перевірка повторно звіряє приватний pending state програми. Скасування прибирає лише статус підготовленого оновлення; встановлення тут не виконується.'); + const help=element('p','Після запуску програма автоматично перевіряє приватний pending state. Скасування прибирає лише статус підготовленого оновлення; встановлення тут не виконується.'); const actions=element('div');actions.className='action-row'; const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; actions.append(check,cancel); - const status=element('p','Стан pending update ще не перевірявся.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const status=element('p','Очікую готовності native host для перевірки pending update.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); section.append(heading,help,actions,status,details);view.append(section); - check.addEventListener('click',checkPending);cancel.addEventListener('click',cancelPending); + check.addEventListener('click',()=>checkPending());cancel.addEventListener('click',cancelPending); + + window.addEventListener('pywebviewready',startStartupCheck,{once:true}); + if(typeof window.pywebview?.api?.invoke==='function')queueMicrotask(startStartupCheck); } mount(); From f4f0c905712d1c4ccac2d43652e400b1dc41898b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:08:18 +0200 Subject: [PATCH 021/118] R06: serialize prepare-apply with all update commands --- .../desktop_host/update_serialization.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py index edc9c3085..883c39edb 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py @@ -6,6 +6,7 @@ from scripture_archive_platform.desktop_host.pending_update import ( CANCEL_PENDING_UPDATE_COMMAND, PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, ) from scripture_archive_platform.desktop_host.update_application import ( STAGE_UPDATE_COMMAND, @@ -18,6 +19,7 @@ UPDATE_COMMAND, STAGE_UPDATE_COMMAND, PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, CANCEL_PENDING_UPDATE_COMMAND, } ) @@ -26,10 +28,10 @@ class SerializedApplicationUpdateLayer: """Serialize all packaged update/recovery commands in one host process. - Staging and recovery share the same fixed pending journal. Without one outer - operation lock a cancel/status call could race a concurrent stage call and make - the UI report a state that was immediately overwritten. The lock is deliberately - host-local: filesystem and signature validation remain fail-closed authorities. + Staging, recovery and apply-handoff preparation share fixed durable update state. + Without one outer operation lock these commands could race and make the UI report + authority that was immediately superseded. The lock is deliberately host-local: + filesystem, byte-identity and signature validation remain fail-closed authorities. """ def __init__(self, app: Any) -> None: From ba301c309b431c01a679e2f26565324edbdd6a69 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:08:28 +0200 Subject: [PATCH 022/118] R06: add standalone atomic updater and rollback core --- .../application_update_updater.py | 252 ++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_updater.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py new file mode 100644 index 000000000..186ae8b2c --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -0,0 +1,252 @@ +"""Standalone atomic consumer for a verified application-update apply handoff. + +This module is intentionally not exposed through browser transport. A trusted host/updater +process supplies the fixed staging root and exact installed executable path. The consumer +re-opens the durable apply handoff, re-verifies the staged bytes and publisher, preserves a +same-directory rollback copy, atomically replaces the target, and rolls back automatically +when installed-byte verification fails. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import os +from pathlib import Path +import shutil +import stat +from typing import Callable + +from .application_update import ApplicationUpdateError +from .application_update_apply import inspect_apply_handoff +from .application_update_pending import PendingApplicationUpdate, staged_artifact_path + + +_ROLLBACK_SUFFIX = ".scripture-archive.rollback" +_COPY_CHUNK = 1024 * 1024 + + +@dataclass(frozen=True) +class UpdateApplyResult: + previous_sha256: str + installed_sha256: str + rollback_path: Path + target_path: Path + target_version: str + + +def consume_apply_handoff( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], + verify_same_publisher: Callable[[Path, Path], bool], +) -> UpdateApplyResult: + """Atomically replace one installed executable from the fixed verified handoff. + + The caller must be a trusted standalone updater/host boundary. ``install_target`` is + never accepted from browser transport. The existing target and staged candidate must + both be regular non-symlink files. Publisher verification is repeated immediately + before replacement and exact SHA-256 is checked both before and after publication. + """ + + if not callable(verify_same_publisher): + raise ApplicationUpdateError("same-publisher verifier is required") + + root = Path(staging_root) + target = Path(install_target) + pending = inspect_apply_handoff(root, current_version=current_version) + if pending is None: + raise ApplicationUpdateError("no verified apply handoff is available") + + staged = staged_artifact_path(root, pending) + _require_regular_file(staged, "staged update artifact") + _require_regular_file(target, "installed application target") + _require_safe_parent(target.parent) + + if staged.name != pending.artifact_name: + raise ApplicationUpdateError("staged artifact name does not match apply handoff") + if _sha256_file(staged) != pending.artifact_sha256: + raise ApplicationUpdateError("staged artifact bytes changed before apply") + if not verify_same_publisher(target, staged): + raise ApplicationUpdateError("staged artifact failed same-publisher verification") + if _sha256_file(staged) != pending.artifact_sha256: + raise ApplicationUpdateError("staged artifact bytes changed during publisher verification") + + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _prepare_rollback_slot(rollback) + previous_sha = _sha256_file(target) + _copy_exact(target, rollback) + if _sha256_file(rollback) != previous_sha: + _discard_file(rollback) + raise ApplicationUpdateError("rollback copy failed exact-byte verification") + + candidate = target.with_name(f".{target.name}.update-{os.getpid()}.tmp") + _prepare_temp_slot(candidate) + try: + _copy_exact(staged, candidate) + if _sha256_file(candidate) != pending.artifact_sha256: + raise ApplicationUpdateError("temporary install candidate failed exact-byte verification") + os.replace(candidate, target) + _fsync_directory(target.parent) + _require_regular_file(target, "installed application target") + installed_sha = _sha256_file(target) + if installed_sha != pending.artifact_sha256: + _rollback_replace(target, rollback, previous_sha) + raise ApplicationUpdateError("installed artifact failed exact-byte verification; rollback restored") + except Exception: + try: + candidate.unlink() + except OSError: + pass + if not target.exists() and rollback.exists(): + _rollback_replace(target, rollback, previous_sha) + raise + + return UpdateApplyResult( + previous_sha256=previous_sha, + installed_sha256=pending.artifact_sha256, + rollback_path=rollback, + target_path=target, + target_version=pending.target_version, + ) + + +def rollback_installed_update( + install_target: str | os.PathLike[str], + *, + expected_previous_sha256: str, +) -> str: + """Restore the fixed same-directory rollback copy and verify exact prior bytes.""" + + target = Path(install_target) + _require_safe_sha256(expected_previous_sha256) + _require_safe_parent(target.parent) + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + _rollback_replace(target, rollback, expected_previous_sha256) + return expected_previous_sha256 + + +def _rollback_replace(target: Path, rollback: Path, expected_sha: str) -> None: + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(rollback) != expected_sha: + raise ApplicationUpdateError("rollback artifact does not match expected prior bytes") + restore = target.with_name(f".{target.name}.rollback-{os.getpid()}.tmp") + _prepare_temp_slot(restore) + try: + _copy_exact(rollback, restore) + if _sha256_file(restore) != expected_sha: + raise ApplicationUpdateError("rollback temporary copy failed exact-byte verification") + os.replace(restore, target) + _fsync_directory(target.parent) + finally: + try: + restore.unlink() + except OSError: + pass + _require_regular_file(target, "restored application target") + if _sha256_file(target) != expected_sha: + raise ApplicationUpdateError("rollback restoration failed exact-byte verification") + + +def _prepare_rollback_slot(path: Path) -> None: + try: + metadata = path.lstat() + except FileNotFoundError: + return + except OSError as exc: + raise ApplicationUpdateError("rollback path is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("rollback path must not redirect update writes") + _discard_file(path) + + +def _prepare_temp_slot(path: Path) -> None: + try: + metadata = path.lstat() + except FileNotFoundError: + return + except OSError as exc: + raise ApplicationUpdateError("temporary update path is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("temporary update path must not redirect update writes") + _discard_file(path) + + +def _discard_file(path: Path) -> None: + try: + path.unlink() + except FileNotFoundError: + return + except OSError as exc: + raise ApplicationUpdateError("update artifact could not be removed safely") from exc + + +def _copy_exact(source: Path, destination: Path) -> None: + try: + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + except OSError as exc: + raise ApplicationUpdateError("could not create update copy safely") from exc + try: + with source.open("rb") as src, os.fdopen(descriptor, "wb", closefd=True) as dst: + shutil.copyfileobj(src, dst, length=_COPY_CHUNK) + dst.flush() + os.fsync(dst.fileno()) + except Exception: + try: + destination.unlink() + except OSError: + pass + raise + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + while True: + chunk = handle.read(_COPY_CHUNK) + if not chunk: + break + digest.update(chunk) + except OSError as exc: + raise ApplicationUpdateError("update artifact could not be hashed") from exc + return digest.hexdigest() + + +def _require_regular_file(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + + +def _require_safe_parent(path: Path) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("install directory is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError("install directory must be a real directory") + + +def _require_safe_sha256(value: str) -> None: + if len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value): + raise ApplicationUpdateError("expected rollback SHA-256 is invalid") + + +def _fsync_directory(path: Path) -> None: + 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 d24eb5822f5d0007aa07c232b4539955e9555aef Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:08:39 +0200 Subject: [PATCH 023/118] R06: regress serialized prepare-apply handoff --- ...ckaged_application_update_serialization.py | 35 +++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py index 68a39b893..efb83c525 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py @@ -4,6 +4,7 @@ from scripture_archive_platform.desktop_host.pending_update import ( CANCEL_PENDING_UPDATE_COMMAND, PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, ) from scripture_archive_platform.desktop_host.update_application import ( STAGE_UPDATE_COMMAND, @@ -76,8 +77,6 @@ def run_second(): second.start() self.assertTrue(app.second_attempted.wait(timeout=2)) - # The first operation deliberately stays inside the wrapped application. - # A broken/no outer lock would allow the second call to enter immediately. self.assertFalse(app.second_entered.wait(timeout=0.1)) self.assertEqual(1, app.max_active) @@ -99,7 +98,7 @@ def run_second(): ) self.assertEqual(2, len(results)) - def test_all_four_update_commands_share_the_serialized_boundary(self): + def test_all_five_update_commands_share_the_serialized_boundary(self): class RecordingApplication: def __init__(self): self.commands = [] @@ -114,12 +113,42 @@ def handle(self, request): UPDATE_COMMAND, STAGE_UPDATE_COMMAND, PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, CANCEL_PENDING_UPDATE_COMMAND, ) for index, command in enumerate(commands): self.assertTrue(layer.handle(self.request(command, f"serial-{index}"))["ok"]) self.assertEqual(list(commands), app.commands) + def test_prepare_apply_cannot_overlap_staging_same_host_process(self): + app = BlockingUpdateApplication() + layer = SerializedApplicationUpdateLayer(app) + results = [] + first = threading.Thread( + target=lambda: results.append( + layer.handle(self.request(STAGE_UPDATE_COMMAND, "first")) + ) + ) + + def run_second(): + app.second_attempted.set() + results.append(layer.handle(self.request(PREPARE_APPLY_COMMAND, "second"))) + + second = threading.Thread(target=run_second) + first.start() + self.assertTrue(app.first_entered.wait(timeout=2)) + second.start() + self.assertTrue(app.second_attempted.wait(timeout=2)) + self.assertFalse(app.second_entered.wait(timeout=0.1)) + app.release_first.set() + first.join(timeout=2) + second.join(timeout=2) + self.assertFalse(first.is_alive()) + self.assertFalse(second.is_alive()) + self.assertTrue(app.second_entered.is_set()) + self.assertEqual(1, app.max_active) + self.assertEqual(2, len(results)) + def test_unrelated_command_delegates_without_rewriting_request(self): seen = [] From de33ff960ac453b5bae36d35025f53906b799c5c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:08:53 +0200 Subject: [PATCH 024/118] R06: add atomic updater rollback regressions --- .../tests/test_application_update_updater.py | 180 ++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_updater.py diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py new file mode 100644 index 000000000..c13a9dcb0 --- /dev/null +++ b/runtime_engine/tests/test_application_update_updater.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import hashlib +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_pending import PendingApplicationUpdate +from scripture_archive_runtime.application_update_updater import ( + consume_apply_handoff, + rollback_installed_update, +) + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class AtomicApplicationUpdaterTests(unittest.TestCase): + def _pending(self, staged: bytes) -> PendingApplicationUpdate: + return PendingApplicationUpdate( + product_id="scripture-archive", + target_platform="windows-x64", + current_version="1.0.0", + target_version="1.1.0", + source_head="a" * 40, + artifact_name="ScriptureArchive.exe", + artifact_size=len(staged), + artifact_sha256=_sha(staged), + ) + + def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + result = consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda current, candidate: current == target and candidate == staged, + ) + + self.assertEqual(target.read_bytes(), new) + self.assertEqual(result.installed_sha256, _sha(new)) + self.assertEqual(result.previous_sha256, _sha(old)) + self.assertEqual(result.target_version, "1.1.0") + self.assertEqual(result.rollback_path.read_bytes(), old) + + def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): + old = b"old" + new = b"new" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "ScriptureArchive.new.exe" + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + staged_named = root / pending.artifact_name + staged_named.write_bytes(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged_named, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "same-publisher"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: False, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse((root / "ScriptureArchive.exe.scripture-archive.rollback").exists()) + + def test_consume_handoff_detects_staged_mutation_during_signature_check(self): + old = b"old" + new = b"new" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + def mutate(_current: Path, candidate: Path) -> bool: + candidate.write_bytes(b"tampered") + return True + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "changed during publisher verification"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=mutate, + ) + + self.assertEqual(target.read_bytes(), old) + + def test_explicit_rollback_restores_exact_previous_bytes(self): + old = b"previous exact executable" + new = b"installed update" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + target.write_bytes(new) + rollback.write_bytes(old) + + restored = rollback_installed_update(target, expected_previous_sha256=_sha(old)) + + self.assertEqual(restored, _sha(old)) + self.assertEqual(target.read_bytes(), old) + self.assertEqual(rollback.read_bytes(), old) + + def test_symlink_install_target_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + real = root / "real.exe" + real.write_bytes(b"old") + target = root / "ScriptureArchive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + staged.write_bytes(b"new") + pending = self._pending(b"new") + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _a, _b: True, + ) + + self.assertEqual(real.read_bytes(), b"old") + + +if __name__ == "__main__": + unittest.main() From e91270243d5638bcab61d1a7987ac919ccd2245c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:09:02 +0200 Subject: [PATCH 025/118] R06: remove duplicate update serialization wrapper --- .../desktop_host/update_serialization.py | 43 ------------------- 1 file changed, 43 deletions(-) delete mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py deleted file mode 100644 index edc9c3085..000000000 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/update_serialization.py +++ /dev/null @@ -1,43 +0,0 @@ -from __future__ import annotations - -import threading -from typing import Any - -from scripture_archive_platform.desktop_host.pending_update import ( - CANCEL_PENDING_UPDATE_COMMAND, - PENDING_UPDATE_STATUS_COMMAND, -) -from scripture_archive_platform.desktop_host.update_application import ( - STAGE_UPDATE_COMMAND, - UPDATE_COMMAND, -) - - -_UPDATE_COMMANDS = frozenset( - { - UPDATE_COMMAND, - STAGE_UPDATE_COMMAND, - PENDING_UPDATE_STATUS_COMMAND, - CANCEL_PENDING_UPDATE_COMMAND, - } -) - - -class SerializedApplicationUpdateLayer: - """Serialize all packaged update/recovery commands in one host process. - - Staging and recovery share the same fixed pending journal. Without one outer - operation lock a cancel/status call could race a concurrent stage call and make - the UI report a state that was immediately overwritten. The lock is deliberately - host-local: filesystem and signature validation remain fail-closed authorities. - """ - - def __init__(self, app: Any) -> None: - self._app = app - self._lock = threading.RLock() - - def handle(self, request: Any) -> dict[str, Any]: - if not isinstance(request, dict) or request.get("command") not in _UPDATE_COMMANDS: - return self._app.handle(request) - with self._lock: - return self._app.handle(request) From 3c4bff127a0ed790623849cf38643840d0fa564d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:09:07 +0200 Subject: [PATCH 026/118] R06: remove duplicate serialization test lineage --- ...ckaged_application_update_serialization.py | 139 ------------------ 1 file changed, 139 deletions(-) delete mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py deleted file mode 100644 index 68a39b893..000000000 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_serialization.py +++ /dev/null @@ -1,139 +0,0 @@ -import threading -import unittest - -from scripture_archive_platform.desktop_host.pending_update import ( - CANCEL_PENDING_UPDATE_COMMAND, - PENDING_UPDATE_STATUS_COMMAND, -) -from scripture_archive_platform.desktop_host.update_application import ( - STAGE_UPDATE_COMMAND, - UPDATE_COMMAND, -) -from scripture_archive_platform.desktop_host.update_serialization import ( - SerializedApplicationUpdateLayer, -) - - -class BlockingUpdateApplication: - def __init__(self): - self.first_entered = threading.Event() - self.second_attempted = threading.Event() - self.second_entered = threading.Event() - self.release_first = threading.Event() - self.state_lock = threading.Lock() - self.active = 0 - self.max_active = 0 - self.order = [] - - def handle(self, request): - request_id = request.get("request_id") if isinstance(request, dict) else None - with self.state_lock: - self.active += 1 - self.max_active = max(self.max_active, self.active) - self.order.append(("enter", request_id)) - try: - if request_id == "first": - self.first_entered.set() - if not self.release_first.wait(timeout=5): - raise AssertionError("test did not release first update operation") - elif request_id == "second": - self.second_entered.set() - return {"ok": True, "request_id": request_id} - finally: - with self.state_lock: - self.order.append(("exit", request_id)) - self.active -= 1 - - -class SerializedApplicationUpdateLayerTests(unittest.TestCase): - @staticmethod - def request(command, request_id): - return { - "api_version": "scripture.transport.v1", - "request_id": request_id, - "command": command, - "payload": {}, - } - - def test_stage_and_cancel_cannot_overlap_same_host_process(self): - app = BlockingUpdateApplication() - layer = SerializedApplicationUpdateLayer(app) - results = [] - - first = threading.Thread( - target=lambda: results.append( - layer.handle(self.request(STAGE_UPDATE_COMMAND, "first")) - ) - ) - - def run_second(): - app.second_attempted.set() - results.append(layer.handle(self.request(CANCEL_PENDING_UPDATE_COMMAND, "second"))) - - second = threading.Thread(target=run_second) - first.start() - self.assertTrue(app.first_entered.wait(timeout=2)) - second.start() - self.assertTrue(app.second_attempted.wait(timeout=2)) - - # The first operation deliberately stays inside the wrapped application. - # A broken/no outer lock would allow the second call to enter immediately. - self.assertFalse(app.second_entered.wait(timeout=0.1)) - self.assertEqual(1, app.max_active) - - app.release_first.set() - first.join(timeout=2) - second.join(timeout=2) - self.assertFalse(first.is_alive()) - self.assertFalse(second.is_alive()) - self.assertTrue(app.second_entered.is_set()) - self.assertEqual(1, app.max_active) - self.assertEqual( - [ - ("enter", "first"), - ("exit", "first"), - ("enter", "second"), - ("exit", "second"), - ], - app.order, - ) - self.assertEqual(2, len(results)) - - def test_all_four_update_commands_share_the_serialized_boundary(self): - class RecordingApplication: - def __init__(self): - self.commands = [] - - def handle(self, request): - self.commands.append(request.get("command")) - return {"ok": True} - - app = RecordingApplication() - layer = SerializedApplicationUpdateLayer(app) - commands = ( - UPDATE_COMMAND, - STAGE_UPDATE_COMMAND, - PENDING_UPDATE_STATUS_COMMAND, - CANCEL_PENDING_UPDATE_COMMAND, - ) - for index, command in enumerate(commands): - self.assertTrue(layer.handle(self.request(command, f"serial-{index}"))["ok"]) - self.assertEqual(list(commands), app.commands) - - def test_unrelated_command_delegates_without_rewriting_request(self): - seen = [] - - class RecordingApplication: - def handle(self, request): - seen.append(request) - return {"ok": True, "data": {"passthrough": True}} - - layer = SerializedApplicationUpdateLayer(RecordingApplication()) - request = self.request("system.bootstrap", "bootstrap-1") - response = layer.handle(request) - self.assertTrue(response["data"]["passthrough"]) - self.assertEqual([request], seen) - - -if __name__ == "__main__": - unittest.main() From d7ef10815429853bc55d56c71b16767ef18f4cd8 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:09:18 +0200 Subject: [PATCH 027/118] R06: keep one canonical update operation lock --- .../scripture_archive_platform/desktop_host/main.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) 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 94c4a09ea..2decc0ad6 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 @@ -12,9 +12,6 @@ NativeApplicationUpdateLayer, NativeUpdateFileSelector, ) -from scripture_archive_platform.desktop_host.update_serialization import ( - SerializedApplicationUpdateLayer, -) # Semantic compatibility version for the current R06-3DEV-A packaged lineage. # It is deliberately host-owned rather than supplied by an update manifest/web payload. @@ -64,17 +61,14 @@ def main() -> int: current_version=CURRENT_APPLICATION_VERSION, staging_root=staging_root, ) + # This outer layer owns one process-local RLock for the complete update command + # family, so verify/stage/status/cancel cannot race the shared pending journal. app = NativePendingUpdateLayer( app, root, staging_root, current_version=CURRENT_APPLICATION_VERSION, ) - # All update/stage/status/cancel commands share one outer process lock so the - # fixed pending journal cannot be concurrently overwritten while another update - # operation reports status or cancellation. Ordinary application commands remain - # unaffected and continue directly through the wrapped application. - app = SerializedApplicationUpdateLayer(app) app = NativeDiagnosticsLayer( app, root, From d97e68f11290a961b32edbde150d4037051f7fd5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:09:44 +0200 Subject: [PATCH 028/118] R06: prove stage and pending cancel cannot overlap --- ..._application_update_pending_concurrency.py | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py new file mode 100644 index 000000000..13f8f096f --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending_concurrency.py @@ -0,0 +1,111 @@ +import tempfile +import threading +import unittest +from pathlib import Path + +from scripture_archive_platform.desktop_host.pending_update import ( + CANCEL_PENDING_UPDATE_COMMAND, + NativePendingUpdateLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +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 runtime not found") + + +def request(command, request_id): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {}, + } + + +class BlockingBaseApplication: + def __init__(self): + self.entered = threading.Event() + self.release = threading.Event() + self.calls = [] + + def handle(self, value): + self.calls.append(value) + if value.get("request_id") == "stage-first": + self.entered.set() + if not self.release.wait(timeout=5): + raise AssertionError("test did not release staged update delegation") + return {"ok": True, "data": {"passthrough": True}} + + +class PendingUpdateConcurrencyTests(unittest.TestCase): + def test_cancel_waits_for_inflight_staging_family_operation(self): + with tempfile.TemporaryDirectory() as temp: + staging = Path(temp) / "application-updates" + staging.mkdir(parents=True) + journal = staging / "pending-update.json" + journal.write_text("corrupt-but-fixed-path", encoding="utf-8") + + base = BlockingBaseApplication() + layer = NativePendingUpdateLayer( + base, + repository_root(), + staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + ) + first_result = [] + second_result = [] + second_started = threading.Event() + second_done = threading.Event() + + first = threading.Thread( + target=lambda: first_result.append( + layer.handle( + request("application_update.select_verify_stage", "stage-first") + ) + ) + ) + + def cancel_pending(): + second_started.set() + second_result.append( + layer.handle(request(CANCEL_PENDING_UPDATE_COMMAND, "cancel-second")) + ) + second_done.set() + + second = threading.Thread(target=cancel_pending) + first.start() + self.assertTrue(base.entered.wait(timeout=2)) + second.start() + self.assertTrue(second_started.wait(timeout=2)) + + # The stage-family call still owns the one update-operation lock. + # Cancellation must not report success or remove journal authority yet. + self.assertFalse(second_done.wait(timeout=0.1)) + self.assertTrue(journal.exists()) + + base.release.set() + first.join(timeout=2) + second.join(timeout=2) + self.assertFalse(first.is_alive()) + self.assertFalse(second.is_alive()) + self.assertEqual(1, len(first_result)) + self.assertEqual(1, len(second_result)) + self.assertTrue(first_result[0]["ok"]) + self.assertTrue(second_result[0]["ok"]) + self.assertEqual("cancelled", second_result[0]["data"]["status"]) + self.assertFalse(journal.exists()) + self.assertEqual( + "application_update.select_verify_stage", + base.calls[0]["command"], + ) + + +if __name__ == "__main__": + unittest.main() From 697f7c444e0d4f376b115ee9616ebe638272369c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:11:23 +0200 Subject: [PATCH 029/118] R06: rollback every post-publication updater failure --- .../application_update_updater.py | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 186ae8b2c..dd17fba3d 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -83,24 +83,34 @@ def consume_apply_handoff( candidate = target.with_name(f".{target.name}.update-{os.getpid()}.tmp") _prepare_temp_slot(candidate) + published = False try: _copy_exact(staged, candidate) if _sha256_file(candidate) != pending.artifact_sha256: raise ApplicationUpdateError("temporary install candidate failed exact-byte verification") os.replace(candidate, target) + published = True _fsync_directory(target.parent) _require_regular_file(target, "installed application target") installed_sha = _sha256_file(target) if installed_sha != pending.artifact_sha256: - _rollback_replace(target, rollback, previous_sha) - raise ApplicationUpdateError("installed artifact failed exact-byte verification; rollback restored") - except Exception: + raise ApplicationUpdateError("installed artifact failed exact-byte verification") + except Exception as apply_error: try: candidate.unlink() except OSError: pass - if not target.exists() and rollback.exists(): - _rollback_replace(target, rollback, previous_sha) + if published or (not target.exists() and rollback.exists()): + try: + _rollback_replace(target, rollback, previous_sha) + except Exception as rollback_error: + raise ApplicationUpdateError( + "update apply failed and automatic rollback also failed" + ) from rollback_error + if published: + raise ApplicationUpdateError( + "update apply failed after publication; rollback restored" + ) from apply_error raise return UpdateApplyResult( From f8d7c404ee43cf156ac9b191fdacef924b9cdb98 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:11:25 +0200 Subject: [PATCH 030/118] R06: regress post-publication verification rollback --- .../tests/test_application_update_updater.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index c13a9dcb0..d80dfd319 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -127,6 +127,58 @@ def mutate(_current: Path, candidate: Path) -> bool: self.assertEqual(target.read_bytes(), old) + def test_consume_handoff_rolls_back_when_post_publish_verification_errors(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + real_hash = hashlib.sha256 + target_hash_reads = 0 + + def fail_post_publish_hash(path: Path) -> str: + nonlocal target_hash_reads + if path == target: + target_hash_reads += 1 + if target_hash_reads == 2: + raise ApplicationUpdateError("forced post-publish hash failure") + digest = real_hash() + digest.update(path.read_bytes()) + return digest.hexdigest() + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater._sha256_file", + side_effect=fail_post_publish_hash, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertEqual( + (root / "ScriptureArchive.exe.scripture-archive.rollback").read_bytes(), + old, + ) + def test_explicit_rollback_restores_exact_previous_bytes(self): old = b"previous exact executable" new = b"installed update" From 4313547796c770fd36fe0bc46c074c3a9b988473 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:12:29 +0200 Subject: [PATCH 031/118] R06: bind updater apply to stable target and handoff --- .../application_update_updater.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index dd17fba3d..c15e2f1b0 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -68,14 +68,19 @@ def consume_apply_handoff( raise ApplicationUpdateError("staged artifact name does not match apply handoff") if _sha256_file(staged) != pending.artifact_sha256: raise ApplicationUpdateError("staged artifact bytes changed before apply") + previous_sha = _sha256_file(target) if not verify_same_publisher(target, staged): raise ApplicationUpdateError("staged artifact failed same-publisher verification") if _sha256_file(staged) != pending.artifact_sha256: raise ApplicationUpdateError("staged artifact bytes changed during publisher verification") + if _sha256_file(target) != previous_sha: + raise ApplicationUpdateError("installed application target changed during publisher verification") + rebound = inspect_apply_handoff(root, current_version=current_version) + if rebound != pending: + raise ApplicationUpdateError("apply handoff changed during publisher verification") rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) _prepare_rollback_slot(rollback) - previous_sha = _sha256_file(target) _copy_exact(target, rollback) if _sha256_file(rollback) != previous_sha: _discard_file(rollback) From 69f7328a736bb9674346043e1253b561d5f96ef3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:12:32 +0200 Subject: [PATCH 032/118] R06: regress target and apply-authority TOCTOU --- .../tests/test_application_update_updater.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index d80dfd319..b165964c1 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -127,6 +127,81 @@ def mutate(_current: Path, candidate: Path) -> bool: self.assertEqual(target.read_bytes(), old) + def test_consume_handoff_rejects_target_mutation_during_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + def mutate_target(current: Path, _candidate: Path) -> bool: + current.write_bytes(b"attacker replacement") + return True + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "target changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=mutate_target, + ) + + self.assertEqual(target.read_bytes(), b"attacker replacement") + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_cancelled_authority_after_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + inspections = [pending, None] + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + side_effect=inspections, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "apply handoff changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + def test_consume_handoff_rolls_back_when_post_publish_verification_errors(self): old = b"old executable bytes" new = b"new signed executable bytes" From 5cec1633208f1bc11a7fec8902a97b81f062e06f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:12:43 +0200 Subject: [PATCH 033/118] R06: keep post-publication rollback regression phase-exact --- runtime_engine/tests/test_application_update_updater.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index b165964c1..0d0ed3d09 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -221,7 +221,7 @@ def fail_post_publish_hash(path: Path) -> str: nonlocal target_hash_reads if path == target: target_hash_reads += 1 - if target_hash_reads == 2: + if target_hash_reads == 3: raise ApplicationUpdateError("forced post-publish hash failure") digest = real_hash() digest.update(path.read_bytes()) From f0653c01366939f31ee95121e0bf86c7949e5a82 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:13:29 +0200 Subject: [PATCH 034/118] R06: disarm apply authority after exact install --- .../scripture_archive_runtime/application_update_updater.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index c15e2f1b0..86c9f119f 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -18,7 +18,7 @@ from typing import Callable from .application_update import ApplicationUpdateError -from .application_update_apply import inspect_apply_handoff +from .application_update_apply import discard_apply_handoff, inspect_apply_handoff from .application_update_pending import PendingApplicationUpdate, staged_artifact_path @@ -93,6 +93,9 @@ def consume_apply_handoff( _copy_exact(staged, candidate) if _sha256_file(candidate) != pending.artifact_sha256: raise ApplicationUpdateError("temporary install candidate failed exact-byte verification") + final_handoff = inspect_apply_handoff(root, current_version=current_version) + if final_handoff != pending: + raise ApplicationUpdateError("apply handoff changed before atomic publication") os.replace(candidate, target) published = True _fsync_directory(target.parent) @@ -100,6 +103,7 @@ def consume_apply_handoff( installed_sha = _sha256_file(target) if installed_sha != pending.artifact_sha256: raise ApplicationUpdateError("installed artifact failed exact-byte verification") + discard_apply_handoff(root) except Exception as apply_error: try: candidate.unlink() From 899fb7def4d0f24820bd4516518643959b578ae7 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:13:31 +0200 Subject: [PATCH 035/118] R06: regress updater replay-authority disarm --- .../tests/test_application_update_updater.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 0d0ed3d09..0ac94ce9a 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -254,6 +254,73 @@ def fail_post_publish_hash(path: Path) -> str: old, ) + def test_consume_handoff_disarms_apply_authority_after_success(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, + ) as discard: + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + discard.assert_called_once_with(root) + self.assertEqual(target.read_bytes(), new) + + def test_consume_handoff_rolls_back_if_apply_authority_cannot_be_disarmed(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + side_effect=ApplicationUpdateError("forced disarm failure"), + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + def test_explicit_rollback_restores_exact_previous_bytes(self): old = b"previous exact executable" new = b"installed update" From 4916b1f3d094453d76447d9b0a5280a7df7fd043 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:14:30 +0200 Subject: [PATCH 036/118] R06: publish rollback backup atomically --- .../application_update_updater.py | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 86c9f119f..28e0083a6 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -80,11 +80,7 @@ def consume_apply_handoff( raise ApplicationUpdateError("apply handoff changed during publisher verification") rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) - _prepare_rollback_slot(rollback) - _copy_exact(target, rollback) - if _sha256_file(rollback) != previous_sha: - _discard_file(rollback) - raise ApplicationUpdateError("rollback copy failed exact-byte verification") + _publish_rollback_copy(target, rollback, previous_sha) candidate = target.with_name(f".{target.name}.update-{os.getpid()}.tmp") _prepare_temp_slot(candidate) @@ -169,16 +165,33 @@ def _rollback_replace(target: Path, rollback: Path, expected_sha: str) -> None: raise ApplicationUpdateError("rollback restoration failed exact-byte verification") -def _prepare_rollback_slot(path: Path) -> None: +def _publish_rollback_copy(source: Path, rollback: Path, expected_sha: str) -> None: try: - metadata = path.lstat() + metadata = rollback.lstat() except FileNotFoundError: - return + pass except OSError as exc: raise ApplicationUpdateError("rollback path is unavailable") from exc - if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): - raise ApplicationUpdateError("rollback path must not redirect update writes") - _discard_file(path) + else: + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("rollback path must not redirect update writes") + + temp = rollback.with_name(f".{rollback.name}.build-{os.getpid()}.tmp") + _prepare_temp_slot(temp) + try: + _copy_exact(source, temp) + if _sha256_file(temp) != expected_sha: + raise ApplicationUpdateError("rollback copy failed exact-byte verification") + os.replace(temp, rollback) + _fsync_directory(rollback.parent) + finally: + try: + temp.unlink() + except OSError: + pass + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(rollback) != expected_sha: + raise ApplicationUpdateError("published rollback copy failed exact-byte verification") def _prepare_temp_slot(path: Path) -> None: From 0ed162e304e7c244cf1710bfad9ec5ee61182bd9 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:14:32 +0200 Subject: [PATCH 037/118] R06: regress crash-safe rollback generation --- .../tests/test_application_update_updater.py | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 0ac94ce9a..738340656 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -63,6 +63,85 @@ def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(self): self.assertEqual(result.target_version, "1.1.0") self.assertEqual(result.rollback_path.read_bytes(), old) + def test_consume_handoff_atomically_replaces_prior_rollback_generation(self): + old = b"current pre-update executable" + older = b"older rollback generation" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + rollback.write_bytes(older) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), new) + self.assertEqual(rollback.read_bytes(), old) + + def test_failed_new_rollback_copy_preserves_prior_generation(self): + old = b"current pre-update executable" + older = b"older rollback generation" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + rollback.write_bytes(older) + staged.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_copy = updater_module._copy_exact + + def fail_backup_copy(source: Path, destination: Path) -> None: + if ".scripture-archive.rollback.build-" in destination.name: + raise ApplicationUpdateError("forced rollback copy failure") + real_copy(source, destination) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater._copy_exact", + side_effect=fail_backup_copy, + ): + with self.assertRaisesRegex(ApplicationUpdateError, "forced rollback copy failure"): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertEqual(rollback.read_bytes(), older) + def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): old = b"old" new = b"new" From b071dbf4c72404fb260271a2bf426d79d88bcbd2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:15:55 +0200 Subject: [PATCH 038/118] R06: serialize standalone updater across processes --- .../application_update_updater.py | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 28e0083a6..49cffdfa2 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -9,6 +9,7 @@ from __future__ import annotations +from contextlib import contextmanager from dataclasses import dataclass import hashlib import os @@ -41,6 +42,25 @@ def consume_apply_handoff( current_version: str, install_target: str | os.PathLike[str], verify_same_publisher: Callable[[Path, Path], bool], +) -> UpdateApplyResult: + """Serialize and consume one verified apply handoff across updater processes.""" + + root = Path(staging_root) + with _exclusive_update_lock(root): + return _consume_apply_handoff_locked( + root, + current_version=current_version, + install_target=install_target, + verify_same_publisher=verify_same_publisher, + ) + + +def _consume_apply_handoff_locked( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], + verify_same_publisher: Callable[[Path, Path], bool], ) -> UpdateApplyResult: """Atomically replace one installed executable from the fixed verified handoff. @@ -165,6 +185,66 @@ def _rollback_replace(target: Path, rollback: Path, expected_sha: str) -> None: raise ApplicationUpdateError("rollback restoration failed exact-byte verification") +@contextmanager +def _exclusive_update_lock(root: Path): + """Hold one non-blocking OS lock for the complete standalone apply transaction.""" + + _require_safe_parent(root) + lock_path = root / ".apply-update.lock" + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(lock_path, flags, 0o600) + except OSError as exc: + raise ApplicationUpdateError("updater lock could not be opened safely") from exc + + locked = False + try: + opened = os.fstat(descriptor) + linked = lock_path.lstat() + if ( + stat.S_ISLNK(linked.st_mode) + or not stat.S_ISREG(linked.st_mode) + or not stat.S_ISREG(opened.st_mode) + or (opened.st_dev, opened.st_ino) != (linked.st_dev, linked.st_ino) + ): + raise ApplicationUpdateError("updater lock path is unsafe") + if opened.st_size == 0: + os.write(descriptor, b"\0") + os.fsync(descriptor) + elif opened.st_size != 1: + raise ApplicationUpdateError("updater lock file has invalid size") + + try: + if os.name == "nt": + import msvcrt + + os.lseek(descriptor, 0, os.SEEK_SET) + msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except (OSError, BlockingIOError) as exc: + raise ApplicationUpdateError("another updater process already owns the apply lock") from exc + locked = True + yield + finally: + if locked: + try: + if os.name == "nt": + import msvcrt + + os.lseek(descriptor, 0, os.SEEK_SET) + msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(descriptor, fcntl.LOCK_UN) + except OSError: + pass + os.close(descriptor) + + def _publish_rollback_copy(source: Path, rollback: Path, expected_sha: str) -> None: try: metadata = rollback.lstat() From bcccd7cbbd3d5d936bf722e26983a62653a3204c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:20:21 +0200 Subject: [PATCH 039/118] R06: add host-only updater process orchestration --- .../application_update_process.py | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_process.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_process.py b/runtime_engine/scripture_archive_runtime/application_update_process.py new file mode 100644 index 000000000..6fd50fdc9 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_process.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +from dataclasses import dataclass +import os +from pathlib import Path +import subprocess +from typing import Callable, Sequence + + +class UpdateProcessError(RuntimeError): + """Fail-closed updater process orchestration error.""" + + +@dataclass(frozen=True) +class UpdaterProcessPlan: + """Host-owned immutable launch plan for the separate updater process. + + The browser never supplies any value represented here. The updater must + still independently re-open and verify its durable apply authority before + mutating installed bytes; this plan only separates the updater from the + application process that is about to exit. + """ + + updater_executable: Path + installed_executable: Path + staging_root: Path + parent_pid: int + + def argv(self) -> tuple[str, ...]: + return ( + str(self.updater_executable), + "--scripture-archive-apply", + "--wait-pid", + str(self.parent_pid), + "--installed-executable", + str(self.installed_executable), + "--staging-root", + str(self.staging_root), + ) + + +def _require_plain_file(path: Path, *, label: str) -> Path: + try: + path.lstat() + except OSError as exc: + raise UpdateProcessError(f"{label} is unavailable") from exc + if path.is_symlink() or not path.is_file(): + raise UpdateProcessError(f"{label} must be a regular non-symlink file") + try: + resolved = path.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError(f"{label} cannot be resolved") from exc + if not resolved.is_file(): + raise UpdateProcessError(f"{label} must resolve to a regular file") + return resolved + + +def _require_plain_directory(path: Path, *, label: str) -> Path: + try: + path.lstat() + except OSError as exc: + raise UpdateProcessError(f"{label} is unavailable") from exc + if path.is_symlink() or not path.is_dir(): + raise UpdateProcessError(f"{label} must be a real directory") + try: + resolved = path.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError(f"{label} cannot be resolved") from exc + if not resolved.is_dir(): + raise UpdateProcessError(f"{label} must resolve to a directory") + return resolved + + +def build_updater_process_plan( + *, + updater_executable: Path, + installed_executable: Path, + staging_root: Path, + parent_pid: int | None = None, +) -> UpdaterProcessPlan: + """Build a fixed host-side process handoff. + + The updater executable is required to be a sibling of the installed + application. This prevents PATH/current-directory substitution and keeps + the launch target inside the packaged installation boundary. The staging + root remains separate and is only an authority location; the updater core + is responsible for reconstructing and re-verifying candidate bytes from + the durable apply handoff. + """ + + updater = _require_plain_file(Path(updater_executable), label="updater executable") + installed = _require_plain_file(Path(installed_executable), label="installed executable") + staging = _require_plain_directory(Path(staging_root), label="staging root") + + if updater.parent != installed.parent: + raise UpdateProcessError("updater executable must be packaged beside the installed application") + if updater == installed: + raise UpdateProcessError("updater executable must be distinct from the installed application") + + current_pid = os.getpid() + effective_parent_pid = current_pid if parent_pid is None else parent_pid + if not isinstance(effective_parent_pid, int) or isinstance(effective_parent_pid, bool): + raise UpdateProcessError("parent pid must be an integer") + if effective_parent_pid <= 0: + raise UpdateProcessError("parent pid must be positive") + if effective_parent_pid != current_pid: + raise UpdateProcessError("parent pid must identify the current host process") + + return UpdaterProcessPlan( + updater_executable=updater, + installed_executable=installed, + staging_root=staging, + parent_pid=effective_parent_pid, + ) + + +def launch_updater_process( + plan: UpdaterProcessPlan, + *, + popen: Callable[..., object] = subprocess.Popen, + os_name: str | None = None, +) -> int: + """Launch the separate updater without shell interpretation. + + On Windows the process is detached into its own process group so it can + survive normal application shutdown. No browser transport command is + added and no arbitrary command-line suffix is accepted. + """ + + if not isinstance(plan, UpdaterProcessPlan): + raise UpdateProcessError("invalid updater process plan") + + creationflags = 0 + effective_os_name = os.name if os_name is None else os_name + if effective_os_name == "nt": + creationflags = ( + getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + | getattr(subprocess, "DETACHED_PROCESS", 0) + ) + + try: + child = popen( + list(plan.argv()), + cwd=str(plan.installed_executable.parent), + shell=False, + close_fds=True, + creationflags=creationflags, + ) + except Exception as exc: + raise UpdateProcessError("failed to launch updater process") from exc + + pid = getattr(child, "pid", None) + if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0: + raise UpdateProcessError("updater process did not return a valid pid") + return pid + + +def parse_trusted_updater_argv(argv: Sequence[str]) -> tuple[int, Path, Path]: + """Parse only the fixed updater command generated by ``UpdaterProcessPlan``. + + This is intentionally not a general CLI parser. Exact positional shape, + marker and flag order are part of the host/updater contract; extra flags or + duplicated options fail closed. The updater must subsequently apply the + same filesystem validation and durable-authority verification as its core. + """ + + values = tuple(argv) + if len(values) != 7: + raise UpdateProcessError("invalid updater command shape") + marker, wait_flag, wait_value, installed_flag, installed_value, staging_flag, staging_value = values + if marker != "--scripture-archive-apply": + raise UpdateProcessError("invalid updater command marker") + if wait_flag != "--wait-pid": + raise UpdateProcessError("invalid updater wait flag") + if installed_flag != "--installed-executable": + raise UpdateProcessError("invalid installed executable flag") + if staging_flag != "--staging-root": + raise UpdateProcessError("invalid staging root flag") + try: + parent_pid = int(wait_value, 10) + except (TypeError, ValueError) as exc: + raise UpdateProcessError("invalid parent pid") from exc + if parent_pid <= 0 or str(parent_pid) != wait_value: + raise UpdateProcessError("invalid parent pid") + if not installed_value or "\x00" in installed_value: + raise UpdateProcessError("invalid installed executable path") + if not staging_value or "\x00" in staging_value: + raise UpdateProcessError("invalid staging root path") + return parent_pid, Path(installed_value), Path(staging_value) From b323615085165b43e6ba8421045e7bd65ee62182 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:20:40 +0200 Subject: [PATCH 040/118] R06: cover updater process orchestration fail-closed semantics --- .../tests/test_application_update_process.py | 173 ++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_process.py diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py new file mode 100644 index 000000000..55390bc03 --- /dev/null +++ b/runtime_engine/tests/test_application_update_process.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +from pathlib import Path +import os + +import pytest + +from scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + build_updater_process_plan, + launch_updater_process, + parse_trusted_updater_argv, +) + + +def _files(tmp_path: Path) -> tuple[Path, Path, Path]: + install = tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return updater, app, staging + + +def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + assert plan.parent_pid == os.getpid() + assert plan.updater_executable == updater.resolve() + assert plan.installed_executable == app.resolve() + assert plan.staging_root == staging.resolve() + assert plan.argv() == ( + str(updater.resolve()), + "--scripture-archive-apply", + "--wait-pid", + str(os.getpid()), + "--installed-executable", + str(app.resolve()), + "--staging-root", + str(staging.resolve()), + ) + + +def test_build_plan_rejects_external_updater(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + external = tmp_path / "outside-updater.exe" + external.write_bytes(updater.read_bytes()) + with pytest.raises(UpdateProcessError, match="packaged beside"): + build_updater_process_plan( + updater_executable=external, + installed_executable=app, + staging_root=staging, + ) + + +def test_build_plan_rejects_current_app_as_updater(tmp_path: Path) -> None: + _, app, staging = _files(tmp_path) + with pytest.raises(UpdateProcessError, match="distinct"): + build_updater_process_plan( + updater_executable=app, + installed_executable=app, + staging_root=staging, + ) + + +def test_build_plan_rejects_symlinked_updater_target_and_staging(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + updater_link = updater.parent / "link-updater.exe" + staging_link = tmp_path / "state-link" + try: + updater_link.symlink_to(updater) + staging_link.symlink_to(staging, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks unavailable") + with pytest.raises(UpdateProcessError, match="non-symlink"): + build_updater_process_plan( + updater_executable=updater_link, + installed_executable=app, + staging_root=staging, + ) + with pytest.raises(UpdateProcessError, match="real directory"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging_link, + ) + + +def test_build_plan_rejects_foreign_parent_pid(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + with pytest.raises(UpdateProcessError, match="current host process"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + parent_pid=os.getpid() + 1, + ) + + +def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + seen: dict[str, object] = {} + + class Child: + pid = 43210 + + def fake_popen(argv, **kwargs): + seen["argv"] = argv + seen.update(kwargs) + return Child() + + pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") + assert pid == 43210 + assert seen["argv"] == list(plan.argv()) + assert seen["cwd"] == str(app.resolve().parent) + assert seen["shell"] is False + assert seen["close_fds"] is True + assert seen["creationflags"] == 0 + + +def test_launch_wraps_process_failure(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + + def broken_popen(*args, **kwargs): + raise OSError("boom") + + with pytest.raises(UpdateProcessError, match="failed to launch"): + launch_updater_process(plan, popen=broken_popen) + + +def test_parser_accepts_only_fixed_host_contract(tmp_path: Path) -> None: + updater, app, staging = _files(tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) + assert pid == os.getpid() + assert parsed_app == app.resolve() + assert parsed_staging == staging.resolve() + + +@pytest.mark.parametrize( + "argv", + [ + (), + ("--scripture-archive-apply",), + ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), + ], +) +def test_parser_rejects_noncanonical_or_extended_commands(argv: tuple[str, ...]) -> None: + with pytest.raises(UpdateProcessError): + parse_trusted_updater_argv(argv) From 9a4889968e328d1564b8bdfb670530262cf245d5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:22:22 +0200 Subject: [PATCH 041/118] R06: add 64-bit-safe Windows parent-exit barrier --- .../application_update_parent_wait.py | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_parent_wait.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py b/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py new file mode 100644 index 000000000..a802b2243 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_parent_wait.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import ctypes +from ctypes import wintypes +import os +from typing import Callable + + +class ParentProcessWaitError(RuntimeError): + """The updater could not prove that the application process exited.""" + + +_SYNCHRONIZE = 0x00100000 +_WAIT_OBJECT_0 = 0x00000000 +_WAIT_TIMEOUT = 0x00000102 +_WAIT_FAILED = 0xFFFFFFFF +_DEFAULT_TIMEOUT_MS = 120_000 + + +def _validate_parent_pid(parent_pid: int) -> int: + if not isinstance(parent_pid, int) or isinstance(parent_pid, bool) or parent_pid <= 0: + raise ParentProcessWaitError("parent pid must be a positive integer") + if parent_pid == os.getpid(): + raise ParentProcessWaitError("updater cannot wait on its own process") + return parent_pid + + +def _windows_wait_backend(parent_pid: int, timeout_ms: int) -> None: + try: + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + except (AttributeError, OSError) as exc: + raise ParentProcessWaitError("Windows synchronization API is unavailable") from exc + + open_process = kernel32.OpenProcess + open_process.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) + open_process.restype = wintypes.HANDLE + + wait_for_single_object = kernel32.WaitForSingleObject + wait_for_single_object.argtypes = (wintypes.HANDLE, wintypes.DWORD) + wait_for_single_object.restype = wintypes.DWORD + + close_handle = kernel32.CloseHandle + close_handle.argtypes = (wintypes.HANDLE,) + close_handle.restype = wintypes.BOOL + + handle = open_process(_SYNCHRONIZE, False, parent_pid) + if not handle: + raise ParentProcessWaitError("cannot open parent process for synchronization") + + try: + result = wait_for_single_object(handle, timeout_ms) + finally: + close_handle(handle) + + if result == _WAIT_OBJECT_0: + return + if result == _WAIT_TIMEOUT: + raise ParentProcessWaitError("parent process did not exit before timeout") + if result == _WAIT_FAILED: + raise ParentProcessWaitError("waiting for parent process failed") + raise ParentProcessWaitError("unexpected parent wait result") + + +def wait_for_parent_exit( + parent_pid: int, + *, + timeout_ms: int = _DEFAULT_TIMEOUT_MS, + wait_backend: Callable[[int, int], None] | None = None, + os_name: str | None = None, +) -> None: + """Prove that the old packaged application has exited before replacement. + + Production Windows execution uses the kernel process handle as the waitable + authority. There is deliberately no polling loop, sleep, process-name + lookup, shell command, or browser-controlled timeout. Tests may inject a + backend to verify ordering without weakening production behavior. + """ + + pid = _validate_parent_pid(parent_pid) + if not isinstance(timeout_ms, int) or isinstance(timeout_ms, bool): + raise ParentProcessWaitError("timeout must be an integer") + if timeout_ms <= 0 or timeout_ms > _DEFAULT_TIMEOUT_MS: + raise ParentProcessWaitError("timeout is outside the permitted bound") + + backend = wait_backend + if backend is None: + effective_os_name = os.name if os_name is None else os_name + if effective_os_name != "nt": + raise ParentProcessWaitError("native parent wait is Windows-only") + backend = _windows_wait_backend + + try: + backend(pid, timeout_ms) + except ParentProcessWaitError: + raise + except Exception as exc: + raise ParentProcessWaitError("parent process wait failed") from exc From 80cff7a6867bf88c160c86bf0a98ac1b206aac56 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:22:32 +0200 Subject: [PATCH 042/118] R06: cover updater parent-exit barrier semantics --- .../test_application_update_parent_wait.py | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_parent_wait.py diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py new file mode 100644 index 000000000..41e41fbc8 --- /dev/null +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import os + +import pytest + +from scripture_archive_runtime.application_update_parent_wait import ( + ParentProcessWaitError, + wait_for_parent_exit, +) + + +def test_wait_uses_exact_pid_and_bounded_timeout() -> None: + seen: list[tuple[int, int]] = [] + + def backend(pid: int, timeout_ms: int) -> None: + seen.append((pid, timeout_ms)) + + wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) + assert seen == [(4242, 30_000)] + + +def test_wait_rejects_own_pid_before_backend() -> None: + called = False + + def backend(pid: int, timeout_ms: int) -> None: + nonlocal called + called = True + + with pytest.raises(ParentProcessWaitError, match="own process"): + wait_for_parent_exit(os.getpid(), wait_backend=backend) + assert called is False + + +@pytest.mark.parametrize("pid", [0, -1, True, 1.5, "1"]) +def test_wait_rejects_invalid_pid(pid) -> None: + with pytest.raises(ParentProcessWaitError): + wait_for_parent_exit(pid, wait_backend=lambda *_: None) + + +@pytest.mark.parametrize("timeout_ms", [0, -1, 120_001, True, 1.5]) +def test_wait_rejects_invalid_or_unbounded_timeout(timeout_ms) -> None: + with pytest.raises(ParentProcessWaitError): + wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) + + +def test_wait_is_windows_only_without_injected_backend() -> None: + with pytest.raises(ParentProcessWaitError, match="Windows-only"): + wait_for_parent_exit(4242, os_name="posix") + + +def test_wait_wraps_backend_failure() -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise OSError("boom") + + with pytest.raises(ParentProcessWaitError, match="wait failed"): + wait_for_parent_exit(4242, wait_backend=backend) + + +def test_wait_preserves_fail_closed_backend_verdict() -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise ParentProcessWaitError("parent process did not exit before timeout") + + with pytest.raises(ParentProcessWaitError, match="did not exit"): + wait_for_parent_exit(4242, wait_backend=backend) From 42c9805dfc7ef7fd1abb979419ab6308583c0267 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:32:34 +0200 Subject: [PATCH 043/118] R06: wire trusted updater runner to atomic apply core --- .../application_update_runner.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_runner.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py new file mode 100644 index 000000000..ba4115e36 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -0,0 +1,67 @@ +"""Trusted standalone updater execution boundary. + +This module connects the fixed host-owned updater command from +``application_update_process`` to the bounded parent-exit barrier and the existing +atomic apply/rollback consumer. It is deliberately not exposed through browser +transport and does not introduce a second update implementation. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import TypeAlias + +from .application_update import ApplicationUpdateError, SemVer +from .application_update_parent_wait import wait_for_parent_exit +from .application_update_process import parse_trusted_updater_argv +from .application_update_updater import UpdateApplyResult, consume_apply_handoff + + +PublisherVerifier: TypeAlias = Callable[[Path, Path], bool] +ParentWaiter: TypeAlias = Callable[[int], None] +ApplyConsumer: TypeAlias = Callable[..., UpdateApplyResult] + + +def execute_trusted_updater( + argv: Sequence[str], + *, + current_version: str, + verify_same_publisher: PublisherVerifier, + wait_for_exit: Callable[..., None] = wait_for_parent_exit, + consume: Callable[..., UpdateApplyResult] = consume_apply_handoff, +) -> UpdateApplyResult: + """Execute one trusted updater invocation in fail-closed order. + + ``argv`` must be the exact fixed payload emitted by ``UpdaterProcessPlan`` with + the executable path already removed (``sys.argv[1:]``). ``current_version`` is + trusted updater/package identity, not browser input. The old application must + be proven exited before the atomic consumer can replace its executable. + + The existing consumer remains the sole authority for apply-intent readback, + exact staged-byte verification, same-publisher verification, rollback + preservation/publication and apply-authority disarm. + """ + + if not isinstance(current_version, str): + raise ApplicationUpdateError("trusted updater current version must be a string") + SemVer.parse(current_version) + if not callable(verify_same_publisher): + raise ApplicationUpdateError("same-publisher verifier is required") + if not callable(wait_for_exit): + raise ApplicationUpdateError("parent-exit waiter is required") + if not callable(consume): + raise ApplicationUpdateError("apply consumer is required") + + parent_pid, installed_executable, staging_root = parse_trusted_updater_argv(argv) + + # Ordering is security- and correctness-significant: never attempt replacement + # while the application process that owns the installed executable is alive. + wait_for_exit(parent_pid) + + return consume( + staging_root, + current_version=current_version, + install_target=installed_executable, + verify_same_publisher=verify_same_publisher, + ) From 36f2dbc5b790634a839fc2a4d96a01db695cebd0 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:32:52 +0200 Subject: [PATCH 044/118] R06: add fail-closed updater runner regressions --- .../tests/test_application_update_runner.py | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_runner.py diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py new file mode 100644 index 000000000..d9317eef9 --- /dev/null +++ b/runtime_engine/tests/test_application_update_runner.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +from pathlib import Path +import os + +import pytest + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError +from scripture_archive_runtime.application_update_process import ( + build_updater_process_plan, +) +from scripture_archive_runtime.application_update_runner import execute_trusted_updater +from scripture_archive_runtime.application_update_updater import UpdateApplyResult + + +def _plan(tmp_path: Path): + install = tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + ) + + +def test_runner_waits_for_exact_parent_before_forwarding_to_atomic_consumer(tmp_path: Path) -> None: + plan = _plan(tmp_path) + events: list[object] = [] + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_name(plan.installed_executable.name + ".scripture-archive.rollback"), + target_path=plan.installed_executable, + target_version="1.1.0", + ) + + def wait_for_exit(parent_pid: int) -> None: + events.append(("wait", parent_pid)) + + def consume(staging_root, **kwargs): + events.append(("consume", Path(staging_root), kwargs)) + return sentinel + + verifier = lambda installed, staged: True + result = execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=verifier, + wait_for_exit=wait_for_exit, + consume=consume, + ) + + assert result is sentinel + assert events[0] == ("wait", os.getpid()) + kind, staging, kwargs = events[1] + assert kind == "consume" + assert staging == plan.staging_root + assert kwargs == { + "current_version": "1.0.0", + "install_target": plan.installed_executable, + "verify_same_publisher": verifier, + } + + +def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: + plan = _plan(tmp_path) + consumed = False + + def blocked_wait(parent_pid: int) -> None: + raise ParentProcessWaitError("parent still alive") + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with pytest.raises(ParentProcessWaitError, match="parent still alive"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=blocked_wait, + consume=consume, + ) + assert consumed is False + + +def test_runner_rejects_malformed_command_before_wait_or_consume() -> None: + waited = False + consumed = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with pytest.raises(Exception): + execute_trusted_updater( + ("--scripture-archive-apply", "--wait-pid", "1"), + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + consume=consume, + ) + assert waited is False + assert consumed is False + + +@pytest.mark.parametrize("current_version", ["", "1", "01.0.0", "1.0", "1.0.0 "]) +def test_runner_rejects_invalid_trusted_current_version_before_wait( + tmp_path: Path, current_version: str +) -> None: + plan = _plan(tmp_path) + waited = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + with pytest.raises(ApplicationUpdateError): + execute_trusted_updater( + plan.argv()[1:], + current_version=current_version, + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + ) + assert waited is False + + +def test_runner_requires_callable_security_dependencies_before_wait(tmp_path: Path) -> None: + plan = _plan(tmp_path) + + with pytest.raises(ApplicationUpdateError, match="same-publisher verifier"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=None, # type: ignore[arg-type] + ) + + with pytest.raises(ApplicationUpdateError, match="parent-exit waiter"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=None, # type: ignore[arg-type] + ) + + with pytest.raises(ApplicationUpdateError, match="apply consumer"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + consume=None, # type: ignore[arg-type] + ) From 19e995b03da33cb906e7350af6244b70c2dbd632 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:33:14 +0200 Subject: [PATCH 045/118] R06: tighten updater runner malformed-command assertion --- runtime_engine/tests/test_application_update_runner.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index d9317eef9..8b6a80c77 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -8,6 +8,7 @@ from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError from scripture_archive_runtime.application_update_process import ( + UpdateProcessError, build_updater_process_plan, ) from scripture_archive_runtime.application_update_runner import execute_trusted_updater @@ -105,7 +106,7 @@ def consume(*args, **kwargs): consumed = True raise AssertionError("must not consume") - with pytest.raises(Exception): + with pytest.raises(UpdateProcessError, match="invalid updater command shape"): execute_trusted_updater( ("--scripture-archive-apply", "--wait-pid", "1"), current_version="1.0.0", From faec7470d720982e86b510ddece2379a825bf306 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:36:19 +0200 Subject: [PATCH 046/118] R06: add trusted post-update relaunch boundary --- .../application_update_relaunch.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_relaunch.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_relaunch.py b/runtime_engine/scripture_archive_runtime/application_update_relaunch.py new file mode 100644 index 000000000..c592e89db --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_relaunch.py @@ -0,0 +1,53 @@ +"""Trusted post-update application relaunch boundary. + +The standalone updater owns this boundary after a successful atomic apply. It launches +only the exact installed target returned by the canonical apply consumer, never a browser- +supplied command line, and never through a shell. +""" + +from __future__ import annotations + +import os +from pathlib import Path +import stat +import subprocess +from typing import Callable + +from .application_update import ApplicationUpdateError + + +ProcessSpawner = Callable[..., object] + + +def launch_installed_application( + install_target: str | os.PathLike[str], + *, + spawn: ProcessSpawner = subprocess.Popen, +) -> None: + """Launch the exact installed executable without shell interpretation. + + This proves the target is still a regular non-symlink file immediately before + process creation and fixes the child working directory to the real install + directory. Successful process creation is the only claim here; later health + confirmation remains a separate post-restart responsibility. + """ + + if not callable(spawn): + raise ApplicationUpdateError("application process spawner is required") + + target = Path(install_target) + try: + target_meta = target.lstat() + parent_meta = target.parent.lstat() + except OSError as exc: + raise ApplicationUpdateError("installed application could not be inspected for relaunch") from exc + + if stat.S_ISLNK(target_meta.st_mode) or not stat.S_ISREG(target_meta.st_mode): + raise ApplicationUpdateError("installed application relaunch target must be a regular non-symlink file") + if stat.S_ISLNK(parent_meta.st_mode) or not stat.S_ISDIR(parent_meta.st_mode): + raise ApplicationUpdateError("installed application directory must be a real directory") + + try: + spawn((str(target),), cwd=str(target.parent), close_fds=True) + except (OSError, ValueError) as exc: + raise ApplicationUpdateError("updated application process could not be started") from exc From c63d5da27c0f816d0dd05629ee50675349abbea7 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:36:33 +0200 Subject: [PATCH 047/118] R06: relaunch installed target and rollback failed spawn --- .../application_update_runner.py | 42 +++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py index ba4115e36..7d289ae3e 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_runner.py +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -15,12 +15,19 @@ from .application_update import ApplicationUpdateError, SemVer from .application_update_parent_wait import wait_for_parent_exit from .application_update_process import parse_trusted_updater_argv -from .application_update_updater import UpdateApplyResult, consume_apply_handoff +from .application_update_relaunch import launch_installed_application +from .application_update_updater import ( + UpdateApplyResult, + consume_apply_handoff, + rollback_installed_update, +) PublisherVerifier: TypeAlias = Callable[[Path, Path], bool] ParentWaiter: TypeAlias = Callable[[int], None] ApplyConsumer: TypeAlias = Callable[..., UpdateApplyResult] +ApplicationLauncher: TypeAlias = Callable[[Path], None] +RollbackConsumer: TypeAlias = Callable[..., str] def execute_trusted_updater( @@ -30,6 +37,8 @@ def execute_trusted_updater( verify_same_publisher: PublisherVerifier, wait_for_exit: Callable[..., None] = wait_for_parent_exit, consume: Callable[..., UpdateApplyResult] = consume_apply_handoff, + launch: ApplicationLauncher = launch_installed_application, + rollback: RollbackConsumer = rollback_installed_update, ) -> UpdateApplyResult: """Execute one trusted updater invocation in fail-closed order. @@ -40,7 +49,10 @@ def execute_trusted_updater( The existing consumer remains the sole authority for apply-intent readback, exact staged-byte verification, same-publisher verification, rollback - preservation/publication and apply-authority disarm. + preservation/publication and apply-authority disarm. After a successful apply, + only the exact installed target returned by that consumer is relaunched. If + process creation itself fails, the already-preserved prior bytes are restored + before the failure is surfaced. """ if not isinstance(current_version, str): @@ -52,6 +64,10 @@ def execute_trusted_updater( raise ApplicationUpdateError("parent-exit waiter is required") if not callable(consume): raise ApplicationUpdateError("apply consumer is required") + if not callable(launch): + raise ApplicationUpdateError("application launcher is required") + if not callable(rollback): + raise ApplicationUpdateError("rollback consumer is required") parent_pid, installed_executable, staging_root = parse_trusted_updater_argv(argv) @@ -59,9 +75,29 @@ def execute_trusted_updater( # while the application process that owns the installed executable is alive. wait_for_exit(parent_pid) - return consume( + result = consume( staging_root, current_version=current_version, install_target=installed_executable, verify_same_publisher=verify_same_publisher, ) + if result.target_path != installed_executable: + raise ApplicationUpdateError("apply consumer returned an unexpected install target") + + try: + launch(result.target_path) + except Exception as launch_error: + try: + rollback( + result.target_path, + expected_previous_sha256=result.previous_sha256, + ) + except Exception as rollback_error: + raise ApplicationUpdateError( + "updated application relaunch failed and rollback also failed" + ) from rollback_error + raise ApplicationUpdateError( + "updated application relaunch failed; rollback restored prior bytes" + ) from launch_error + + return result From 63b101c45c1f15ac2091aa75c1d197c2338843f5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:37:00 +0200 Subject: [PATCH 048/118] R06: cover relaunch ordering and failed-spawn rollback --- .../tests/test_application_update_runner.py | 106 +++++++++++++++++- 1 file changed, 102 insertions(+), 4 deletions(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index 8b6a80c77..99e9ca151 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -31,10 +31,8 @@ def _plan(tmp_path: Path): ) -def test_runner_waits_for_exact_parent_before_forwarding_to_atomic_consumer(tmp_path: Path) -> None: - plan = _plan(tmp_path) - events: list[object] = [] - sentinel = UpdateApplyResult( +def _result(plan) -> UpdateApplyResult: + return UpdateApplyResult( previous_sha256="1" * 64, installed_sha256="2" * 64, rollback_path=plan.installed_executable.with_name(plan.installed_executable.name + ".scripture-archive.rollback"), @@ -42,6 +40,12 @@ def test_runner_waits_for_exact_parent_before_forwarding_to_atomic_consumer(tmp_ target_version="1.1.0", ) + +def test_runner_waits_applies_then_relaunches_exact_installed_target(tmp_path: Path) -> None: + plan = _plan(tmp_path) + events: list[object] = [] + sentinel = _result(plan) + def wait_for_exit(parent_pid: int) -> None: events.append(("wait", parent_pid)) @@ -49,6 +53,9 @@ def consume(staging_root, **kwargs): events.append(("consume", Path(staging_root), kwargs)) return sentinel + def launch(target: Path) -> None: + events.append(("launch", target)) + verifier = lambda installed, staged: True result = execute_trusted_updater( plan.argv()[1:], @@ -56,6 +63,7 @@ def consume(staging_root, **kwargs): verify_same_publisher=verifier, wait_for_exit=wait_for_exit, consume=consume, + launch=launch, ) assert result is sentinel @@ -68,6 +76,80 @@ def consume(staging_root, **kwargs): "install_target": plan.installed_executable, "verify_same_publisher": verifier, } + assert events[2] == ("launch", plan.installed_executable) + + +def test_runner_rolls_back_when_updated_process_cannot_be_started(tmp_path: Path) -> None: + plan = _plan(tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def launch(target: Path) -> None: + events.append(("launch", target)) + raise ApplicationUpdateError("spawn failed") + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with pytest.raises(ApplicationUpdateError, match="rollback restored prior bytes"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + launch=launch, + rollback=rollback, + ) + + assert events == [ + ("launch", plan.installed_executable), + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ] + + +def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) -> None: + plan = _plan(tmp_path) + sentinel = _result(plan) + + with pytest.raises(ApplicationUpdateError, match="relaunch failed and rollback also failed"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), + rollback=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("rollback failed")), + ) + + +def test_runner_rejects_consumer_target_substitution_before_launch(tmp_path: Path) -> None: + plan = _plan(tmp_path) + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_suffix(".rollback"), + target_path=tmp_path / "other.exe", + target_version="1.1.0", + ) + launched = False + + def launch(target: Path) -> None: + nonlocal launched + launched = True + + with pytest.raises(ApplicationUpdateError, match="unexpected install target"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + launch=launch, + ) + assert launched is False def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: @@ -164,3 +246,19 @@ def test_runner_requires_callable_security_dependencies_before_wait(tmp_path: Pa verify_same_publisher=lambda installed, staged: True, consume=None, # type: ignore[arg-type] ) + + with pytest.raises(ApplicationUpdateError, match="application launcher"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + launch=None, # type: ignore[arg-type] + ) + + with pytest.raises(ApplicationUpdateError, match="rollback consumer"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + rollback=None, # type: ignore[arg-type] + ) From 5b8063bbf7d6b119c635935c44f55a576dcdd7cf Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:37:10 +0200 Subject: [PATCH 049/118] R06: test trusted exact-target relaunch boundary --- .../tests/test_application_update_relaunch.py | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_relaunch.py diff --git a/runtime_engine/tests/test_application_update_relaunch.py b/runtime_engine/tests/test_application_update_relaunch.py new file mode 100644 index 000000000..0f631ea48 --- /dev/null +++ b/runtime_engine/tests/test_application_update_relaunch.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_relaunch import launch_installed_application + + +def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(tmp_path: Path) -> None: + install = tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + target = install / "Scripture Archive.exe" + target.write_bytes(b"updated") + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + + def spawn(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + + launch_installed_application(target, spawn=spawn) + + assert calls == [ + ((str(target),), {"cwd": str(install), "close_fds": True}), + ] + + +def test_relaunch_rejects_symlink_target_before_spawn(tmp_path: Path) -> None: + real = tmp_path / "real.exe" + real.write_bytes(b"updated") + target = tmp_path / "Scripture Archive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + pytest.skip("symlinks unavailable") + spawned = False + + def spawn(*args, **kwargs): + nonlocal spawned + spawned = True + + with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): + launch_installed_application(target, spawn=spawn) + assert spawned is False + + +def test_relaunch_translates_process_creation_failure(tmp_path: Path) -> None: + target = tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + + def spawn(*args, **kwargs): + raise OSError("cannot execute") + + with pytest.raises(ApplicationUpdateError, match="could not be started"): + launch_installed_application(target, spawn=spawn) + + +def test_relaunch_requires_callable_spawner(tmp_path: Path) -> None: + target = tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + + with pytest.raises(ApplicationUpdateError, match="process spawner"): + launch_installed_application(target, spawn=None) # type: ignore[arg-type] From f45b188786f0f20b5e3f3b21394f60ae77b8e738 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:38:11 +0200 Subject: [PATCH 050/118] R06: rollback unexpected post-apply target substitution --- .../application_update_runner.py | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py index 7d289ae3e..f8fcbf1a4 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_runner.py +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -50,9 +50,9 @@ def execute_trusted_updater( The existing consumer remains the sole authority for apply-intent readback, exact staged-byte verification, same-publisher verification, rollback preservation/publication and apply-authority disarm. After a successful apply, - only the exact installed target returned by that consumer is relaunched. If - process creation itself fails, the already-preserved prior bytes are restored - before the failure is surfaced. + only the exact installed target returned by that consumer is relaunched. Any + detected target substitution or process-creation failure restores the already- + preserved prior bytes before the failure is surfaced. """ if not isinstance(current_version, str): @@ -82,14 +82,25 @@ def execute_trusted_updater( verify_same_publisher=verify_same_publisher, ) if result.target_path != installed_executable: - raise ApplicationUpdateError("apply consumer returned an unexpected install target") + try: + rollback( + installed_executable, + expected_previous_sha256=result.previous_sha256, + ) + except Exception as rollback_error: + raise ApplicationUpdateError( + "apply consumer returned an unexpected install target and rollback failed" + ) from rollback_error + raise ApplicationUpdateError( + "apply consumer returned an unexpected install target; rollback restored prior bytes" + ) try: - launch(result.target_path) + launch(installed_executable) except Exception as launch_error: try: rollback( - result.target_path, + installed_executable, expected_previous_sha256=result.previous_sha256, ) except Exception as rollback_error: From 590288f9fa7729b578bbe6a61749448a6cb84660 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:38:55 +0200 Subject: [PATCH 051/118] R06: prove target-substitution rollback uses parsed install target --- .../tests/test_application_update_runner.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index 99e9ca151..fe54c9a02 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -125,7 +125,7 @@ def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) ) -def test_runner_rejects_consumer_target_substitution_before_launch(tmp_path: Path) -> None: +def test_runner_rolls_back_consumer_target_substitution_before_launch(tmp_path: Path) -> None: plan = _plan(tmp_path) sentinel = UpdateApplyResult( previous_sha256="1" * 64, @@ -134,13 +134,16 @@ def test_runner_rejects_consumer_target_substitution_before_launch(tmp_path: Pat target_path=tmp_path / "other.exe", target_version="1.1.0", ) - launched = False + events: list[object] = [] def launch(target: Path) -> None: - nonlocal launched - launched = True + events.append(("launch", target)) - with pytest.raises(ApplicationUpdateError, match="unexpected install target"): + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with pytest.raises(ApplicationUpdateError, match="unexpected install target; rollback restored"): execute_trusted_updater( plan.argv()[1:], current_version="1.0.0", @@ -148,8 +151,9 @@ def launch(target: Path) -> None: wait_for_exit=lambda parent_pid: None, consume=lambda *args, **kwargs: sentinel, launch=launch, + rollback=rollback, ) - assert launched is False + assert events == [("rollback", plan.installed_executable, sentinel.previous_sha256)] def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: From f95acaf1f2e753a23af0ccb548ae64b6e22f131a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:43:22 +0200 Subject: [PATCH 052/118] R06: centralize host-owned packaged application version --- .../scripture_archive_platform/desktop_host/version.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py new file mode 100644 index 000000000..7cafc6a31 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/version.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +# Semantic compatibility version for the current R06-3DEV-A packaged lineage. +# This is host-owned release identity. Update manifests/browser payloads must never +# select or override it. +CURRENT_APPLICATION_VERSION = "0.6.0-r06.3dev.a" From 82721e2114cc9d5afd8a5972831074af992e397c Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:43:33 +0200 Subject: [PATCH 053/118] R06: add packaged standalone updater entrypoint --- .../desktop_host/updater_main.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py new file mode 100644 index 000000000..f14446bc3 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from collections.abc import Callable, Sequence +import sys +from typing import Any + +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION +from runtime_engine.scripture_archive_runtime.application_update_runner import ( + execute_trusted_updater, +) + + +UPDATER_OK = 0 +UPDATER_FAILED = 2 + + +def run_updater( + argv: Sequence[str], + *, + execute: Callable[..., Any] = execute_trusted_updater, + verifier: Callable[..., bool] = verify_same_publisher_authenticode, +) -> int: + """Run one fixed updater command with packaged trust authorities. + + The semantic current version and Authenticode verifier are imported from the + packaged native host. No browser/web payload can select either authority. Error + details are intentionally not echoed because argv contains local filesystem paths. + """ + + if not callable(execute) or not callable(verifier): + return UPDATER_FAILED + try: + execute( + tuple(argv), + current_version=CURRENT_APPLICATION_VERSION, + verify_same_publisher=verifier, + ) + except Exception: + return UPDATER_FAILED + return UPDATER_OK + + +def main() -> int: + return run_updater(sys.argv[1:]) + + +if __name__ == "__main__": + raise SystemExit(main()) From 65052610ac7ae80286a1fbc2668fca285c702149 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:43:44 +0200 Subject: [PATCH 054/118] R06: share host-owned version with packaged updater --- .../scripture_archive_platform/desktop_host/main.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) 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 2decc0ad6..258844627 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 @@ -12,10 +12,7 @@ NativeApplicationUpdateLayer, NativeUpdateFileSelector, ) - -# Semantic compatibility version for the current R06-3DEV-A packaged lineage. -# It is deliberately host-owned rather than supplied by an update manifest/web payload. -CURRENT_APPLICATION_VERSION = "0.6.0-r06.3dev.a" +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION def _runtime_root() -> Path: From 80f2da96412e4031bb61eb820c0d60896d204a07 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:44:19 +0200 Subject: [PATCH 055/118] R06: package standalone updater with release artifact evidence --- .../packaging/build_windows.ps1 | 56 ++++++++++++++++--- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 index 6bccead6b..613f1bfa7 100644 --- a/lanes/dev1/repair_overlay/packaging/build_windows.ps1 +++ b/lanes/dev1/repair_overlay/packaging/build_windows.ps1 @@ -79,9 +79,13 @@ Assert-NativeSuccess "packaged payload manifest generation" $Sep = ";" $Name = "ScriptureArchive-R06-DEV01" +$UpdaterName = "$Name-Updater" $Out = Join-Path $Dist "$Name.exe" -if (Test-Path -LiteralPath $Out) { - Remove-Item -LiteralPath $Out -Force +$UpdaterOut = Join-Path $Dist "$UpdaterName.exe" +foreach ($artifact in @($Out, $UpdaterOut)) { + if (Test-Path -LiteralPath $artifact) { + Remove-Item -LiteralPath $artifact -Force + } } try { & (Join-Path $Venv "Scripts\pyinstaller.exe") --noconfirm --clean --onefile --windowed ` @@ -98,7 +102,14 @@ try { --paths $PlatformRoot --paths $Repo ` --distpath $Dist --workpath $Work --specpath $Spec ` (Join-Path $PlatformRoot "run_windows.py") - Assert-NativeSuccess "PyInstaller build" + Assert-NativeSuccess "PyInstaller application build" + + & (Join-Path $Venv "Scripts\pyinstaller.exe") --noconfirm --clean --onefile --windowed ` + --name $UpdaterName ` + --paths $PlatformRoot --paths $Repo ` + --distpath $Dist --workpath $Work --specpath $Spec ` + (Join-Path $PlatformRoot "scripture_archive_platform\desktop_host\updater_main.py") + Assert-NativeSuccess "PyInstaller updater build" } finally { Remove-Item -LiteralPath $BuildIdentityDir -Recurse -Force -ErrorAction SilentlyContinue } @@ -106,6 +117,9 @@ try { if (-not (Test-Path -LiteralPath $Out -PathType Leaf)) { throw "Expected executable not produced: $Out" } +if (-not (Test-Path -LiteralPath $UpdaterOut -PathType Leaf)) { + throw "Expected updater executable not produced: $UpdaterOut" +} $PayloadReadback = Join-Path $Dist "packaged_payload_fidelity.json" & $Python $FidelityTool verify ` @@ -116,6 +130,8 @@ Assert-NativeSuccess "embedded packaged payload fidelity verification" $hash = (Get-FileHash -Algorithm SHA256 $Out).Hash.ToLowerInvariant() $size = (Get-Item $Out).Length +$updaterHash = (Get-FileHash -Algorithm SHA256 $UpdaterOut).Hash.ToLowerInvariant() +$updaterSize = (Get-Item $UpdaterOut).Length $payloadEvidenceHash = (Get-FileHash -Algorithm SHA256 $PayloadReadback).Hash.ToLowerInvariant() $pythonVersion = (& $Python --version 2>&1 | Out-String).Trim() Assert-NativeSuccess "Python version query" @@ -126,6 +142,10 @@ $manifest = [ordered]@{ artifact_path = $Out size_bytes = $size sha256 = $hash + updater_artifact_name = (Split-Path -Leaf $UpdaterOut) + updater_artifact_path = $UpdaterOut + updater_size_bytes = $updaterSize + updater_sha256 = $updaterHash built_utc = (Get-Date).ToUniversalTime().ToString("o") git_sha = $actualGitSha github_event_sha = $env:GITHUB_SHA @@ -137,19 +157,20 @@ $manifest = [ordered]@{ packaged_payload_fidelity_file = (Split-Path -Leaf $PayloadReadback) packaged_payload_fidelity_sha256 = $payloadEvidenceHash proof_scope = @( - "PyInstaller build completed", - "artifact size/hash readback verified", + "PyInstaller application and standalone updater builds completed", + "application and updater artifact size/hash readback verified", "embedded frontend/campaign/build-identity bytes verified against exact staged manifest", "Git-tracked embedded frontend overlay/campaign bytes verified against exact checkout Git blob IDs", "WebView2 runtime presence probed before build", "packaged diagnostics build identity bound to exact checkout SHA" ) not_proven = @( + "production Authenticode signing identity is configured", "Python module bytecode identity inside PYZ", "human NVDA acceptance", "full application functional acceptance", "visual correctness", - "recovery execution" + "post-restart health commit" ) } $ManifestPath = Join-Path $Dist "build_manifest.json" @@ -157,11 +178,32 @@ $manifest | ConvertTo-Json -Depth 6 | Set-Content -Encoding utf8 $ManifestPath "SHA256=$hash" | Set-Content -Encoding utf8 (Join-Path $Dist "$Name.sha256.txt") "SIZE=$size" | Add-Content -Encoding utf8 (Join-Path $Dist "$Name.sha256.txt") +"SHA256=$updaterHash" | Set-Content -Encoding utf8 (Join-Path $Dist "$UpdaterName.sha256.txt") +"SIZE=$updaterSize" | Add-Content -Encoding utf8 (Join-Path $Dist "$UpdaterName.sha256.txt") & $Python (Join-Path $PSScriptRoot "windows_release.py") verify-artifact ` --artifact $Out ` --manifest $ManifestPath ` --output (Join-Path $Dist "artifact_readback.json") -Assert-NativeSuccess "artifact verification" +Assert-NativeSuccess "application artifact verification" + +$UpdaterManifestPath = Join-Path $Dist "updater_build_manifest.json" +$updaterManifest = [ordered]@{ + schema_version = 1 + artifact_name = (Split-Path -Leaf $UpdaterOut) + artifact_path = $UpdaterOut + size_bytes = $updaterSize + sha256 = $updaterHash + git_sha = $actualGitSha + application_version_authority = "scripture_archive_platform.desktop_host.version.CURRENT_APPLICATION_VERSION" + authenticode_authority = "scripture_archive_platform.desktop_host.authenticode.verify_same_publisher_authenticode" +} +$updaterManifest | ConvertTo-Json -Depth 4 | Set-Content -Encoding utf8 $UpdaterManifestPath +& $Python (Join-Path $PSScriptRoot "windows_release.py") verify-artifact ` + --artifact $UpdaterOut ` + --manifest $UpdaterManifestPath ` + --output (Join-Path $Dist "updater_artifact_readback.json") +Assert-NativeSuccess "updater artifact verification" Write-Output "Built $Out ($size bytes) SHA256=$hash" +Write-Output "Built $UpdaterOut ($updaterSize bytes) SHA256=$updaterHash" From 5da88d4d4d638c5e3ef81ceede95c724a9bd86a6 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:44:36 +0200 Subject: [PATCH 056/118] R06: qualify packaged updater trust wiring --- .../tests/test_packaged_updater_entrypoint.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py new file mode 100644 index 000000000..8e03685d3 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import unittest + +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) +from scripture_archive_platform.desktop_host.updater_main import ( + UPDATER_FAILED, + UPDATER_OK, + run_updater, +) +from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION + + +class PackagedUpdaterEntrypointTests(unittest.TestCase): + def test_forwards_fixed_argv_with_host_owned_version_and_canonical_authenticode(self) -> None: + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + + def execute(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + + argv = ( + "--scripture-archive-apply", + "--wait-pid", + "41", + "--installed-executable", + r"C:\Program Files\Scripture Archive\ScriptureArchive-R06-DEV01.exe", + "--staging-root", + r"C:\Users\user\AppData\Local\ScriptureArchive\application-updates", + ) + result = run_updater(argv, execute=execute) + + self.assertEqual(result, UPDATER_OK) + self.assertEqual(len(calls), 1) + forwarded, kwargs = calls[0] + self.assertEqual(forwarded, argv) + self.assertEqual(kwargs["current_version"], CURRENT_APPLICATION_VERSION) + self.assertIs(kwargs["verify_same_publisher"], verify_same_publisher_authenticode) + + def test_failure_is_fail_closed_without_retrying_or_rewriting_argv(self) -> None: + calls = 0 + + def execute(argv, **kwargs): + nonlocal calls + calls += 1 + raise ValueError("local path detail must not escape through entrypoint") + + self.assertEqual(run_updater(("bad",), execute=execute), UPDATER_FAILED) + self.assertEqual(calls, 1) + + def test_requires_callable_execution_and_verifier_authorities(self) -> None: + self.assertEqual(run_updater((), execute=None), UPDATER_FAILED) # type: ignore[arg-type] + self.assertEqual(run_updater((), verifier=None), UPDATER_FAILED) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() From 784ec4c514620179fac1fe3efdc6f2d91a33302f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:46:33 +0200 Subject: [PATCH 057/118] R06: qualify standalone updater artifact in canonical release gate --- .../packaging/run_windows_release_gate.ps1 | 55 +++++++++++++++++-- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 b/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 index 76b994a2f..b2fde64da 100644 --- a/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 +++ b/lanes/dev1/repair_overlay/packaging/run_windows_release_gate.ps1 @@ -11,10 +11,14 @@ $OverlayTests = Join-Path $Repo "lanes\dev1\repair_overlay\tests" $Dist = Join-Path $PlatformRoot "dist" $Name = "ScriptureArchive-R06-DEV01" $Exe = Join-Path $Dist "$Name.exe" +$UpdaterExe = Join-Path $Dist "$Name-Updater.exe" $BuildManifest = Join-Path $Dist "build_manifest.json" +$UpdaterBuildManifest = Join-Path $Dist "updater_build_manifest.json" $Diagnostics = Join-Path $Dist "windows_release_diagnostics.json" $WebView2Probe = Join-Path $Dist "webview2_host_probe.json" $StartupProbe = Join-Path $Dist "packaged_startup_probe.json" +$ArtifactReadback = Join-Path $Dist "artifact_readback.json" +$UpdaterArtifactReadback = Join-Path $Dist "updater_artifact_readback.json" if (-not $OutputJson) { $OutputJson = Join-Path $Dist "release_gate.json" } $result = [ordered]@{ @@ -31,6 +35,7 @@ $result = [ordered]@{ tools_smoke = $false build = $false artifact_readback = $false + updater_artifact_readback = $false webview2_detected = $false webview2_host_probe = $false process_liveness = $false @@ -38,8 +43,13 @@ $result = [ordered]@{ running_without_admin = $false artifact_sha256 = $null artifact_size_bytes = $null + updater_artifact_sha256 = $null + updater_artifact_size_bytes = $null status = "RUNNING" not_proven = @( + "production Authenticode signing identity/private key", + "host launch/shutdown handoff to standalone updater", + "post-restart health commit/rollback cleanup", "human NVDA acceptance", "complete functional WebView UI acceptance", "packaged application's own WebView2 content-ready signal", @@ -105,19 +115,54 @@ try { } & (Join-Path $PSScriptRoot "build_windows.ps1") - if (-not (Test-Path $Exe) -or -not (Test-Path $BuildManifest) -or -not (Test-Path $Diagnostics)) { - throw "Build did not produce the complete expected evidence set" + if ( + -not (Test-Path -LiteralPath $Exe -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterExe -PathType Leaf) -or + -not (Test-Path -LiteralPath $BuildManifest -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterBuildManifest -PathType Leaf) -or + -not (Test-Path -LiteralPath $ArtifactReadback -PathType Leaf) -or + -not (Test-Path -LiteralPath $UpdaterArtifactReadback -PathType Leaf) -or + -not (Test-Path -LiteralPath $Diagnostics -PathType Leaf) + ) { + throw "Build did not produce the complete application + updater evidence set" } $result.build = $true $build = Get-Content -Raw -Encoding utf8 $BuildManifest | ConvertFrom-Json + $updaterBuild = Get-Content -Raw -Encoding utf8 $UpdaterBuildManifest | ConvertFrom-Json $diag = Get-Content -Raw -Encoding utf8 $Diagnostics | ConvertFrom-Json - $readbackPath = Join-Path $Dist "artifact_readback.json" - $readback = Get-Content -Raw -Encoding utf8 $readbackPath | ConvertFrom-Json - if (-not $readback.ok) { throw "Artifact hash/size readback did not pass" } + $readback = Get-Content -Raw -Encoding utf8 $ArtifactReadback | ConvertFrom-Json + $updaterReadback = Get-Content -Raw -Encoding utf8 $UpdaterArtifactReadback | ConvertFrom-Json + if (-not $readback.ok) { throw "Application artifact hash/size readback did not pass" } + if (-not $updaterReadback.ok) { throw "Updater artifact hash/size readback did not pass" } + + $actualUpdaterHash = (Get-FileHash -LiteralPath $UpdaterExe -Algorithm SHA256).Hash.ToLowerInvariant() + $actualUpdaterSize = (Get-Item -LiteralPath $UpdaterExe).Length + if ($build.updater_artifact_name -ne (Split-Path -Leaf $UpdaterExe)) { + throw "Main build manifest updater artifact name does not match packaged updater" + } + if ([string]$build.updater_sha256 -ne [string]$updaterBuild.sha256) { + throw "Updater SHA differs between build manifests" + } + if ([long]$build.updater_size_bytes -ne [long]$updaterBuild.size_bytes) { + throw "Updater size differs between build manifests" + } + if ([string]$updaterBuild.sha256 -ne $actualUpdaterHash) { + throw "Updater SHA manifest does not match exact packaged updater bytes" + } + if ([long]$updaterBuild.size_bytes -ne [long]$actualUpdaterSize) { + throw "Updater size manifest does not match exact packaged updater bytes" + } + if ([string]$updaterReadback.actual_sha256 -ne $actualUpdaterHash -or [long]$updaterReadback.actual_size_bytes -ne [long]$actualUpdaterSize) { + throw "Updater artifact readback evidence is detached from exact packaged updater bytes" + } + $result.artifact_readback = $true + $result.updater_artifact_readback = $true $result.artifact_sha256 = $build.sha256 $result.artifact_size_bytes = $build.size_bytes + $result.updater_artifact_sha256 = $actualUpdaterHash + $result.updater_artifact_size_bytes = $actualUpdaterSize $result.webview2_detected = @($diag.webview2_candidates).Count -gt 0 $result.per_user_state_writable = [bool]$diag.state_write_probe.writable $result.running_without_admin = ($diag.is_admin -eq $false) From 0a1d2b46040f32752af959bf8dbf724ef41bb7f1 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:48:45 +0200 Subject: [PATCH 058/118] R06: bind host launch to canonical same-publisher updater --- .../desktop_host/updater_launch.py | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py new file mode 100644 index 000000000..c2c19f9dd --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from collections.abc import Callable +import os +from pathlib import Path +import sys + +from runtime_engine.scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + UpdaterProcessPlan, + build_updater_process_plan, + launch_updater_process, +) +from scripture_archive_platform.desktop_host.authenticode import ( + verify_same_publisher_authenticode, +) + + +PublisherVerifier = Callable[[Path, Path], bool] +PlanBuilder = Callable[..., UpdaterProcessPlan] +ProcessLauncher = Callable[[UpdaterProcessPlan], int] + + +def packaged_updater_path(installed_executable: Path) -> Path: + """Derive the fixed sibling updater name from the packaged executable identity.""" + + installed = Path(installed_executable) + if installed.suffix.casefold() != ".exe": + raise UpdateProcessError("installed packaged executable must have .exe suffix") + return installed.with_name(f"{installed.stem}-Updater{installed.suffix}") + + +def launch_packaged_updater( + staging_root: str | os.PathLike[str], + *, + current_executable: str | os.PathLike[str] | None = None, + verify_same_publisher: PublisherVerifier = verify_same_publisher_authenticode, + build_plan: PlanBuilder = build_updater_process_plan, + launch_process: ProcessLauncher = launch_updater_process, +) -> int: + """Verify and launch only the canonical same-publisher sibling updater. + + The browser supplies none of these values. The installed executable defaults to + the currently running packaged process, the updater path is mechanically derived + beside it, and the existing Authenticode authority must positively prove that + current host and updater share a valid signer before #245's fixed process plan is + constructed or launched. + """ + + if not callable(verify_same_publisher): + raise UpdateProcessError("same-publisher verifier is required") + if not callable(build_plan): + raise UpdateProcessError("updater process-plan builder is required") + if not callable(launch_process): + raise UpdateProcessError("updater process launcher is required") + + installed = Path(sys.executable if current_executable is None else current_executable) + updater = packaged_updater_path(installed) + try: + trusted_updater = bool(verify_same_publisher(installed, updater)) + except Exception as exc: + raise UpdateProcessError("packaged updater authenticity could not be verified") from exc + if not trusted_updater: + raise UpdateProcessError("packaged updater same-publisher authenticity is required") + + plan = build_plan( + updater_executable=updater, + installed_executable=installed, + staging_root=Path(staging_root), + ) + return launch_process(plan) From 83aa50edebf02ee93ad4b43fc075134a9c777117 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:49:15 +0200 Subject: [PATCH 059/118] R06: add explicit apply-and-restart native execution boundary --- .../desktop_host/pending_update.py | 87 +++++++++++++++++-- 1 file changed, 79 insertions(+), 8 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index 384a29015..58ca76948 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -17,9 +17,15 @@ PENDING_UPDATE_STATUS_COMMAND = "application_update.pending_status" PREPARE_APPLY_COMMAND = "application_update.prepare_apply" +APPLY_AND_RESTART_COMMAND = "application_update.apply_and_restart" CANCEL_PENDING_UPDATE_COMMAND = "application_update.cancel_pending" _PENDING_COMMANDS = frozenset( - {PENDING_UPDATE_STATUS_COMMAND, PREPARE_APPLY_COMMAND, CANCEL_PENDING_UPDATE_COMMAND} + { + PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, + APPLY_AND_RESTART_COMMAND, + CANCEL_PENDING_UPDATE_COMMAND, + } ) _UPDATE_COMMAND_FAMILY = frozenset( { @@ -27,18 +33,20 @@ "application_update.select_verify_stage", PENDING_UPDATE_STATUS_COMMAND, PREPARE_APPLY_COMMAND, + APPLY_AND_RESTART_COMMAND, CANCEL_PENDING_UPDATE_COMMAND, } ) class NativePendingUpdateLayer: - """Expose serialized fixed-path staged-update recovery and apply handoff. + """Expose serialized fixed-path staged-update recovery and apply execution. The outer packaged-host lock serializes the complete application-update command - family so staging, status, prepare-apply and cancellation cannot publish - contradictory durable state. Prepare-apply only creates a host-owned intent; it - does not replace, execute, install or restart application bytes. + family so staging, status, prepare-apply, execution and cancellation cannot + publish contradictory durable state. Execution remains two-step: the browser may + request only an empty-payload action after a matching durable apply handoff exists; + all paths, process identity, updater identity and shutdown behavior stay native. """ def __init__( @@ -49,6 +57,8 @@ def __init__( *, current_version: str, authenticity_verifier: Callable[[Path], bool] | None = None, + apply_executor: Callable[[], int] | None = None, + shutdown_request: Callable[[], None] | None = None, ) -> None: self._app = app self._repo_root = Path(repo_root).resolve() @@ -59,8 +69,25 @@ def __init__( if authenticity_verifier is not None else self._default_authenticity_verifier ) + self._apply_executor = apply_executor + self._shutdown_request = shutdown_request self._operation_lock = threading.RLock() + def bind_apply_execution( + self, + apply_executor: Callable[[], int], + shutdown_request: Callable[[], None], + ) -> None: + """Bind host-owned launch/shutdown callbacks after the native window exists.""" + + if not callable(apply_executor): + raise ValueError("apply executor must be callable") + if not callable(shutdown_request): + raise ValueError("shutdown request must be callable") + with self._operation_lock: + self._apply_executor = apply_executor + self._shutdown_request = shutdown_request + def handle(self, request: Any) -> dict[str, Any]: if not isinstance(request, dict): return self._app.handle(request) @@ -85,7 +112,9 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: inspect_pending_update, staged_artifact_path, discard_pending_update = ( self._load_pending_core() ) - prepare_apply_handoff, discard_apply_handoff = self._load_apply_core() + prepare_apply_handoff, inspect_apply_handoff, discard_apply_handoff = ( + self._load_apply_core() + ) if command == CANCEL_PENDING_UPDATE_COMMAND: apply_removed = discard_apply_handoff(self._staging_root) @@ -162,6 +191,47 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: }, ) + if command == APPLY_AND_RESTART_COMMAND: + if not callable(self._apply_executor) or not callable(self._shutdown_request): + return error_response( + rid, + "UPDATE_EXECUTION_UNAVAILABLE", + "Packaged updater execution is unavailable in this host.", + ) + handoff = inspect_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if handoff is None or handoff != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_REQUIRED", + "A current verified apply handoff is required before restart.", + ) + updater_pid = self._apply_executor() + if not isinstance(updater_pid, int) or isinstance(updater_pid, bool) or updater_pid <= 0: + raise ValueError("packaged updater launch did not return a valid process id") + self._shutdown_request() + return ok_response( + rid, + { + "pending": True, + "status": "updater_started", + "product_id": handoff.product_id, + "target_platform": handoff.target_platform, + "current_version": handoff.current_version, + "target_version": handoff.target_version, + "source_head": handoff.source_head, + "artifact_name": handoff.artifact_name, + "artifact_size": handoff.artifact_size, + "artifact_sha256": handoff.artifact_sha256, + "authenticity": handoff.authenticity, + "installation_performed": False, + "updater_process_started": True, + "restart_requested": True, + }, + ) + return ok_response( rid, { @@ -213,13 +283,14 @@ def _load_pending_core(self) -> tuple[Any, Any, Any]: return inspect_pending_update, staged_artifact_path, discard_pending_update - def _load_apply_core(self) -> tuple[Any, Any]: + def _load_apply_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) from runtime_engine.scripture_archive_runtime.application_update_apply import ( discard_apply_handoff, + inspect_apply_handoff, prepare_apply_handoff, ) - return prepare_apply_handoff, discard_apply_handoff + return prepare_apply_handoff, inspect_apply_handoff, discard_apply_handoff From 6f7fef84568592d8a4440509f764c0b159cb98b5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:49:34 +0200 Subject: [PATCH 060/118] R06: bind packaged updater launch and host shutdown --- .../scripture_archive_platform/desktop_host/main.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) 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 258844627..3e216a445 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 @@ -12,6 +12,7 @@ NativeApplicationUpdateLayer, NativeUpdateFileSelector, ) +from scripture_archive_platform.desktop_host.updater_launch import launch_packaged_updater from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION @@ -59,15 +60,15 @@ def main() -> int: staging_root=staging_root, ) # This outer layer owns one process-local RLock for the complete update command - # family, so verify/stage/status/cancel cannot race the shared pending journal. - app = NativePendingUpdateLayer( + # family, so verify/stage/status/cancel/execute cannot race shared durable state. + pending_layer = NativePendingUpdateLayer( app, root, staging_root, current_version=CURRENT_APPLICATION_VERSION, ) app = NativeDiagnosticsLayer( - app, + pending_layer, root, Path(platform_app.store.root) / "runtime-v2", current_version=CURRENT_APPLICATION_VERSION, @@ -87,6 +88,10 @@ def main() -> int: text_select=True, ) selector.bind_window(window) + pending_layer.bind_apply_execution( + lambda: launch_packaged_updater(staging_root), + window.destroy, + ) logging.info("Starting EdgeChromium WebView; frontend=%s log=%s", front, log_path) webview.start(gui="edgechromium", debug=False, private_mode=True) return 0 From 536a521d2122d1d539707075f89fc417c400d35a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:50:17 +0200 Subject: [PATCH 061/118] R06: surface durable apply-ready authority across restarts --- .../desktop_host/pending_update.py | 95 +++++++++---------- 1 file changed, 43 insertions(+), 52 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index 58ca76948..acd3de63a 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -172,24 +172,7 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: "UPDATE_APPLY_HANDOFF_INVALID", "Apply handoff did not remain bound to the verified pending update.", ) - return ok_response( - rid, - { - "pending": True, - "status": "apply_ready", - "product_id": rebound.product_id, - "target_platform": rebound.target_platform, - "current_version": rebound.current_version, - "target_version": rebound.target_version, - "source_head": rebound.source_head, - "artifact_name": rebound.artifact_name, - "artifact_size": rebound.artifact_size, - "artifact_sha256": rebound.artifact_sha256, - "authenticity": rebound.authenticity, - "installation_performed": False, - "restart_performed": False, - }, - ) + return self._pending_response(rebound, status="apply_ready", restart_requested=False) if command == APPLY_AND_RESTART_COMMAND: if not callable(self._apply_executor) or not callable(self._shutdown_request): @@ -212,42 +195,28 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: if not isinstance(updater_pid, int) or isinstance(updater_pid, bool) or updater_pid <= 0: raise ValueError("packaged updater launch did not return a valid process id") self._shutdown_request() - return ok_response( - rid, - { - "pending": True, - "status": "updater_started", - "product_id": handoff.product_id, - "target_platform": handoff.target_platform, - "current_version": handoff.current_version, - "target_version": handoff.target_version, - "source_head": handoff.source_head, - "artifact_name": handoff.artifact_name, - "artifact_size": handoff.artifact_size, - "artifact_sha256": handoff.artifact_sha256, - "authenticity": handoff.authenticity, - "installation_performed": False, - "updater_process_started": True, - "restart_requested": True, - }, + response = self._pending_response( + handoff, + status="updater_started", + restart_requested=True, ) + response["data"]["updater_process_started"] = True + return response - return ok_response( - rid, - { - "pending": True, - "status": pending.status, - "product_id": pending.product_id, - "target_platform": pending.target_platform, - "current_version": pending.current_version, - "target_version": pending.target_version, - "source_head": pending.source_head, - "artifact_name": pending.artifact_name, - "artifact_size": pending.artifact_size, - "artifact_sha256": pending.artifact_sha256, - "authenticity": pending.authenticity, - "installation_performed": False, - }, + handoff = inspect_apply_handoff( + self._staging_root, + current_version=self._current_version, + ) + if handoff is not None and handoff != pending: + return error_response( + rid, + "UPDATE_APPLY_HANDOFF_INVALID", + "Apply handoff is detached from the current verified pending update.", + ) + return self._pending_response( + pending, + status="apply_ready" if handoff == pending else pending.status, + restart_requested=False, ) except ValueError: return error_response( @@ -268,6 +237,28 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: "Pending application update recovery failed closed.", ) + @staticmethod + def _pending_response(pending: Any, *, status: str, restart_requested: bool) -> dict[str, Any]: + return ok_response( + "pending-native", + { + "pending": True, + "status": status, + "product_id": pending.product_id, + "target_platform": pending.target_platform, + "current_version": pending.current_version, + "target_version": pending.target_version, + "source_head": pending.source_head, + "artifact_name": pending.artifact_name, + "artifact_size": pending.artifact_size, + "artifact_sha256": pending.artifact_sha256, + "authenticity": pending.authenticity, + "installation_performed": False, + "restart_performed": False, + "restart_requested": restart_requested, + }, + ) + def _default_authenticity_verifier(self, candidate: Path) -> bool: return verify_same_publisher_authenticode(Path(sys.executable), candidate) From 12d82b483b629a3773330a111773d4ce08175f61 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:50:48 +0200 Subject: [PATCH 062/118] R06: preserve exact request identity in update responses --- .../desktop_host/pending_update.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py index acd3de63a..7086bd5cf 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/pending_update.py @@ -172,7 +172,12 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: "UPDATE_APPLY_HANDOFF_INVALID", "Apply handoff did not remain bound to the verified pending update.", ) - return self._pending_response(rebound, status="apply_ready", restart_requested=False) + return self._pending_response( + rid, + rebound, + status="apply_ready", + restart_requested=False, + ) if command == APPLY_AND_RESTART_COMMAND: if not callable(self._apply_executor) or not callable(self._shutdown_request): @@ -196,6 +201,7 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: raise ValueError("packaged updater launch did not return a valid process id") self._shutdown_request() response = self._pending_response( + rid, handoff, status="updater_started", restart_requested=True, @@ -214,6 +220,7 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: "Apply handoff is detached from the current verified pending update.", ) return self._pending_response( + rid, pending, status="apply_ready" if handoff == pending else pending.status, restart_requested=False, @@ -238,9 +245,15 @@ def _handle_pending(self, request: dict[str, Any]) -> dict[str, Any]: ) @staticmethod - def _pending_response(pending: Any, *, status: str, restart_requested: bool) -> dict[str, Any]: + def _pending_response( + request_id: str, + pending: Any, + *, + status: str, + restart_requested: bool, + ) -> dict[str, Any]: return ok_response( - "pending-native", + request_id, { "pending": True, "status": status, From c0e5a32accef8fde499803e1a470eaba41071724 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:51:34 +0200 Subject: [PATCH 063/118] R06: expose accessible explicit install-and-restart action --- .../repair_overlay/frontend/pending-update.js | 58 ++++++++++++++----- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js index 4c0e6d7a5..9dce1c7a2 100644 --- a/lanes/dev1/repair_overlay/frontend/pending-update.js +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -1,6 +1,7 @@ const API_VERSION='scripture.transport.v1'; const STATUS_COMMAND='application_update.pending_status'; const PREPARE_APPLY_COMMAND='application_update.prepare_apply'; +const APPLY_AND_RESTART_COMMAND='application_update.apply_and_restart'; const CANCEL_COMMAND='application_update.cancel_pending'; const $=id=>document.getElementById(id); let sequence=0; @@ -30,11 +31,18 @@ async function invoke(command){ } function setBusy(busy){ - for(const id of ['pending-update-check','pending-update-prepare-apply','pending-update-cancel']){ - const button=$(id);if(button)button.disabled=busy; + for(const id of ['pending-update-check','pending-update-prepare-apply','pending-update-apply-restart','pending-update-cancel']){ + const button=$(id);if(button)button.disabled=busy||(id==='pending-update-apply-restart'&&button.dataset.ready!=='true'); } } +function setApplyReady(ready){ + const button=$('pending-update-apply-restart'); + if(!button)return; + button.dataset.ready=ready?'true':'false'; + button.disabled=!ready; +} + function clearDetails(){$('pending-update-details')?.replaceChildren()} function renderPending(data){ @@ -42,7 +50,7 @@ function renderPending(data){ if(!host||data.pending!==true)return; host.replaceChildren(); const rows=[ - ['Статус',data.status==='apply_ready'?'Намір встановлення підготовлено; заміна ще не виконана':'Підготовлено, але не встановлено'], + ['Статус',data.status==='apply_ready'?'Намір встановлення підготовлено; можна встановити й перезапустити':'Підготовлено, але не встановлено'], ['Продукт',data.product_id],['Платформа',data.target_platform], ['Поточна версія',data.current_version],['Цільова версія',data.target_version], ['Source head',data.source_head],['Файл пакета',data.artifact_name], @@ -57,32 +65,51 @@ async function checkPending({startup=false}={}){ if(!startup)setStatus('Повторно перевіряю підготовлене оновлення.'); try{ const data=await invoke(STATUS_COMMAND); - if(data.pending===true&&data.status==='staged'){ + if(data.pending===true&&(data.status==='staged'||data.status==='apply_ready')){ renderPending(data); - setStatus(`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); + const ready=data.status==='apply_ready'; + setApplyReady(ready); + setStatus(ready + ?`Захищений намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} відновлено й повторно перевірено. Можна встановити та перезапустити програму.` + :`Підготовлене оновлення ${data.artifact_name??'пакет'} → ${data.target_version??'цільова версія'} повторно перевірено. Воно ще не встановлене.`); }else if(data.pending===false&&data.status==='none'){ + setApplyReady(false); setStatus('Підготовленого оновлення немає.',{global:!startup}); }else throw new Error('Отримано неочікуваний стан.'); }catch(error){ - clearDetails(); + clearDetails();setApplyReady(false); setStatus(`Pending update не підтверджено: ${error?.message||'невідома помилка'}`); }finally{setBusy(false)} } async function prepareApply(){ - setBusy(true);setStatus('Повторно перевіряю пакет і готую захищений намір встановлення.'); + setBusy(true);setApplyReady(false);setStatus('Повторно перевіряю пакет і готую захищений намір встановлення.'); try{ const data=await invoke(PREPARE_APPLY_COMMAND); if(data.pending===true&&data.status==='apply_ready'&&data.installation_performed===false){ - renderPending(data); - setStatus(`Намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} підготовлено. Файли програми ще не замінювались і перезапуск не виконувався.`); + renderPending(data);setApplyReady(true); + setStatus(`Намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} підготовлено. Файли програми ще не замінювались. Окрема кнопка «Встановити й перезапустити» запускає підписаний native updater.`); }else throw new Error('Підготовку apply handoff не підтверджено.'); - }catch(error){setStatus(`Не вдалося безпечно підготувати встановлення: ${error?.message||'невідома помилка'}`)} + }catch(error){setApplyReady(false);setStatus(`Не вдалося безпечно підготувати встановлення: ${error?.message||'невідома помилка'}`)} finally{setBusy(false)} } +async function applyAndRestart(){ + setBusy(true); + setStatus('Запускаю перевірений native updater. Програма закриється; updater дочекається завершення цього процесу, встановить точні повторно перевірені байти й запустить програму знову.'); + try{ + const data=await invoke(APPLY_AND_RESTART_COMMAND); + if(data.pending===true&&data.status==='updater_started'&&data.updater_process_started===true&&data.restart_requested===true){ + setStatus('Native updater запущено. Завершую поточну програму для безпечного встановлення та перезапуску.'); + }else throw new Error('Запуск native updater не підтверджено.'); + }catch(error){ + setStatus(`Не вдалося безпечно запустити встановлення: ${error?.message||'невідома помилка'}`); + setBusy(false); + } +} + async function cancelPending(){ - setBusy(true);clearDetails();setStatus('Скасовую підготовлений стан оновлення.'); + setBusy(true);clearDetails();setApplyReady(false);setStatus('Скасовую підготовлений стан оновлення.'); try{ const data=await invoke(CANCEL_COMMAND); if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ @@ -102,16 +129,17 @@ function mount(){ const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; - const help=element('p','Після запуску програма автоматично перевіряє приватний pending state. «Підготувати встановлення» створює лише захищений host-owned apply handoff для наступного окремого updater-кроку: воно не замінює файли і не перезапускає програму. Скасування прибирає pending/apply authority, але не виконує інсталяцію.'); + const help=element('p','Після запуску програма автоматично повторно перевіряє pending state. «Підготувати встановлення» створює захищений durable apply handoff. Лише після цього «Встановити й перезапустити» перевіряє packaged updater, запускає його окремим native процесом і закриває поточну програму. Browser не передає шляхів, PID або командного рядка updater.'); const actions=element('div');actions.className='action-row'; const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; - const apply=element('button','Підготувати встановлення');apply.type='button';apply.id='pending-update-prepare-apply'; + const prepare=element('button','Підготувати встановлення');prepare.type='button';prepare.id='pending-update-prepare-apply'; + const apply=element('button','Встановити й перезапустити');apply.type='button';apply.id='pending-update-apply-restart';apply.dataset.ready='false';apply.disabled=true; const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; - actions.append(check,apply,cancel); + actions.append(check,prepare,apply,cancel); const status=element('p','Очікую готовності native host для перевірки pending update.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); section.append(heading,help,actions,status,details);view.append(section); - check.addEventListener('click',()=>checkPending());apply.addEventListener('click',prepareApply);cancel.addEventListener('click',cancelPending); + check.addEventListener('click',()=>checkPending());prepare.addEventListener('click',prepareApply);apply.addEventListener('click',applyAndRestart);cancel.addEventListener('click',cancelPending); window.addEventListener('pywebviewready',startStartupCheck,{once:true}); if(typeof window.pywebview?.api?.invoke==='function')queueMicrotask(startStartupCheck); From 56eb145bc9f741d39f7c240a4156c45e32376105 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:52:19 +0200 Subject: [PATCH 064/118] R06: qualify host-owned updater launch and restart boundary --- .../test_packaged_updater_host_launch.py | 260 ++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py new file mode 100644 index 000000000..5098cedad --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from runtime_engine.scripture_archive_runtime.application_update import ApplicationUpdateManifest +from runtime_engine.scripture_archive_runtime.application_update_process import ( + UpdateProcessError, + UpdaterProcessPlan, +) +from runtime_engine.scripture_archive_runtime.application_update_staging import stage_local_update +from scripture_archive_platform.desktop_host.pending_update import ( + APPLY_AND_RESTART_COMMAND, + PENDING_UPDATE_STATUS_COMMAND, + PREPARE_APPLY_COMMAND, + NativePendingUpdateLayer, +) +from scripture_archive_platform.desktop_host.updater_launch import ( + launch_packaged_updater, + packaged_updater_path, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +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 runtime not found") + + +def request(command: str, payload=None, request_id: str = "host-launch-1"): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def handle(self, value): + return {"ok": True, "data": {"passthrough": value}} + + +class PackagedUpdaterLaunchBoundaryTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.install = self.root / "install" + self.install.mkdir() + self.current = self.install / "ScriptureArchive-R06-DEV01.exe" + self.current.write_bytes(b"current-host") + self.updater = self.install / "ScriptureArchive-R06-DEV01-Updater.exe" + self.updater.write_bytes(b"packaged-updater") + self.staging = self.root / "state" / "application-updates" + self.staging.mkdir(parents=True) + + def tearDown(self): + self.temp.cleanup() + + def test_fixed_updater_name_is_derived_from_installed_executable(self): + self.assertEqual(self.updater, packaged_updater_path(self.current)) + with self.assertRaises(UpdateProcessError): + packaged_updater_path(self.install / "not-an-executable") + + def test_same_publisher_is_required_before_plan_or_launch(self): + events = [] + + def verify(current, updater): + events.append(("verify", current, updater)) + return True + + def build_plan(**kwargs): + events.append(("plan", kwargs)) + return UpdaterProcessPlan( + updater_executable=kwargs["updater_executable"], + installed_executable=kwargs["installed_executable"], + staging_root=kwargs["staging_root"], + parent_pid=41, + ) + + def launch(plan): + events.append(("launch", plan)) + return 777 + + pid = launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verify, + build_plan=build_plan, + launch_process=launch, + ) + self.assertEqual(777, pid) + self.assertEqual(("verify", self.current, self.updater), events[0]) + self.assertEqual("plan", events[1][0]) + self.assertEqual(self.updater, events[1][1]["updater_executable"]) + self.assertEqual(self.current, events[1][1]["installed_executable"]) + self.assertEqual(self.staging, events[1][1]["staging_root"]) + self.assertEqual("launch", events[2][0]) + + def test_negative_or_failed_publisher_proof_never_builds_process_plan(self): + for verifier in ( + lambda current, updater: False, + lambda current, updater: (_ for _ in ()).throw(RuntimeError("unavailable")), + ): + built = [] + with self.subTest(verifier=verifier), self.assertRaises(UpdateProcessError): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verifier, + build_plan=lambda **kwargs: built.append(kwargs), + launch_process=lambda plan: 1, + ) + self.assertEqual([], built) + + +class PackagedUpdaterHostExecutionTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.staging = self.root / "application-updates" + self.artifact = self.root / "ScriptureArchive-0.6.1.exe" + self.artifact.write_bytes(b"host-execution-candidate") + digest = hashlib.sha256(self.artifact.read_bytes()).hexdigest() + manifest = ApplicationUpdateManifest.from_mapping( + { + "schema": "scripture.application-update.v1", + "product_id": "scripture-archive", + "target_platform": "windows-x64", + "target_version": "0.6.1", + "source_head": "f" * 40, + "artifact_name": self.artifact.name, + "artifact_size": self.artifact.stat().st_size, + "artifact_sha256": digest, + } + ) + stage_local_update( + manifest, + self.artifact, + self.staging, + current_version=CURRENT_VERSION, + same_publisher_authenticode_verified=True, + ) + + def tearDown(self): + self.temp.cleanup() + + def layer(self, events, *, pid=222): + return NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + apply_executor=lambda: events.append("launch") or pid, + shutdown_request=lambda: events.append("shutdown"), + ) + + def test_status_recovers_durable_apply_ready_with_exact_request_id(self): + events = [] + layer = self.layer(events) + prepared = layer.handle(request(PREPARE_APPLY_COMMAND, request_id="prepare-rid")) + self.assertTrue(prepared["ok"]) + self.assertEqual("prepare-rid", prepared["request_id"]) + + recovered = layer.handle(request(PENDING_UPDATE_STATUS_COMMAND, request_id="status-rid")) + self.assertTrue(recovered["ok"]) + self.assertEqual("status-rid", recovered["request_id"]) + self.assertEqual("apply_ready", recovered["data"]["status"]) + self.assertFalse(recovered["data"]["installation_performed"]) + self.assertEqual([], events) + + def test_explicit_execute_launches_before_shutdown_and_leaks_no_pid_or_path(self): + events = [] + layer = self.layer(events) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle(request(APPLY_AND_RESTART_COMMAND, request_id="execute-rid")) + self.assertTrue(response["ok"]) + self.assertEqual("execute-rid", response["request_id"]) + self.assertEqual(["launch", "shutdown"], events) + self.assertEqual("updater_started", response["data"]["status"]) + self.assertTrue(response["data"]["updater_process_started"]) + self.assertTrue(response["data"]["restart_requested"]) + self.assertFalse(response["data"]["installation_performed"]) + serialized = json.dumps(response, ensure_ascii=False) + self.assertNotIn("222", serialized) + self.assertNotIn(str(self.root), serialized) + self.assertNotIn("path", serialized) + + def test_execute_without_matching_handoff_never_launches_or_shuts_down(self): + events = [] + response = self.layer(events).handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_APPLY_HANDOFF_REQUIRED", response["error"]["code"]) + self.assertEqual([], events) + + def test_browser_payload_cannot_supply_process_or_path_authority(self): + events = [] + layer = self.layer(events) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle( + request( + APPLY_AND_RESTART_COMMAND, + {"pid": 1, "updater": r"C:\attacker.exe"}, + ) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual([], events) + + def test_invalid_child_pid_fails_closed_before_shutdown(self): + events = [] + layer = self.layer(events, pid=0) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + response = layer.handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_PENDING_INVALID", response["error"]["code"]) + self.assertEqual(["launch"], events) + + def test_execution_callbacks_can_be_bound_after_window_creation(self): + events = [] + layer = NativePendingUpdateLayer( + FakeBaseApplication(), + repository_root(), + self.staging, + current_version=CURRENT_VERSION, + authenticity_verifier=lambda candidate: True, + ) + unavailable = layer.handle(request(APPLY_AND_RESTART_COMMAND)) + self.assertFalse(unavailable["ok"]) + self.assertEqual("UPDATE_EXECUTION_UNAVAILABLE", unavailable["error"]["code"]) + layer.bind_apply_execution( + lambda: events.append("launch") or 333, + lambda: events.append("shutdown"), + ) + self.assertTrue(layer.handle(request(PREPARE_APPLY_COMMAND))["ok"]) + self.assertTrue(layer.handle(request(APPLY_AND_RESTART_COMMAND))["ok"]) + self.assertEqual(["launch", "shutdown"], events) + + def test_frontend_exposes_accessible_two_step_install_without_html_injection(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.apply_and_restart", script) + self.assertIn("pending-update-apply-restart", script) + self.assertIn("Встановити й перезапустити", script) + self.assertIn("button.disabled=true", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() From 630beb9dbf98a85b10e4d0765909c0f7215b9ca3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:54:59 +0200 Subject: [PATCH 065/118] R06: add durable post-update health receipt authority --- .../application_update_health.py | 329 ++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 runtime_engine/scripture_archive_runtime/application_update_health.py diff --git a/runtime_engine/scripture_archive_runtime/application_update_health.py b/runtime_engine/scripture_archive_runtime/application_update_health.py new file mode 100644 index 000000000..c45bcb445 --- /dev/null +++ b/runtime_engine/scripture_archive_runtime/application_update_health.py @@ -0,0 +1,329 @@ +"""Durable post-update health receipt for rollback-preserving application updates. + +The standalone updater publishes this fixed-path receipt only after exact-byte atomic +publication and before relaunch. The new packaged application can later prove that +its own executable/version and the preserved rollback bytes still match the receipt +before disarming stale pending authority and rollback recovery state. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import stat +from typing import Any + +from .application_update import ApplicationUpdateError, SemVer +from .application_update_pending import discard_pending_update + + +HEALTH_RECEIPT_SCHEMA = "scripture.application-update-health.v1" +_HEALTH_RECEIPT_NAME = "update-health.json" +_ROLLBACK_SUFFIX = ".scripture-archive.rollback" +_COPY_CHUNK = 1024 * 1024 +_RECEIPT_KEYS = frozenset( + { + "schema", + "status", + "previous_version", + "target_version", + "installed_executable_name", + "previous_sha256", + "installed_sha256", + } +) + + +@dataclass(frozen=True) +class UpdateHealthReceipt: + previous_version: str + target_version: str + installed_executable_name: str + previous_sha256: str + installed_sha256: str + + +def publish_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + previous_version: str, + target_version: str, + install_target: str | os.PathLike[str], + previous_sha256: str, + installed_sha256: str, +) -> UpdateHealthReceipt: + """Publish one fixed receipt after verifying installed and rollback exact bytes.""" + + SemVer.parse(previous_version) + SemVer.parse(target_version) + _require_sha256(previous_sha256) + _require_sha256(installed_sha256) + target = Path(install_target) + root = Path(staging_root) + _require_real_directory(root, "update staging root") + _require_regular_file(target, "installed application target") + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(target) != installed_sha256: + raise ApplicationUpdateError("installed bytes do not match health receipt identity") + if _sha256_file(rollback) != previous_sha256: + raise ApplicationUpdateError("rollback bytes do not match health receipt identity") + + receipt = UpdateHealthReceipt( + previous_version=previous_version, + target_version=target_version, + installed_executable_name=target.name, + previous_sha256=previous_sha256, + installed_sha256=installed_sha256, + ) + payload = _encode_receipt(receipt) + path = root / _HEALTH_RECEIPT_NAME + existing = _read_receipt_if_present(path) + if existing is not None: + if existing != receipt: + raise ApplicationUpdateError("existing update health receipt has different identity") + return receipt + _atomic_write(path, payload) + if _read_receipt(path) != receipt: + raise ApplicationUpdateError("published update health receipt failed readback") + return receipt + + +def inspect_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], +) -> UpdateHealthReceipt | None: + """Re-verify a receipt against the currently running version and exact files.""" + + SemVer.parse(current_version) + root = Path(staging_root) + _require_real_directory(root, "update staging root") + path = root / _HEALTH_RECEIPT_NAME + receipt = _read_receipt_if_present(path) + if receipt is None: + return None + target = Path(install_target) + if receipt.target_version != current_version: + raise ApplicationUpdateError("update health receipt target version is not current") + if receipt.installed_executable_name != target.name: + raise ApplicationUpdateError("update health receipt executable identity changed") + _require_regular_file(target, "installed application target") + rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + _require_regular_file(rollback, "rollback artifact") + if _sha256_file(target) != receipt.installed_sha256: + raise ApplicationUpdateError("installed application bytes changed before health commit") + if _sha256_file(rollback) != receipt.previous_sha256: + raise ApplicationUpdateError("rollback bytes changed before health commit") + return receipt + + +def commit_update_health_receipt( + staging_root: str | os.PathLike[str], + *, + current_version: str, + install_target: str | os.PathLike[str], +) -> UpdateHealthReceipt | None: + """Commit a proven healthy relaunch and disarm stale update recovery authority. + + The fixed pending journal is removed first without parsing its old-version identity. + The health receipt is then removed before the rollback artifact, so a crash during + cleanup can leave at most inert rollback bytes rather than live rollback authority. + """ + + receipt = inspect_update_health_receipt( + staging_root, + current_version=current_version, + install_target=install_target, + ) + if receipt is None: + return None + root = Path(staging_root) + target = Path(install_target) + discard_pending_update(root) + _discard_regular_file(root / _HEALTH_RECEIPT_NAME, "update health receipt") + _discard_regular_file( + target.with_name(target.name + _ROLLBACK_SUFFIX), + "rollback artifact", + ) + return receipt + + +def discard_update_health_receipt(staging_root: str | os.PathLike[str]) -> bool: + """Disarm only the fixed health receipt, leaving recovery bytes untouched.""" + + root = Path(staging_root) + _require_real_directory(root, "update staging root") + path = root / _HEALTH_RECEIPT_NAME + try: + metadata = path.lstat() + except FileNotFoundError: + return False + except OSError as exc: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("update health receipt must be a regular non-symlink file") + try: + path.unlink() + except OSError as exc: + raise ApplicationUpdateError("update health receipt could not be removed") from exc + return True + + +def _encode_receipt(receipt: UpdateHealthReceipt) -> bytes: + payload = { + "schema": HEALTH_RECEIPT_SCHEMA, + "status": "awaiting_health_commit", + "previous_version": receipt.previous_version, + "target_version": receipt.target_version, + "installed_executable_name": receipt.installed_executable_name, + "previous_sha256": receipt.previous_sha256, + "installed_sha256": receipt.installed_sha256, + } + return (json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + + +def _read_receipt_if_present(path: Path) -> UpdateHealthReceipt | None: + try: + path.lstat() + except FileNotFoundError: + return None + except OSError as exc: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + return _read_receipt(path) + + +def _read_receipt(path: Path) -> UpdateHealthReceipt: + _require_regular_file(path, "update health receipt") + try: + raw = path.read_bytes() + except OSError as exc: + raise ApplicationUpdateError("update health receipt could not be read") from exc + if len(raw) > 4096: + raise ApplicationUpdateError("update health receipt is unexpectedly large") + try: + payload: Any = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ApplicationUpdateError("update health receipt is invalid JSON") from exc + if not isinstance(payload, dict) or frozenset(payload) != _RECEIPT_KEYS: + raise ApplicationUpdateError("update health receipt shape is invalid") + if payload.get("schema") != HEALTH_RECEIPT_SCHEMA or payload.get("status") != "awaiting_health_commit": + raise ApplicationUpdateError("update health receipt schema/status is invalid") + fields = ( + payload.get("previous_version"), + payload.get("target_version"), + payload.get("installed_executable_name"), + payload.get("previous_sha256"), + payload.get("installed_sha256"), + ) + if not all(isinstance(value, str) for value in fields): + raise ApplicationUpdateError("update health receipt fields must be strings") + previous_version, target_version, executable_name, previous_sha, installed_sha = fields + SemVer.parse(previous_version) + SemVer.parse(target_version) + if not executable_name or Path(executable_name).name != executable_name: + raise ApplicationUpdateError("update health receipt executable name is invalid") + _require_sha256(previous_sha) + _require_sha256(installed_sha) + return UpdateHealthReceipt( + previous_version=previous_version, + target_version=target_version, + installed_executable_name=executable_name, + previous_sha256=previous_sha, + installed_sha256=installed_sha, + ) + + +def _atomic_write(path: Path, content: bytes) -> None: + temp = path.with_name(f".{path.name}.write-{os.getpid()}.tmp") + try: + metadata = temp.lstat() + except FileNotFoundError: + pass + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary path is unavailable") from exc + else: + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError("health receipt temporary path is unsafe") + try: + temp.unlink() + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary path could not be cleared") from exc + try: + descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except OSError as exc: + raise ApplicationUpdateError("health receipt temporary file could not be created") from exc + try: + with os.fdopen(descriptor, "wb", closefd=True) as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp, path) + _fsync_directory(path.parent) + except Exception: + try: + temp.unlink() + except OSError: + pass + raise + + +def _discard_regular_file(path: Path, label: str) -> None: + _require_regular_file(path, label) + try: + path.unlink() + except OSError as exc: + raise ApplicationUpdateError(f"{label} could not be removed") from exc + + +def _require_sha256(value: str) -> None: + if len(value) != 64 or any(ch not in "0123456789abcdef" for ch in value): + raise ApplicationUpdateError("update health SHA-256 identity is invalid") + + +def _require_regular_file(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + + +def _require_real_directory(path: Path, label: str) -> None: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a real directory") + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + while True: + chunk = handle.read(_COPY_CHUNK) + if not chunk: + break + digest.update(chunk) + except OSError as exc: + raise ApplicationUpdateError("update health artifact could not be hashed") from exc + return digest.hexdigest() + + +def _fsync_directory(path: Path) -> None: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) + try: + descriptor = os.open(path, flags) + except OSError: + return + try: + os.fsync(descriptor) + finally: + os.close(descriptor) From 7cedf9173cccd8731ee1894f16e1163ee8a15ddc Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:56:51 +0200 Subject: [PATCH 066/118] R06: preserve rollback through post-restart health receipt --- .../application_update_runner.py | 109 ++++++++++++------ 1 file changed, 73 insertions(+), 36 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py index f8fcbf1a4..45270373e 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_runner.py +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -13,6 +13,10 @@ from typing import TypeAlias from .application_update import ApplicationUpdateError, SemVer +from .application_update_health import ( + discard_update_health_receipt, + publish_update_health_receipt, +) from .application_update_parent_wait import wait_for_parent_exit from .application_update_process import parse_trusted_updater_argv from .application_update_relaunch import launch_installed_application @@ -24,10 +28,10 @@ PublisherVerifier: TypeAlias = Callable[[Path, Path], bool] -ParentWaiter: TypeAlias = Callable[[int], None] -ApplyConsumer: TypeAlias = Callable[..., UpdateApplyResult] ApplicationLauncher: TypeAlias = Callable[[Path], None] RollbackConsumer: TypeAlias = Callable[..., str] +HealthPublisher: TypeAlias = Callable[..., object] +HealthDiscarder: TypeAlias = Callable[[Path], bool] def execute_trusted_updater( @@ -35,44 +39,39 @@ def execute_trusted_updater( *, current_version: str, verify_same_publisher: PublisherVerifier, - wait_for_exit: Callable[..., None] = wait_for_parent_exit, + wait_for_exit: Callable[[int], None] = wait_for_parent_exit, consume: Callable[..., UpdateApplyResult] = consume_apply_handoff, launch: ApplicationLauncher = launch_installed_application, rollback: RollbackConsumer = rollback_installed_update, + publish_health: HealthPublisher = publish_update_health_receipt, + discard_health: HealthDiscarder = discard_update_health_receipt, ) -> UpdateApplyResult: """Execute one trusted updater invocation in fail-closed order. - ``argv`` must be the exact fixed payload emitted by ``UpdaterProcessPlan`` with - the executable path already removed (``sys.argv[1:]``). ``current_version`` is - trusted updater/package identity, not browser input. The old application must - be proven exited before the atomic consumer can replace its executable. - - The existing consumer remains the sole authority for apply-intent readback, - exact staged-byte verification, same-publisher verification, rollback - preservation/publication and apply-authority disarm. After a successful apply, - only the exact installed target returned by that consumer is relaunched. Any - detected target substitution or process-creation failure restores the already- - preserved prior bytes before the failure is surfaced. + The old application is proven exited before replacement. After canonical atomic + apply, a durable exact-byte health receipt is published before relaunch while the + prior rollback bytes still exist. The new application later commits that receipt + only after its packaged native/frontend bridge is healthy. If receipt publication + or process creation fails, the already-preserved prior bytes are restored and any + published receipt is disarmed before failure is surfaced. """ if not isinstance(current_version, str): raise ApplicationUpdateError("trusted updater current version must be a string") SemVer.parse(current_version) - if not callable(verify_same_publisher): - raise ApplicationUpdateError("same-publisher verifier is required") - if not callable(wait_for_exit): - raise ApplicationUpdateError("parent-exit waiter is required") - if not callable(consume): - raise ApplicationUpdateError("apply consumer is required") - if not callable(launch): - raise ApplicationUpdateError("application launcher is required") - if not callable(rollback): - raise ApplicationUpdateError("rollback consumer is required") + for dependency, label in ( + (verify_same_publisher, "same-publisher verifier"), + (wait_for_exit, "parent-exit waiter"), + (consume, "apply consumer"), + (launch, "application launcher"), + (rollback, "rollback consumer"), + (publish_health, "health receipt publisher"), + (discard_health, "health receipt discarder"), + ): + if not callable(dependency): + raise ApplicationUpdateError(f"{label} is required") parent_pid, installed_executable, staging_root = parse_trusted_updater_argv(argv) - - # Ordering is security- and correctness-significant: never attempt replacement - # while the application process that owns the installed executable is alive. wait_for_exit(parent_pid) result = consume( @@ -83,10 +82,7 @@ def execute_trusted_updater( ) if result.target_path != installed_executable: try: - rollback( - installed_executable, - expected_previous_sha256=result.previous_sha256, - ) + rollback(installed_executable, expected_previous_sha256=result.previous_sha256) except Exception as rollback_error: raise ApplicationUpdateError( "apply consumer returned an unexpected install target and rollback failed" @@ -95,18 +91,59 @@ def execute_trusted_updater( "apply consumer returned an unexpected install target; rollback restored prior bytes" ) + try: + publish_health( + staging_root, + previous_version=current_version, + target_version=result.target_version, + install_target=installed_executable, + previous_sha256=result.previous_sha256, + installed_sha256=result.installed_sha256, + ) + except Exception as health_error: + rollback_error: Exception | None = None + discard_error: Exception | None = None + try: + rollback(installed_executable, expected_previous_sha256=result.previous_sha256) + except Exception as exc: + rollback_error = exc + try: + discard_health(staging_root) + except Exception as exc: + discard_error = exc + if rollback_error is not None: + raise ApplicationUpdateError( + "health receipt publication failed and rollback also failed" + ) from rollback_error + if discard_error is not None: + raise ApplicationUpdateError( + "health receipt publication failed; rollback restored prior bytes but receipt disarm failed" + ) from discard_error + raise ApplicationUpdateError( + "health receipt publication failed; rollback restored prior bytes" + ) from health_error + try: launch(installed_executable) except Exception as launch_error: + rollback_error: Exception | None = None + discard_error: Exception | None = None try: - rollback( - installed_executable, - expected_previous_sha256=result.previous_sha256, - ) - except Exception as rollback_error: + rollback(installed_executable, expected_previous_sha256=result.previous_sha256) + except Exception as exc: + rollback_error = exc + try: + discard_health(staging_root) + except Exception as exc: + discard_error = exc + if rollback_error is not None: raise ApplicationUpdateError( "updated application relaunch failed and rollback also failed" ) from rollback_error + if discard_error is not None: + raise ApplicationUpdateError( + "updated application relaunch failed; rollback restored prior bytes but receipt disarm failed" + ) from discard_error raise ApplicationUpdateError( "updated application relaunch failed; rollback restored prior bytes" ) from launch_error From 55f4d2e29699dc97e6cf42f6daf17bf1b9fe197f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:57:31 +0200 Subject: [PATCH 067/118] R06: qualify health receipt ordering and recovery paths --- .../tests/test_application_update_runner.py | 147 ++++++++++++------ 1 file changed, 103 insertions(+), 44 deletions(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index fe54c9a02..e2599005e 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -41,7 +41,15 @@ def _result(plan) -> UpdateApplyResult: ) -def test_runner_waits_applies_then_relaunches_exact_installed_target(tmp_path: Path) -> None: +def _publish_noop(*args, **kwargs): + return object() + + +def _discard_noop(*args, **kwargs): + return False + + +def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(tmp_path: Path) -> None: plan = _plan(tmp_path) events: list[object] = [] sentinel = _result(plan) @@ -53,6 +61,10 @@ def consume(staging_root, **kwargs): events.append(("consume", Path(staging_root), kwargs)) return sentinel + def publish_health(staging_root, **kwargs): + events.append(("health", Path(staging_root), kwargs)) + return object() + def launch(target: Path) -> None: events.append(("launch", target)) @@ -63,6 +75,8 @@ def launch(target: Path) -> None: verify_same_publisher=verifier, wait_for_exit=wait_for_exit, consume=consume, + publish_health=publish_health, + discard_health=_discard_noop, launch=launch, ) @@ -76,14 +90,62 @@ def launch(target: Path) -> None: "install_target": plan.installed_executable, "verify_same_publisher": verifier, } - assert events[2] == ("launch", plan.installed_executable) + kind, staging, kwargs = events[2] + assert kind == "health" + assert staging == plan.staging_root + assert kwargs == { + "previous_version": "1.0.0", + "target_version": "1.1.0", + "install_target": plan.installed_executable, + "previous_sha256": sentinel.previous_sha256, + "installed_sha256": sentinel.installed_sha256, + } + assert events[3] == ("launch", plan.installed_executable) + + +def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(tmp_path: Path) -> None: + plan = _plan(tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True -def test_runner_rolls_back_when_updated_process_cannot_be_started(tmp_path: Path) -> None: + def launch(target: Path) -> None: + events.append(("launch", target)) + + with pytest.raises(ApplicationUpdateError, match="health receipt publication failed; rollback restored"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("receipt failed")), + discard_health=discard, + rollback=rollback, + launch=launch, + ) + assert events == [ + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ] + + +def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(tmp_path: Path) -> None: plan = _plan(tmp_path) sentinel = _result(plan) events: list[object] = [] + def publish(staging_root, **kwargs): + events.append(("publish", Path(staging_root))) + return object() + def launch(target: Path) -> None: events.append(("launch", target)) raise ApplicationUpdateError("spawn failed") @@ -92,6 +154,10 @@ def rollback(target: Path, *, expected_previous_sha256: str) -> str: events.append(("rollback", target, expected_previous_sha256)) return expected_previous_sha256 + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + with pytest.raises(ApplicationUpdateError, match="rollback restored prior bytes"): execute_trusted_updater( plan.argv()[1:], @@ -99,13 +165,17 @@ def rollback(target: Path, *, expected_previous_sha256: str) -> str: verify_same_publisher=lambda installed, staged: True, wait_for_exit=lambda parent_pid: None, consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=discard, launch=launch, rollback=rollback, ) assert events == [ + ("publish", plan.staging_root), ("launch", plan.installed_executable), ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), ] @@ -120,12 +190,14 @@ def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) verify_same_publisher=lambda installed, staged: True, wait_for_exit=lambda parent_pid: None, consume=lambda *args, **kwargs: sentinel, + publish_health=_publish_noop, + discard_health=_discard_noop, launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), rollback=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("rollback failed")), ) -def test_runner_rolls_back_consumer_target_substitution_before_launch(tmp_path: Path) -> None: +def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(tmp_path: Path) -> None: plan = _plan(tmp_path) sentinel = UpdateApplyResult( previous_sha256="1" * 64, @@ -136,6 +208,9 @@ def test_runner_rolls_back_consumer_target_substitution_before_launch(tmp_path: ) events: list[object] = [] + def publish(*args, **kwargs): + events.append(("health",)) + def launch(target: Path) -> None: events.append(("launch", target)) @@ -150,6 +225,8 @@ def rollback(target: Path, *, expected_previous_sha256: str) -> str: verify_same_publisher=lambda installed, staged: True, wait_for_exit=lambda parent_pid: None, consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=_discard_noop, launch=launch, rollback=rollback, ) @@ -225,44 +302,26 @@ def wait_for_exit(parent_pid: int) -> None: assert waited is False -def test_runner_requires_callable_security_dependencies_before_wait(tmp_path: Path) -> None: +@pytest.mark.parametrize( + ("override", "message"), + [ + ({"verify_same_publisher": None}, "same-publisher verifier"), + ({"wait_for_exit": None}, "parent-exit waiter"), + ({"consume": None}, "apply consumer"), + ({"launch": None}, "application launcher"), + ({"rollback": None}, "rollback consumer"), + ({"publish_health": None}, "health receipt publisher"), + ({"discard_health": None}, "health receipt discarder"), + ], +) +def test_runner_requires_callable_security_dependencies_before_wait( + tmp_path: Path, override: dict[str, object], message: str +) -> None: plan = _plan(tmp_path) - - with pytest.raises(ApplicationUpdateError, match="same-publisher verifier"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=None, # type: ignore[arg-type] - ) - - with pytest.raises(ApplicationUpdateError, match="parent-exit waiter"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=None, # type: ignore[arg-type] - ) - - with pytest.raises(ApplicationUpdateError, match="apply consumer"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - consume=None, # type: ignore[arg-type] - ) - - with pytest.raises(ApplicationUpdateError, match="application launcher"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - launch=None, # type: ignore[arg-type] - ) - - with pytest.raises(ApplicationUpdateError, match="rollback consumer"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - rollback=None, # type: ignore[arg-type] - ) + kwargs = { + "current_version": "1.0.0", + "verify_same_publisher": lambda installed, staged: True, + } + kwargs.update(override) + with pytest.raises(ApplicationUpdateError, match=message): + execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] From ec72bec6009905cd66ff0d80f6f27bdfcfa02a7e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:57:56 +0200 Subject: [PATCH 068/118] R06: test durable post-restart health receipt lifecycle --- .../tests/test_application_update_health.py | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 runtime_engine/tests/test_application_update_health.py diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py new file mode 100644 index 000000000..e5fa9db77 --- /dev/null +++ b/runtime_engine/tests/test_application_update_health.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from scripture_archive_runtime.application_update import ApplicationUpdateError +from scripture_archive_runtime.application_update_health import ( + HEALTH_RECEIPT_SCHEMA, + commit_update_health_receipt, + discard_update_health_receipt, + inspect_update_health_receipt, + publish_update_health_receipt, +) + + +PREVIOUS_VERSION = "1.0.0" +TARGET_VERSION = "1.1.0" + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _fixture(tmp_path: Path): + root = tmp_path / "state" / "updates" + root.mkdir(parents=True) + target = tmp_path / "install" / "Scripture Archive.exe" + target.parent.mkdir() + previous = b"previous-installed-exact-bytes" + installed = b"updated-installed-exact-bytes" + target.write_bytes(installed) + rollback = target.with_name(target.name + ".scripture-archive.rollback") + rollback.write_bytes(previous) + return root, target, rollback, previous, installed + + +def _publish(tmp_path: Path): + root, target, rollback, previous, installed = _fixture(tmp_path) + receipt = publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version=TARGET_VERSION, + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + return root, target, rollback, previous, installed, receipt + + +def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + + assert receipt.previous_version == PREVIOUS_VERSION + assert receipt.target_version == TARGET_VERSION + assert receipt.installed_executable_name == target.name + assert receipt.previous_sha256 == _sha(previous) + assert receipt.installed_sha256 == _sha(installed) + assert inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) == receipt + + payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) + assert payload["schema"] == HEALTH_RECEIPT_SCHEMA + assert payload["status"] == "awaiting_health_commit" + serialized = json.dumps(payload) + assert str(tmp_path) not in serialized + assert "install_target" not in payload + assert "rollback_path" not in payload + + +def test_publish_is_idempotent_only_for_same_exact_identity(tmp_path: Path) -> None: + root, target, rollback, previous, installed, first = _publish(tmp_path) + before = (root / "update-health.json").read_bytes() + second = publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version=TARGET_VERSION, + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + assert second == first + assert (root / "update-health.json").read_bytes() == before + + with pytest.raises(ApplicationUpdateError, match="different identity"): + publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version="1.2.0", + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + + +def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + + with pytest.raises(ApplicationUpdateError, match="target version is not current"): + inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) + + target.write_bytes(b"x" * len(installed)) + with pytest.raises(ApplicationUpdateError, match="installed application bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + target.write_bytes(installed) + + rollback.write_bytes(b"y" * len(previous)) + with pytest.raises(ApplicationUpdateError, match="rollback bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + +def test_receipt_shape_extra_field_and_symlink_fail_closed(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + path = root / "update-health.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["unexpected"] = True + path.write_text(json.dumps(payload), encoding="utf-8") + with pytest.raises(ApplicationUpdateError, match="shape is invalid"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + path.unlink() + real = root / "real-health.json" + real.write_text("{}", encoding="utf-8") + try: + path.symlink_to(real) + except (OSError, NotImplementedError): + pytest.skip("symlinks unavailable") + with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + +def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal need not be parsed", encoding="utf-8") + + committed = commit_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + assert committed == receipt + assert not pending.exists() + assert not (root / "update-health.json").exists() + assert not rollback.exists() + assert target.read_bytes() == installed + + +def test_failed_health_proof_preserves_receipt_pending_and_rollback(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal", encoding="utf-8") + target.write_bytes(b"tampered") + + with pytest.raises(ApplicationUpdateError): + commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + assert pending.exists() + assert (root / "update-health.json").exists() + assert rollback.exists() + + +def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(tmp_path: Path) -> None: + root, target, rollback, previous, installed, receipt = _publish(tmp_path) + assert discard_update_health_receipt(root) is True + assert discard_update_health_receipt(root) is False + assert rollback.read_bytes() == previous + assert target.read_bytes() == installed From ebd45b7c0a2dd9bae52e90276a3df8ef28e29d8e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:58:15 +0200 Subject: [PATCH 069/118] R06: add host-owned post-restart health commit boundary --- .../desktop_host/post_update_health.py | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py new file mode 100644 index 000000000..0855a86c0 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/post_update_health.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from pathlib import Path +import sys +from typing import Any, Callable + +from runtime_engine.scripture_archive_runtime.application_update_health import ( + commit_update_health_receipt, +) +from scripture_archive_platform.transport.contracts import ( + error_response, + ok_response, + validate_request_shape, +) + + +POST_UPDATE_HEALTH_COMMAND = "application_update.commit_post_restart_health" + + +class NativePostUpdateHealthLayer: + """Commit rollback cleanup only after the relaunched packaged bridge is alive. + + The browser can request only this fixed empty-payload action. Executable identity, + current semantic version and staging root are host-owned constructor values. The + runtime health authority re-verifies exact installed and rollback bytes before any + stale pending journal or rollback bytes are disarmed. + """ + + def __init__( + self, + app: Any, + staging_root: Path, + *, + current_version: str, + install_target: Path | None = None, + commit_health: Callable[..., object | None] = commit_update_health_receipt, + ) -> None: + self._app = app + self._staging_root = Path(staging_root) + self._current_version = current_version + self._install_target = Path(sys.executable if install_target is None else install_target) + self._commit_health = commit_health + + def handle(self, request: Any) -> dict[str, Any]: + if not isinstance(request, dict) or request.get("command") != POST_UPDATE_HEALTH_COMMAND: + return self._app.handle(request) + rid = str(request.get("request_id", "invalid")) + try: + rid, command, payload = validate_request_shape(request) + if command != POST_UPDATE_HEALTH_COMMAND or payload: + raise ValueError("post-update health commit requires an empty payload") + except ValueError as exc: + return error_response(rid, "VALIDATION_ERROR", str(exc)) + + if not callable(self._commit_health): + return error_response( + rid, + "UPDATE_HEALTH_UNAVAILABLE", + "Post-update health authority is unavailable.", + ) + try: + receipt = self._commit_health( + self._staging_root, + current_version=self._current_version, + install_target=self._install_target, + ) + except Exception: + return error_response( + rid, + "UPDATE_HEALTH_NOT_COMMITTED", + "Updated application health could not be proven; rollback recovery remains preserved.", + ) + + if receipt is None: + return ok_response( + rid, + { + "status": "none", + "health_committed": False, + "rollback_cleanup_performed": False, + }, + ) + return ok_response( + rid, + { + "status": "healthy", + "health_committed": True, + "rollback_cleanup_performed": True, + "previous_version": receipt.previous_version, + "target_version": receipt.target_version, + }, + ) From 3f5cddbf830453045118d2dd1d7a89c2c212c52d Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:58:31 +0200 Subject: [PATCH 070/118] R06: bind post-restart health commit ahead of pending recovery --- .../desktop_host/main.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) 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 3e216a445..ccaa3a57d 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 @@ -8,6 +8,7 @@ from scripture_archive_platform.desktop_host.bridge import DesktopBridge from scripture_archive_platform.desktop_host.diagnostics import NativeDiagnosticsLayer from scripture_archive_platform.desktop_host.pending_update import NativePendingUpdateLayer +from scripture_archive_platform.desktop_host.post_update_health import NativePostUpdateHealthLayer from scripture_archive_platform.desktop_host.update_application import ( NativeApplicationUpdateLayer, NativeUpdateFileSelector, @@ -59,16 +60,24 @@ def main() -> int: current_version=CURRENT_APPLICATION_VERSION, staging_root=staging_root, ) - # This outer layer owns one process-local RLock for the complete update command - # family, so verify/stage/status/cancel/execute cannot race shared durable state. + # This layer owns one process-local RLock for the complete update command family, + # so verify/stage/status/cancel/execute cannot race shared durable state. pending_layer = NativePendingUpdateLayer( app, root, staging_root, current_version=CURRENT_APPLICATION_VERSION, ) - app = NativeDiagnosticsLayer( + # Health commit is intentionally outside pending recovery: after a successful + # updater relaunch the pending journal still carries the previous version and must + # be disarmed only after the new packaged native/frontend bridge is alive. + app = NativePostUpdateHealthLayer( pending_layer, + staging_root, + current_version=CURRENT_APPLICATION_VERSION, + ) + app = NativeDiagnosticsLayer( + app, root, Path(platform_app.store.root) / "runtime-v2", current_version=CURRENT_APPLICATION_VERSION, From f51a1109e355a95462c58a51ada6d280b8f0682b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:59:08 +0200 Subject: [PATCH 071/118] R06: commit update health before pending startup recovery --- .../repair_overlay/frontend/pending-update.js | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js index 9dce1c7a2..febb711eb 100644 --- a/lanes/dev1/repair_overlay/frontend/pending-update.js +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -1,4 +1,5 @@ const API_VERSION='scripture.transport.v1'; +const HEALTH_COMMAND='application_update.commit_post_restart_health'; const STATUS_COMMAND='application_update.pending_status'; const PREPARE_APPLY_COMMAND='application_update.prepare_apply'; const APPLY_AND_RESTART_COMMAND='application_update.apply_and_restart'; @@ -119,24 +120,41 @@ async function cancelPending(){ finally{setBusy(false)} } +async function commitPostRestartHealth(){ + setBusy(true); + setStatus('Перевіряю стан після перезапуску та збережений rollback.'); + try{ + const data=await invoke(HEALTH_COMMAND); + if(data.status==='healthy'&&data.health_committed===true&&data.rollback_cleanup_performed===true){ + setStatus(`Оновлена версія ${data.target_version??'програми'} успішно запустила native bridge. Rollback попередньої версії ${data.previous_version??''} безпечно завершено.`); + }else if(data.status!=='none'||data.health_committed!==false){ + throw new Error('Отримано неочікуваний post-update health state.'); + } + await checkPending({startup:true}); + }catch(error){ + clearDetails();setApplyReady(false);setBusy(false); + setStatus(`Post-update health не підтверджено: ${error?.message||'невідома помилка'}. Rollback recovery збережено; автоматичне очищення не виконано.`); + } +} + function startStartupCheck(){ if(startupCheckStarted)return; startupCheckStarted=true; - void checkPending({startup:true}); + void commitPostRestartHealth(); } function mount(){ const view=$('application-update-view');if(!view||$('pending-update-recovery'))return; const section=element('section');section.id='pending-update-recovery';section.className='surface';section.setAttribute('aria-labelledby','pending-update-heading'); const heading=element('h3','Підготовлене оновлення після перезапуску');heading.id='pending-update-heading'; - const help=element('p','Після запуску програма автоматично повторно перевіряє pending state. «Підготувати встановлення» створює захищений durable apply handoff. Лише після цього «Встановити й перезапустити» перевіряє packaged updater, запускає його окремим native процесом і закриває поточну програму. Browser не передає шляхів, PID або командного рядка updater.'); + const help=element('p','Після запуску програма спочатку перевіряє post-update health receipt: точну поточну версію, встановлені байти та збережений rollback. Лише після успішної перевірки старий rollback і stale pending authority прибираються. Потім програма перевіряє звичайний pending state. «Підготувати встановлення» створює durable apply handoff, а «Встановити й перезапустити» запускає підписаний native updater. Browser не передає шляхів, PID або командного рядка updater.'); const actions=element('div');actions.className='action-row'; const check=element('button','Перевірити підготовлене оновлення');check.type='button';check.id='pending-update-check'; const prepare=element('button','Підготувати встановлення');prepare.type='button';prepare.id='pending-update-prepare-apply'; const apply=element('button','Встановити й перезапустити');apply.type='button';apply.id='pending-update-apply-restart';apply.dataset.ready='false';apply.disabled=true; const cancel=element('button','Скасувати підготовлене оновлення');cancel.type='button';cancel.id='pending-update-cancel'; actions.append(check,prepare,apply,cancel); - const status=element('p','Очікую готовності native host для перевірки pending update.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); + const status=element('p','Очікую готовності native host для post-update health і pending перевірки.');status.id='pending-update-status';status.className='notice info';status.setAttribute('role','status');status.setAttribute('aria-live','polite');status.setAttribute('aria-atomic','true'); const details=element('dl');details.id='pending-update-details';details.className='details-list';details.setAttribute('aria-label','Повторно перевірені метадані підготовленого оновлення'); section.append(heading,help,actions,status,details);view.append(section); check.addEventListener('click',()=>checkPending());prepare.addEventListener('click',prepareApply);apply.addEventListener('click',applyAndRestart);cancel.addEventListener('click',cancelPending); From 617f656b154ef777afe6e8454d625549168e2ccb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 01:59:31 +0200 Subject: [PATCH 072/118] R06: qualify packaged post-restart health commit boundary --- .../tests/test_packaged_post_update_health.py | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py b/lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py new file mode 100644 index 000000000..2e30b80ab --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_packaged_post_update_health.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import json +import unittest +from dataclasses import dataclass +from pathlib import Path + +from scripture_archive_platform.desktop_host.post_update_health import ( + POST_UPDATE_HEALTH_COMMAND, + NativePostUpdateHealthLayer, +) + + +CURRENT_VERSION = "0.6.0-r06.3dev.a" + + +def request(command=POST_UPDATE_HEALTH_COMMAND, payload=None, request_id="health-rid"): + return { + "api_version": "scripture.transport.v1", + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class FakeBaseApplication: + def __init__(self): + self.calls = [] + + def handle(self, value): + self.calls.append(value) + return {"ok": True, "data": {"passthrough": True}} + + +@dataclass(frozen=True) +class FakeReceipt: + previous_version: str = "0.5.9" + target_version: str = CURRENT_VERSION + + +class PackagedPostUpdateHealthTests(unittest.TestCase): + def setUp(self): + self.base = FakeBaseApplication() + self.staging = Path("state") / "application-updates" + self.installed = Path("install") / "ScriptureArchive-R06-DEV01.exe" + + def layer(self, commit): + return NativePostUpdateHealthLayer( + self.base, + self.staging, + current_version=CURRENT_VERSION, + install_target=self.installed, + commit_health=commit, + ) + + def test_health_commit_uses_only_host_owned_version_path_and_preserves_request_id(self): + calls = [] + + def commit(staging_root, **kwargs): + calls.append((Path(staging_root), kwargs)) + return FakeReceipt() + + response = self.layer(commit).handle(request(request_id="exact-health-rid")) + self.assertTrue(response["ok"]) + self.assertEqual("exact-health-rid", response["request_id"]) + self.assertEqual("healthy", response["data"]["status"]) + self.assertTrue(response["data"]["health_committed"]) + self.assertTrue(response["data"]["rollback_cleanup_performed"]) + self.assertEqual( + [ + ( + self.staging, + { + "current_version": CURRENT_VERSION, + "install_target": self.installed, + }, + ) + ], + calls, + ) + serialized = json.dumps(response) + self.assertNotIn(str(self.installed), serialized) + self.assertNotIn(str(self.staging), serialized) + + def test_no_receipt_is_successful_noop(self): + response = self.layer(lambda *args, **kwargs: None).handle(request()) + self.assertTrue(response["ok"]) + self.assertEqual("none", response["data"]["status"]) + self.assertFalse(response["data"]["health_committed"]) + self.assertFalse(response["data"]["rollback_cleanup_performed"]) + + def test_failed_exact_health_proof_returns_recovery_preserved_error(self): + def fail(*args, **kwargs): + raise ValueError("tampered installed bytes") + + response = self.layer(fail).handle(request()) + self.assertFalse(response["ok"]) + self.assertEqual("UPDATE_HEALTH_NOT_COMMITTED", response["error"]["code"]) + self.assertIn("rollback recovery remains preserved", response["error"]["message"]) + self.assertNotIn("tampered", json.dumps(response)) + + def test_browser_cannot_supply_health_path_version_or_hash(self): + calls = [] + response = self.layer(lambda *args, **kwargs: calls.append((args, kwargs))).handle( + request(payload={"path": "C:\\attacker.exe", "version": "9.9.9", "sha256": "0" * 64}) + ) + self.assertFalse(response["ok"]) + self.assertEqual("VALIDATION_ERROR", response["error"]["code"]) + self.assertEqual([], calls) + + def test_unrelated_command_is_delegated(self): + original = request(command="system.bootstrap") + response = self.layer(lambda *args, **kwargs: None).handle(original) + self.assertTrue(response["data"]["passthrough"]) + self.assertEqual([original], self.base.calls) + + def test_frontend_runs_health_commit_before_pending_startup_recovery(self): + platform = Path(__file__).resolve().parents[1] + script = (platform / "frontend" / "pending-update.js").read_text(encoding="utf-8") + self.assertIn("application_update.commit_post_restart_health", script) + start = script.index("async function commitPostRestartHealth") + health_call = script.index("invoke(HEALTH_COMMAND)", start) + pending_call = script.index("checkPending({startup:true})", start) + self.assertLess(health_call, pending_call) + self.assertIn("Rollback recovery збережено", script) + self.assertIn("aria-live", script) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + + +if __name__ == "__main__": + unittest.main() From b840c8dc080037778e55a91b40767123bc20f579 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 02:00:25 +0200 Subject: [PATCH 073/118] R06: preserve health receipt when rollback itself fails --- .../application_update_runner.py | 97 +++++++++++-------- 1 file changed, 58 insertions(+), 39 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_runner.py b/runtime_engine/scripture_archive_runtime/application_update_runner.py index 45270373e..b923237eb 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_runner.py +++ b/runtime_engine/scripture_archive_runtime/application_update_runner.py @@ -34,6 +34,33 @@ HealthDiscarder: TypeAlias = Callable[[Path], bool] +def _rollback_then_disarm_health( + installed_executable: Path, + staging_root: Path, + *, + previous_sha256: str, + rollback: RollbackConsumer, + discard_health: HealthDiscarder, + rollback_failure_message: str, + disarm_failure_message: str, +) -> None: + """Restore prior bytes before disarming health authority. + + If rollback itself fails, the receipt is intentionally preserved: that durable + exact-byte identity is most valuable in the worst recovery state. Only a proven + successful rollback permits receipt disarm. + """ + + try: + rollback(installed_executable, expected_previous_sha256=previous_sha256) + except Exception as rollback_error: + raise ApplicationUpdateError(rollback_failure_message) from rollback_error + try: + discard_health(staging_root) + except Exception as discard_error: + raise ApplicationUpdateError(disarm_failure_message) from discard_error + + def execute_trusted_updater( argv: Sequence[str], *, @@ -48,12 +75,12 @@ def execute_trusted_updater( ) -> UpdateApplyResult: """Execute one trusted updater invocation in fail-closed order. - The old application is proven exited before replacement. After canonical atomic + The old application is proven exited before replacement. After canonical atomic apply, a durable exact-byte health receipt is published before relaunch while the - prior rollback bytes still exist. The new application later commits that receipt - only after its packaged native/frontend bridge is healthy. If receipt publication - or process creation fails, the already-preserved prior bytes are restored and any - published receipt is disarmed before failure is surfaced. + prior rollback bytes still exist. The new application later commits that receipt + only after its packaged native/frontend bridge is healthy. If receipt publication + or process creation fails, prior bytes are restored before receipt disarm. A failed + rollback deliberately preserves the receipt for recovery evidence. """ if not isinstance(current_version, str): @@ -101,24 +128,20 @@ def execute_trusted_updater( installed_sha256=result.installed_sha256, ) except Exception as health_error: - rollback_error: Exception | None = None - discard_error: Exception | None = None - try: - rollback(installed_executable, expected_previous_sha256=result.previous_sha256) - except Exception as exc: - rollback_error = exc try: - discard_health(staging_root) - except Exception as exc: - discard_error = exc - if rollback_error is not None: - raise ApplicationUpdateError( - "health receipt publication failed and rollback also failed" - ) from rollback_error - if discard_error is not None: - raise ApplicationUpdateError( - "health receipt publication failed; rollback restored prior bytes but receipt disarm failed" - ) from discard_error + _rollback_then_disarm_health( + installed_executable, + staging_root, + previous_sha256=result.previous_sha256, + rollback=rollback, + discard_health=discard_health, + rollback_failure_message="health receipt publication failed and rollback also failed", + disarm_failure_message=( + "health receipt publication failed; rollback restored prior bytes but receipt disarm failed" + ), + ) + except ApplicationUpdateError as recovery_error: + raise recovery_error from health_error raise ApplicationUpdateError( "health receipt publication failed; rollback restored prior bytes" ) from health_error @@ -126,24 +149,20 @@ def execute_trusted_updater( try: launch(installed_executable) except Exception as launch_error: - rollback_error: Exception | None = None - discard_error: Exception | None = None try: - rollback(installed_executable, expected_previous_sha256=result.previous_sha256) - except Exception as exc: - rollback_error = exc - try: - discard_health(staging_root) - except Exception as exc: - discard_error = exc - if rollback_error is not None: - raise ApplicationUpdateError( - "updated application relaunch failed and rollback also failed" - ) from rollback_error - if discard_error is not None: - raise ApplicationUpdateError( - "updated application relaunch failed; rollback restored prior bytes but receipt disarm failed" - ) from discard_error + _rollback_then_disarm_health( + installed_executable, + staging_root, + previous_sha256=result.previous_sha256, + rollback=rollback, + discard_health=discard_health, + rollback_failure_message="updated application relaunch failed and rollback also failed", + disarm_failure_message=( + "updated application relaunch failed; rollback restored prior bytes but receipt disarm failed" + ), + ) + except ApplicationUpdateError as recovery_error: + raise recovery_error from launch_error raise ApplicationUpdateError( "updated application relaunch failed; rollback restored prior bytes" ) from launch_error From 433b30ac2a5d06e013be0c1c5214ed3be5c1c796 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 02:03:17 +0200 Subject: [PATCH 074/118] R06: bind updater direct invocation to its signed app sibling --- .../desktop_host/updater_main.py | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py index f14446bc3..c4d04f1f9 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_main.py @@ -1,6 +1,8 @@ from __future__ import annotations from collections.abc import Callable, Sequence +from pathlib import Path +import stat import sys from typing import Any @@ -8,6 +10,9 @@ verify_same_publisher_authenticode, ) from scripture_archive_platform.desktop_host.version import CURRENT_APPLICATION_VERSION +from runtime_engine.scripture_archive_runtime.application_update_process import ( + parse_trusted_updater_argv, +) from runtime_engine.scripture_archive_runtime.application_update_runner import ( execute_trusted_updater, ) @@ -15,6 +20,34 @@ UPDATER_OK = 0 UPDATER_FAILED = 2 +_UPDATER_SUFFIX = "-Updater.exe" + + +def _resolve_packaged_installed_sibling( + argv: Sequence[str], + *, + updater_executable: Path, +) -> tuple[Path, Path]: + """Bind direct invocation to the exact app sibling of this updater executable.""" + + _, installed_argument, _ = parse_trusted_updater_argv(tuple(argv)) + updater = Path(updater_executable) + updater_meta = updater.lstat() + if stat.S_ISLNK(updater_meta.st_mode) or not stat.S_ISREG(updater_meta.st_mode): + raise ValueError("packaged updater executable identity is invalid") + updater = updater.resolve(strict=True) + if not updater.name.casefold().endswith(_UPDATER_SUFFIX.casefold()): + raise ValueError("packaged updater executable name is invalid") + + installed_name = updater.name[: -len(_UPDATER_SUFFIX)] + ".exe" + expected_installed = updater.with_name(installed_name) + installed_meta = installed_argument.lstat() + if stat.S_ISLNK(installed_meta.st_mode) or not stat.S_ISREG(installed_meta.st_mode): + raise ValueError("installed application identity is invalid") + installed = installed_argument.resolve(strict=True) + if installed != expected_installed: + raise ValueError("installed application is not the canonical updater sibling") + return installed, updater def run_updater( @@ -22,17 +55,25 @@ def run_updater( *, execute: Callable[..., Any] = execute_trusted_updater, verifier: Callable[..., bool] = verify_same_publisher_authenticode, + updater_executable: Path | None = None, ) -> int: """Run one fixed updater command with packaged trust authorities. - The semantic current version and Authenticode verifier are imported from the - packaged native host. No browser/web payload can select either authority. Error - details are intentionally not echoed because argv contains local filesystem paths. + Direct invocation is bound to the exact application sibling mechanically derived + from this updater's own executable identity. That installed app and this updater + must also share a valid publisher before the runner can consume any apply handoff. + The runner independently verifies installed app versus staged candidate again. """ if not callable(execute) or not callable(verifier): return UPDATER_FAILED try: + installed, updater = _resolve_packaged_installed_sibling( + tuple(argv), + updater_executable=Path(sys.executable if updater_executable is None else updater_executable), + ) + if not verifier(installed, updater): + return UPDATER_FAILED execute( tuple(argv), current_version=CURRENT_APPLICATION_VERSION, From 9688f50439639e62ef6391cac7e6969c7f27ad9e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 02:03:43 +0200 Subject: [PATCH 075/118] R06: qualify updater self-identity and confused-deputy rejection --- .../tests/test_packaged_updater_entrypoint.py | 136 +++++++++++++++--- 1 file changed, 117 insertions(+), 19 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py index 8e03685d3..053dd0a73 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_entrypoint.py @@ -1,10 +1,9 @@ from __future__ import annotations +import tempfile import unittest +from pathlib import Path -from scripture_archive_platform.desktop_host.authenticode import ( - verify_same_publisher_authenticode, -) from scripture_archive_platform.desktop_host.updater_main import ( UPDATER_FAILED, UPDATER_OK, @@ -14,41 +13,140 @@ class PackagedUpdaterEntrypointTests(unittest.TestCase): - def test_forwards_fixed_argv_with_host_owned_version_and_canonical_authenticode(self) -> None: - calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.install = self.root / "Program Files" / "Scripture Archive" + self.install.mkdir(parents=True) + self.installed = self.install / "ScriptureArchive-R06-DEV01.exe" + self.updater = self.install / "ScriptureArchive-R06-DEV01-Updater.exe" + self.installed.write_bytes(b"installed") + self.updater.write_bytes(b"updater") + self.staging = self.root / "state" / "application-updates" + self.staging.mkdir(parents=True) - def execute(argv, **kwargs): - calls.append((tuple(argv), dict(kwargs))) - return object() + def tearDown(self) -> None: + self.temp.cleanup() - argv = ( + def argv(self, installed: Path | None = None) -> tuple[str, ...]: + return ( "--scripture-archive-apply", "--wait-pid", "41", "--installed-executable", - r"C:\Program Files\Scripture Archive\ScriptureArchive-R06-DEV01.exe", + str(self.installed if installed is None else installed), "--staging-root", - r"C:\Users\user\AppData\Local\ScriptureArchive\application-updates", + str(self.staging), + ) + + def test_forwards_fixed_sibling_argv_with_host_version_and_verifier(self) -> None: + execute_calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] + verify_calls: list[tuple[Path, Path]] = [] + + def execute(argv, **kwargs): + execute_calls.append((tuple(argv), dict(kwargs))) + return object() + + def verifier(installed: Path, updater: Path) -> bool: + verify_calls.append((installed, updater)) + return True + + argv = self.argv() + result = run_updater( + argv, + execute=execute, + verifier=verifier, + updater_executable=self.updater, ) - result = run_updater(argv, execute=execute) self.assertEqual(result, UPDATER_OK) - self.assertEqual(len(calls), 1) - forwarded, kwargs = calls[0] + self.assertEqual(verify_calls, [(self.installed.resolve(), self.updater.resolve())]) + self.assertEqual(len(execute_calls), 1) + forwarded, kwargs = execute_calls[0] self.assertEqual(forwarded, argv) self.assertEqual(kwargs["current_version"], CURRENT_APPLICATION_VERSION) - self.assertIs(kwargs["verify_same_publisher"], verify_same_publisher_authenticode) + self.assertIs(kwargs["verify_same_publisher"], verifier) - def test_failure_is_fail_closed_without_retrying_or_rewriting_argv(self) -> None: + def test_existing_noncanonical_installed_target_never_reaches_verifier_or_executor(self) -> None: + other = self.install / "Other.exe" + other.write_bytes(b"other") + verified = [] + executed = [] + result = run_updater( + self.argv(other), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: verified.append(args) or True, + updater_executable=self.updater, + ) + self.assertEqual(result, UPDATER_FAILED) + self.assertEqual([], verified) + self.assertEqual([], executed) + + def test_wrong_updater_filename_never_reaches_executor(self) -> None: + wrong = self.install / "Updater.exe" + wrong.write_bytes(b"updater") + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: True, + updater_executable=wrong, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_symlink_installed_target_never_reaches_executor(self) -> None: + real = self.install / "real.exe" + real.write_bytes(b"real") + self.installed.unlink() + try: + self.installed.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda *args: True, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_negative_updater_publisher_proof_never_reaches_executor(self) -> None: + executed = [] + self.assertEqual( + run_updater( + self.argv(), + execute=lambda *args, **kwargs: executed.append((args, kwargs)), + verifier=lambda installed, updater: False, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual([], executed) + + def test_malformed_command_fails_before_executor(self) -> None: calls = 0 def execute(argv, **kwargs): nonlocal calls calls += 1 - raise ValueError("local path detail must not escape through entrypoint") - self.assertEqual(run_updater(("bad",), execute=execute), UPDATER_FAILED) - self.assertEqual(calls, 1) + self.assertEqual( + run_updater( + ("bad",), + execute=execute, + verifier=lambda *args: True, + updater_executable=self.updater, + ), + UPDATER_FAILED, + ) + self.assertEqual(calls, 0) def test_requires_callable_execution_and_verifier_authorities(self) -> None: self.assertEqual(run_updater((), execute=None), UPDATER_FAILED) # type: ignore[arg-type] From b8285ee6b09f5ef5e457d2f66aae6f1d45466f74 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:15 +0200 Subject: [PATCH 076/118] R06: allowlist updater execution and post-restart health commands --- .../scripture_archive_platform/transport/contracts.py | 4 ++-- 1 file changed, 2 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 95fdbc006..ae7d9a423 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,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","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.cancel_pending","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.apply_and_restart","application_update.cancel_pending","application_update.commit_post_restart_health","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,7 +102,7 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') - if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.cancel_pending'} and payload: + if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.apply_and_restart','application_update.cancel_pending','application_update.commit_post_restart_health'} and payload: raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} From ae21639dd6d44730008faef60fdbdb464ce366ae Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:18 +0200 Subject: [PATCH 077/118] R06: isolate staged candidate in publisher rejection regression --- runtime_engine/tests/test_application_update_updater.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 738340656..79d16c131 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -148,11 +148,10 @@ def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) target = root / "ScriptureArchive.exe" - staged = root / "ScriptureArchive.new.exe" target.write_bytes(old) - staged.write_bytes(new) pending = self._pending(new) - staged_named = root / pending.artifact_name + staged_named = root / "staged" / pending.artifact_name + staged_named.parent.mkdir() staged_named.write_bytes(new) with patch( From b25ce1852c219bb66c47142ab38b7596553dd6f6 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:23 +0200 Subject: [PATCH 078/118] R06: provision pytest for runtime integration suite --- .github/workflows/r06-dev10-integration.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index eb32befdc..ec10d8675 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -31,6 +31,8 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.13' + - name: Install runtime test dependency + run: python -m pip install --disable-pip-version-check pytest - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools From a617ea13d08192e49f4aaca28f1caccc8d4e52cb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:26 +0200 Subject: [PATCH 079/118] R06: align packaging fail-closed assertions with dual artifacts --- .../tests/test_packaged_diagnostics.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 38488669a..9287fc175 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -166,22 +166,32 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "pip upgrade"', 'Assert-NativeSuccess "build dependency install"', 'Assert-NativeSuccess "Windows release diagnostics"', - 'Assert-NativeSuccess "PyInstaller build"', + 'Assert-NativeSuccess "PyInstaller application build"', + 'Assert-NativeSuccess "PyInstaller updater build"', 'Assert-NativeSuccess "Python version query"', - 'Assert-NativeSuccess "artifact verification"', + 'Assert-NativeSuccess "application artifact verification"', + 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) stale_cleanup = "Remove-Item -LiteralPath $Out -Force" self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( - build.index('Assert-NativeSuccess "PyInstaller build"'), + build.index('Assert-NativeSuccess "PyInstaller application build"'), build.index('if (-not (Test-Path -LiteralPath $Out -PathType Leaf))'), ) self.assertLess( - build.index('Assert-NativeSuccess "artifact verification"'), + build.index('Assert-NativeSuccess "PyInstaller updater build"'), + build.index('if (-not (Test-Path -LiteralPath $UpdaterOut -PathType Leaf))'), + ) + self.assertLess( + build.index('Assert-NativeSuccess "application artifact verification"'), build.index('Write-Output "Built $Out'), ) + self.assertLess( + build.index('Assert-NativeSuccess "updater artifact verification"'), + build.index('Write-Output "Built $UpdaterOut'), + ) def test_desktop_host_wraps_update_layer_with_read_only_diagnostics(self): platform = Path(__file__).resolve().parents[1] From 798010afccfc7d70e6e5e1f108b487d7983304ed Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:29 +0200 Subject: [PATCH 080/118] R06: assert semantic initial install-button disable state --- .../repair_overlay/tests/test_packaged_updater_host_launch.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index 5098cedad..5c7f5c36a 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -250,7 +250,8 @@ def test_frontend_exposes_accessible_two_step_install_without_html_injection(sel self.assertIn("application_update.apply_and_restart", script) self.assertIn("pending-update-apply-restart", script) self.assertIn("Встановити й перезапустити", script) - self.assertIn("button.disabled=true", script) + self.assertIn("apply.disabled=true", script) + self.assertIn("button.disabled=busy", script) self.assertIn("aria-live", script) self.assertIn("textContent", script) self.assertNotIn("innerHTML", script) From 70cf1175bb20854a86c1be37c2316a894c18b72a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:18:47 +0200 Subject: [PATCH 081/118] R06: assert stale cleanup covers both packaged artifacts --- lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 9287fc175..ab9b50e49 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -173,7 +173,8 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) - stale_cleanup = "Remove-Item -LiteralPath $Out -Force" + stale_cleanup = "Remove-Item -LiteralPath $artifact -Force" + self.assertIn("foreach ($artifact in @($Out, $UpdaterOut))", build) self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( From 4b282bee917ac72d2e434949061794d0d08ef3f7 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:19:36 +0200 Subject: [PATCH 082/118] R06: repair exact-head update qualification contracts --- .github/workflows/r06-dev05-runtime.yml | 4 +++- .github/workflows/r06-dev10-integration.yml | 5 ++++- .../scripture_archive_platform/transport/contracts.py | 4 ++-- .../repair_overlay/tests/test_packaged_diagnostics.py | 10 ++++++---- .../tests/test_packaged_updater_host_launch.py | 3 ++- .../tests/test_application_update_updater.py | 3 ++- 6 files changed, 19 insertions(+), 10 deletions(-) diff --git a/.github/workflows/r06-dev05-runtime.yml b/.github/workflows/r06-dev05-runtime.yml index 65cee9f47..bc574fe32 100644 --- a/.github/workflows/r06-dev05-runtime.yml +++ b/.github/workflows/r06-dev05-runtime.yml @@ -34,5 +34,7 @@ jobs: python-version: "3.11" - name: Compile runtime and tests run: python -m compileall -q scripture_archive_runtime tests + - name: Install runtime test runner + run: python -m pip install --disable-pip-version-check pytest==8.4.2 - name: Runtime regression suite - run: python -m unittest discover -s tests -v + run: python -m pytest -v tests diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index eb32befdc..8a51ec525 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -34,9 +34,12 @@ jobs: - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools + - name: Install runtime test runner + working-directory: runtime_engine + run: python -m pip install --disable-pip-version-check pytest==8.4.2 - name: Run complete runtime regression suite working-directory: runtime_engine - run: python -m unittest discover -s tests -v + run: python -m pytest -v tests release-secret-scan: runs-on: ubuntu-latest 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 95fdbc006..ee663c478 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,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","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.cancel_pending","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.apply_and_restart","application_update.commit_post_restart_health","application_update.cancel_pending","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,7 +102,7 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') - if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.cancel_pending'} and payload: + if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.apply_and_restart','application_update.commit_post_restart_health','application_update.cancel_pending'} and payload: raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 38488669a..7356fa288 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -166,20 +166,22 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "pip upgrade"', 'Assert-NativeSuccess "build dependency install"', 'Assert-NativeSuccess "Windows release diagnostics"', - 'Assert-NativeSuccess "PyInstaller build"', + 'Assert-NativeSuccess "PyInstaller application build"', + 'Assert-NativeSuccess "PyInstaller updater build"', 'Assert-NativeSuccess "Python version query"', - 'Assert-NativeSuccess "artifact verification"', + 'Assert-NativeSuccess "application artifact verification"', + 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) stale_cleanup = "Remove-Item -LiteralPath $Out -Force" self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( - build.index('Assert-NativeSuccess "PyInstaller build"'), + build.index('Assert-NativeSuccess "PyInstaller updater build"'), build.index('if (-not (Test-Path -LiteralPath $Out -PathType Leaf))'), ) self.assertLess( - build.index('Assert-NativeSuccess "artifact verification"'), + build.index('Assert-NativeSuccess "updater artifact verification"'), build.index('Write-Output "Built $Out'), ) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index 5098cedad..4395d7647 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -250,7 +250,8 @@ def test_frontend_exposes_accessible_two_step_install_without_html_injection(sel self.assertIn("application_update.apply_and_restart", script) self.assertIn("pending-update-apply-restart", script) self.assertIn("Встановити й перезапустити", script) - self.assertIn("button.disabled=true", script) + self.assertIn("apply.disabled=true", script) + self.assertIn("button.disabled=busy||", script) self.assertIn("aria-live", script) self.assertIn("textContent", script) self.assertNotIn("innerHTML", script) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 738340656..dff112d17 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -152,7 +152,8 @@ def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): target.write_bytes(old) staged.write_bytes(new) pending = self._pending(new) - staged_named = root / pending.artifact_name + staged_named = root / "staged" / pending.artifact_name + staged_named.parent.mkdir() staged_named.write_bytes(new) with patch( From 6658c41a13aca369b12e5b39f5b1dd0ec95d38cd Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:22:20 +0200 Subject: [PATCH 083/118] R06: make health regressions discoverable by unittest --- .../tests/test_application_update_health.py | 239 +++++++++--------- 1 file changed, 124 insertions(+), 115 deletions(-) diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index e5fa9db77..3c459511f 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -3,8 +3,8 @@ import hashlib import json from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_health import ( @@ -50,123 +50,132 @@ def _publish(tmp_path: Path): return root, target, rollback, previous, installed, receipt -def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - assert receipt.previous_version == PREVIOUS_VERSION - assert receipt.target_version == TARGET_VERSION - assert receipt.installed_executable_name == target.name - assert receipt.previous_sha256 == _sha(previous) - assert receipt.installed_sha256 == _sha(installed) - assert inspect_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) == receipt - - payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) - assert payload["schema"] == HEALTH_RECEIPT_SCHEMA - assert payload["status"] == "awaiting_health_commit" - serialized = json.dumps(payload) - assert str(tmp_path) not in serialized - assert "install_target" not in payload - assert "rollback_path" not in payload - - -def test_publish_is_idempotent_only_for_same_exact_identity(tmp_path: Path) -> None: - root, target, rollback, previous, installed, first = _publish(tmp_path) - before = (root / "update-health.json").read_bytes() - second = publish_update_health_receipt( - root, - previous_version=PREVIOUS_VERSION, - target_version=TARGET_VERSION, - install_target=target, - previous_sha256=_sha(previous), - installed_sha256=_sha(installed), - ) - assert second == first - assert (root / "update-health.json").read_bytes() == before +class ApplicationUpdateHealthTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + + self.assertEqual(receipt.previous_version, PREVIOUS_VERSION) + self.assertEqual(receipt.target_version, TARGET_VERSION) + self.assertEqual(receipt.installed_executable_name, target.name) + self.assertEqual(receipt.previous_sha256, _sha(previous)) + self.assertEqual(receipt.installed_sha256, _sha(installed)) + self.assertEqual( + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ), + receipt, + ) - with pytest.raises(ApplicationUpdateError, match="different identity"): - publish_update_health_receipt( + payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) + self.assertEqual(payload["schema"], HEALTH_RECEIPT_SCHEMA) + self.assertEqual(payload["status"], "awaiting_health_commit") + serialized = json.dumps(payload) + self.assertNotIn(str(self.tmp_path), serialized) + self.assertNotIn("install_target", payload) + self.assertNotIn("rollback_path", payload) + + def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: + root, target, rollback, previous, installed, first = _publish(self.tmp_path) + before = (root / "update-health.json").read_bytes() + second = publish_update_health_receipt( root, previous_version=PREVIOUS_VERSION, - target_version="1.2.0", + target_version=TARGET_VERSION, install_target=target, previous_sha256=_sha(previous), installed_sha256=_sha(installed), ) - - -def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - with pytest.raises(ApplicationUpdateError, match="target version is not current"): - inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) - - target.write_bytes(b"x" * len(installed)) - with pytest.raises(ApplicationUpdateError, match="installed application bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - target.write_bytes(installed) - - rollback.write_bytes(b"y" * len(previous)) - with pytest.raises(ApplicationUpdateError, match="rollback bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_receipt_shape_extra_field_and_symlink_fail_closed(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - path = root / "update-health.json" - payload = json.loads(path.read_text(encoding="utf-8")) - payload["unexpected"] = True - path.write_text(json.dumps(payload), encoding="utf-8") - with pytest.raises(ApplicationUpdateError, match="shape is invalid"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - path.unlink() - real = root / "real-health.json" - real.write_text("{}", encoding="utf-8") - try: - path.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal need not be parsed", encoding="utf-8") - - committed = commit_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) - assert committed == receipt - assert not pending.exists() - assert not (root / "update-health.json").exists() - assert not rollback.exists() - assert target.read_bytes() == installed - - -def test_failed_health_proof_preserves_receipt_pending_and_rollback(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal", encoding="utf-8") - target.write_bytes(b"tampered") - - with pytest.raises(ApplicationUpdateError): - commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - assert pending.exists() - assert (root / "update-health.json").exists() - assert rollback.exists() - - -def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - assert discard_update_health_receipt(root) is True - assert discard_update_health_receipt(root) is False - assert rollback.read_bytes() == previous - assert target.read_bytes() == installed + self.assertEqual(second, first) + self.assertEqual((root / "update-health.json").read_bytes(), before) + + with self.assertRaisesRegex(ApplicationUpdateError, "different identity"): + publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version="1.2.0", + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + + def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + + with self.assertRaisesRegex(ApplicationUpdateError, "target version is not current"): + inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) + + target.write_bytes(b"x" * len(installed)) + with self.assertRaisesRegex(ApplicationUpdateError, "installed application bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + target.write_bytes(installed) + + rollback.write_bytes(b"y" * len(previous)) + with self.assertRaisesRegex(ApplicationUpdateError, "rollback bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + path = root / "update-health.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["unexpected"] = True + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaisesRegex(ApplicationUpdateError, "shape is invalid"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + path.unlink() + real = root / "real-health.json" + real.write_text("{}", encoding="utf-8") + try: + path.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal need not be parsed", encoding="utf-8") + + committed = commit_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + self.assertEqual(committed, receipt) + self.assertFalse(pending.exists()) + self.assertFalse((root / "update-health.json").exists()) + self.assertFalse(rollback.exists()) + self.assertEqual(target.read_bytes(), installed) + + def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal", encoding="utf-8") + target.write_bytes(b"tampered") + + with self.assertRaises(ApplicationUpdateError): + commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + self.assertTrue(pending.exists()) + self.assertTrue((root / "update-health.json").exists()) + self.assertTrue(rollback.exists()) + + def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + self.assertIs(discard_update_health_receipt(root), True) + self.assertIs(discard_update_health_receipt(root), False) + self.assertEqual(rollback.read_bytes(), previous) + self.assertEqual(target.read_bytes(), installed) + + +if __name__ == "__main__": + unittest.main() From 620b45915b2543eea7f8a34c9d9f2a04c7b8c0d2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:22:37 +0200 Subject: [PATCH 084/118] R06: make parent-wait regressions discoverable by unittest --- .../test_application_update_parent_wait.py | 86 ++++++++++--------- 1 file changed, 45 insertions(+), 41 deletions(-) diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py index 41e41fbc8..aafb2497e 100644 --- a/runtime_engine/tests/test_application_update_parent_wait.py +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -1,8 +1,7 @@ from __future__ import annotations import os - -import pytest +import unittest from scripture_archive_runtime.application_update_parent_wait import ( ParentProcessWaitError, @@ -10,56 +9,61 @@ ) -def test_wait_uses_exact_pid_and_bounded_timeout() -> None: - seen: list[tuple[int, int]] = [] - - def backend(pid: int, timeout_ms: int) -> None: - seen.append((pid, timeout_ms)) - - wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) - assert seen == [(4242, 30_000)] - - -def test_wait_rejects_own_pid_before_backend() -> None: - called = False +class ParentProcessWaitTests(unittest.TestCase): + def test_wait_uses_exact_pid_and_bounded_timeout(self) -> None: + seen: list[tuple[int, int]] = [] - def backend(pid: int, timeout_ms: int) -> None: - nonlocal called - called = True + def backend(pid: int, timeout_ms: int) -> None: + seen.append((pid, timeout_ms)) - with pytest.raises(ParentProcessWaitError, match="own process"): - wait_for_parent_exit(os.getpid(), wait_backend=backend) - assert called is False + wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) + self.assertEqual(seen, [(4242, 30_000)]) + def test_wait_rejects_own_pid_before_backend(self) -> None: + called = False -@pytest.mark.parametrize("pid", [0, -1, True, 1.5, "1"]) -def test_wait_rejects_invalid_pid(pid) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(pid, wait_backend=lambda *_: None) + def backend(pid: int, timeout_ms: int) -> None: + nonlocal called + called = True + with self.assertRaisesRegex(ParentProcessWaitError, "own process"): + wait_for_parent_exit(os.getpid(), wait_backend=backend) + self.assertFalse(called) -@pytest.mark.parametrize("timeout_ms", [0, -1, 120_001, True, 1.5]) -def test_wait_rejects_invalid_or_unbounded_timeout(timeout_ms) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) + def test_wait_rejects_invalid_pid(self) -> None: + for pid in [0, -1, True, 1.5, "1"]: + with self.subTest(pid=pid): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit(pid, wait_backend=lambda *_: None) # type: ignore[arg-type] + def test_wait_rejects_invalid_or_unbounded_timeout(self) -> None: + for timeout_ms in [0, -1, 120_001, True, 1.5]: + with self.subTest(timeout_ms=timeout_ms): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit( # type: ignore[arg-type] + 4242, + timeout_ms=timeout_ms, + wait_backend=lambda *_: None, + ) -def test_wait_is_windows_only_without_injected_backend() -> None: - with pytest.raises(ParentProcessWaitError, match="Windows-only"): - wait_for_parent_exit(4242, os_name="posix") + def test_wait_is_windows_only_without_injected_backend(self) -> None: + with self.assertRaisesRegex(ParentProcessWaitError, "Windows-only"): + wait_for_parent_exit(4242, os_name="posix") + def test_wait_wraps_backend_failure(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise OSError("boom") -def test_wait_wraps_backend_failure() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise OSError("boom") + with self.assertRaisesRegex(ParentProcessWaitError, "wait failed"): + wait_for_parent_exit(4242, wait_backend=backend) - with pytest.raises(ParentProcessWaitError, match="wait failed"): - wait_for_parent_exit(4242, wait_backend=backend) + def test_wait_preserves_fail_closed_backend_verdict(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise ParentProcessWaitError("parent process did not exit before timeout") + with self.assertRaisesRegex(ParentProcessWaitError, "did not exit"): + wait_for_parent_exit(4242, wait_backend=backend) -def test_wait_preserves_fail_closed_backend_verdict() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise ParentProcessWaitError("parent process did not exit before timeout") - with pytest.raises(ParentProcessWaitError, match="did not exit"): - wait_for_parent_exit(4242, wait_backend=backend) +if __name__ == "__main__": + unittest.main() From 09e2b92bac9f6490cda6a69638f676bdc3be02de Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:23:07 +0200 Subject: [PATCH 085/118] R06: make process regressions discoverable by unittest --- .../tests/test_application_update_process.py | 275 +++++++++--------- 1 file changed, 145 insertions(+), 130 deletions(-) diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py index 55390bc03..ddb75ba75 100644 --- a/runtime_engine/tests/test_application_update_process.py +++ b/runtime_engine/tests/test_application_update_process.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update_process import ( UpdateProcessError, @@ -25,149 +25,164 @@ def _files(tmp_path: Path) -> tuple[Path, Path, Path]: return updater, app, staging -def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - assert plan.parent_pid == os.getpid() - assert plan.updater_executable == updater.resolve() - assert plan.installed_executable == app.resolve() - assert plan.staging_root == staging.resolve() - assert plan.argv() == ( - str(updater.resolve()), - "--scripture-archive-apply", - "--wait-pid", - str(os.getpid()), - "--installed-executable", - str(app.resolve()), - "--staging-root", - str(staging.resolve()), - ) - - -def test_build_plan_rejects_external_updater(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - external = tmp_path / "outside-updater.exe" - external.write_bytes(updater.read_bytes()) - with pytest.raises(UpdateProcessError, match="packaged beside"): - build_updater_process_plan( - updater_executable=external, - installed_executable=app, - staging_root=staging, - ) +class ApplicationUpdateProcessTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + def tearDown(self) -> None: + self.temp.cleanup() -def test_build_plan_rejects_current_app_as_updater(tmp_path: Path) -> None: - _, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="distinct"): - build_updater_process_plan( - updater_executable=app, + def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) + self.assertEqual(plan.parent_pid, os.getpid()) + self.assertEqual(plan.updater_executable, updater.resolve()) + self.assertEqual(plan.installed_executable, app.resolve()) + self.assertEqual(plan.staging_root, staging.resolve()) + self.assertEqual( + plan.argv(), + ( + str(updater.resolve()), + "--scripture-archive-apply", + "--wait-pid", + str(os.getpid()), + "--installed-executable", + str(app.resolve()), + "--staging-root", + str(staging.resolve()), + ), + ) - -def test_build_plan_rejects_symlinked_updater_target_and_staging(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - updater_link = updater.parent / "link-updater.exe" - staging_link = tmp_path / "state-link" - try: - updater_link.symlink_to(updater) - staging_link.symlink_to(staging, target_is_directory=True) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(UpdateProcessError, match="non-symlink"): - build_updater_process_plan( - updater_executable=updater_link, + def test_build_plan_rejects_external_updater(self) -> None: + updater, app, staging = _files(self.tmp_path) + external = self.tmp_path / "outside-updater.exe" + external.write_bytes(updater.read_bytes()) + with self.assertRaisesRegex(UpdateProcessError, "packaged beside"): + build_updater_process_plan( + updater_executable=external, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_current_app_as_updater(self) -> None: + _, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "distinct"): + build_updater_process_plan( + updater_executable=app, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: + updater, app, staging = _files(self.tmp_path) + updater_link = updater.parent / "link-updater.exe" + staging_link = self.tmp_path / "state-link" + try: + updater_link.symlink_to(updater) + staging_link.symlink_to(staging, target_is_directory=True) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(UpdateProcessError, "non-symlink"): + build_updater_process_plan( + updater_executable=updater_link, + installed_executable=app, + staging_root=staging, + ) + with self.assertRaisesRegex(UpdateProcessError, "real directory"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging_link, + ) + + def test_build_plan_rejects_foreign_parent_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "current host process"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + parent_pid=os.getpid() + 1, + ) + + def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) - with pytest.raises(UpdateProcessError, match="real directory"): - build_updater_process_plan( + seen: dict[str, object] = {} + + class Child: + pid = 43210 + + def fake_popen(argv, **kwargs): + seen["argv"] = argv + seen.update(kwargs) + return Child() + + pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") + self.assertEqual(pid, 43210) + self.assertEqual(seen["argv"], list(plan.argv())) + self.assertEqual(seen["cwd"], str(app.resolve().parent)) + self.assertIs(seen["shell"], False) + self.assertIs(seen["close_fds"], True) + self.assertEqual(seen["creationflags"], 0) + + def test_launch_wraps_process_failure(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, - staging_root=staging_link, + staging_root=staging, ) + def broken_popen(*args, **kwargs): + raise OSError("boom") + + with self.assertRaisesRegex(UpdateProcessError, "failed to launch"): + launch_updater_process(plan, popen=broken_popen) -def test_build_plan_rejects_foreign_parent_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="current host process"): - build_updater_process_plan( + def test_parser_accepts_only_fixed_host_contract(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, staging_root=staging, - parent_pid=os.getpid() + 1, ) - - -def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - seen: dict[str, object] = {} - - class Child: - pid = 43210 - - def fake_popen(argv, **kwargs): - seen["argv"] = argv - seen.update(kwargs) - return Child() - - pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") - assert pid == 43210 - assert seen["argv"] == list(plan.argv()) - assert seen["cwd"] == str(app.resolve().parent) - assert seen["shell"] is False - assert seen["close_fds"] is True - assert seen["creationflags"] == 0 - - -def test_launch_wraps_process_failure(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - - def broken_popen(*args, **kwargs): - raise OSError("boom") - - with pytest.raises(UpdateProcessError, match="failed to launch"): - launch_updater_process(plan, popen=broken_popen) - - -def test_parser_accepts_only_fixed_host_contract(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) - assert pid == os.getpid() - assert parsed_app == app.resolve() - assert parsed_staging == staging.resolve() - - -@pytest.mark.parametrize( - "argv", - [ - (), - ("--scripture-archive-apply",), - ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), - ], -) -def test_parser_rejects_noncanonical_or_extended_commands(argv: tuple[str, ...]) -> None: - with pytest.raises(UpdateProcessError): - parse_trusted_updater_argv(argv) + pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) + self.assertEqual(pid, os.getpid()) + self.assertEqual(parsed_app, app.resolve()) + self.assertEqual(parsed_staging, staging.resolve()) + + def test_parser_rejects_noncanonical_or_extended_commands(self) -> None: + invalid_commands = [ + (), + ("--scripture-archive-apply",), + ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), + ( + "--scripture-archive-apply", + "--wait-pid", + "1", + "--installed-executable", + "a", + "--staging-root", + "b", + "--extra", + ), + ] + for argv in invalid_commands: + with self.subTest(argv=argv): + with self.assertRaises(UpdateProcessError): + parse_trusted_updater_argv(argv) + + +if __name__ == "__main__": + unittest.main() From 2c89169f1085f6c9263d0b9eadd015073c9fe4f6 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:23:21 +0200 Subject: [PATCH 086/118] R06: make relaunch regressions discoverable by unittest --- .../tests/test_application_update_relaunch.py | 96 +++++++++++-------- 1 file changed, 54 insertions(+), 42 deletions(-) diff --git a/runtime_engine/tests/test_application_update_relaunch.py b/runtime_engine/tests/test_application_update_relaunch.py index 0f631ea48..6c05123d0 100644 --- a/runtime_engine/tests/test_application_update_relaunch.py +++ b/runtime_engine/tests/test_application_update_relaunch.py @@ -1,64 +1,76 @@ from __future__ import annotations from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_relaunch import launch_installed_application -def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(tmp_path: Path) -> None: - install = tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - target = install / "Scripture Archive.exe" - target.write_bytes(b"updated") - calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] +class ApplicationUpdateRelaunchTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) - def spawn(argv, **kwargs): - calls.append((tuple(argv), dict(kwargs))) - return object() + def tearDown(self) -> None: + self.temp.cleanup() - launch_installed_application(target, spawn=spawn) + def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(self) -> None: + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + target = install / "Scripture Archive.exe" + target.write_bytes(b"updated") + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] - assert calls == [ - ((str(target),), {"cwd": str(install), "close_fds": True}), - ] + def spawn(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + launch_installed_application(target, spawn=spawn) -def test_relaunch_rejects_symlink_target_before_spawn(tmp_path: Path) -> None: - real = tmp_path / "real.exe" - real.write_bytes(b"updated") - target = tmp_path / "Scripture Archive.exe" - try: - target.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - spawned = False + self.assertEqual( + calls, + [ + ((str(target),), {"cwd": str(install), "close_fds": True}), + ], + ) - def spawn(*args, **kwargs): - nonlocal spawned - spawned = True + def test_relaunch_rejects_symlink_target_before_spawn(self) -> None: + real = self.tmp_path / "real.exe" + real.write_bytes(b"updated") + target = self.tmp_path / "Scripture Archive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + spawned = False - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - launch_installed_application(target, spawn=spawn) - assert spawned is False + def spawn(*args, **kwargs): + nonlocal spawned + spawned = True + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + launch_installed_application(target, spawn=spawn) + self.assertFalse(spawned) -def test_relaunch_translates_process_creation_failure(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") + def test_relaunch_translates_process_creation_failure(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") - def spawn(*args, **kwargs): - raise OSError("cannot execute") + def spawn(*args, **kwargs): + raise OSError("cannot execute") - with pytest.raises(ApplicationUpdateError, match="could not be started"): - launch_installed_application(target, spawn=spawn) + with self.assertRaisesRegex(ApplicationUpdateError, "could not be started"): + launch_installed_application(target, spawn=spawn) + + def test_relaunch_requires_callable_spawner(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + with self.assertRaisesRegex(ApplicationUpdateError, "process spawner"): + launch_installed_application(target, spawn=None) # type: ignore[arg-type] -def test_relaunch_requires_callable_spawner(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") - with pytest.raises(ApplicationUpdateError, match="process spawner"): - launch_installed_application(target, spawn=None) # type: ignore[arg-type] +if __name__ == "__main__": + unittest.main() From 37eba77e187bf96a4460902b368d333eaed7fe1f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:24:07 +0200 Subject: [PATCH 087/118] R06: make updater runner regressions discoverable by unittest --- .../tests/test_application_update_runner.py | 551 +++++++++--------- 1 file changed, 291 insertions(+), 260 deletions(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index e2599005e..87a7551eb 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError @@ -35,7 +35,9 @@ def _result(plan) -> UpdateApplyResult: return UpdateApplyResult( previous_sha256="1" * 64, installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_name(plan.installed_executable.name + ".scripture-archive.rollback"), + rollback_path=plan.installed_executable.with_name( + plan.installed_executable.name + ".scripture-archive.rollback" + ), target_path=plan.installed_executable, target_version="1.1.0", ) @@ -49,279 +51,308 @@ def _discard_noop(*args, **kwargs): return False -def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(tmp_path: Path) -> None: - plan = _plan(tmp_path) - events: list[object] = [] - sentinel = _result(plan) - - def wait_for_exit(parent_pid: int) -> None: - events.append(("wait", parent_pid)) +class ApplicationUpdateRunnerTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) - def consume(staging_root, **kwargs): - events.append(("consume", Path(staging_root), kwargs)) - return sentinel + def tearDown(self) -> None: + self.temp.cleanup() - def publish_health(staging_root, **kwargs): - events.append(("health", Path(staging_root), kwargs)) - return object() + def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(self) -> None: + plan = _plan(self.tmp_path) + events: list[object] = [] + sentinel = _result(plan) - def launch(target: Path) -> None: - events.append(("launch", target)) - - verifier = lambda installed, staged: True - result = execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=verifier, - wait_for_exit=wait_for_exit, - consume=consume, - publish_health=publish_health, - discard_health=_discard_noop, - launch=launch, - ) + def wait_for_exit(parent_pid: int) -> None: + events.append(("wait", parent_pid)) - assert result is sentinel - assert events[0] == ("wait", os.getpid()) - kind, staging, kwargs = events[1] - assert kind == "consume" - assert staging == plan.staging_root - assert kwargs == { - "current_version": "1.0.0", - "install_target": plan.installed_executable, - "verify_same_publisher": verifier, - } - kind, staging, kwargs = events[2] - assert kind == "health" - assert staging == plan.staging_root - assert kwargs == { - "previous_version": "1.0.0", - "target_version": "1.1.0", - "install_target": plan.installed_executable, - "previous_sha256": sentinel.previous_sha256, - "installed_sha256": sentinel.installed_sha256, - } - assert events[3] == ("launch", plan.installed_executable) - - -def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - def launch(target: Path) -> None: - events.append(("launch", target)) - - with pytest.raises(ApplicationUpdateError, match="health receipt publication failed; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("receipt failed")), - discard_health=discard, - rollback=rollback, - launch=launch, - ) - assert events == [ - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] + def consume(staging_root, **kwargs): + events.append(("consume", Path(staging_root), kwargs)) + return sentinel + def publish_health(staging_root, **kwargs): + events.append(("health", Path(staging_root), kwargs)) + return object() -def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] + def launch(target: Path) -> None: + events.append(("launch", target)) - def publish(staging_root, **kwargs): - events.append(("publish", Path(staging_root))) - return object() - - def launch(target: Path) -> None: - events.append(("launch", target)) - raise ApplicationUpdateError("spawn failed") - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - with pytest.raises(ApplicationUpdateError, match="rollback restored prior bytes"): - execute_trusted_updater( + verifier = lambda installed, staged: True + result = execute_trusted_updater( plan.argv()[1:], current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=discard, + verify_same_publisher=verifier, + wait_for_exit=wait_for_exit, + consume=consume, + publish_health=publish_health, + discard_health=_discard_noop, launch=launch, - rollback=rollback, ) - assert events == [ - ("publish", plan.staging_root), - ("launch", plan.installed_executable), - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] - - -def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - - with pytest.raises(ApplicationUpdateError, match="relaunch failed and rollback also failed"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=_publish_noop, - discard_health=_discard_noop, - launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), - rollback=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("rollback failed")), + self.assertIs(result, sentinel) + self.assertEqual(events[0], ("wait", os.getpid())) + kind, staging, kwargs = events[1] + self.assertEqual(kind, "consume") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "current_version": "1.0.0", + "install_target": plan.installed_executable, + "verify_same_publisher": verifier, + }, ) - - -def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = UpdateApplyResult( - previous_sha256="1" * 64, - installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_suffix(".rollback"), - target_path=tmp_path / "other.exe", - target_version="1.1.0", - ) - events: list[object] = [] - - def publish(*args, **kwargs): - events.append(("health",)) - - def launch(target: Path) -> None: - events.append(("launch", target)) - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - with pytest.raises(ApplicationUpdateError, match="unexpected install target; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=_discard_noop, - launch=launch, - rollback=rollback, + kind, staging, kwargs = events[2] + self.assertEqual(kind, "health") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "previous_version": "1.0.0", + "target_version": "1.1.0", + "install_target": plan.installed_executable, + "previous_sha256": sentinel.previous_sha256, + "installed_sha256": sentinel.installed_sha256, + }, ) - assert events == [("rollback", plan.installed_executable, sentinel.previous_sha256)] - - -def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: - plan = _plan(tmp_path) - consumed = False - - def blocked_wait(parent_pid: int) -> None: - raise ParentProcessWaitError("parent still alive") - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(ParentProcessWaitError, match="parent still alive"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=blocked_wait, - consume=consume, + self.assertEqual(events[3], ("launch", plan.installed_executable)) + + def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + def launch(target: Path) -> None: + events.append(("launch", target)) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "health receipt publication failed; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("receipt failed") + ), + discard_health=discard, + rollback=rollback, + launch=launch, + ) + self.assertEqual( + events, + [ + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert consumed is False - -def test_runner_rejects_malformed_command_before_wait_or_consume() -> None: - waited = False - consumed = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(UpdateProcessError, match="invalid updater command shape"): - execute_trusted_updater( - ("--scripture-archive-apply", "--wait-pid", "1"), - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, - consume=consume, + def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def publish(staging_root, **kwargs): + events.append(("publish", Path(staging_root))) + return object() + + def launch(target: Path) -> None: + events.append(("launch", target)) + raise ApplicationUpdateError("spawn failed") + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + with self.assertRaisesRegex(ApplicationUpdateError, "rollback restored prior bytes"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=discard, + launch=launch, + rollback=rollback, + ) + + self.assertEqual( + events, + [ + ("publish", plan.staging_root), + ("launch", plan.installed_executable), + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert waited is False - assert consumed is False - -@pytest.mark.parametrize("current_version", ["", "1", "01.0.0", "1.0", "1.0.0 "]) -def test_runner_rejects_invalid_trusted_current_version_before_wait( - tmp_path: Path, current_version: str -) -> None: - plan = _plan(tmp_path) - waited = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - with pytest.raises(ApplicationUpdateError): - execute_trusted_updater( - plan.argv()[1:], - current_version=current_version, - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, + def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "relaunch failed and rollback also failed", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=_publish_noop, + discard_health=_discard_noop, + launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), + rollback=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("rollback failed") + ), + ) + + def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_suffix(".rollback"), + target_path=self.tmp_path / "other.exe", + target_version="1.1.0", ) - assert waited is False - - -@pytest.mark.parametrize( - ("override", "message"), - [ - ({"verify_same_publisher": None}, "same-publisher verifier"), - ({"wait_for_exit": None}, "parent-exit waiter"), - ({"consume": None}, "apply consumer"), - ({"launch": None}, "application launcher"), - ({"rollback": None}, "rollback consumer"), - ({"publish_health": None}, "health receipt publisher"), - ({"discard_health": None}, "health receipt discarder"), - ], -) -def test_runner_requires_callable_security_dependencies_before_wait( - tmp_path: Path, override: dict[str, object], message: str -) -> None: - plan = _plan(tmp_path) - kwargs = { - "current_version": "1.0.0", - "verify_same_publisher": lambda installed, staged: True, - } - kwargs.update(override) - with pytest.raises(ApplicationUpdateError, match=message): - execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + events: list[object] = [] + + def publish(*args, **kwargs): + events.append(("health",)) + + def launch(target: Path) -> None: + events.append(("launch", target)) + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with self.assertRaisesRegex( + ApplicationUpdateError, + "unexpected install target; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=_discard_noop, + launch=launch, + rollback=rollback, + ) + self.assertEqual( + events, + [("rollback", plan.installed_executable, sentinel.previous_sha256)], + ) + + def test_runner_never_consumes_when_parent_exit_cannot_be_proven(self) -> None: + plan = _plan(self.tmp_path) + consumed = False + + def blocked_wait(parent_pid: int) -> None: + raise ParentProcessWaitError("parent still alive") + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(ParentProcessWaitError, "parent still alive"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=blocked_wait, + consume=consume, + ) + self.assertFalse(consumed) + + def test_runner_rejects_malformed_command_before_wait_or_consume(self) -> None: + waited = False + consumed = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(UpdateProcessError, "invalid updater command shape"): + execute_trusted_updater( + ("--scripture-archive-apply", "--wait-pid", "1"), + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + consume=consume, + ) + self.assertFalse(waited) + self.assertFalse(consumed) + + def test_runner_rejects_invalid_trusted_current_version_before_wait(self) -> None: + invalid_versions = ["", "1", "01.0.0", "1.0", "1.0.0 "] + for current_version in invalid_versions: + with self.subTest(current_version=current_version): + plan = _plan(self.tmp_path / current_version.replace(".", "_").replace(" ", "_")) + waited = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + with self.assertRaises(ApplicationUpdateError): + execute_trusted_updater( + plan.argv()[1:], + current_version=current_version, + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + ) + self.assertFalse(waited) + + def test_runner_requires_callable_security_dependencies_before_wait(self) -> None: + overrides = [ + ({"verify_same_publisher": None}, "same-publisher verifier"), + ({"wait_for_exit": None}, "parent-exit waiter"), + ({"consume": None}, "apply consumer"), + ({"launch": None}, "application launcher"), + ({"rollback": None}, "rollback consumer"), + ({"publish_health": None}, "health receipt publisher"), + ({"discard_health": None}, "health receipt discarder"), + ] + for index, (override, message) in enumerate(overrides): + with self.subTest(message=message): + plan = _plan(self.tmp_path / f"dependency-{index}") + kwargs = { + "current_version": "1.0.0", + "verify_same_publisher": lambda installed, staged: True, + } + kwargs.update(override) + with self.assertRaisesRegex(ApplicationUpdateError, message): + execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() From afbd2276852a893b4aae9aeeed2c5fd48f3d6dcb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:24:22 +0200 Subject: [PATCH 088/118] R06: keep runtime regression gates dependency-free --- .github/workflows/r06-dev10-integration.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index ec10d8675..eb32befdc 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -31,8 +31,6 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.13' - - name: Install runtime test dependency - run: python -m pip install --disable-pip-version-check pytest - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools From b5cd9f14885e15f0ab1e6b8f8f1e7a6261c7671b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:25:06 +0200 Subject: [PATCH 089/118] R06: keep updater qualification on canonical unittest runner --- .github/workflows/r06-dev05-runtime.yml | 4 +- .github/workflows/r06-dev10-integration.yml | 5 +- .../tests/test_application_update_health.py | 289 ++++----- .../test_application_update_parent_wait.py | 80 ++- .../tests/test_application_update_process.py | 290 ++++----- .../tests/test_application_update_relaunch.py | 96 +-- .../tests/test_application_update_runner.py | 589 ++++++++++-------- 7 files changed, 703 insertions(+), 650 deletions(-) diff --git a/.github/workflows/r06-dev05-runtime.yml b/.github/workflows/r06-dev05-runtime.yml index bc574fe32..65cee9f47 100644 --- a/.github/workflows/r06-dev05-runtime.yml +++ b/.github/workflows/r06-dev05-runtime.yml @@ -34,7 +34,5 @@ jobs: python-version: "3.11" - name: Compile runtime and tests run: python -m compileall -q scripture_archive_runtime tests - - name: Install runtime test runner - run: python -m pip install --disable-pip-version-check pytest==8.4.2 - name: Runtime regression suite - run: python -m pytest -v tests + run: python -m unittest discover -s tests -v diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index 8a51ec525..eb32befdc 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -34,12 +34,9 @@ jobs: - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools - - name: Install runtime test runner - working-directory: runtime_engine - run: python -m pip install --disable-pip-version-check pytest==8.4.2 - name: Run complete runtime regression suite working-directory: runtime_engine - run: python -m pytest -v tests + run: python -m unittest discover -s tests -v release-secret-scan: runs-on: ubuntu-latest diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index e5fa9db77..6a6aa2a29 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -3,8 +3,8 @@ import hashlib import json from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_health import ( @@ -24,149 +24,156 @@ def _sha(data: bytes) -> str: return hashlib.sha256(data).hexdigest() -def _fixture(tmp_path: Path): - root = tmp_path / "state" / "updates" - root.mkdir(parents=True) - target = tmp_path / "install" / "Scripture Archive.exe" - target.parent.mkdir() - previous = b"previous-installed-exact-bytes" - installed = b"updated-installed-exact-bytes" - target.write_bytes(installed) - rollback = target.with_name(target.name + ".scripture-archive.rollback") - rollback.write_bytes(previous) - return root, target, rollback, previous, installed - - -def _publish(tmp_path: Path): - root, target, rollback, previous, installed = _fixture(tmp_path) - receipt = publish_update_health_receipt( - root, - previous_version=PREVIOUS_VERSION, - target_version=TARGET_VERSION, - install_target=target, - previous_sha256=_sha(previous), - installed_sha256=_sha(installed), - ) - return root, target, rollback, previous, installed, receipt - - -def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - assert receipt.previous_version == PREVIOUS_VERSION - assert receipt.target_version == TARGET_VERSION - assert receipt.installed_executable_name == target.name - assert receipt.previous_sha256 == _sha(previous) - assert receipt.installed_sha256 == _sha(installed) - assert inspect_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) == receipt - - payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) - assert payload["schema"] == HEALTH_RECEIPT_SCHEMA - assert payload["status"] == "awaiting_health_commit" - serialized = json.dumps(payload) - assert str(tmp_path) not in serialized - assert "install_target" not in payload - assert "rollback_path" not in payload - - -def test_publish_is_idempotent_only_for_same_exact_identity(tmp_path: Path) -> None: - root, target, rollback, previous, installed, first = _publish(tmp_path) - before = (root / "update-health.json").read_bytes() - second = publish_update_health_receipt( - root, - previous_version=PREVIOUS_VERSION, - target_version=TARGET_VERSION, - install_target=target, - previous_sha256=_sha(previous), - installed_sha256=_sha(installed), - ) - assert second == first - assert (root / "update-health.json").read_bytes() == before - - with pytest.raises(ApplicationUpdateError, match="different identity"): - publish_update_health_receipt( +class ApplicationUpdateHealthTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def _fixture(self): + root = self.tmp_path / "state" / "updates" + root.mkdir(parents=True) + target = self.tmp_path / "install" / "Scripture Archive.exe" + target.parent.mkdir() + previous = b"previous-installed-exact-bytes" + installed = b"updated-installed-exact-bytes" + target.write_bytes(installed) + rollback = target.with_name(target.name + ".scripture-archive.rollback") + rollback.write_bytes(previous) + return root, target, rollback, previous, installed + + def _publish(self): + root, target, rollback, previous, installed = self._fixture() + receipt = publish_update_health_receipt( root, previous_version=PREVIOUS_VERSION, - target_version="1.2.0", + target_version=TARGET_VERSION, install_target=target, previous_sha256=_sha(previous), installed_sha256=_sha(installed), ) + return root, target, rollback, previous, installed, receipt + + def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + + self.assertEqual(receipt.previous_version, PREVIOUS_VERSION) + self.assertEqual(receipt.target_version, TARGET_VERSION) + self.assertEqual(receipt.installed_executable_name, target.name) + self.assertEqual(receipt.previous_sha256, _sha(previous)) + self.assertEqual(receipt.installed_sha256, _sha(installed)) + self.assertEqual( + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ), + receipt, + ) - -def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - with pytest.raises(ApplicationUpdateError, match="target version is not current"): - inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) - - target.write_bytes(b"x" * len(installed)) - with pytest.raises(ApplicationUpdateError, match="installed application bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - target.write_bytes(installed) - - rollback.write_bytes(b"y" * len(previous)) - with pytest.raises(ApplicationUpdateError, match="rollback bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_receipt_shape_extra_field_and_symlink_fail_closed(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - path = root / "update-health.json" - payload = json.loads(path.read_text(encoding="utf-8")) - payload["unexpected"] = True - path.write_text(json.dumps(payload), encoding="utf-8") - with pytest.raises(ApplicationUpdateError, match="shape is invalid"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - path.unlink() - real = root / "real-health.json" - real.write_text("{}", encoding="utf-8") - try: - path.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal need not be parsed", encoding="utf-8") - - committed = commit_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) - assert committed == receipt - assert not pending.exists() - assert not (root / "update-health.json").exists() - assert not rollback.exists() - assert target.read_bytes() == installed - - -def test_failed_health_proof_preserves_receipt_pending_and_rollback(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal", encoding="utf-8") - target.write_bytes(b"tampered") - - with pytest.raises(ApplicationUpdateError): - commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - assert pending.exists() - assert (root / "update-health.json").exists() - assert rollback.exists() - - -def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - assert discard_update_health_receipt(root) is True - assert discard_update_health_receipt(root) is False - assert rollback.read_bytes() == previous - assert target.read_bytes() == installed + payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) + self.assertEqual(payload["schema"], HEALTH_RECEIPT_SCHEMA) + self.assertEqual(payload["status"], "awaiting_health_commit") + serialized = json.dumps(payload) + self.assertNotIn(str(self.tmp_path), serialized) + self.assertNotIn("install_target", payload) + self.assertNotIn("rollback_path", payload) + + def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: + root, target, rollback, previous, installed, first = self._publish() + before = (root / "update-health.json").read_bytes() + second = publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version=TARGET_VERSION, + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + self.assertEqual(second, first) + self.assertEqual((root / "update-health.json").read_bytes(), before) + + with self.assertRaisesRegex(ApplicationUpdateError, "different identity"): + publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version="1.2.0", + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + + def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + + with self.assertRaisesRegex(ApplicationUpdateError, "target version is not current"): + inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) + + target.write_bytes(b"x" * len(installed)) + with self.assertRaisesRegex(ApplicationUpdateError, "installed application bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + target.write_bytes(installed) + + rollback.write_bytes(b"y" * len(previous)) + with self.assertRaisesRegex(ApplicationUpdateError, "rollback bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + path = root / "update-health.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["unexpected"] = True + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaisesRegex(ApplicationUpdateError, "shape is invalid"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + path.unlink() + real = root / "real-health.json" + real.write_text("{}", encoding="utf-8") + try: + path.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + pending = root / "pending-update.json" + pending.write_text("old-version journal need not be parsed", encoding="utf-8") + + committed = commit_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + self.assertEqual(committed, receipt) + self.assertFalse(pending.exists()) + self.assertFalse((root / "update-health.json").exists()) + self.assertFalse(rollback.exists()) + self.assertEqual(target.read_bytes(), installed) + + def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + pending = root / "pending-update.json" + pending.write_text("old-version journal", encoding="utf-8") + target.write_bytes(b"tampered") + + with self.assertRaises(ApplicationUpdateError): + commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + self.assertTrue(pending.exists()) + self.assertTrue((root / "update-health.json").exists()) + self.assertTrue(rollback.exists()) + + def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = self._publish() + self.assertTrue(discard_update_health_receipt(root)) + self.assertFalse(discard_update_health_receipt(root)) + self.assertEqual(rollback.read_bytes(), previous) + self.assertEqual(target.read_bytes(), installed) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py index 41e41fbc8..e22ecc7c4 100644 --- a/runtime_engine/tests/test_application_update_parent_wait.py +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -1,8 +1,7 @@ from __future__ import annotations import os - -import pytest +import unittest from scripture_archive_runtime.application_update_parent_wait import ( ParentProcessWaitError, @@ -10,56 +9,55 @@ ) -def test_wait_uses_exact_pid_and_bounded_timeout() -> None: - seen: list[tuple[int, int]] = [] - - def backend(pid: int, timeout_ms: int) -> None: - seen.append((pid, timeout_ms)) - - wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) - assert seen == [(4242, 30_000)] - - -def test_wait_rejects_own_pid_before_backend() -> None: - called = False +class ParentProcessWaitTests(unittest.TestCase): + def test_wait_uses_exact_pid_and_bounded_timeout(self) -> None: + seen: list[tuple[int, int]] = [] - def backend(pid: int, timeout_ms: int) -> None: - nonlocal called - called = True + def backend(pid: int, timeout_ms: int) -> None: + seen.append((pid, timeout_ms)) - with pytest.raises(ParentProcessWaitError, match="own process"): - wait_for_parent_exit(os.getpid(), wait_backend=backend) - assert called is False + wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) + self.assertEqual(seen, [(4242, 30_000)]) + def test_wait_rejects_own_pid_before_backend(self) -> None: + called = False -@pytest.mark.parametrize("pid", [0, -1, True, 1.5, "1"]) -def test_wait_rejects_invalid_pid(pid) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(pid, wait_backend=lambda *_: None) + def backend(pid: int, timeout_ms: int) -> None: + nonlocal called + called = True + with self.assertRaisesRegex(ParentProcessWaitError, "own process"): + wait_for_parent_exit(os.getpid(), wait_backend=backend) + self.assertFalse(called) -@pytest.mark.parametrize("timeout_ms", [0, -1, 120_001, True, 1.5]) -def test_wait_rejects_invalid_or_unbounded_timeout(timeout_ms) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) + def test_wait_rejects_invalid_pid(self) -> None: + for pid in [0, -1, True, 1.5, "1"]: + with self.subTest(pid=pid), self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit(pid, wait_backend=lambda *_: None) + def test_wait_rejects_invalid_or_unbounded_timeout(self) -> None: + for timeout_ms in [0, -1, 120_001, True, 1.5]: + with self.subTest(timeout_ms=timeout_ms), self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) -def test_wait_is_windows_only_without_injected_backend() -> None: - with pytest.raises(ParentProcessWaitError, match="Windows-only"): - wait_for_parent_exit(4242, os_name="posix") + def test_wait_is_windows_only_without_injected_backend(self) -> None: + with self.assertRaisesRegex(ParentProcessWaitError, "Windows-only"): + wait_for_parent_exit(4242, os_name="posix") + def test_wait_wraps_backend_failure(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise OSError("boom") -def test_wait_wraps_backend_failure() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise OSError("boom") + with self.assertRaisesRegex(ParentProcessWaitError, "wait failed"): + wait_for_parent_exit(4242, wait_backend=backend) - with pytest.raises(ParentProcessWaitError, match="wait failed"): - wait_for_parent_exit(4242, wait_backend=backend) + def test_wait_preserves_fail_closed_backend_verdict(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise ParentProcessWaitError("parent process did not exit before timeout") + with self.assertRaisesRegex(ParentProcessWaitError, "did not exit"): + wait_for_parent_exit(4242, wait_backend=backend) -def test_wait_preserves_fail_closed_backend_verdict() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise ParentProcessWaitError("parent process did not exit before timeout") - with pytest.raises(ParentProcessWaitError, match="did not exit"): - wait_for_parent_exit(4242, wait_backend=backend) +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py index 55390bc03..c5106b341 100644 --- a/runtime_engine/tests/test_application_update_process.py +++ b/runtime_engine/tests/test_application_update_process.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update_process import ( UpdateProcessError, @@ -13,161 +13,165 @@ ) -def _files(tmp_path: Path) -> tuple[Path, Path, Path]: - install = tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - app = install / "Scripture Archive.exe" - updater = install / "Scripture Archive Updater.exe" - app.write_bytes(b"installed") - updater.write_bytes(b"updater") - staging = tmp_path / "state" / "updates" - staging.mkdir(parents=True) - return updater, app, staging - - -def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - assert plan.parent_pid == os.getpid() - assert plan.updater_executable == updater.resolve() - assert plan.installed_executable == app.resolve() - assert plan.staging_root == staging.resolve() - assert plan.argv() == ( - str(updater.resolve()), - "--scripture-archive-apply", - "--wait-pid", - str(os.getpid()), - "--installed-executable", - str(app.resolve()), - "--staging-root", - str(staging.resolve()), - ) - - -def test_build_plan_rejects_external_updater(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - external = tmp_path / "outside-updater.exe" - external.write_bytes(updater.read_bytes()) - with pytest.raises(UpdateProcessError, match="packaged beside"): - build_updater_process_plan( - updater_executable=external, +class ApplicationUpdateProcessTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def _files(self) -> tuple[Path, Path, Path]: + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = self.tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return updater, app, staging + + def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(self) -> None: + updater, app, staging = self._files() + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) - - -def test_build_plan_rejects_current_app_as_updater(tmp_path: Path) -> None: - _, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="distinct"): - build_updater_process_plan( - updater_executable=app, - installed_executable=app, - staging_root=staging, + self.assertEqual(plan.parent_pid, os.getpid()) + self.assertEqual(plan.updater_executable, updater.resolve()) + self.assertEqual(plan.installed_executable, app.resolve()) + self.assertEqual(plan.staging_root, staging.resolve()) + self.assertEqual( + plan.argv(), + ( + str(updater.resolve()), + "--scripture-archive-apply", + "--wait-pid", + str(os.getpid()), + "--installed-executable", + str(app.resolve()), + "--staging-root", + str(staging.resolve()), + ), ) - -def test_build_plan_rejects_symlinked_updater_target_and_staging(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - updater_link = updater.parent / "link-updater.exe" - staging_link = tmp_path / "state-link" - try: - updater_link.symlink_to(updater) - staging_link.symlink_to(staging, target_is_directory=True) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(UpdateProcessError, match="non-symlink"): - build_updater_process_plan( - updater_executable=updater_link, + def test_build_plan_rejects_external_updater(self) -> None: + updater, app, staging = self._files() + external = self.tmp_path / "outside-updater.exe" + external.write_bytes(updater.read_bytes()) + with self.assertRaisesRegex(UpdateProcessError, "packaged beside"): + build_updater_process_plan( + updater_executable=external, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_current_app_as_updater(self) -> None: + _, app, staging = self._files() + with self.assertRaisesRegex(UpdateProcessError, "distinct"): + build_updater_process_plan( + updater_executable=app, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: + updater, app, staging = self._files() + updater_link = updater.parent / "link-updater.exe" + staging_link = self.tmp_path / "state-link" + try: + updater_link.symlink_to(updater) + staging_link.symlink_to(staging, target_is_directory=True) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(UpdateProcessError, "non-symlink"): + build_updater_process_plan( + updater_executable=updater_link, + installed_executable=app, + staging_root=staging, + ) + with self.assertRaisesRegex(UpdateProcessError, "real directory"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging_link, + ) + + def test_build_plan_rejects_foreign_parent_pid(self) -> None: + updater, app, staging = self._files() + with self.assertRaisesRegex(UpdateProcessError, "current host process"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + parent_pid=os.getpid() + 1, + ) + + def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(self) -> None: + updater, app, staging = self._files() + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) - with pytest.raises(UpdateProcessError, match="real directory"): - build_updater_process_plan( + seen: dict[str, object] = {} + + class Child: + pid = 43210 + + def fake_popen(argv, **kwargs): + seen["argv"] = argv + seen.update(kwargs) + return Child() + + pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") + self.assertEqual(pid, 43210) + self.assertEqual(seen["argv"], list(plan.argv())) + self.assertEqual(seen["cwd"], str(app.resolve().parent)) + self.assertIs(seen["shell"], False) + self.assertIs(seen["close_fds"], True) + self.assertEqual(seen["creationflags"], 0) + + def test_launch_wraps_process_failure(self) -> None: + updater, app, staging = self._files() + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, - staging_root=staging_link, + staging_root=staging, ) + def broken_popen(*args, **kwargs): + raise OSError("boom") + + with self.assertRaisesRegex(UpdateProcessError, "failed to launch"): + launch_updater_process(plan, popen=broken_popen) -def test_build_plan_rejects_foreign_parent_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="current host process"): - build_updater_process_plan( + def test_parser_accepts_only_fixed_host_contract(self) -> None: + updater, app, staging = self._files() + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, staging_root=staging, - parent_pid=os.getpid() + 1, ) - - -def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - seen: dict[str, object] = {} - - class Child: - pid = 43210 - - def fake_popen(argv, **kwargs): - seen["argv"] = argv - seen.update(kwargs) - return Child() - - pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") - assert pid == 43210 - assert seen["argv"] == list(plan.argv()) - assert seen["cwd"] == str(app.resolve().parent) - assert seen["shell"] is False - assert seen["close_fds"] is True - assert seen["creationflags"] == 0 - - -def test_launch_wraps_process_failure(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - - def broken_popen(*args, **kwargs): - raise OSError("boom") - - with pytest.raises(UpdateProcessError, match="failed to launch"): - launch_updater_process(plan, popen=broken_popen) - - -def test_parser_accepts_only_fixed_host_contract(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) - assert pid == os.getpid() - assert parsed_app == app.resolve() - assert parsed_staging == staging.resolve() - - -@pytest.mark.parametrize( - "argv", - [ - (), - ("--scripture-archive-apply",), - ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), - ], -) -def test_parser_rejects_noncanonical_or_extended_commands(argv: tuple[str, ...]) -> None: - with pytest.raises(UpdateProcessError): - parse_trusted_updater_argv(argv) + pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) + self.assertEqual(pid, os.getpid()) + self.assertEqual(parsed_app, app.resolve()) + self.assertEqual(parsed_staging, staging.resolve()) + + def test_parser_rejects_noncanonical_or_extended_commands(self) -> None: + cases = [ + (), + ("--scripture-archive-apply",), + ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), + ] + for argv in cases: + with self.subTest(argv=argv), self.assertRaises(UpdateProcessError): + parse_trusted_updater_argv(argv) + + +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_relaunch.py b/runtime_engine/tests/test_application_update_relaunch.py index 0f631ea48..6c05123d0 100644 --- a/runtime_engine/tests/test_application_update_relaunch.py +++ b/runtime_engine/tests/test_application_update_relaunch.py @@ -1,64 +1,76 @@ from __future__ import annotations from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_relaunch import launch_installed_application -def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(tmp_path: Path) -> None: - install = tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - target = install / "Scripture Archive.exe" - target.write_bytes(b"updated") - calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] +class ApplicationUpdateRelaunchTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) - def spawn(argv, **kwargs): - calls.append((tuple(argv), dict(kwargs))) - return object() + def tearDown(self) -> None: + self.temp.cleanup() - launch_installed_application(target, spawn=spawn) + def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(self) -> None: + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + target = install / "Scripture Archive.exe" + target.write_bytes(b"updated") + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] - assert calls == [ - ((str(target),), {"cwd": str(install), "close_fds": True}), - ] + def spawn(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + launch_installed_application(target, spawn=spawn) -def test_relaunch_rejects_symlink_target_before_spawn(tmp_path: Path) -> None: - real = tmp_path / "real.exe" - real.write_bytes(b"updated") - target = tmp_path / "Scripture Archive.exe" - try: - target.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - spawned = False + self.assertEqual( + calls, + [ + ((str(target),), {"cwd": str(install), "close_fds": True}), + ], + ) - def spawn(*args, **kwargs): - nonlocal spawned - spawned = True + def test_relaunch_rejects_symlink_target_before_spawn(self) -> None: + real = self.tmp_path / "real.exe" + real.write_bytes(b"updated") + target = self.tmp_path / "Scripture Archive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + spawned = False - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - launch_installed_application(target, spawn=spawn) - assert spawned is False + def spawn(*args, **kwargs): + nonlocal spawned + spawned = True + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + launch_installed_application(target, spawn=spawn) + self.assertFalse(spawned) -def test_relaunch_translates_process_creation_failure(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") + def test_relaunch_translates_process_creation_failure(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") - def spawn(*args, **kwargs): - raise OSError("cannot execute") + def spawn(*args, **kwargs): + raise OSError("cannot execute") - with pytest.raises(ApplicationUpdateError, match="could not be started"): - launch_installed_application(target, spawn=spawn) + with self.assertRaisesRegex(ApplicationUpdateError, "could not be started"): + launch_installed_application(target, spawn=spawn) + + def test_relaunch_requires_callable_spawner(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + with self.assertRaisesRegex(ApplicationUpdateError, "process spawner"): + launch_installed_application(target, spawn=None) # type: ignore[arg-type] -def test_relaunch_requires_callable_spawner(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") - with pytest.raises(ApplicationUpdateError, match="process spawner"): - launch_installed_application(target, spawn=None) # type: ignore[arg-type] +if __name__ == "__main__": + unittest.main() diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index e2599005e..fef0f8101 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError @@ -15,27 +15,13 @@ from scripture_archive_runtime.application_update_updater import UpdateApplyResult -def _plan(tmp_path: Path): - install = tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - app = install / "Scripture Archive.exe" - updater = install / "Scripture Archive Updater.exe" - app.write_bytes(b"installed") - updater.write_bytes(b"updater") - staging = tmp_path / "state" / "updates" - staging.mkdir(parents=True) - return build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - - def _result(plan) -> UpdateApplyResult: return UpdateApplyResult( previous_sha256="1" * 64, installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_name(plan.installed_executable.name + ".scripture-archive.rollback"), + rollback_path=plan.installed_executable.with_name( + plan.installed_executable.name + ".scripture-archive.rollback" + ), target_path=plan.installed_executable, target_version="1.1.0", ) @@ -49,279 +35,330 @@ def _discard_noop(*args, **kwargs): return False -def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(tmp_path: Path) -> None: - plan = _plan(tmp_path) - events: list[object] = [] - sentinel = _result(plan) - - def wait_for_exit(parent_pid: int) -> None: - events.append(("wait", parent_pid)) - - def consume(staging_root, **kwargs): - events.append(("consume", Path(staging_root), kwargs)) - return sentinel - - def publish_health(staging_root, **kwargs): - events.append(("health", Path(staging_root), kwargs)) - return object() - - def launch(target: Path) -> None: - events.append(("launch", target)) - - verifier = lambda installed, staged: True - result = execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=verifier, - wait_for_exit=wait_for_exit, - consume=consume, - publish_health=publish_health, - discard_health=_discard_noop, - launch=launch, - ) - - assert result is sentinel - assert events[0] == ("wait", os.getpid()) - kind, staging, kwargs = events[1] - assert kind == "consume" - assert staging == plan.staging_root - assert kwargs == { - "current_version": "1.0.0", - "install_target": plan.installed_executable, - "verify_same_publisher": verifier, - } - kind, staging, kwargs = events[2] - assert kind == "health" - assert staging == plan.staging_root - assert kwargs == { - "previous_version": "1.0.0", - "target_version": "1.1.0", - "install_target": plan.installed_executable, - "previous_sha256": sentinel.previous_sha256, - "installed_sha256": sentinel.installed_sha256, - } - assert events[3] == ("launch", plan.installed_executable) - - -def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - def launch(target: Path) -> None: - events.append(("launch", target)) - - with pytest.raises(ApplicationUpdateError, match="health receipt publication failed; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("receipt failed")), - discard_health=discard, - rollback=rollback, - launch=launch, +class ApplicationUpdateRunnerTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def _plan(self): + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + app = install / "Scripture Archive.exe" + updater = install / "Scripture Archive Updater.exe" + app.write_bytes(b"installed") + updater.write_bytes(b"updater") + staging = self.tmp_path / "state" / "updates" + staging.mkdir(parents=True) + return build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, ) - assert events == [ - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] + def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(self) -> None: + plan = self._plan() + events: list[object] = [] + sentinel = _result(plan) -def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] + def wait_for_exit(parent_pid: int) -> None: + events.append(("wait", parent_pid)) - def publish(staging_root, **kwargs): - events.append(("publish", Path(staging_root))) - return object() + def consume(staging_root, **kwargs): + events.append(("consume", Path(staging_root), kwargs)) + return sentinel - def launch(target: Path) -> None: - events.append(("launch", target)) - raise ApplicationUpdateError("spawn failed") + def publish_health(staging_root, **kwargs): + events.append(("health", Path(staging_root), kwargs)) + return object() - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 + def launch(target: Path) -> None: + events.append(("launch", target)) - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - with pytest.raises(ApplicationUpdateError, match="rollback restored prior bytes"): - execute_trusted_updater( + verifier = lambda installed, staged: True + result = execute_trusted_updater( plan.argv()[1:], current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=discard, + verify_same_publisher=verifier, + wait_for_exit=wait_for_exit, + consume=consume, + publish_health=publish_health, + discard_health=_discard_noop, launch=launch, - rollback=rollback, ) - assert events == [ - ("publish", plan.staging_root), - ("launch", plan.installed_executable), - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] - - -def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - - with pytest.raises(ApplicationUpdateError, match="relaunch failed and rollback also failed"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=_publish_noop, - discard_health=_discard_noop, - launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), - rollback=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("rollback failed")), + self.assertIs(result, sentinel) + self.assertEqual(events[0], ("wait", os.getpid())) + kind, staging, kwargs = events[1] + self.assertEqual(kind, "consume") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "current_version": "1.0.0", + "install_target": plan.installed_executable, + "verify_same_publisher": verifier, + }, ) - - -def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = UpdateApplyResult( - previous_sha256="1" * 64, - installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_suffix(".rollback"), - target_path=tmp_path / "other.exe", - target_version="1.1.0", - ) - events: list[object] = [] - - def publish(*args, **kwargs): - events.append(("health",)) - - def launch(target: Path) -> None: - events.append(("launch", target)) - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - with pytest.raises(ApplicationUpdateError, match="unexpected install target; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=_discard_noop, - launch=launch, - rollback=rollback, + kind, staging, kwargs = events[2] + self.assertEqual(kind, "health") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "previous_version": "1.0.0", + "target_version": "1.1.0", + "install_target": plan.installed_executable, + "previous_sha256": sentinel.previous_sha256, + "installed_sha256": sentinel.installed_sha256, + }, ) - assert events == [("rollback", plan.installed_executable, sentinel.previous_sha256)] - - -def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: - plan = _plan(tmp_path) - consumed = False - - def blocked_wait(parent_pid: int) -> None: - raise ParentProcessWaitError("parent still alive") - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(ParentProcessWaitError, match="parent still alive"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=blocked_wait, - consume=consume, + self.assertEqual(events[3], ("launch", plan.installed_executable)) + + def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(self) -> None: + plan = self._plan() + sentinel = _result(plan) + events: list[object] = [] + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + def launch(target: Path) -> None: + events.append(("launch", target)) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "health receipt publication failed; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("receipt failed") + ), + discard_health=discard, + rollback=rollback, + launch=launch, + ) + self.assertEqual( + events, + [ + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert consumed is False - -def test_runner_rejects_malformed_command_before_wait_or_consume() -> None: - waited = False - consumed = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(UpdateProcessError, match="invalid updater command shape"): - execute_trusted_updater( - ("--scripture-archive-apply", "--wait-pid", "1"), - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, - consume=consume, + def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(self) -> None: + plan = self._plan() + sentinel = _result(plan) + events: list[object] = [] + + def publish(staging_root, **kwargs): + events.append(("publish", Path(staging_root))) + return object() + + def launch(target: Path) -> None: + events.append(("launch", target)) + raise ApplicationUpdateError("spawn failed") + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + with self.assertRaisesRegex(ApplicationUpdateError, "rollback restored prior bytes"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=discard, + launch=launch, + rollback=rollback, + ) + + self.assertEqual( + events, + [ + ("publish", plan.staging_root), + ("launch", plan.installed_executable), + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert waited is False - assert consumed is False - -@pytest.mark.parametrize("current_version", ["", "1", "01.0.0", "1.0", "1.0.0 "]) -def test_runner_rejects_invalid_trusted_current_version_before_wait( - tmp_path: Path, current_version: str -) -> None: - plan = _plan(tmp_path) - waited = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - with pytest.raises(ApplicationUpdateError): - execute_trusted_updater( - plan.argv()[1:], - current_version=current_version, - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, + def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: + plan = self._plan() + sentinel = _result(plan) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "relaunch failed and rollback also failed", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=_publish_noop, + discard_health=_discard_noop, + launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), + rollback=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("rollback failed") + ), + ) + + def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(self) -> None: + plan = self._plan() + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_suffix(".rollback"), + target_path=self.tmp_path / "other.exe", + target_version="1.1.0", ) - assert waited is False - - -@pytest.mark.parametrize( - ("override", "message"), - [ - ({"verify_same_publisher": None}, "same-publisher verifier"), - ({"wait_for_exit": None}, "parent-exit waiter"), - ({"consume": None}, "apply consumer"), - ({"launch": None}, "application launcher"), - ({"rollback": None}, "rollback consumer"), - ({"publish_health": None}, "health receipt publisher"), - ({"discard_health": None}, "health receipt discarder"), - ], -) -def test_runner_requires_callable_security_dependencies_before_wait( - tmp_path: Path, override: dict[str, object], message: str -) -> None: - plan = _plan(tmp_path) - kwargs = { - "current_version": "1.0.0", - "verify_same_publisher": lambda installed, staged: True, - } - kwargs.update(override) - with pytest.raises(ApplicationUpdateError, match=message): - execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + events: list[object] = [] + + def publish(*args, **kwargs): + events.append(("health",)) + + def launch(target: Path) -> None: + events.append(("launch", target)) + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with self.assertRaisesRegex( + ApplicationUpdateError, + "unexpected install target; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=_discard_noop, + launch=launch, + rollback=rollback, + ) + self.assertEqual( + events, + [("rollback", plan.installed_executable, sentinel.previous_sha256)], + ) + + def test_runner_never_consumes_when_parent_exit_cannot_be_proven(self) -> None: + plan = self._plan() + consumed = False + + def blocked_wait(parent_pid: int) -> None: + raise ParentProcessWaitError("parent still alive") + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(ParentProcessWaitError, "parent still alive"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=blocked_wait, + consume=consume, + ) + self.assertFalse(consumed) + + def test_runner_rejects_malformed_command_before_wait_or_consume(self) -> None: + waited = False + consumed = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(UpdateProcessError, "invalid updater command shape"): + execute_trusted_updater( + ("--scripture-archive-apply", "--wait-pid", "1"), + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + consume=consume, + ) + self.assertFalse(waited) + self.assertFalse(consumed) + + def test_runner_rejects_invalid_trusted_current_version_before_wait(self) -> None: + for current_version in ["", "1", "01.0.0", "1.0", "1.0.0 "]: + with self.subTest(current_version=current_version): + plan = self._plan() + waited = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + with self.assertRaises(ApplicationUpdateError): + execute_trusted_updater( + plan.argv()[1:], + current_version=current_version, + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + ) + self.assertFalse(waited) + # Recreate the temporary fixture for the next subtest. + if current_version != "1.0.0 ": + self.temp.cleanup() + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def test_runner_requires_callable_security_dependencies_before_wait(self) -> None: + cases = [ + ({"verify_same_publisher": None}, "same-publisher verifier"), + ({"wait_for_exit": None}, "parent-exit waiter"), + ({"consume": None}, "apply consumer"), + ({"launch": None}, "application launcher"), + ({"rollback": None}, "rollback consumer"), + ({"publish_health": None}, "health receipt publisher"), + ({"discard_health": None}, "health receipt discarder"), + ] + for override, message in cases: + with self.subTest(override=override, message=message): + plan = self._plan() + kwargs = { + "current_version": "1.0.0", + "verify_same_publisher": lambda installed, staged: True, + } + kwargs.update(override) + with self.assertRaisesRegex(ApplicationUpdateError, message): + execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + self.temp.cleanup() + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + +if __name__ == "__main__": + unittest.main() From 1f6b307cf6c2b4da5845d51d5f1e0e8e57bdb6ce Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:26:34 +0200 Subject: [PATCH 090/118] R06: align packaged artifact cleanup qualification --- lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 7356fa288..e97bfbe1a 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -173,8 +173,11 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) - stale_cleanup = "Remove-Item -LiteralPath $Out -Force" + stale_cleanup_loop = "foreach ($artifact in @($Out, $UpdaterOut))" + stale_cleanup = "Remove-Item -LiteralPath $artifact -Force" + self.assertIn(stale_cleanup_loop, build) self.assertIn(stale_cleanup, build) + self.assertLess(build.index(stale_cleanup_loop), build.index("pyinstaller.exe")) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( build.index('Assert-NativeSuccess "PyInstaller updater build"'), From 0ac5ba484d386be0b066938929584d1fda19990f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:27:11 +0200 Subject: [PATCH 091/118] R06: lock update transport commands to empty payload --- ..._application_update_transport_contracts.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py new file mode 100644 index 000000000..8e1b1a07f --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import unittest + +from scripture_archive_platform.transport.contracts import validate_request_shape + + +API_VERSION = "scripture.transport.v1" +UPDATE_COMMANDS = ( + "application_update.apply_and_restart", + "application_update.commit_post_restart_health", +) + + +def request(command: str, payload=None, *, request_id: str = "update-contract-rid"): + return { + "api_version": API_VERSION, + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class ApplicationUpdateTransportContractTests(unittest.TestCase): + def test_host_owned_update_commands_are_allowlisted_with_empty_payload(self) -> None: + for command in UPDATE_COMMANDS: + with self.subTest(command=command): + rid, parsed_command, payload = validate_request_shape(request(command)) + self.assertEqual(rid, "update-contract-rid") + self.assertEqual(parsed_command, command) + self.assertEqual(payload, {}) + + def test_browser_cannot_supply_update_process_path_or_identity_authority(self) -> None: + injected_payloads = ( + {"pid": 1}, + {"path": r"C:\attacker.exe"}, + {"version": "9.9.9"}, + {"sha256": "0" * 64}, + ) + for command in UPDATE_COMMANDS: + for payload in injected_payloads: + with self.subTest(command=command, payload=payload): + with self.assertRaisesRegex(ValueError, "empty payload"): + validate_request_shape(request(command, payload)) + + +if __name__ == "__main__": + unittest.main() From b448b40de9f7cbcedc29aba96989ca5678003090 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:36:20 +0200 Subject: [PATCH 092/118] R06 updater: carry atomic authority/resource repair into convergence --- .../application_update_updater.py | 48 ++++++++++++++----- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 49cffdfa2..249a479b1 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -119,7 +119,11 @@ def _consume_apply_handoff_locked( installed_sha = _sha256_file(target) if installed_sha != pending.artifact_sha256: raise ApplicationUpdateError("installed artifact failed exact-byte verification") - discard_apply_handoff(root) + post_publish_handoff = inspect_apply_handoff(root, current_version=current_version) + if post_publish_handoff != pending: + raise ApplicationUpdateError("apply handoff changed after atomic publication") + if discard_apply_handoff(root) is not True: + raise ApplicationUpdateError("apply handoff disappeared during disarm") except Exception as apply_error: try: candidate.unlink() @@ -297,20 +301,38 @@ def _discard_file(path: Path) -> None: def _copy_exact(source: Path, destination: Path) -> None: try: - descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + source_handle = source.open("rb") except OSError as exc: - raise ApplicationUpdateError("could not create update copy safely") from exc - try: - with source.open("rb") as src, os.fdopen(descriptor, "wb", closefd=True) as dst: - shutil.copyfileobj(src, dst, length=_COPY_CHUNK) - dst.flush() - os.fsync(dst.fileno()) - except Exception: + raise ApplicationUpdateError("update source could not be opened") from exc + + with source_handle as src: try: - destination.unlink() - except OSError: - pass - raise + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + except OSError as exc: + raise ApplicationUpdateError("could not create update copy safely") from exc + try: + destination_handle = os.fdopen(descriptor, "wb", closefd=True) + except Exception: + try: + os.close(descriptor) + finally: + try: + destination.unlink() + except OSError: + pass + raise + + try: + with destination_handle as dst: + shutil.copyfileobj(src, dst, length=_COPY_CHUNK) + dst.flush() + os.fsync(dst.fileno()) + except Exception: + try: + destination.unlink() + except OSError: + pass + raise def _sha256_file(path: Path) -> str: From 0446825c6bfff2d33cf7e7c8b2895f06c516856a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:36:49 +0200 Subject: [PATCH 093/118] R06 updater: carry authority/resource regressions into convergence --- .../tests/test_application_update_updater.py | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 79d16c131..7b5a18a47 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -1,6 +1,7 @@ from __future__ import annotations import hashlib +import os from pathlib import Path import tempfile import unittest @@ -9,6 +10,7 @@ from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_pending import PendingApplicationUpdate from scripture_archive_runtime.application_update_updater import ( + _copy_exact, consume_apply_handoff, rollback_installed_update, ) @@ -332,6 +334,126 @@ def fail_post_publish_hash(path: Path) -> str: old, ) + def test_consume_handoff_rolls_back_when_authority_changes_after_publication(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + inspections = [pending, pending, pending, None] + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + side_effect=inspections, + ) as inspect, patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, + ) as discard: + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(inspect.call_count, 4) + discard.assert_not_called() + self.assertEqual(target.read_bytes(), old) + self.assertEqual( + (root / "ScriptureArchive.exe.scripture-archive.rollback").read_bytes(), + old, + ) + + def test_consume_handoff_rolls_back_if_disarm_reports_missing_authority(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=False, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + + def test_copy_exact_source_open_failure_never_creates_destination(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + + with patch.object( + Path, + "open", + side_effect=OSError("forced source-open failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.open", + ) as destination_open: + with self.assertRaisesRegex( + ApplicationUpdateError, + "update source could not be opened", + ): + _copy_exact(source, destination) + + destination_open.assert_not_called() + self.assertFalse(destination.exists()) + + def test_copy_exact_fdopen_failure_closes_descriptor_and_removes_destination(self): + source_bytes = b"source bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + source.write_bytes(source_bytes) + + with patch( + "scripture_archive_runtime.application_update_updater.os.fdopen", + side_effect=OSError("forced fdopen failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.close", + wraps=os.close, + ) as close_descriptor: + with self.assertRaisesRegex(OSError, "forced fdopen failure"): + _copy_exact(source, destination) + + close_descriptor.assert_called_once() + self.assertFalse(destination.exists()) + def test_consume_handoff_disarms_apply_authority_after_success(self): old = b"old executable bytes" new = b"new signed executable bytes" From c55bb2731ba4415372134a75103fd5b2147748b2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:39:19 +0200 Subject: [PATCH 094/118] R06 updater: align convergence success fixture with disarm contract --- runtime_engine/tests/test_application_update_updater.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 7b5a18a47..cdf97e150 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -51,6 +51,9 @@ def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(self): ), patch( "scripture_archive_runtime.application_update_updater.staged_artifact_path", return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, ): result = consume_apply_handoff( root, From 34f8036f027134dc74572b07d0245661502a906a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 21:18:45 +0200 Subject: [PATCH 095/118] R06 health: bind receipt readback to opened descriptor --- .../application_update_health.py | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_health.py b/runtime_engine/scripture_archive_runtime/application_update_health.py index c45bcb445..56d32d3ff 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_health.py +++ b/runtime_engine/scripture_archive_runtime/application_update_health.py @@ -24,6 +24,7 @@ _HEALTH_RECEIPT_NAME = "update-health.json" _ROLLBACK_SUFFIX = ".scripture-archive.rollback" _COPY_CHUNK = 1024 * 1024 +_MAX_RECEIPT_BYTES = 4096 _RECEIPT_KEYS = frozenset( { "schema", @@ -198,13 +199,48 @@ def _read_receipt_if_present(path: Path) -> UpdateHealthReceipt | None: def _read_receipt(path: Path) -> UpdateHealthReceipt: - _require_regular_file(path, "update health receipt") try: - raw = path.read_bytes() + before = path.lstat() except OSError as exc: - raise ApplicationUpdateError("update health receipt could not be read") from exc - if len(raw) > 4096: + raise ApplicationUpdateError("update health receipt is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update health receipt must be a regular non-symlink file") + if before.st_size > _MAX_RECEIPT_BYTES: raise ApplicationUpdateError("update health receipt is unexpectedly large") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: + 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 not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update health receipt changed before readback") + raw = handle.read(_MAX_RECEIPT_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 ApplicationUpdateError("update health receipt changed during readback") + after = path.lstat() + except ApplicationUpdateError: + raise + except OSError as exc: + raise ApplicationUpdateError("update health receipt could not be read safely") from exc + after_identity = (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + if ( + after_identity != before_identity + or len(raw) != before.st_size + or len(raw) > _MAX_RECEIPT_BYTES + ): + raise ApplicationUpdateError("update health receipt changed during readback") try: payload: Any = json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as exc: From 45a8395205cd05546611d908200b4f8fa58b8dde Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 21:18:48 +0200 Subject: [PATCH 096/118] R06 health: regress descriptor-bound receipt reads --- .../tests/test_application_update_health.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index 3c459511f..7633cc189 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -2,13 +2,16 @@ import hashlib import json +import os from pathlib import Path import tempfile import unittest +from unittest.mock import patch from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_health import ( HEALTH_RECEIPT_SCHEMA, + _read_receipt, commit_update_health_receipt, discard_update_health_receipt, inspect_update_health_receipt, @@ -141,6 +144,46 @@ def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + def test_receipt_path_swap_before_open_fails_closed(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + path = root / "update-health.json" + replacement = root / "replacement-health.json" + parked = root / "parked-health.json" + replacement.write_bytes(path.read_bytes()) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == path and not swapped: + swapped = True + os.replace(path, parked) + os.replace(replacement, path) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex(ApplicationUpdateError, "changed before readback"): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(path.exists()) + + def test_oversized_receipt_is_rejected_before_open(self) -> None: + root = self.tmp_path / "state" / "updates" + root.mkdir(parents=True) + path = root / "update-health.json" + path.write_bytes(b"x" * 4097) + + with patch.object(Path, "open", side_effect=AssertionError("receipt must not be opened")) as opened: + with self.assertRaisesRegex(ApplicationUpdateError, "unexpectedly large"): + _read_receipt(path) + opened.assert_not_called() + def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) pending = root / "pending-update.json" From dd09b8fedeabe4f88df8181e2c4828c8890d2388 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 21:23:34 +0200 Subject: [PATCH 097/118] R06 health: bind artifact hashing to opened descriptor --- .../application_update_health.py | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_health.py b/runtime_engine/scripture_archive_runtime/application_update_health.py index 56d32d3ff..7f0f22b8b 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_health.py +++ b/runtime_engine/scripture_archive_runtime/application_update_health.py @@ -68,9 +68,9 @@ def publish_update_health_receipt( _require_regular_file(target, "installed application target") rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) _require_regular_file(rollback, "rollback artifact") - if _sha256_file(target) != installed_sha256: + if _sha256_file(target, "installed application target") != installed_sha256: raise ApplicationUpdateError("installed bytes do not match health receipt identity") - if _sha256_file(rollback) != previous_sha256: + if _sha256_file(rollback, "rollback artifact") != previous_sha256: raise ApplicationUpdateError("rollback bytes do not match health receipt identity") receipt = UpdateHealthReceipt( @@ -116,9 +116,9 @@ def inspect_update_health_receipt( _require_regular_file(target, "installed application target") rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) _require_regular_file(rollback, "rollback artifact") - if _sha256_file(target) != receipt.installed_sha256: + if _sha256_file(target, "installed application target") != receipt.installed_sha256: raise ApplicationUpdateError("installed application bytes changed before health commit") - if _sha256_file(rollback) != receipt.previous_sha256: + if _sha256_file(rollback, "rollback artifact") != receipt.previous_sha256: raise ApplicationUpdateError("rollback bytes changed before health commit") return receipt @@ -339,17 +339,48 @@ def _require_real_directory(path: Path, label: str) -> None: raise ApplicationUpdateError(f"{label} must be a real directory") -def _sha256_file(path: Path) -> str: +def _sha256_file(path: Path, label: str) -> str: + try: + before = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) digest = hashlib.sha256() try: 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 not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError(f"{label} changed before hashing") while True: chunk = handle.read(_COPY_CHUNK) if not chunk: break digest.update(chunk) + 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 ApplicationUpdateError(f"{label} changed during hashing") + after = path.lstat() + except ApplicationUpdateError: + raise except OSError as exc: - raise ApplicationUpdateError("update health artifact could not be hashed") from exc + raise ApplicationUpdateError(f"{label} could not be hashed 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(f"{label} changed during hashing") return digest.hexdigest() From 3b250b75b2f32cea5fda9f9694102f8b807256ad Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 21:24:14 +0200 Subject: [PATCH 098/118] R06 health: regress artifact pathname swaps --- .../tests/test_application_update_health.py | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index 7633cc189..3f656b8f7 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -125,6 +125,68 @@ def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> N with self.assertRaisesRegex(ApplicationUpdateError, "rollback bytes changed"): inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + def test_installed_path_swap_before_hash_fails_closed_even_for_identical_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + replacement = target.with_name("replacement-installed.exe") + parked = target.with_name("parked-installed.exe") + replacement.write_bytes(installed) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == target and not swapped: + swapped = True + os.replace(target, parked) + os.replace(replacement, target) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target changed before hashing", + ): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(target.exists()) + + def test_rollback_path_swap_before_hash_fails_closed_even_for_identical_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + replacement = rollback.with_name("replacement-rollback.bin") + parked = rollback.with_name("parked-rollback.bin") + replacement.write_bytes(previous) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == rollback and not swapped: + swapped = True + os.replace(rollback, parked) + os.replace(replacement, rollback) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "rollback artifact changed before hashing", + ): + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + + self.assertTrue(swapped) + self.assertTrue(parked.exists()) + self.assertTrue(rollback.exists()) + def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) path = root / "update-health.json" From 8605b8b7c4b81e7dc663474e4ad1f8677b2da959 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 23:13:42 +0200 Subject: [PATCH 099/118] Qualify #257 on literal pull-request head Adopt the already integrated #260 DEV05/DEV06/DEV10 checkout authority so hosted updater-health evidence is bound to this exact candidate SHA. Product/runtime bytes are unchanged. --- .github/workflows/r06-dev05-runtime.yml | 6 ++++++ .github/workflows/r06-dev06-memory.yml | 6 ++++++ .github/workflows/r06-dev10-integration.yml | 13 +++++++++++++ 3 files changed, 25 insertions(+) diff --git a/.github/workflows/r06-dev05-runtime.yml b/.github/workflows/r06-dev05-runtime.yml index 65cee9f47..f862fc743 100644 --- a/.github/workflows/r06-dev05-runtime.yml +++ b/.github/workflows/r06-dev05-runtime.yml @@ -24,11 +24,17 @@ jobs: runtime: runs-on: ubuntu-latest timeout-minutes: 15 + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} defaults: run: working-directory: runtime_engine steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - name: Confirm exact source checkout + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - uses: actions/setup-python@v5 with: python-version: "3.11" diff --git a/.github/workflows/r06-dev06-memory.yml b/.github/workflows/r06-dev06-memory.yml index 875aa9b48..e0f521f04 100644 --- a/.github/workflows/r06-dev06-memory.yml +++ b/.github/workflows/r06-dev06-memory.yml @@ -26,11 +26,17 @@ jobs: memory: runs-on: ubuntu-latest timeout-minutes: 15 + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} defaults: run: working-directory: runtime_engine steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - name: Confirm exact source checkout + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - uses: actions/setup-python@v5 with: python-version: "3.11" diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index eb32befdc..81748b357 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -14,6 +14,9 @@ on: permissions: contents: read +env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + concurrency: group: r06-dev10-${{ github.ref }} cancel-in-progress: true @@ -28,6 +31,11 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - uses: actions/setup-python@v5 with: python-version: '3.13' @@ -43,6 +51,11 @@ jobs: timeout-minutes: 10 steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - uses: actions/setup-python@v5 with: python-version: '3.13' From ccd3f8a52fa10246b285d94bec8af5f3c402b6e2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:35:00 +0200 Subject: [PATCH 100/118] R06: sanitize updater live failures and expose busy state --- .../repair_overlay/frontend/pending-update.js | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/frontend/pending-update.js b/lanes/dev1/repair_overlay/frontend/pending-update.js index febb711eb..9067cf23e 100644 --- a/lanes/dev1/repair_overlay/frontend/pending-update.js +++ b/lanes/dev1/repair_overlay/frontend/pending-update.js @@ -32,11 +32,18 @@ async function invoke(command){ } function setBusy(busy){ + const section=$('pending-update-recovery'); + if(section)section.setAttribute('aria-busy',busy?'true':'false'); for(const id of ['pending-update-check','pending-update-prepare-apply','pending-update-apply-restart','pending-update-cancel']){ const button=$(id);if(button)button.disabled=busy||(id==='pending-update-apply-restart'&&button.dataset.ready!=='true'); } } +function reportFailure(context,error,message){ + console.error(context,error); + setStatus(message); +} + function setApplyReady(ready){ const button=$('pending-update-apply-restart'); if(!button)return; @@ -79,7 +86,7 @@ async function checkPending({startup=false}={}){ }else throw new Error('Отримано неочікуваний стан.'); }catch(error){ clearDetails();setApplyReady(false); - setStatus(`Pending update не підтверджено: ${error?.message||'невідома помилка'}`); + reportFailure('pending update status failed',error,'Підготовлене оновлення не вдалося безпечно перевірити. Спробуйте перевірити його ще раз.'); }finally{setBusy(false)} } @@ -91,7 +98,10 @@ async function prepareApply(){ renderPending(data);setApplyReady(true); setStatus(`Намір встановлення ${data.artifact_name??'пакета'} → ${data.target_version??'цільова версія'} підготовлено. Файли програми ще не замінювались. Окрема кнопка «Встановити й перезапустити» запускає підписаний native updater.`); }else throw new Error('Підготовку apply handoff не підтверджено.'); - }catch(error){setApplyReady(false);setStatus(`Не вдалося безпечно підготувати встановлення: ${error?.message||'невідома помилка'}`)} + }catch(error){ + setApplyReady(false); + reportFailure('prepare update apply failed',error,'Не вдалося безпечно підготувати встановлення. Файли програми не змінено.'); + } finally{setBusy(false)} } @@ -104,7 +114,7 @@ async function applyAndRestart(){ setStatus('Native updater запущено. Завершую поточну програму для безпечного встановлення та перезапуску.'); }else throw new Error('Запуск native updater не підтверджено.'); }catch(error){ - setStatus(`Не вдалося безпечно запустити встановлення: ${error?.message||'невідома помилка'}`); + reportFailure('start native updater failed',error,'Не вдалося безпечно запустити встановлення. Поточна версія програми залишається активною.'); setBusy(false); } } @@ -116,7 +126,9 @@ async function cancelPending(){ if(data.pending===false&&(data.status==='cancelled'||data.status==='none')){ setStatus(data.status==='cancelled'?'Підготовлене оновлення та його apply-наміри скасовано. Інсталяція не виконувалась.':'Підготовленого оновлення вже немає.'); }else throw new Error('Скасування не підтверджено.'); - }catch(error){setStatus(`Не вдалося безпечно скасувати pending update: ${error?.message||'невідома помилка'}`)} + }catch(error){ + reportFailure('cancel pending update failed',error,'Не вдалося безпечно скасувати підготовлене оновлення. Повторіть перевірку стану перед наступною дією.'); + } finally{setBusy(false)} } @@ -133,7 +145,7 @@ async function commitPostRestartHealth(){ await checkPending({startup:true}); }catch(error){ clearDetails();setApplyReady(false);setBusy(false); - setStatus(`Post-update health не підтверджено: ${error?.message||'невідома помилка'}. Rollback recovery збережено; автоматичне очищення не виконано.`); + reportFailure('post-update health check failed',error,'Перевірку стану після перезапуску не підтверджено. Rollback recovery збережено; автоматичне очищення не виконано.'); } } From 4cdf5e0601e543fa8b02247fc7c6b2158466142a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:35:10 +0200 Subject: [PATCH 101/118] R06: regress updater failure sanitization and busy semantics --- .../tests/test_packaged_application_update_pending.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py index d12e66040..6fcf514b9 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_application_update_pending.py @@ -290,8 +290,13 @@ def test_frontend_exposes_keyboard_native_status_and_cancel_without_html_injecti self.assertIn("pending-update-check", script) self.assertIn("pending-update-cancel", script) self.assertIn("aria-live", script) + self.assertIn("aria-busy", script) + self.assertIn("console.error", script) self.assertIn("textContent", script) self.assertNotIn("innerHTML", script) + self.assertNotIn("${error?.message", script) + self.assertIn("Файли програми не змінено.", script) + self.assertIn("Rollback recovery збережено", script) self.assertIn("./pending-update.js", entry) From 9bc58b333c322e6955873d818a726bdeee1a9b85 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:36:06 +0200 Subject: [PATCH 102/118] R06: sanitize staging UI failures and expose busy state --- .../repair_overlay/frontend/application-update.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/frontend/application-update.js b/lanes/dev1/repair_overlay/frontend/application-update.js index d6625b403..2196936d4 100644 --- a/lanes/dev1/repair_overlay/frontend/application-update.js +++ b/lanes/dev1/repair_overlay/frontend/application-update.js @@ -78,12 +78,19 @@ async function invokeNativeUpdate(command){ } function setBusy(busy){ + const view=$('application-update-view'); + if(view)view.setAttribute('aria-busy',busy?'true':'false'); for(const id of ['application-update-select','application-update-stage']){ const button=$(id); if(button)button.disabled=busy; } } +function reportFailure(error,message){ + console.error('application update operation failed',error); + announce(message); +} + async function selectAndVerify(command=VERIFY_UPDATE_COMMAND){ const staging=command===STAGE_UPDATE_COMMAND; setBusy(true); @@ -109,7 +116,12 @@ async function selectAndVerify(command=VERIFY_UPDATE_COMMAND){ } }catch(error){ clearDetails(); - announce(`${staging?'Оновлення не підготовлено':'Оновлення не перевірено'}: ${error?.message||'невідома помилка'}`); + reportFailure( + error, + staging + ?'Оновлення не підготовлено. Пакет не встановлено й файли програми не змінено.' + :'Оновлення не перевірено. Виберіть локальний manifest і пакет та повторіть перевірку.' + ); }finally{ setBusy(false); } From db4257768157701b80f5db0c9bf03ba30861eff4 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:36:15 +0200 Subject: [PATCH 103/118] R06: regress sanitized updater staging failures --- .../repair_overlay/tests/test_application_update_staging_ui.py | 3 +++ 1 file changed, 3 insertions(+) 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 index 4148a98f1..b463209e8 100644 --- a/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py +++ b/lanes/dev1/repair_overlay/tests/test_application_update_staging_ui.py @@ -11,6 +11,9 @@ def test_staging_action_is_semantic_empty_payload_and_truthful_about_boundary(se self.assertIn("payload:{}", script) self.assertIn("application-update-stage", script) self.assertIn("aria-describedby", script) + self.assertIn("aria-busy", script) + self.assertIn("console.error", script) + self.assertNotIn("${error?.message", script) self.assertIn("same-publisher Authenticode", script) self.assertIn("Install, replace, restart і rollback не виконуються", script) self.assertIn("Нічого не встановлено, не замінено й не запущено", script) From 5c477bb99250deb10073dc59c0b2fd729c053cac Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:37:17 +0200 Subject: [PATCH 104/118] R06: syntax-check pending updater frontend module --- ...st_application_update_staging_js_syntax.py | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) 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 index e028c6cec..d5a17b9d2 100644 --- 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 @@ -6,18 +6,24 @@ @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): + def test_application_update_modules_parse_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) + for filename in ("application-update.js", "pending-update.js"): + with self.subTest(filename=filename): + script = platform / "frontend" / filename + 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__": From 8a0652c302c412fced717a573e35b884ed647f05 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:38:48 +0200 Subject: [PATCH 105/118] R06: bind updater hashing to opened descriptor identity --- .../application_update_updater.py | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 249a479b1..54d9c35df 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -336,16 +336,49 @@ def _copy_exact(source: Path, destination: Path) -> None: def _sha256_file(path: Path) -> str: + try: + before = path.lstat() + except OSError as exc: + raise ApplicationUpdateError("update artifact is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update artifact must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + digest = hashlib.sha256() try: 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 not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update artifact changed before hashing") while True: chunk = handle.read(_COPY_CHUNK) if not chunk: break digest.update(chunk) + 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 ApplicationUpdateError("update artifact changed during hashing") + after = path.lstat() + except ApplicationUpdateError: + raise except OSError as exc: - raise ApplicationUpdateError("update artifact could not be hashed") from exc + raise ApplicationUpdateError("update artifact could not be hashed 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 hashing") return digest.hexdigest() From 9518f34d4d22ee3a7564abbc2a6f5eb02f49290a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:39:07 +0200 Subject: [PATCH 106/118] R06: regress updater hash pathname replacement --- .../tests/test_application_update_updater.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index cdf97e150..33c877d65 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -11,6 +11,7 @@ from scripture_archive_runtime.application_update_pending import PendingApplicationUpdate from scripture_archive_runtime.application_update_updater import ( _copy_exact, + _sha256_file, consume_apply_handoff, rollback_installed_update, ) @@ -414,6 +415,56 @@ def test_consume_handoff_rolls_back_if_disarm_reports_missing_authority(self): self.assertEqual(target.read_bytes(), old) + def test_hash_rejects_path_swap_before_open_even_for_identical_bytes(self): + data = b"same exact updater bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "artifact.exe" + replacement = root / "replacement.exe" + parked = root / "parked.exe" + target.write_bytes(data) + replacement.write_bytes(data) + original_open = Path.open + swapped = False + + def swapping_open(path_obj: Path, *args, **kwargs): + nonlocal swapped + if path_obj == target and not swapped: + swapped = True + os.replace(target, parked) + os.replace(replacement, target) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=swapping_open): + with self.assertRaisesRegex( + ApplicationUpdateError, + "changed before hashing", + ): + _sha256_file(target) + + self.assertTrue(swapped) + self.assertEqual(data, target.read_bytes()) + self.assertEqual(data, parked.read_bytes()) + + def test_hash_rejects_symlink_without_following_target(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + real = root / "real.exe" + link = root / "artifact.exe" + real.write_bytes(b"trusted bytes") + try: + link.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + + with self.assertRaisesRegex( + ApplicationUpdateError, + "regular non-symlink", + ): + _sha256_file(link) + + self.assertEqual(b"trusted bytes", real.read_bytes()) + def test_copy_exact_source_open_failure_never_creates_destination(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From e28d2821e1256c0eff7eb7c7571f10b550579a26 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:39:41 +0200 Subject: [PATCH 107/118] R06: bind updater copies to source descriptor identity --- .../application_update_updater.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 54d9c35df..702f99ddb 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -300,12 +300,30 @@ def _discard_file(path: Path) -> None: def _copy_exact(source: Path, destination: Path) -> None: + try: + before = source.lstat() + except OSError as exc: + raise ApplicationUpdateError("update source is unavailable") from exc + if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode): + raise ApplicationUpdateError("update source must be a regular non-symlink file") + before_identity = (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + try: source_handle = source.open("rb") except OSError as exc: raise ApplicationUpdateError("update source could not be opened") from exc with source_handle as src: + opened = os.fstat(src.fileno()) + opened_identity = ( + opened.st_dev, + opened.st_ino, + opened.st_size, + opened.st_mtime_ns, + ) + if not stat.S_ISREG(opened.st_mode) or opened_identity != before_identity: + raise ApplicationUpdateError("update source changed before copy") + try: descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) except OSError as exc: @@ -327,6 +345,24 @@ def _copy_exact(source: Path, destination: Path) -> None: shutil.copyfileobj(src, dst, length=_COPY_CHUNK) dst.flush() os.fsync(dst.fileno()) + opened_after = os.fstat(src.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 ApplicationUpdateError("update source changed during copy") + after = source.lstat() + after_identity = ( + after.st_dev, + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + if after_identity != before_identity: + raise ApplicationUpdateError("update source changed during copy") except Exception: try: destination.unlink() From f497513fbe563fb582295c9ee78d96c9f55ed0a5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:40:09 +0200 Subject: [PATCH 108/118] R06: regress updater source identity replacement --- .../tests/test_application_update_updater.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 33c877d65..dd41198bb 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -465,6 +465,34 @@ def test_hash_rejects_symlink_without_following_target(self): self.assertEqual(b"trusted bytes", real.read_bytes()) + def test_copy_exact_rejects_replaced_source_before_open(self): + data = b"same exact source bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + alternate = root / "alternate.exe" + original = root / "original.exe" + destination = root / "destination.exe" + source.write_bytes(data) + alternate.write_bytes(data) + original_open = Path.open + replaced = False + + def replacing_open(path_obj: Path, *args, **kwargs): + nonlocal replaced + if path_obj == source and not replaced: + replaced = True + os.replace(source, original) + os.replace(alternate, source) + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=replacing_open): + with self.assertRaisesRegex(ApplicationUpdateError, "changed before copy"): + _copy_exact(source, destination) + + self.assertTrue(replaced) + self.assertFalse(destination.exists()) + def test_copy_exact_source_open_failure_never_creates_destination(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From b6803c767d557c97f29abf03d522421f4070d7fe Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:42:18 +0200 Subject: [PATCH 109/118] R06: keep updater open-failure regression on valid source fixture --- runtime_engine/tests/test_application_update_updater.py | 1 + 1 file changed, 1 insertion(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index dd41198bb..e79465bd6 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -498,6 +498,7 @@ def test_copy_exact_source_open_failure_never_creates_destination(self): root = Path(tmp) source = root / "source.exe" destination = root / "destination.exe" + source.write_bytes(b"source exists before forced open failure") with patch.object( Path, From 946fcd9ef0e0b61e2b91cad123ea26de3e7a9d9b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:43:23 +0200 Subject: [PATCH 110/118] R06: preserve updater artifact identity across publisher verification --- .../application_update_updater.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 702f99ddb..184861f1f 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -86,11 +86,17 @@ def _consume_apply_handoff_locked( if staged.name != pending.artifact_name: raise ApplicationUpdateError("staged artifact name does not match apply handoff") + staged_identity = _file_identity(staged, "staged update artifact") + target_identity = _file_identity(target, "installed application target") if _sha256_file(staged) != pending.artifact_sha256: raise ApplicationUpdateError("staged artifact bytes changed before apply") previous_sha = _sha256_file(target) if not verify_same_publisher(target, staged): raise ApplicationUpdateError("staged artifact failed same-publisher verification") + if _file_identity(staged, "staged update artifact") != staged_identity: + raise ApplicationUpdateError("staged artifact identity changed during publisher verification") + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target identity changed during publisher verification") if _sha256_file(staged) != pending.artifact_sha256: raise ApplicationUpdateError("staged artifact bytes changed during publisher verification") if _sha256_file(target) != previous_sha: @@ -100,18 +106,24 @@ def _consume_apply_handoff_locked( raise ApplicationUpdateError("apply handoff changed during publisher verification") rollback = target.with_name(target.name + _ROLLBACK_SUFFIX) + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target identity changed before rollback capture") _publish_rollback_copy(target, rollback, previous_sha) candidate = target.with_name(f".{target.name}.update-{os.getpid()}.tmp") _prepare_temp_slot(candidate) published = False try: + if _file_identity(staged, "staged update artifact") != staged_identity: + raise ApplicationUpdateError("staged artifact identity changed before install copy") _copy_exact(staged, candidate) if _sha256_file(candidate) != pending.artifact_sha256: raise ApplicationUpdateError("temporary install candidate failed exact-byte verification") final_handoff = inspect_apply_handoff(root, current_version=current_version) if final_handoff != pending: raise ApplicationUpdateError("apply handoff changed before atomic publication") + if _file_identity(target, "installed application target") != target_identity: + raise ApplicationUpdateError("installed application target identity changed before atomic publication") os.replace(candidate, target) published = True _fsync_directory(target.parent) @@ -418,6 +430,16 @@ def _sha256_file(path: Path) -> str: return digest.hexdigest() +def _file_identity(path: Path, label: str) -> tuple[int, int, int, int]: + try: + metadata = path.lstat() + except OSError as exc: + raise ApplicationUpdateError(f"{label} is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise ApplicationUpdateError(f"{label} must be a regular non-symlink file") + return (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns) + + def _require_regular_file(path: Path, label: str) -> None: try: metadata = path.lstat() From 0d0e2cb5a2d0cb1650ed6a7eb64b5fc816a06b7e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:43:47 +0200 Subject: [PATCH 111/118] R06: regress byte-identical updater identity swaps --- .../tests/test_application_update_updater.py | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index e79465bd6..08c1dbeb6 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -211,6 +211,92 @@ def mutate(_current: Path, candidate: Path) -> bool: self.assertEqual(target.read_bytes(), old) + def test_consume_handoff_rejects_byte_identical_staged_replacement_during_signature_check(self): + old = b"old executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + alternate = root / "staged" / "alternate.exe" + parked = root / "staged" / "parked.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + alternate.write_bytes(new) + pending = self._pending(new) + + def replace_staged(_current: Path, candidate: Path) -> bool: + os.replace(candidate, parked) + os.replace(alternate, candidate) + return True + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "staged artifact identity changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=replace_staged, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + + def test_consume_handoff_rejects_byte_identical_target_replacement_during_signature_check(self): + old = b"old trusted executable" + new = b"new signed executable" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + alternate = root / "alternate-installed.exe" + parked = root / "parked-installed.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + alternate.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + def replace_target(current: Path, _candidate: Path) -> bool: + os.replace(current, parked) + os.replace(alternate, current) + return True + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target identity changed during publisher verification", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=replace_target, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertFalse( + (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() + ) + def test_consume_handoff_rejects_target_mutation_during_signature_check(self): old = b"old trusted executable" new = b"new signed executable" From 5541b4f72cc92279cb61e06bf9d1d105ab00d34e Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:44:07 +0200 Subject: [PATCH 112/118] R06: preserve updater verification failure contract --- .../scripture_archive_runtime/application_update_updater.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 184861f1f..666d2c246 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -94,9 +94,9 @@ def _consume_apply_handoff_locked( if not verify_same_publisher(target, staged): raise ApplicationUpdateError("staged artifact failed same-publisher verification") if _file_identity(staged, "staged update artifact") != staged_identity: - raise ApplicationUpdateError("staged artifact identity changed during publisher verification") + raise ApplicationUpdateError("staged artifact changed during publisher verification (identity)") if _file_identity(target, "installed application target") != target_identity: - raise ApplicationUpdateError("installed application target identity changed during publisher verification") + raise ApplicationUpdateError("installed application target changed during publisher verification (identity)") if _sha256_file(staged) != pending.artifact_sha256: raise ApplicationUpdateError("staged artifact bytes changed during publisher verification") if _sha256_file(target) != previous_sha: From 08756ffbbb4809f21541fdf23fc11ddcfbf58afe Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:44:16 +0200 Subject: [PATCH 113/118] R06: align identity-swap regressions with stable diagnostics --- runtime_engine/tests/test_application_update_updater.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 08c1dbeb6..4780d7179 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -240,7 +240,7 @@ def replace_staged(_current: Path, candidate: Path) -> bool: ): with self.assertRaisesRegex( ApplicationUpdateError, - "staged artifact identity changed during publisher verification", + "staged artifact changed during publisher verification", ): consume_apply_handoff( root, @@ -283,7 +283,7 @@ def replace_target(current: Path, _candidate: Path) -> bool: ): with self.assertRaisesRegex( ApplicationUpdateError, - "installed application target identity changed during publisher verification", + "installed application target changed during publisher verification", ): consume_apply_handoff( root, From d2fdaa3b34ec73f7bbb2798049d1271eaf027776 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:44:48 +0200 Subject: [PATCH 114/118] test: isolate updater source-open failure on Windows --- .../tests/test_application_update_updater.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 4780d7179..dd3d1423c 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -586,20 +586,20 @@ def test_copy_exact_source_open_failure_never_creates_destination(self): destination = root / "destination.exe" source.write_bytes(b"source exists before forced open failure") - with patch.object( - Path, - "open", - side_effect=OSError("forced source-open failure"), - ), patch( - "scripture_archive_runtime.application_update_updater.os.open", - ) as destination_open: + original_open = Path.open + + def fail_source_open(path_obj, *args, **kwargs): + if path_obj == source: + raise OSError("forced source-open failure") + return original_open(path_obj, *args, **kwargs) + + with patch.object(Path, "open", new=fail_source_open): with self.assertRaisesRegex( ApplicationUpdateError, "update source could not be opened", ): _copy_exact(source, destination) - destination_open.assert_not_called() self.assertFalse(destination.exists()) def test_copy_exact_fdopen_failure_closes_descriptor_and_removes_destination(self): From fd687242c96d21b5850a9b306cd2c7f958fb3fa5 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:45:30 +0200 Subject: [PATCH 115/118] R06: regress updater identity swaps before publication --- .../tests/test_application_update_updater.py | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index dd3d1423c..d48ba31ca 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -372,6 +372,104 @@ def test_consume_handoff_rejects_cancelled_authority_after_signature_check(self) (root / "ScriptureArchive.exe.scripture-archive.rollback").exists() ) + def test_consume_handoff_rejects_staged_replacement_before_install_copy(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + staged = root / "staged" / "ScriptureArchive.exe" + alternate = root / "staged" / "alternate.exe" + parked = root / "staged" / "parked.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + alternate.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_publish = updater_module._publish_rollback_copy + + def publish_then_replace(source: Path, destination: Path, expected_sha: str) -> None: + real_publish(source, destination, expected_sha) + os.replace(staged, parked) + os.replace(alternate, staged) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater._publish_rollback_copy", + side_effect=publish_then_replace, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "staged artifact identity changed before install copy", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertEqual(rollback.read_bytes(), old) + + def test_consume_handoff_rejects_target_replacement_before_atomic_publication(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + rollback = root / "ScriptureArchive.exe.scripture-archive.rollback" + alternate = root / "alternate-installed.exe" + parked = root / "parked-installed.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + alternate.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + from scripture_archive_runtime import application_update_updater as updater_module + real_copy = updater_module._copy_exact + + def copy_then_replace(source: Path, destination: Path) -> None: + real_copy(source, destination) + if ".update-" in destination.name: + os.replace(target, parked) + os.replace(alternate, target) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater._copy_exact", + side_effect=copy_then_replace, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "installed application target identity changed before atomic publication", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + self.assertEqual(rollback.read_bytes(), old) + self.assertEqual(parked.read_bytes(), old) + def test_consume_handoff_rolls_back_when_post_publish_verification_errors(self): old = b"old executable bytes" new = b"new signed executable bytes" From e0e9d76315f36c491d01a78073be0be9779b5e70 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:46:43 +0200 Subject: [PATCH 116/118] R06: rebind updater launch plan to verified host authority --- .../desktop_host/updater_launch.py | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py index c2c19f9dd..e99098bf7 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/desktop_host/updater_launch.py @@ -63,9 +63,36 @@ def launch_packaged_updater( if not trusted_updater: raise UpdateProcessError("packaged updater same-publisher authenticity is required") + requested_staging = Path(staging_root) plan = build_plan( updater_executable=updater, installed_executable=installed, - staging_root=Path(staging_root), + staging_root=requested_staging, ) + if not isinstance(plan, UpdaterProcessPlan): + raise UpdateProcessError("updater process-plan builder returned an invalid plan") + try: + expected_updater = updater.resolve(strict=True) + expected_installed = installed.resolve(strict=True) + expected_staging = requested_staging.resolve(strict=True) + except OSError as exc: + raise UpdateProcessError("packaged updater launch authority could not be rebound") from exc + if ( + plan.updater_executable != expected_updater + or plan.installed_executable != expected_installed + or plan.staging_root != expected_staging + ): + raise UpdateProcessError("updater process plan changed host-owned launch authority") + try: + launch_trusted = bool( + verify_same_publisher(plan.installed_executable, plan.updater_executable) + ) + except Exception as exc: + raise UpdateProcessError( + "packaged updater authenticity could not be reverified before launch" + ) from exc + if not launch_trusted: + raise UpdateProcessError( + "packaged updater same-publisher authenticity changed before launch" + ) return launch_process(plan) From a4a9eb4c80d4f3dc6424314750eaa612616f7c34 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:47:04 +0200 Subject: [PATCH 117/118] R06: regress updater launch-plan substitution and reverify --- .../test_packaged_updater_host_launch.py | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index 5c7f5c36a..ce113e501 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -102,7 +102,50 @@ def launch(plan): self.assertEqual(self.updater, events[1][1]["updater_executable"]) self.assertEqual(self.current, events[1][1]["installed_executable"]) self.assertEqual(self.staging, events[1][1]["staging_root"]) - self.assertEqual("launch", events[2][0]) + self.assertEqual(("verify", self.current.resolve(), self.updater.resolve()), events[2]) + self.assertEqual("launch", events[3][0]) + + def test_process_plan_cannot_substitute_host_owned_launch_paths(self): + external = self.root / "external-updater.exe" + external.write_bytes(b"external") + launched = [] + + def substituted_plan(**kwargs): + return UpdaterProcessPlan( + updater_executable=external, + installed_executable=kwargs["installed_executable"].resolve(), + staging_root=kwargs["staging_root"].resolve(), + parent_pid=41, + ) + + with self.assertRaisesRegex(UpdateProcessError, "changed host-owned launch authority"): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=lambda _current, _updater: True, + build_plan=substituted_plan, + launch_process=lambda plan: launched.append(plan) or 1, + ) + self.assertEqual([], launched) + + def test_publisher_is_reverified_after_plan_before_launch(self): + verdicts = iter((True, False)) + calls = [] + launched = [] + + def verify(current, updater): + calls.append((current, updater)) + return next(verdicts) + + with self.assertRaisesRegex(UpdateProcessError, "changed before launch"): + launch_packaged_updater( + self.staging, + current_executable=self.current, + verify_same_publisher=verify, + launch_process=lambda plan: launched.append(plan) or 1, + ) + self.assertEqual(2, len(calls)) + self.assertEqual([], launched) def test_negative_or_failed_publisher_proof_never_builds_process_plan(self): for verifier in ( From b8798c93038ddd32fda311df15adf39a5767d81a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Wed, 30 Sep 2026 15:49:42 +0200 Subject: [PATCH 118/118] R06: align launch test double with resolved plan contract --- .../tests/test_packaged_updater_host_launch.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index ce113e501..4b6b34402 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -79,9 +79,9 @@ def verify(current, updater): def build_plan(**kwargs): events.append(("plan", kwargs)) return UpdaterProcessPlan( - updater_executable=kwargs["updater_executable"], - installed_executable=kwargs["installed_executable"], - staging_root=kwargs["staging_root"], + updater_executable=kwargs["updater_executable"].resolve(strict=True), + installed_executable=kwargs["installed_executable"].resolve(strict=True), + staging_root=kwargs["staging_root"].resolve(strict=True), parent_pid=41, )