From ebfe2edcdadf4d2347241279bb2455b476eb9a5b Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:26:11 +0200 Subject: [PATCH 01/20] R06 constructor v2: persist history snapshots and safe versions --- .../authoring/service.py | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py index 2c864ea48..afbd33975 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/service.py @@ -7,6 +7,10 @@ import uuid from typing import Any, Callable +from runtime_engine.scripture_archive_runtime.content_packs import ( + CONTENT_PACK_SCHEMA, + CONTENT_SCHEMA_VERSION, +) from scripture_archive_platform.transport.contracts import MAX_IMPORT_BYTES from .model import ( CHANGE_RECORD_SCHEMA, DRAFT_SCHEMA, KINDS, PUBLISH_SCHEMA, @@ -15,6 +19,14 @@ from .validation import identity, identity_errors, publish_blockers, validate_draft +HISTORY_SCHEMA = "scripture.authoring-history.v1" +SNAPSHOT_SCHEMA = "scripture.authoring-snapshot.v1" +VERSION_SCHEMA = "scripture.authoring-version.v1" +PACK_COMPAT_SCHEMA = "scripture.authoring-pack-compat.v1" +MAX_HISTORY_DEPTH = 50 +MAX_DIFF_PATHS = 1000 + + class AuthoringService: """Backward-compatible data-only constructor; never mutates audited canonical files.""" @@ -94,12 +106,15 @@ def save_draft(self, draft: Any) -> dict[str, Any]: out.setdefault("change_record", []).append({ "timestamp": now, "action": "save_draft", "revision": revision, }) + if stored is not None: + self._remember_for_undo(out["draft_id"], stored) self.store.put_json("drafts", out["draft_id"], out) return copy.deepcopy(out) def delete_draft(self, draft_id: str) -> dict[str, Any]: self.load_draft(draft_id) self.store.delete("drafts", draft_id) + self.store.delete("authoring_history", draft_id) return {"draft_id": draft_id, "deleted": True} def fork_record(self, kind: str, record: dict[str, Any], title: str | None = None) -> dict[str, Any]: @@ -181,6 +196,154 @@ def prepare_publish_candidate(self, draft: Any) -> dict[str, Any]: } return candidate + def pack_compatibility(self) -> dict[str, str]: + return { + "schema": PACK_COMPAT_SCHEMA, + "content_pack_schema": CONTENT_PACK_SCHEMA, + "content_schema_version": CONTENT_SCHEMA_VERSION, + "constructor_draft_schema": DRAFT_SCHEMA, + } + + def create_snapshot(self, draft_id: str, label: str = "") -> dict[str, Any]: + draft = self.load_draft(draft_id) + label = self._label(label) + snapshot = self._snapshot_from_draft(draft, label=label) + return copy.deepcopy(snapshot) + + def list_snapshots(self, draft_id: str) -> list[dict[str, Any]]: + self._validate_id(draft_id, "draft id") + out: list[dict[str, Any]] = [] + for key in self.store.list_keys("authoring_snapshots"): + value = self.store.get_json("authoring_snapshots", key, {}) or {} + if value.get("draft_id") != draft_id: + continue + out.append({ + "snapshot_id": value.get("snapshot_id", key), + "draft_id": draft_id, + "draft_revision": value.get("draft_revision"), + "created_at": value.get("created_at"), + "label": value.get("label", ""), + }) + return sorted(out, key=lambda row: (int(row.get("created_at") or 0), str(row.get("snapshot_id")))) + + def restore_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + snapshot = self._load_snapshot(draft_id, snapshot_id) + self._snapshot_from_draft(current, label="Automatic safety snapshot before snapshot restore") + self._remember_for_undo(draft_id, current) + return self._restore_draft(current, snapshot["draft"], "restore_snapshot", snapshot_id) + + def diff_draft(self, draft_id: str, from_snapshot_id: str, + to_snapshot_id: str | None = None) -> dict[str, Any]: + left = self._load_snapshot(draft_id, from_snapshot_id)["draft"] + if to_snapshot_id: + right = self._load_snapshot(draft_id, to_snapshot_id)["draft"] + right_ref = to_snapshot_id + else: + right = self.load_draft(draft_id) + right_ref = "CURRENT" + paths: list[str] = [] + self._diff_paths(left, right, "$", paths) + return { + "schema": "scripture.authoring-diff.v1", + "draft_id": draft_id, + "from": from_snapshot_id, + "to": right_ref, + "changed": bool(paths), + "changed_paths": paths, + "truncated": len(paths) >= MAX_DIFF_PATHS, + } + + def history(self, draft_id: str) -> dict[str, Any]: + draft = self.load_draft(draft_id) + state = self._history_state(draft_id) + return { + "schema": HISTORY_SCHEMA, + "draft_id": draft_id, + "revision": draft.get("revision", 1), + "can_undo": bool(state["undo"]), + "can_redo": bool(state["redo"]), + "change_record": self._json_copy(draft.get("change_record", [])), + "snapshots": self.list_snapshots(draft_id), + "versions": self.list_versions(draft_id), + } + + def undo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["undo"]: + raise ValueError("nothing to undo") + target = state["undo"].pop() + state["redo"].append(self._json_copy(current)) + state["redo"] = state["redo"][-MAX_HISTORY_DEPTH:] + self._write_history(draft_id, state) + return self._restore_draft(current, target, "undo") + + def redo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["redo"]: + raise ValueError("nothing to redo") + target = state["redo"].pop() + state["undo"].append(self._json_copy(current)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + self._write_history(draft_id, state) + return self._restore_draft(current, target, "redo") + + def publish_version(self, draft_id: str, compatibility: Any) -> dict[str, Any]: + draft = self.load_draft(draft_id) + compat = self._validate_pack_compatibility(compatibility) + candidate = self.prepare_publish_candidate(draft) + version_id = "version-" + self.id_factory() + self._validate_id(version_id, "version id") + version = { + "schema": VERSION_SCHEMA, + "version_id": version_id, + "draft_id": draft_id, + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "kind": draft.get("kind", "node"), + "stable_identity": identity(draft.get("kind", "node"), draft.get(draft.get("kind", "node")) or {}), + "compatibility": compat, + "candidate": candidate, + "canonical_mutation_performed": False, + "requires_explicit_integration": True, + } + self.store.put_json("authoring_versions", version_id, version) + return copy.deepcopy(version) + + def list_versions(self, draft_id: str) -> list[dict[str, Any]]: + self._validate_id(draft_id, "draft id") + out: list[dict[str, Any]] = [] + for key in self.store.list_keys("authoring_versions"): + value = self.store.get_json("authoring_versions", key, {}) or {} + if value.get("draft_id") != draft_id: + continue + out.append({ + "version_id": value.get("version_id", key), + "draft_id": draft_id, + "draft_revision": value.get("draft_revision"), + "created_at": value.get("created_at"), + "kind": value.get("kind"), + "stable_identity": value.get("stable_identity"), + "compatibility": self._json_copy(value.get("compatibility", {})), + "canonical_mutation_performed": False, + }) + return sorted(out, key=lambda row: (int(row.get("created_at") or 0), str(row.get("version_id")))) + + def rollback_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + version = self._load_version(draft_id, version_id) + target = self._json_copy(version.get("candidate") or {}) + if target.get("draft_id") != draft_id: + raise ValueError("version draft identity mismatch") + self._snapshot_from_draft(current, label="Automatic safety snapshot before version rollback") + self._remember_for_undo(draft_id, current) + target.pop("publish_manifest", None) + target.pop("publish_change_record", None) + target.pop("canonical_mutation_performed", None) + return self._restore_draft(current, target, "rollback_version", version_id) + def export_draft(self, draft_id: str) -> str: return json.dumps(self.load_draft(draft_id), ensure_ascii=False, indent=2) + "\n" @@ -213,6 +376,123 @@ def _envelope(self, draft: Any) -> dict[str, Any]: raise ValueError(f"{key} must be an object") return out + def _history_state(self, draft_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + state = self.store.get_json("authoring_history", draft_id, None) + if state is None: + return {"schema": HISTORY_SCHEMA, "draft_id": draft_id, "undo": [], "redo": []} + if not isinstance(state, dict) or state.get("schema") != HISTORY_SCHEMA or state.get("draft_id") != draft_id: + raise ValueError("invalid persisted authoring history") + undo = state.get("undo") + redo = state.get("redo") + if not isinstance(undo, list) or not isinstance(redo, list): + raise ValueError("invalid persisted authoring history") + return self._json_copy(state) + + def _write_history(self, draft_id: str, state: dict[str, Any]) -> None: + state = self._json_copy(state) + state.update({"schema": HISTORY_SCHEMA, "draft_id": draft_id}) + state["undo"] = list(state.get("undo", []))[-MAX_HISTORY_DEPTH:] + state["redo"] = list(state.get("redo", []))[-MAX_HISTORY_DEPTH:] + self.store.put_json("authoring_history", draft_id, state) + + def _remember_for_undo(self, draft_id: str, prior: dict[str, Any]) -> None: + state = self._history_state(draft_id) + state["undo"].append(self._json_copy(prior)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + state["redo"] = [] + self._write_history(draft_id, state) + + def _restore_draft(self, current: dict[str, Any], target: Any, + action: str, reference_id: str | None = None) -> dict[str, Any]: + target = self._envelope(target) + if target["draft_id"] != current["draft_id"]: + raise ValueError("restore draft identity mismatch") + out = self._json_copy(target) + now = int(self.clock()) + out["status"] = "DRAFT" + out["created_at"] = int(current.get("created_at", now)) + out["updated_at"] = now + out["revision"] = int(current.get("revision", 1)) + 1 + out["base_identity"] = current.get("base_identity") or out.get("base_identity") + record = {"timestamp": now, "action": action, "revision": out["revision"]} + if reference_id: + record["reference_id"] = reference_id + out.setdefault("change_record", []).append(record) + self._protect_identity(out) + self.store.put_json("drafts", out["draft_id"], out) + return copy.deepcopy(out) + + def _snapshot_from_draft(self, draft: dict[str, Any], *, label: str) -> dict[str, Any]: + snapshot_id = "snapshot-" + self.id_factory() + self._validate_id(snapshot_id, "snapshot id") + snapshot = { + "schema": SNAPSHOT_SCHEMA, + "snapshot_id": snapshot_id, + "draft_id": draft["draft_id"], + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "label": self._label(label), + "draft": self._json_copy(draft), + } + self.store.put_json("authoring_snapshots", snapshot_id, snapshot) + return snapshot + + def _load_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + self._validate_id(snapshot_id, "snapshot id") + value = self.store.get_json("authoring_snapshots", snapshot_id) + if not isinstance(value, dict) or value.get("schema") != SNAPSHOT_SCHEMA: + raise ValueError("snapshot not found") + if value.get("draft_id") != draft_id: + raise ValueError("snapshot belongs to another draft") + return self._json_copy(value) + + def _load_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + self._validate_id(draft_id, "draft id") + self._validate_id(version_id, "version id") + value = self.store.get_json("authoring_versions", version_id) + if not isinstance(value, dict) or value.get("schema") != VERSION_SCHEMA: + raise ValueError("version not found") + if value.get("draft_id") != draft_id: + raise ValueError("version belongs to another draft") + if value.get("compatibility") != self.pack_compatibility(): + raise ValueError("version pack compatibility no longer matches this runtime") + return self._json_copy(value) + + def _validate_pack_compatibility(self, value: Any) -> dict[str, str]: + expected = self.pack_compatibility() + if not isinstance(value, dict) or value != expected: + raise ValueError("pack compatibility mismatch; refresh Constructor compatibility before publish") + return self._json_copy(expected) + + def _diff_paths(self, left: Any, right: Any, path: str, out: list[str]) -> None: + if len(out) >= MAX_DIFF_PATHS: + return + if type(left) is not type(right): + out.append(path) + return + if isinstance(left, dict): + for key in sorted(set(left) | set(right)): + if len(out) >= MAX_DIFF_PATHS: + return + child = f"{path}.{key}" + if key not in left or key not in right: + out.append(child) + else: + self._diff_paths(left[key], right[key], child, out) + return + if isinstance(left, list): + if len(left) != len(right): + out.append(f"{path}.length") + for index, (a, b) in enumerate(zip(left, right)): + if len(out) >= MAX_DIFF_PATHS: + return + self._diff_paths(a, b, f"{path}[{index}]", out) + return + if left != right: + out.append(path) + @staticmethod def _protect_identity(draft: dict[str, Any]) -> None: errors = identity_errors(draft) @@ -233,6 +513,15 @@ def _title(title: str) -> str: raise ValueError("title must be 1..300 characters") return title + @staticmethod + def _label(label: Any) -> str: + if not isinstance(label, str): + raise ValueError("snapshot label must be text") + label = label.strip() + if len(label) > 160: + raise ValueError("snapshot label must be at most 160 characters") + return label + @staticmethod def _validate_id(value: Any, label: str) -> None: if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9._-]{1,80}", value): From 1fb915771360dc5945c4c50b52355bf913d6ff75 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:26:50 +0200 Subject: [PATCH 02/20] R06 constructor v2: allowlist history and version operations --- .../scripture_archive_platform/transport/contracts.py | 8 ++++++-- 1 file changed, 6 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 d69447d69..f3d8b8b10 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -16,7 +16,9 @@ "authoring.list_drafts","authoring.new_draft","authoring.new_node_from_task_type","authoring.load_draft","authoring.save_draft", "authoring.delete_draft","authoring.fork_record","authoring.fork_canonical_node","authoring.move_collection_item", "authoring.validate_draft","authoring.preview_draft","authoring.prepare_publish_candidate", - "authoring.export_draft","authoring.import_draft", + "authoring.export_draft","authoring.import_draft","authoring.pack_compatibility", + "authoring.create_snapshot","authoring.list_snapshots","authoring.restore_snapshot","authoring.diff_draft","authoring.history", + "authoring.undo","authoring.redo","authoring.publish_version","authoring.list_versions","authoring.rollback_version", "keymap.list","keymap.rebind","keymap.clear","keymap.reset_context","keymap.reset_all", "keymap.export","keymap.import","settings.get","settings.set" }) @@ -73,6 +75,8 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('research.get_evidence_graph accepts an empty payload') if cmd=='research.get_witness_matrix' and payload: raise ValueError('research.get_witness_matrix accepts an empty payload') + if cmd=='authoring.pack_compatibility' and payload: + raise ValueError('authoring.pack_compatibility accepts an empty payload') return rid,cmd,payload def _redact_private_player_task(value:Any)->Any: @@ -98,4 +102,4 @@ def ok_response(request_id:str,data:Any)->dict[str,Any]: def error_response(request_id:str,code:str,message:str,details:Any=None)->dict[str,Any]: err={"code":code,"message":message} if details is not None: err['details']=details - return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} \ No newline at end of file + return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} From f0c38593c1b4c0e7c64ddad0f35bcf7f4767cb48 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:27:38 +0200 Subject: [PATCH 03/20] R06 constructor v2: expose persisted lifecycle through app bridge --- .../application/service.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py index 46226f51d..f691a3ed6 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -72,6 +72,17 @@ def _dispatch(self,cmd,p): if cmd=='authoring.validate_draft':return self.authoring.validate_draft(p.get('draft')) if cmd=='authoring.preview_draft':return self.authoring.preview(p.get('draft')) if cmd=='authoring.prepare_publish_candidate':return {'candidate':self.authoring.prepare_publish_candidate(p.get('draft'))} + if cmd=='authoring.pack_compatibility':return {'compatibility':self.authoring.pack_compatibility()} + if cmd=='authoring.create_snapshot':return {'snapshot':self.authoring.create_snapshot(self._id(p,'draft_id'),str(p.get('label') or ''))} + if cmd=='authoring.list_snapshots':return {'snapshots':self.authoring.list_snapshots(self._id(p,'draft_id'))} + if cmd=='authoring.restore_snapshot':return {'draft':self.authoring.restore_snapshot(self._id(p,'draft_id'),self._id(p,'snapshot_id'))} + if cmd=='authoring.diff_draft':return self.authoring.diff_draft(self._id(p,'draft_id'),self._id(p,'from_snapshot_id'),self._id(p,'to_snapshot_id') if p.get('to_snapshot_id') else None) + if cmd=='authoring.history':return self.authoring.history(self._id(p,'draft_id')) + if cmd=='authoring.undo':return {'draft':self.authoring.undo(self._id(p,'draft_id'))} + if cmd=='authoring.redo':return {'draft':self.authoring.redo(self._id(p,'draft_id'))} + if cmd=='authoring.publish_version':return {'version':self.authoring.publish_version(self._id(p,'draft_id'),p.get('compatibility'))} + if cmd=='authoring.list_versions':return {'versions':self.authoring.list_versions(self._id(p,'draft_id'))} + if cmd=='authoring.rollback_version':return {'draft':self.authoring.rollback_version(self._id(p,'draft_id'),self._id(p,'version_id'))} if cmd=='authoring.export_draft':return {'format':'json','text':self.authoring.export_draft(self._id(p,'draft_id'))} if cmd=='authoring.import_draft':return {'draft':self.authoring.import_draft(str(p.get('text') or ''))} if cmd=='keymap.list':return {'actions':self.keymap.list(p.get('context'),str(p.get('search') or ''))} @@ -89,7 +100,7 @@ def _dispatch(self,cmd,p): raise ValueError('command not implemented') def _bootstrap(self): campaigns=self.loader.list_campaigns() - return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} + return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'constructor_v2_history':True,'constructor_v2_snapshots':True,'constructor_v2_undo_redo':True,'constructor_v2_versioned_publish_rollback':True,'constructor_v2_pack_compatibility':True,'constructor_canonical_write':False,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} def _load_node(self,nid): if self.player_gateway:self.player_gateway.invoke('player.load_node',{'node_id':nid},request_id='load-'+nid) node=self.loader.load_node(nid); mission=self.loader.mission_for_node(nid); renderable=self.mapper.to_renderable(node,mission); self._last_node[nid]=node @@ -165,4 +176,4 @@ def build_default_application(repo_root:Path|None=None,store_root:Path|None=None if runtime_application.exists(): from scripture_archive_platform.application.runtime_gateway import build_runtime_gateway gateway=build_runtime_gateway(repo_root,effective_store.root); return PlatformApplication(repo_root,store=effective_store,player_gateway=gateway) - return PlatformApplication(repo_root,store=effective_store) \ No newline at end of file + return PlatformApplication(repo_root,store=effective_store) From caec5236297ee6955551de456463d23461347e5f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:28:31 +0200 Subject: [PATCH 04/20] R06 constructor v2: prove restart history snapshots and safe rollback --- .../tests/test_constructor_v2_lifecycle.py | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py new file mode 100644 index 000000000..13209a088 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py @@ -0,0 +1,134 @@ +import itertools +import tempfile +import unittest +from pathlib import Path +import sys + +for _parent in Path(__file__).resolve().parents: + _runtime_root = _parent / "runtime_engine" + if (_runtime_root / "scripture_archive_runtime").is_dir(): + sys.path.insert(0, str(_runtime_root)) + break + +from scripture_archive_platform.authoring.service import AuthoringService +from scripture_archive_platform.content.loader import TaskPresentationMapper +from scripture_archive_platform.domain.registries import build_task_registries +from scripture_archive_platform.persistence.store import JsonFileStore + + +class ConstructorV2LifecycleTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.ids = itertools.count(1) + self.registry = build_task_registries()[0] + self.service = self._service() + + def tearDown(self): + self.tmp.cleanup() + + def _service(self): + return AuthoringService( + JsonFileStore(self.root), self.registry, TaskPresentationMapper(), + clock=lambda: 1700000000, + id_factory=lambda: f"{next(self.ids):012d}", + ) + + def _campaign(self, title="Version one"): + draft = self.service.new_draft("Campaign draft", "campaign") + draft["campaign"].update({ + "campaign_id": "ZZ-CAMPAIGN", + "title_ua": title, + "scope": "Bounded fixture scope", + "player_promise": "Fixture promise", + "estimated_total_time": "5 min", + "completion_reward_type": "none", + "editorial_status": "DRAFT", + "source_audit_status": "NOT_AUDITED", + }) + return self.service.save_draft(draft) + + def test_undo_redo_persist_across_service_restart_with_monotonic_revision(self): + draft = self._campaign("Version one") + draft["campaign"]["title_ua"] = "Version two" + saved = self.service.save_draft(draft) + saved_revision = saved["revision"] + + restarted = self._service() + history = restarted.history(saved["draft_id"]) + self.assertTrue(history["can_undo"]) + self.assertFalse(history["can_redo"]) + + undone = restarted.undo(saved["draft_id"]) + self.assertEqual("Version one", undone["campaign"]["title_ua"]) + self.assertGreater(undone["revision"], saved_revision) + redone = restarted.redo(saved["draft_id"]) + self.assertEqual("Version two", redone["campaign"]["title_ua"]) + self.assertGreater(redone["revision"], undone["revision"]) + + restarted_again = self._service() + self.assertEqual("Version two", restarted_again.load_draft(saved["draft_id"])["campaign"]["title_ua"]) + self.assertTrue(restarted_again.history(saved["draft_id"])["can_undo"]) + + def test_snapshot_diff_restore_is_persisted_and_creates_safety_snapshot(self): + draft = self._campaign("Before snapshot") + snap = self.service.create_snapshot(draft["draft_id"], "Known good") + draft["campaign"]["title_ua"] = "After snapshot" + changed = self.service.save_draft(draft) + + diff = self.service.diff_draft(changed["draft_id"], snap["snapshot_id"]) + self.assertTrue(diff["changed"]) + self.assertIn("$.campaign.title_ua", diff["changed_paths"]) + + restarted = self._service() + restored = restarted.restore_snapshot(changed["draft_id"], snap["snapshot_id"]) + self.assertEqual("Before snapshot", restored["campaign"]["title_ua"]) + self.assertGreater(restored["revision"], changed["revision"]) + snapshots = restarted.list_snapshots(changed["draft_id"]) + self.assertGreaterEqual(len(snapshots), 2) + self.assertIn("Known good", {row["label"] for row in snapshots}) + self.assertIn( + "Automatic safety snapshot before snapshot restore", + {row["label"] for row in snapshots}, + ) + + def test_publish_version_is_fail_closed_compatible_persistent_and_never_canonical_write(self): + draft = self._campaign("Publishable campaign") + expected = self.service.pack_compatibility() + bad = dict(expected) + bad["content_schema_version"] = "CONTENT_NODE_SCHEMA_future" + with self.assertRaisesRegex(ValueError, "pack compatibility mismatch"): + self.service.publish_version(draft["draft_id"], bad) + + version = self.service.publish_version(draft["draft_id"], expected) + self.assertFalse(version["canonical_mutation_performed"]) + self.assertTrue(version["requires_explicit_integration"]) + self.assertFalse(version["candidate"]["canonical_mutation_performed"]) + self.assertEqual(expected, version["compatibility"]) + + draft["campaign"]["title_ua"] = "Later edit" + later = self.service.save_draft(draft) + restarted = self._service() + versions = restarted.list_versions(draft["draft_id"]) + self.assertEqual([version["version_id"]], [row["version_id"] for row in versions]) + + rolled = restarted.rollback_version(draft["draft_id"], version["version_id"]) + self.assertEqual("Publishable campaign", rolled["campaign"]["title_ua"]) + self.assertGreater(rolled["revision"], later["revision"]) + self.assertEqual("DRAFT", rolled["status"]) + self.assertNotIn("publish_manifest", rolled) + self.assertNotIn("canonical_mutation_performed", rolled) + + def test_cross_draft_snapshot_and_version_restore_are_rejected(self): + first = self._campaign("First") + snapshot = self.service.create_snapshot(first["draft_id"], "First only") + version = self.service.publish_version(first["draft_id"], self.service.pack_compatibility()) + second = self._campaign("Second") + with self.assertRaisesRegex(ValueError, "another draft"): + self.service.restore_snapshot(second["draft_id"], snapshot["snapshot_id"]) + with self.assertRaisesRegex(ValueError, "another draft"): + self.service.rollback_version(second["draft_id"], version["version_id"]) + + +if __name__ == "__main__": + unittest.main() From 46cf8a5d4881ac45b255a7147493ee26a4e607d0 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:28:51 +0200 Subject: [PATCH 05/20] R06 constructor v2: cover allowlisted lifecycle bridge --- .../tests/test_authoring_transport.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_authoring_transport.py b/lanes/dev1/repair_overlay/tests/test_authoring_transport.py index 0c14c63e8..de7164051 100644 --- a/lanes/dev1/repair_overlay/tests/test_authoring_transport.py +++ b/lanes/dev1/repair_overlay/tests/test_authoring_transport.py @@ -20,6 +20,22 @@ def test_reorder_command_is_data_only(self): d=self.req('authoring.new_node_from_task_type',{'title':'Order','task_type':'ORDERING'})['data']['draft']; d['node']['ui_metadata']['items']=[{'id':'a'},{'id':'b'},{'id':'c'}] r=self.req('authoring.move_collection_item',{'draft':d,'path':'node.ui_metadata.items','index':2,'direction':'up'}); self.assertTrue(r['ok'],r); self.assertEqual(['a','c','b'],[x['id'] for x in r['data']['draft']['node']['ui_metadata']['items']]) self.assertEqual(['a','b','c'],[x['id'] for x in d['node']['ui_metadata']['items']]) + def test_constructor_v2_lifecycle_is_allowlisted_and_fail_closed(self): + expected={'authoring.pack_compatibility','authoring.create_snapshot','authoring.list_snapshots','authoring.restore_snapshot','authoring.diff_draft','authoring.history','authoring.undo','authoring.redo','authoring.publish_version','authoring.list_versions','authoring.rollback_version'} + self.assertTrue(expected.issubset(ALLOWLISTED_COMMANDS)) + r=self.req('authoring.new_draft',{'title':'Campaign','kind':'campaign'}); self.assertTrue(r['ok'],r); d=r['data']['draft']; did=d['draft_id'] + d['campaign']['campaign_id']='ZZ-CAMPAIGN'; d['campaign']['title_ua']='V1' + r=self.req('authoring.save_draft',{'draft':d}); self.assertTrue(r['ok'],r); d=r['data']['draft'] + r=self.req('authoring.create_snapshot',{'draft_id':did,'label':'Known good'}); self.assertTrue(r['ok'],r); sid=r['data']['snapshot']['snapshot_id'] + d['campaign']['title_ua']='V2'; r=self.req('authoring.save_draft',{'draft':d}); self.assertTrue(r['ok'],r); d=r['data']['draft'] + r=self.req('authoring.diff_draft',{'draft_id':did,'from_snapshot_id':sid}); self.assertTrue(r['ok'],r); self.assertIn('$.campaign.title_ua',r['data']['changed_paths']) + r=self.req('authoring.undo',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual('V1',r['data']['draft']['campaign']['title_ua']) + r=self.req('authoring.redo',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual('V2',r['data']['draft']['campaign']['title_ua']) + compat=self.req('authoring.pack_compatibility',{}); self.assertTrue(compat['ok'],compat); compatibility=compat['data']['compatibility'] + bad=dict(compatibility); bad['content_schema_version']='future' + r=self.req('authoring.publish_version',{'draft_id':did,'compatibility':bad}); self.assertFalse(r['ok'],r); self.assertEqual('VALIDATION_ERROR',r['error']['code']) + r=self.req('authoring.publish_version',{'draft_id':did,'compatibility':compatibility}); self.assertTrue(r['ok'],r); version=r['data']['version']; self.assertFalse(version['canonical_mutation_performed']) + r=self.req('authoring.list_versions',{'draft_id':did}); self.assertTrue(r['ok'],r); self.assertEqual(version['version_id'],r['data']['versions'][0]['version_id']) def test_player_branch_target_stays_runtime_owned(self): self.assertNotIn('player.navigate_branch',ALLOWLISTED_COMMANDS) self.assertIn('player.next',ALLOWLISTED_COMMANDS) From aaa43151052f98d44d81640803d2e88709e906f2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:30:39 +0200 Subject: [PATCH 06/20] R06 constructor v2: add keyboard semantic lifecycle surface --- .../frontend/constructor-v2-ui.js | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js diff --git a/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js b/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js new file mode 100644 index 000000000..d747ccbb9 --- /dev/null +++ b/lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js @@ -0,0 +1,86 @@ +import {chooseTransport,unwrap} from './transport.js'; + +const $=id=>document.getElementById(id); +let transport=null,mounted=false; + +async function api(command,payload={}){return await unwrap(transport,command,payload)} +function announce(text){const host=$('global-status');if(host){host.textContent='';requestAnimationFrame(()=>host.textContent=text)}} +function currentDraftId(){const value=$('draft-id')?.value?.trim();if(!value)throw new Error('Спочатку відкрийте збережену чернетку.');return value} +function makeButton(label,handler){const button=document.createElement('button');button.type='button';button.textContent=label;button.onclick=handler;return button} +function text(tag,value){const el=document.createElement(tag);el.textContent=value;return el} +function syncDraftList(){const nav=$('nav-authoring');if(nav)nav.click()} + +async function refreshHistory(){ + const output=$('constructor-v2-output'); + if(!output)return; + output.replaceChildren(); + let draftId; + try{draftId=currentDraftId()}catch(error){output.append(text('p',error.message));return} + try{ + const history=await api('authoring.history',{draft_id:draftId}); + output.append(text('p',`Revision ${history.revision}. Undo: ${history.can_undo?'так':'ні'}. Redo: ${history.can_redo?'так':'ні'}.`)); + const changes=text('h4','Історія змін');output.append(changes); + const changeList=document.createElement('ol'); + (history.change_record||[]).slice(-20).forEach(row=>changeList.append(text('li',`${row.action||'change'} · revision ${row.revision??'—'} · ${row.timestamp??'—'}`))); + if(!changeList.children.length)changeList.append(text('li','Записів змін ще немає.')); + output.append(changeList); + + output.append(text('h4','Snapshots')); + const snapshots=document.createElement('ul'); + for(const row of history.snapshots||[]){ + const li=document.createElement('li'); + li.append(document.createTextNode(`${row.label||row.snapshot_id} · revision ${row.draft_revision??'—'} `)); + li.append(makeButton('Diff до поточної',async()=>{ + try{const diff=await api('authoring.diff_draft',{draft_id:draftId,from_snapshot_id:row.snapshot_id});announce(diff.changed?`Змінено шляхів: ${diff.changed_paths.length}`:'Відмінностей немає');const pre=document.createElement('pre');pre.textContent=(diff.changed_paths||[]).join('\n')||'No changes';li.append(pre)}catch(error){announce(`Constructor: ${error.message}`)} + })); + li.append(makeButton('Відновити snapshot',async()=>{ + try{await api('authoring.restore_snapshot',{draft_id:draftId,snapshot_id:row.snapshot_id});announce('Snapshot відновлено як нову revision; попередній стан збережено safety snapshot. Перевідкрийте чернетку.');syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} + })); + snapshots.append(li); + } + if(!snapshots.children.length)snapshots.append(text('li','Snapshots ще немає.')); + output.append(snapshots); + + output.append(text('h4','Published version artifacts')); + const versions=document.createElement('ul'); + for(const row of history.versions||[]){ + const li=document.createElement('li'); + li.append(document.createTextNode(`${row.version_id} · source revision ${row.draft_revision??'—'} · canonical write: ні `)); + li.append(makeButton('Rollback у draft',async()=>{ + try{await api('authoring.rollback_version',{draft_id:draftId,version_id:row.version_id});announce('Version artifact відновлено у draft як нову revision; canonical content не змінено. Перевідкрийте чернетку.');syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} + })); + versions.append(li); + } + if(!versions.children.length)versions.append(text('li','Version artifacts ще немає.')); + output.append(versions); + }catch(error){output.append(text('p',`Не вдалося прочитати Constructor history: ${error.message}`))} +} + +async function mutate(command,message){ + try{const draftId=currentDraftId();await api(command,{draft_id:draftId});announce(message);syncDraftList();await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)} +} + +async function installConstructorV2Surface(){ + if(mounted)return; + const form=$('authoring-form'); + if(!form)return; + try{transport=chooseTransport();const bootstrap=await api('system.bootstrap');if(!bootstrap?.capabilities?.constructor_v2_history)return}catch(_error){return} + mounted=true; + const actions=form.querySelector('.sticky-actions')||form; + actions.append( + makeButton('Snapshot',async()=>{try{const draftId=currentDraftId();await api('authoring.create_snapshot',{draft_id:draftId,label:'Manual snapshot'});announce('Snapshot збережено.');await refreshHistory()}catch(error){announce(`Constructor: ${error.message}`)}}), + makeButton('Undo saved',()=>mutate('authoring.undo','Undo виконано як нову persisted revision. Перевідкрийте чернетку.')), + makeButton('Redo saved',()=>mutate('authoring.redo','Redo виконано як нову persisted revision. Перевідкрийте чернетку.')), + makeButton('History / versions',refreshHistory), + makeButton('Publish saved version',async()=>{ + try{const draftId=currentDraftId();const compatibility=(await api('authoring.pack_compatibility',{})).compatibility;const result=await api('authoring.publish_version',{draft_id:draftId,compatibility});announce(`Version artifact ${result.version.version_id} створено. Canonical content не змінено.`);await refreshHistory()}catch(error){announce(`Constructor publish: ${error.message}`)} + }), + ); + const section=document.createElement('section');section.id='constructor-v2-panel';section.className='surface subtle';section.setAttribute('aria-labelledby','constructor-v2-heading'); + const heading=text('h3','Constructor V2 — історія та версії');heading.id='constructor-v2-heading';heading.tabIndex=-1; + const note=text('p','Операції працюють лише зі збереженою draft revision. Publish створює version artifact для explicit integration review і ніколи не записує canonical source-audited corpus напряму.'); + const output=document.createElement('div');output.id='constructor-v2-output';output.setAttribute('aria-live','polite'); + section.append(heading,note,output);form.append(section); +} + +export {installConstructorV2Surface}; From 7c7d187965e89e2b847e932c4a7cf3135a6c45a3 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:30:48 +0200 Subject: [PATCH 07/20] R06 constructor v2: mount supplemental lifecycle UI --- lanes/dev1/repair_overlay/frontend/transport.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lanes/dev1/repair_overlay/frontend/transport.js b/lanes/dev1/repair_overlay/frontend/transport.js index da74dd864..b343ad624 100644 --- a/lanes/dev1/repair_overlay/frontend/transport.js +++ b/lanes/dev1/repair_overlay/frontend/transport.js @@ -43,3 +43,5 @@ void import('./content-pack-manager.js').then(({installContentPackManagerSurface void import('./evidence-graph-ui.js').then(({installEvidenceGraphSurface})=>installEvidenceGraphSurface()); // Canonical source-local Witness Matrix is a read-only projection from unlocked runtime evidence. void import('./witness-matrix-ui.js').then(({installWitnessMatrixSurface})=>installWitnessMatrixSurface()); +// Constructor V2 augments the existing AuthoringUI; it remains draft/version-only and capability-gated. +void import('./constructor-v2-ui.js').then(({installConstructorV2Surface})=>installConstructorV2Surface()); From 4b12806364f12d96cee9a8bfce6c834d47ae6212 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 19:31:44 +0200 Subject: [PATCH 08/20] R06 constructor v2: qualify supplemental frontend module --- .../tests/test_constructor_v2_frontend.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py new file mode 100644 index 000000000..843e5cd89 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py @@ -0,0 +1,44 @@ +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + + +class ConstructorV2FrontendTests(unittest.TestCase): + def setUp(self): + self.frontend = Path(__file__).resolve().parents[1] / "frontend" + self.source = (self.frontend / "constructor-v2-ui.js").read_text(encoding="utf-8") + + def test_surface_is_semantic_keyboard_native_and_never_uses_unsafe_html(self): + self.assertIn("button.type='button'", self.source) + self.assertIn("aria-live", self.source) + self.assertIn("Constructor V2 — історія та версії", self.source) + self.assertIn("canonical content не змінено", self.source) + self.assertNotIn("innerHTML", self.source) + self.assertNotIn("eval(", self.source) + self.assertNotIn("new Function", self.source) + + def test_module_is_mounted_by_existing_transport_additive_pattern(self): + transport = (self.frontend / "transport.js").read_text(encoding="utf-8") + self.assertIn("./constructor-v2-ui.js", transport) + self.assertIn("installConstructorV2Surface", transport) + + def test_javascript_module_parses_when_node_is_available(self): + node = shutil.which("node") + if not node: + self.skipTest("node is not installed in this local test environment") + with tempfile.TemporaryDirectory() as tmp: + candidate = Path(tmp) / "constructor-v2-ui.mjs" + candidate.write_text(self.source, encoding="utf-8") + completed = subprocess.run( + [node, "--check", str(candidate)], + capture_output=True, + text=True, + timeout=20, + ) + self.assertEqual(0, completed.returncode, completed.stderr) + + +if __name__ == "__main__": + unittest.main() From 3796e56036c25673c648ac6a73f654d03a84aa62 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 20:43:21 +0200 Subject: [PATCH 09/20] R06: make Constructor V2 mutations restart-recoverable --- .../authoring/recoverable.py | 293 ++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py new file mode 100644 index 000000000..00d9b0a90 --- /dev/null +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/authoring/recoverable.py @@ -0,0 +1,293 @@ +from __future__ import annotations + +import copy +from typing import Any, Iterable + +from .service import ( + HISTORY_SCHEMA, + MAX_HISTORY_DEPTH, + SNAPSHOT_SCHEMA, + AuthoringService, +) + + +TRANSACTION_SCHEMA = "scripture.authoring-transaction.v1" +TRANSACTION_CATEGORY = "authoring_transactions" + + +class RecoverableAuthoringService(AuthoringService): + """Constructor V2 service with restart-recoverable multi-record mutations. + + ``JsonFileStore`` makes each individual JSON record replacement atomic, but + Constructor V2 operations span several records (draft, undo/redo history and + safety snapshots). A crash between those writes used to allow history to + advance while the draft remained at the previous revision. This subclass + records the complete intended post-mutation state first and replays it + idempotently on startup. The intent is deleted only after every component + has been persisted. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._recover_pending_mutations() + + def save_draft(self, draft: Any) -> dict[str, Any]: + draft = self._envelope(draft) + stored = self.store.get_json("drafts", draft["draft_id"]) + now = int(self.clock()) + if stored is not None: + expected = int(stored.get("revision", 1)) + if int(draft.get("revision", expected)) != expected: + raise ValueError("stale draft revision; reload before saving") + created_at = int(stored.get("created_at", now)) + revision = expected + 1 + base_identity = stored.get("base_identity") or draft.get("base_identity") + else: + created_at = int(draft.get("created_at", now)) + revision = max(1, int(draft.get("revision", 1))) + base_identity = draft.get("base_identity") + + out = copy.deepcopy(draft) + out.update({ + "status": "DRAFT", + "created_at": created_at, + "updated_at": now, + "revision": revision, + "base_identity": base_identity, + }) + self._protect_identity(out) + out.setdefault("change_record", []).append({ + "timestamp": now, + "action": "save_draft", + "revision": revision, + }) + + history = None + if stored is not None: + history = self._history_with_prior(out["draft_id"], stored) + self._commit_mutation(out["draft_id"], out, history=history) + return copy.deepcopy(out) + + def restore_snapshot(self, draft_id: str, snapshot_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + snapshot = self._load_snapshot(draft_id, snapshot_id) + safety = self._build_snapshot( + current, + label="Automatic safety snapshot before snapshot restore", + ) + history = self._history_with_prior(draft_id, current) + restored = self._build_restored_draft( + current, + snapshot["draft"], + "restore_snapshot", + snapshot_id, + ) + self._commit_mutation( + draft_id, + restored, + history=history, + snapshots=[safety], + ) + return copy.deepcopy(restored) + + def undo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["undo"]: + raise ValueError("nothing to undo") + target = state["undo"].pop() + state["redo"].append(self._json_copy(current)) + state["redo"] = state["redo"][-MAX_HISTORY_DEPTH:] + history = self._normalized_history(draft_id, state) + restored = self._build_restored_draft(current, target, "undo") + self._commit_mutation(draft_id, restored, history=history) + return copy.deepcopy(restored) + + def redo(self, draft_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + state = self._history_state(draft_id) + if not state["redo"]: + raise ValueError("nothing to redo") + target = state["redo"].pop() + state["undo"].append(self._json_copy(current)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + history = self._normalized_history(draft_id, state) + restored = self._build_restored_draft(current, target, "redo") + self._commit_mutation(draft_id, restored, history=history) + return copy.deepcopy(restored) + + def rollback_version(self, draft_id: str, version_id: str) -> dict[str, Any]: + current = self.load_draft(draft_id) + version = self._load_version(draft_id, version_id) + target = self._json_copy(version.get("candidate") or {}) + if target.get("draft_id") != draft_id: + raise ValueError("version draft identity mismatch") + target.pop("publish_manifest", None) + target.pop("publish_change_record", None) + target.pop("canonical_mutation_performed", None) + + safety = self._build_snapshot( + current, + label="Automatic safety snapshot before version rollback", + ) + history = self._history_with_prior(draft_id, current) + restored = self._build_restored_draft( + current, + target, + "rollback_version", + version_id, + ) + self._commit_mutation( + draft_id, + restored, + history=history, + snapshots=[safety], + ) + return copy.deepcopy(restored) + + def _history_with_prior(self, draft_id: str, prior: dict[str, Any]) -> dict[str, Any]: + state = self._history_state(draft_id) + state["undo"].append(self._json_copy(prior)) + state["undo"] = state["undo"][-MAX_HISTORY_DEPTH:] + state["redo"] = [] + return self._normalized_history(draft_id, state) + + def _normalized_history(self, draft_id: str, state: dict[str, Any]) -> dict[str, Any]: + out = self._json_copy(state) + out.update({"schema": HISTORY_SCHEMA, "draft_id": draft_id}) + out["undo"] = list(out.get("undo", []))[-MAX_HISTORY_DEPTH:] + out["redo"] = list(out.get("redo", []))[-MAX_HISTORY_DEPTH:] + return out + + def _build_restored_draft( + self, + current: dict[str, Any], + target: Any, + action: str, + reference_id: str | None = None, + ) -> dict[str, Any]: + target = self._envelope(target) + if target["draft_id"] != current["draft_id"]: + raise ValueError("restore draft identity mismatch") + out = self._json_copy(target) + now = int(self.clock()) + out["status"] = "DRAFT" + out["created_at"] = int(current.get("created_at", now)) + out["updated_at"] = now + out["revision"] = int(current.get("revision", 1)) + 1 + out["base_identity"] = current.get("base_identity") or out.get("base_identity") + record = { + "timestamp": now, + "action": action, + "revision": out["revision"], + } + if reference_id: + record["reference_id"] = reference_id + out.setdefault("change_record", []).append(record) + self._protect_identity(out) + return out + + def _build_snapshot(self, draft: dict[str, Any], *, label: str) -> dict[str, Any]: + snapshot_id = "snapshot-" + self.id_factory() + self._validate_id(snapshot_id, "snapshot id") + return { + "schema": SNAPSHOT_SCHEMA, + "snapshot_id": snapshot_id, + "draft_id": draft["draft_id"], + "draft_revision": draft.get("revision", 1), + "created_at": int(self.clock()), + "label": self._label(label), + "draft": self._json_copy(draft), + } + + def _commit_mutation( + self, + draft_id: str, + draft: dict[str, Any], + *, + history: dict[str, Any] | None = None, + snapshots: Iterable[dict[str, Any]] = (), + ) -> None: + self._validate_id(draft_id, "draft id") + transaction = { + "schema": TRANSACTION_SCHEMA, + "draft_id": draft_id, + "draft": self._json_copy(draft), + "history": self._json_copy(history) if history is not None else None, + "snapshots": self._json_copy(list(snapshots)), + } + # Write-ahead ordering is the invariant: no component write occurs before + # the complete recovery intent itself is durable. + self.store.put_json(TRANSACTION_CATEGORY, draft_id, transaction) + self._apply_transaction(transaction) + self.store.delete(TRANSACTION_CATEGORY, draft_id) + + def _recover_pending_mutations(self) -> None: + for draft_id in sorted(self.store.list_keys(TRANSACTION_CATEGORY)): + self._validate_id(draft_id, "draft id") + transaction = self.store.get_json(TRANSACTION_CATEGORY, draft_id) + self._apply_transaction(transaction) + self.store.delete(TRANSACTION_CATEGORY, draft_id) + + def _apply_transaction(self, transaction: Any) -> None: + draft_id, draft, history, snapshots = self._validate_transaction(transaction) + if history is not None: + self.store.put_json("authoring_history", draft_id, history) + for snapshot in snapshots: + self.store.put_json( + "authoring_snapshots", + snapshot["snapshot_id"], + snapshot, + ) + # Draft is deliberately written last. If any earlier component write is + # interrupted, the durable transaction remains and startup completes the + # same intended revision before the Constructor can be used again. + self.store.put_json("drafts", draft_id, draft) + + def _validate_transaction( + self, + transaction: Any, + ) -> tuple[str, dict[str, Any], dict[str, Any] | None, list[dict[str, Any]]]: + if not isinstance(transaction, dict) or transaction.get("schema") != TRANSACTION_SCHEMA: + raise ValueError("invalid persisted authoring transaction") + draft_id = transaction.get("draft_id") + self._validate_id(draft_id, "draft id") + + draft = self._envelope(transaction.get("draft")) + if draft.get("draft_id") != draft_id: + raise ValueError("authoring transaction draft identity mismatch") + self._protect_identity(draft) + + history = transaction.get("history") + if history is not None: + if ( + not isinstance(history, dict) + or history.get("schema") != HISTORY_SCHEMA + or history.get("draft_id") != draft_id + or not isinstance(history.get("undo"), list) + or not isinstance(history.get("redo"), list) + ): + raise ValueError("invalid authoring transaction history") + history = self._normalized_history(draft_id, history) + + raw_snapshots = transaction.get("snapshots") + if not isinstance(raw_snapshots, list): + raise ValueError("invalid authoring transaction snapshots") + snapshots: list[dict[str, Any]] = [] + seen: set[str] = set() + for raw in raw_snapshots: + if not isinstance(raw, dict) or raw.get("schema") != SNAPSHOT_SCHEMA: + raise ValueError("invalid authoring transaction snapshot") + snapshot_id = raw.get("snapshot_id") + self._validate_id(snapshot_id, "snapshot id") + if snapshot_id in seen: + raise ValueError("duplicate authoring transaction snapshot") + seen.add(snapshot_id) + if raw.get("draft_id") != draft_id: + raise ValueError("authoring transaction snapshot identity mismatch") + embedded = self._envelope(raw.get("draft")) + if embedded.get("draft_id") != draft_id: + raise ValueError("authoring transaction snapshot draft identity mismatch") + snapshots.append(self._json_copy(raw)) + + return draft_id, self._json_copy(draft), history, snapshots From 96e8a30f497ceaf3d1af435603f3a74e64a96663 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 20:44:01 +0200 Subject: [PATCH 10/20] R06: wire packaged Constructor to recoverable authoring service --- .../scripture_archive_platform/application/service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py index f691a3ed6..f9f81117b 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -13,14 +13,14 @@ from scripture_archive_platform.application.keymap import KeybindingService from scripture_archive_platform.application.content_pack_manager import ContentPackManagerService from scripture_archive_platform.application.research_workspace import ResearchWorkspaceService -from scripture_archive_platform.authoring.service import AuthoringService +from scripture_archive_platform.authoring.recoverable import RecoverableAuthoringService class PlatformApplication: def __init__(self,repo_root:Path,store=None,loader=None,grader=None,player_gateway=None): self.repo_root=Path(repo_root).resolve(); self.store=store or JsonFileStore(JsonFileStore.default_root()) self.loader=loader or CanonicalContentLoader(self.repo_root); self.library=CanonicalLibraryIndex(self.loader); self.mapper=TaskPresentationMapper(); self.grader=grader or ReferenceGrader(); self.player_gateway=player_gateway self.task_types,self.renderers,self.graders,self.editors,self.templates=build_task_registries() - self.keymap=KeybindingService(self.store); self.research=ResearchWorkspaceService(self.store,self.loader,self.mapper); self.authoring=AuthoringService(self.store,self.task_types,self.mapper); self.content_packs=ContentPackManagerService(self.store.root) + self.keymap=KeybindingService(self.store); self.research=ResearchWorkspaceService(self.store,self.loader,self.mapper); self.authoring=RecoverableAuthoringService(self.store,self.task_types,self.mapper); self.content_packs=ContentPackManagerService(self.store.root) self._hint_level:dict[str,int]={}; self._last_node:dict[str,dict[str,Any]]={} def handle(self,request:dict[str,Any])->dict[str,Any]: rid=str(request.get('request_id','invalid')) if isinstance(request,dict) else 'invalid' From d386e5c15eb8095c77602c72f6bc8f1bef335292 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 20:44:28 +0200 Subject: [PATCH 11/20] R06: fault-inject Constructor V2 recovery boundaries --- .../test_constructor_v2_recovery_atomicity.py | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py new file mode 100644 index 000000000..281dcddd5 --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py @@ -0,0 +1,172 @@ +import itertools +import tempfile +import unittest +from pathlib import Path +import sys + +for _parent in Path(__file__).resolve().parents: + _runtime_root = _parent / "runtime_engine" + if (_runtime_root / "scripture_archive_runtime").is_dir(): + sys.path.insert(0, str(_runtime_root)) + break + +from scripture_archive_platform.authoring.recoverable import ( + RecoverableAuthoringService, + TRANSACTION_CATEGORY, +) +from scripture_archive_platform.content.loader import TaskPresentationMapper +from scripture_archive_platform.domain.registries import build_task_registries +from scripture_archive_platform.persistence.store import JsonFileStore + + +class SimulatedCrash(RuntimeError): + pass + + +class FailAfterWriteStore: + """Proxy that simulates process death after one durable component write.""" + + def __init__(self, inner): + self.inner = inner + self.fail_category = None + + def arm(self, category): + self.fail_category = category + + def put_json(self, category, key, value): + self.inner.put_json(category, key, value) + if self.fail_category == category: + self.fail_category = None + raise SimulatedCrash(f"crash after {category} write") + + def __getattr__(self, name): + return getattr(self.inner, name) + + +class ConstructorV2RecoveryAtomicityTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.ids = itertools.count(1) + self.registry = build_task_registries()[0] + self.base_store = JsonFileStore(self.root) + self.service = self._service(self.base_store) + + def tearDown(self): + self.tmp.cleanup() + + def _service(self, store): + return RecoverableAuthoringService( + store, + self.registry, + TaskPresentationMapper(), + clock=lambda: 1700000000, + id_factory=lambda: f"{next(self.ids):012d}", + ) + + def _restart(self): + return self._service(JsonFileStore(self.root)) + + def _campaign(self, title="Version one"): + draft = self.service.new_draft("Campaign draft", "campaign") + draft["campaign"].update({ + "campaign_id": "ZZ-CAMPAIGN", + "title_ua": title, + "scope": "Bounded fixture scope", + "player_promise": "Fixture promise", + "estimated_total_time": "5 min", + "completion_reward_type": "none", + "editorial_status": "DRAFT", + "source_audit_status": "NOT_AUDITED", + }) + return self.service.save_draft(draft) + + def _assert_recovered(self, service, draft_id): + self.assertEqual([], service.store.list_keys(TRANSACTION_CATEGORY)) + return service.load_draft(draft_id) + + def test_save_recovers_if_crash_occurs_after_history_before_draft(self): + saved = self._campaign("Version one") + saved["campaign"]["title_ua"] = "Version two" + + crashing = FailAfterWriteStore(self.base_store) + crashing.arm("authoring_history") + self.service.store = crashing + with self.assertRaises(SimulatedCrash): + self.service.save_draft(saved) + + # The draft write did not happen yet, but the durable intent did. + self.assertEqual( + "Version one", + self.base_store.get_json("drafts", saved["draft_id"])["campaign"]["title_ua"], + ) + restarted = self._restart() + recovered = self._assert_recovered(restarted, saved["draft_id"]) + self.assertEqual("Version two", recovered["campaign"]["title_ua"]) + self.assertTrue(restarted.history(saved["draft_id"])["can_undo"]) + + def test_undo_recovers_consumed_history_and_draft_as_one_revision(self): + first = self._campaign("Version one") + first["campaign"]["title_ua"] = "Version two" + second = self.service.save_draft(first) + + crashing = FailAfterWriteStore(self.base_store) + crashing.arm("authoring_history") + self.service.store = crashing + with self.assertRaises(SimulatedCrash): + self.service.undo(second["draft_id"]) + + restarted = self._restart() + recovered = self._assert_recovered(restarted, second["draft_id"]) + self.assertEqual("Version one", recovered["campaign"]["title_ua"]) + history = restarted.history(second["draft_id"]) + self.assertTrue(history["can_redo"]) + redone = restarted.redo(second["draft_id"]) + self.assertEqual("Version two", redone["campaign"]["title_ua"]) + + def test_snapshot_restore_recovers_after_safety_snapshot_write(self): + original = self._campaign("Before snapshot") + snapshot = self.service.create_snapshot(original["draft_id"], "Known good") + original["campaign"]["title_ua"] = "After snapshot" + changed = self.service.save_draft(original) + + crashing = FailAfterWriteStore(self.base_store) + crashing.arm("authoring_snapshots") + self.service.store = crashing + with self.assertRaises(SimulatedCrash): + self.service.restore_snapshot(changed["draft_id"], snapshot["snapshot_id"]) + + restarted = self._restart() + recovered = self._assert_recovered(restarted, changed["draft_id"]) + self.assertEqual("Before snapshot", recovered["campaign"]["title_ua"]) + labels = {row["label"] for row in restarted.list_snapshots(changed["draft_id"])} + self.assertIn("Known good", labels) + self.assertIn("Automatic safety snapshot before snapshot restore", labels) + + def test_version_rollback_recovers_after_safety_snapshot_write(self): + original = self._campaign("Publishable") + version = self.service.publish_version( + original["draft_id"], + self.service.pack_compatibility(), + ) + original["campaign"]["title_ua"] = "Later edit" + later = self.service.save_draft(original) + + crashing = FailAfterWriteStore(self.base_store) + crashing.arm("authoring_snapshots") + self.service.store = crashing + with self.assertRaises(SimulatedCrash): + self.service.rollback_version(later["draft_id"], version["version_id"]) + + restarted = self._restart() + recovered = self._assert_recovered(restarted, later["draft_id"]) + self.assertEqual("Publishable", recovered["campaign"]["title_ua"]) + self.assertEqual("DRAFT", recovered["status"]) + self.assertNotIn("publish_manifest", recovered) + self.assertNotIn("canonical_mutation_performed", recovered) + labels = {row["label"] for row in restarted.list_snapshots(later["draft_id"])} + self.assertIn("Automatic safety snapshot before version rollback", labels) + + +if __name__ == "__main__": + unittest.main() From 23e00b2cf739a47ca652edfa2e87ecaa56696620 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 20:45:45 +0200 Subject: [PATCH 12/20] R06: run Constructor lifecycle tests through recoverable service --- .../repair_overlay/tests/test_constructor_v2_lifecycle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py index 13209a088..02f929801 100644 --- a/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(_runtime_root)) break -from scripture_archive_platform.authoring.service import AuthoringService +from scripture_archive_platform.authoring.recoverable import RecoverableAuthoringService from scripture_archive_platform.content.loader import TaskPresentationMapper from scripture_archive_platform.domain.registries import build_task_registries from scripture_archive_platform.persistence.store import JsonFileStore @@ -28,7 +28,7 @@ def tearDown(self): self.tmp.cleanup() def _service(self): - return AuthoringService( + return RecoverableAuthoringService( JsonFileStore(self.root), self.registry, TaskPresentationMapper(), clock=lambda: 1700000000, id_factory=lambda: f"{next(self.ids):012d}", From f577536cd52684c4010d5316bdd7d3f27d2eec56 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sat, 12 Sep 2026 20:47:04 +0200 Subject: [PATCH 13/20] R06: trigger exact-head Constructor recovery qualification From 0f511bfc14d3bc4d3f97eeca8c4142b88ee5cad4 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 03:51:06 +0200 Subject: [PATCH 14/20] test: cover all Constructor V2 recovery write boundaries --- .../test_constructor_v2_recovery_atomicity.py | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py b/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py index 281dcddd5..c4f16a25b 100644 --- a/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py +++ b/lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py @@ -124,6 +124,24 @@ def test_undo_recovers_consumed_history_and_draft_as_one_revision(self): redone = restarted.redo(second["draft_id"]) self.assertEqual("Version two", redone["campaign"]["title_ua"]) + def test_redo_recovers_consumed_history_and_draft_as_one_revision(self): + first = self._campaign("Version one") + first["campaign"]["title_ua"] = "Version two" + second = self.service.save_draft(first) + undone = self.service.undo(second["draft_id"]) + self.assertEqual("Version one", undone["campaign"]["title_ua"]) + + crashing = FailAfterWriteStore(self.base_store) + crashing.arm("authoring_history") + self.service.store = crashing + with self.assertRaises(SimulatedCrash): + self.service.redo(second["draft_id"]) + + restarted = self._restart() + recovered = self._assert_recovered(restarted, second["draft_id"]) + self.assertEqual("Version two", recovered["campaign"]["title_ua"]) + self.assertTrue(restarted.history(second["draft_id"])["can_undo"]) + def test_snapshot_restore_recovers_after_safety_snapshot_write(self): original = self._campaign("Before snapshot") snapshot = self.service.create_snapshot(original["draft_id"], "Known good") @@ -167,6 +185,118 @@ def test_version_rollback_recovers_after_safety_snapshot_write(self): labels = {row["label"] for row in restarted.list_snapshots(later["draft_id"])} self.assertIn("Automatic safety snapshot before version rollback", labels) + def test_all_state_mutations_replay_from_every_durable_write_boundary(self): + """Exercise intent/component/draft crash boundaries for every V2 mutation. + + The earlier independent QA finding required restart recovery at every + inter-write boundary, including redo. Each subcase gets an isolated + store so a pending transaction from one simulated process death cannot + contaminate another scenario. + """ + + cases = { + "save": ("authoring_transactions", "authoring_history", "drafts"), + "undo": ("authoring_transactions", "authoring_history", "drafts"), + "redo": ("authoring_transactions", "authoring_history", "drafts"), + "restore_snapshot": ( + "authoring_transactions", + "authoring_history", + "authoring_snapshots", + "drafts", + ), + "rollback_version": ( + "authoring_transactions", + "authoring_history", + "authoring_snapshots", + "drafts", + ), + } + + for operation, fail_categories in cases.items(): + for fail_category in fail_categories: + with self.subTest(operation=operation, fail_category=fail_category): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + ids = itertools.count(1) + base_store = JsonFileStore(root) + + def make_service(store): + return RecoverableAuthoringService( + store, + self.registry, + TaskPresentationMapper(), + clock=lambda: 1700000000, + id_factory=lambda: f"{next(ids):012d}", + ) + + service = make_service(base_store) + + def campaign(title): + draft = service.new_draft("Campaign draft", "campaign") + draft["campaign"].update({ + "campaign_id": "ZZ-CAMPAIGN", + "title_ua": title, + "scope": "Bounded fixture scope", + "player_promise": "Fixture promise", + "estimated_total_time": "5 min", + "completion_reward_type": "none", + "editorial_status": "DRAFT", + "source_audit_status": "NOT_AUDITED", + }) + return service.save_draft(draft) + + if operation == "save": + current = campaign("Version one") + current["campaign"]["title_ua"] = "Version two" + draft_id = current["draft_id"] + expected_title = "Version two" + invoke = lambda: service.save_draft(current) + elif operation == "undo": + current = campaign("Version one") + current["campaign"]["title_ua"] = "Version two" + current = service.save_draft(current) + draft_id = current["draft_id"] + expected_title = "Version one" + invoke = lambda: service.undo(draft_id) + elif operation == "redo": + current = campaign("Version one") + current["campaign"]["title_ua"] = "Version two" + current = service.save_draft(current) + draft_id = current["draft_id"] + service.undo(draft_id) + expected_title = "Version two" + invoke = lambda: service.redo(draft_id) + elif operation == "restore_snapshot": + current = campaign("Before snapshot") + snapshot = service.create_snapshot(current["draft_id"], "Known good") + current["campaign"]["title_ua"] = "After snapshot" + current = service.save_draft(current) + draft_id = current["draft_id"] + expected_title = "Before snapshot" + invoke = lambda: service.restore_snapshot(draft_id, snapshot["snapshot_id"]) + else: + current = campaign("Publishable") + version = service.publish_version( + current["draft_id"], + service.pack_compatibility(), + ) + current["campaign"]["title_ua"] = "Later edit" + current = service.save_draft(current) + draft_id = current["draft_id"] + expected_title = "Publishable" + invoke = lambda: service.rollback_version(draft_id, version["version_id"]) + + crashing = FailAfterWriteStore(base_store) + crashing.arm(fail_category) + service.store = crashing + with self.assertRaises(SimulatedCrash): + invoke() + + restarted = make_service(JsonFileStore(root)) + self.assertEqual([], restarted.store.list_keys(TRANSACTION_CATEGORY)) + recovered = restarted.load_draft(draft_id) + self.assertEqual(expected_title, recovered["campaign"]["title_ua"]) + if __name__ == "__main__": unittest.main() From 784402f6d4c5fc938646c7c3f3701f31f8081d49 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 03:51:41 +0200 Subject: [PATCH 15/20] ci: qualify Constructor V2 directly across OSes --- ...06-constructor-v2-direct-qualification.yml | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 .github/workflows/r06-constructor-v2-direct-qualification.yml diff --git a/.github/workflows/r06-constructor-v2-direct-qualification.yml b/.github/workflows/r06-constructor-v2-direct-qualification.yml new file mode 100644 index 000000000..38dd6d9f6 --- /dev/null +++ b/.github/workflows/r06-constructor-v2-direct-qualification.yml @@ -0,0 +1,74 @@ +name: R06 Constructor V2 Direct Qualification + +on: + pull_request: + paths: + - 'lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js' + - 'lanes/dev1/repair_overlay/frontend/transport.js' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/authoring/**' + - 'lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py' + - 'lanes/dev1/repair_overlay/tests/test_authoring_transport.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py' + - 'lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py' + - '.github/workflows/r06-constructor-v2-direct-qualification.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: r06-constructor-v2-direct-${{ github.ref }} + cancel-in-progress: true + +jobs: + constructor-v2-direct-overlay: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + pathsep: ':' + - os: windows-latest + pathsep: ';' + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + PYTHONPATH: "${{ github.workspace }}/lanes/dev1/repair_overlay${{ matrix.pathsep }}${{ github.workspace }}" + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.EXPECTED_HEAD }} + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Confirm exact source checkout + shell: bash + run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + - name: Compile Constructor V2 direct-overlay surface + run: >- + python -m compileall -q + lanes/dev1/repair_overlay/scripture_archive_platform/authoring + lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py + lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py + lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py + lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py + lanes/dev1/repair_overlay/tests/test_authoring_transport.py + - name: Run Constructor V2 lifecycle regression + run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py + - name: Run Constructor V2 crash-recovery regression + run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py + - name: Run Constructor V2 allowlist and source-isolation regression + run: python lanes/dev1/repair_overlay/tests/test_authoring_transport.py + - name: Run Constructor V2 semantic frontend regression + run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py + - name: Verify Constructor V2 frontend module syntax + run: node --check lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js + - name: Diff hygiene + shell: bash + run: git diff --check From 3c43790a1c6bd0c2ef84f50c231e92ac2a214aa0 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 03:55:49 +0200 Subject: [PATCH 16/20] converge: preserve Review Training with Constructor V2 service --- .../application/service.py | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py index 7d2deedae..2abd19b64 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py @@ -54,6 +54,12 @@ def _dispatch(self,cmd,p): if cmd=='player.get_progress':return {'progress':self._progress(self._id(p,'node_id'))} if cmd=='player.get_mastery':return self._mastery() if cmd=='player.get_review_queue':return self._review_queue() + if cmd=='player.start_review': + if p:raise ValueError('player.start_review accepts an empty payload') + return self._start_review() + if cmd=='player.finish_review': + if p:raise ValueError('player.finish_review accepts an empty payload') + return self._finish_review() if cmd=='player.get_daily_case': if p:raise ValueError('player.get_daily_case accepts an empty payload') return self._daily_case() @@ -68,8 +74,7 @@ def _dispatch(self,cmd,p): if cmd=='authoring.fork_record':return {'draft':self.authoring.fork_record(self._id(p,'kind'),p.get('record'),str(p.get('title') or '') or None)} if cmd=='authoring.fork_canonical_node': nid=self._id(p,'node_id'); node=self.loader.load_node(nid); return {'draft':self.authoring.fork_record('node',node,str(p.get('title') or f'Edit {nid}'))} - if cmd=='authoring.move_collection_item': - return {'draft':self.authoring.move_collection_item(p.get('draft'),self._id(p,'path'),p.get('index'),self._id(p,'direction'))} + if cmd=='authoring.move_collection_item':return {'draft':self.authoring.move_collection_item(p.get('draft'),self._id(p,'path'),p.get('index'),self._id(p,'direction'))} if cmd=='authoring.validate_draft':return self.authoring.validate_draft(p.get('draft')) if cmd=='authoring.preview_draft':return self.authoring.preview(p.get('draft')) if cmd=='authoring.prepare_publish_candidate':return {'candidate':self.authoring.prepare_publish_candidate(p.get('draft'))} @@ -101,7 +106,7 @@ def _dispatch(self,cmd,p): raise ValueError('command not implemented') def _bootstrap(self): campaigns=self.loader.list_campaigns() - return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'constructor_v2_history':True,'constructor_v2_snapshots':True,'constructor_v2_undo_redo':True,'constructor_v2_versioned_publish_rollback':True,'constructor_v2_pack_compatibility':True,'constructor_canonical_write':False,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'research_export':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} + return {'app':{'name':'Архів Писання','version':'R06-3DEV-A','runtime':'Windows 11 x64 / WebView2 semantic UI','transport_api_version':TRANSPORT_API_VERSION},'registries':{'task_types':self.task_types.list(),'renderers':self.renderers.list(),'graders':self.graders.list(),'editors':self.editors.list(),'templates':self.templates.list()},'campaigns':campaigns,'keymap':self.keymap.list(),'capabilities':{'constructor':True,'draft_vs_canonical':True,'constructor_v2_history':True,'constructor_v2_snapshots':True,'constructor_v2_undo_redo':True,'constructor_v2_versioned_publish_rollback':True,'constructor_v2_pack_compatibility':True,'constructor_canonical_write':False,'web_portable_transport':True,'allowlisted_bridge':True,'library_catalog_search':True,'bundled_full_bible_text':False,'research_bookmarks_notes':True,'research_workspace_persistence':True,'evidence_graph':bool(self.player_gateway),'chronology_lab':bool(self.player_gateway),'research_export':bool(self.player_gateway),'arbitrary_filesystem':False,'content_pack_manager':True,'content_pack_inbox_only':True,'shell':False,'python_eval':False,'runtime_truth':bool(self.player_gateway),'review_queue':bool(self.player_gateway),'review_training':bool(self.player_gateway),'grading_truth':'D5/runtime' if self.player_gateway else 'REFERENCE_TEST_ONLY'}} def _load_node(self,nid): if self.player_gateway:self.player_gateway.invoke('player.load_node',{'node_id':nid},request_id='load-'+nid) node=self.loader.load_node(nid); mission=self.loader.mission_for_node(nid); renderable=self.mapper.to_renderable(node,mission); self._last_node[nid]=node @@ -111,7 +116,7 @@ def _submit(self,p): if self.player_gateway: rr=self.player_gateway.invoke('player.submit_answer',{'node_id':nid,'task_type':renderable['task_type'],'answer':p.get('answer')},request_id='submit-'+nid) grade=dict(rr.get('grade') or {}); branch=dict(rr.get('branch') or {}); status=str(grade.get('correctness') or 'INCORRECT') - return {'node_id':nid,'status':status,'score':grade.get('score'),'feedback':grade.get('feedback') or '','confidence_code':grade.get('confidence'),'textual_variant_flag':'TX1' if grade.get('tx1') else 'none','evidence':grade.get('evidence') or [],'uncertainty':grade.get('uncertainty'),'next_node_id':branch.get('next_node_id'),'branch':branch,'mastery_consequence':rr.get('mastery_consequence') or [],'accessibility':rr.get('accessibility') or [],'progress':self._progress(nid),'truth_owner':'D5/runtime'} + return {'node_id':nid,'status':status,'score':grade.get('score'),'feedback':grade.get('feedback') or '','confidence_code':grade.get('confidence'),'textual_variant_flag':'TX1' if grade.get('tx1') else 'none','evidence':grade.get('evidence') or [],'uncertainty':grade.get('uncertainty'),'next_node_id':branch.get('next_node_id'),'branch':branch,'mastery_consequence':rr.get('mastery_consequence') or [],'review_session':rr.get('review_session'),'accessibility':rr.get('accessibility') or [],'progress':self._progress(nid),'truth_owner':'D5/runtime'} result=self.grader.grade(node,renderable,p.get('answer')); hist=self.store.get_json('player','history',{}) or {}; rec=hist.setdefault(nid,{'attempts':0,'hints':0,'last_status':None});rec['attempts']+=1;rec['hints']=max(rec['hints'],self._hint_level.get(nid,0));rec['last_status']=result.status;rec['updated_at']=int(time.time());self.store.put_json('player','history',hist) next_id=self.loader.next_node_id(nid,'correct' if result.status=='CORRECT' else 'partial' if result.status in {'PARTIAL','REVIEW_REQUIRED'} else 'incorrect'); data=result.as_dict();data.update({'node_id':nid,'next_node_id':next_id,'progress':self._progress(nid),'truth_owner':'REFERENCE_TEST_ONLY'}); return data def _hint(self,nid): @@ -150,6 +155,19 @@ def _mastery(self): def _review_queue(self): if not self.player_gateway:return {'review_queue':[],'truth_owner':'REFERENCE_TEST_ONLY'} rr=self.player_gateway.invoke('player.get_review_queue',{},request_id='review-queue-player'); return {'review_queue':validate_review_queue_projection(rr.get('review_queue')),'truth_owner':'D5/runtime'} + def _start_review(self): + if not self.player_gateway:raise ValueError('Review Training requires canonical runtime') + rr=self.player_gateway.invoke('player.start_review',{},request_id='review-start-player'); task=rr.get('task'); session=dict(rr.get('review_session') or {}) + if task is None:return {'task':None,'review_session':session,'review_selection':rr.get('review_selection'),'truth_owner':'D5/runtime'} + if not isinstance(task,dict):raise ValueError('runtime review task is invalid') + nid=self._id(task,'node_id'); node=self.loader.load_node(nid); mission=self.loader.mission_for_node(nid) + if task.get('mission_id') not in {None,mission.get('mission_id')}:raise ValueError('runtime review task mission does not match canonical content') + renderable=self.mapper.to_renderable(node,mission); self._last_node[nid]=node + return {'mission':mission,'task':renderable,'progress':self._progress(nid),'hint_level':0,'review_session':session,'review_selection':rr.get('review_selection'),'truth_owner':'D5/runtime'} + def _finish_review(self): + if not self.player_gateway:raise ValueError('Review Training requires canonical runtime') + rr=self.player_gateway.invoke('player.finish_review',{},request_id='review-finish-player') + return {'review_session':rr.get('review_session') or {},'truth_owner':'D5/runtime'} def _daily_case(self): if not self.player_gateway:raise ValueError('Daily Case requires canonical runtime') return self.player_gateway.get_daily_case() @@ -188,4 +206,4 @@ def build_default_application(repo_root:Path|None=None,store_root:Path|None=None if runtime_application.exists(): from scripture_archive_platform.application.runtime_gateway import build_runtime_gateway gateway=build_runtime_gateway(repo_root,effective_store.root); return PlatformApplication(repo_root,store=effective_store,player_gateway=gateway) - return PlatformApplication(repo_root,store=effective_store) + return PlatformApplication(repo_root,store=effective_store) \ No newline at end of file From aa092b2a151de6506fc7e0713282a5ad24ce2e23 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 03:56:09 +0200 Subject: [PATCH 17/20] converge: union Review Training and Constructor V2 transport --- .../scripture_archive_platform/transport/contracts.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 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 4af5a5e0a..53e0304e8 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -10,7 +10,7 @@ "system.bootstrap", "content.list_campaigns","content.list_missions","library.catalog","library.search","player.load_node", "player.submit_answer","player.request_hint","player.reveal_evidence","player.next", - "player.get_progress","player.get_mastery","player.get_review_queue","player.get_daily_case","player.save_checkpoint","player.restore_checkpoint", + "player.get_progress","player.get_mastery","player.get_review_queue","player.start_review","player.finish_review","player.get_daily_case","player.save_checkpoint","player.restore_checkpoint", "research.list_bookmarks","research.upsert_bookmark","research.delete_bookmark", "research.list_notes","research.upsert_note","research.delete_note","research.get_chronology_lab","research.get_evidence_graph","research.get_witness_matrix","research.export", "authoring.list_drafts","authoring.new_draft","authoring.new_node_from_task_type","authoring.load_draft","authoring.save_draft", @@ -65,8 +65,8 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: unknown=set(payload)-{'node_id'} if unknown: raise ValueError('player.next accepts only current node_id context; target selection is forbidden') if 'node_id' in payload and (not isinstance(payload['node_id'],str) or not payload['node_id'] or len(payload['node_id'])>100): raise ValueError('invalid node_id') - if cmd=='player.get_review_queue' and payload: - raise ValueError('player.get_review_queue accepts an empty payload') + if cmd in {'player.get_review_queue','player.start_review','player.finish_review'} and payload: + raise ValueError(f'{cmd} accepts an empty payload') if cmd=='player.get_daily_case' and payload: raise ValueError('player.get_daily_case accepts an empty payload') if cmd=='research.get_chronology_lab' and payload: @@ -104,4 +104,4 @@ def ok_response(request_id:str,data:Any)->dict[str,Any]: def error_response(request_id:str,code:str,message:str,details:Any=None)->dict[str,Any]: err={"code":code,"message":message} if details is not None: err['details']=details - return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} + return {"api_version":TRANSPORT_API_VERSION,"request_id":request_id,"ok":False,"error":err} \ No newline at end of file From e896eeed8a5503b640c9bf9fa2c7cabe1d2b8581 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 03:59:12 +0200 Subject: [PATCH 18/20] ci: compose exact-head DEV1 substrate for Constructor V2 tests --- ...06-constructor-v2-direct-qualification.yml | 51 ++++++++++++++----- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/.github/workflows/r06-constructor-v2-direct-qualification.yml b/.github/workflows/r06-constructor-v2-direct-qualification.yml index 38dd6d9f6..786c762a4 100644 --- a/.github/workflows/r06-constructor-v2-direct-qualification.yml +++ b/.github/workflows/r06-constructor-v2-direct-qualification.yml @@ -36,7 +36,7 @@ jobs: timeout-minutes: 15 env: EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} - PYTHONPATH: "${{ github.workspace }}/lanes/dev1/repair_overlay${{ matrix.pathsep }}${{ github.workspace }}" + PYTHONPATH: "${{ github.workspace }}/r06_platform${{ matrix.pathsep }}${{ github.workspace }}" steps: - uses: actions/checkout@v4 with: @@ -50,25 +50,50 @@ jobs: - name: Confirm exact source checkout shell: bash run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - - name: Compile Constructor V2 direct-overlay surface + - name: Reconstruct exact-head DEV1 test substrate and apply overlay + shell: bash + run: | + python - <<'PY' + import base64, hashlib, shutil, zipfile + from pathlib import Path + + parts = sorted(Path('lanes/dev1/source_parts').glob('part-*.b64')) + if not parts: + raise SystemExit('missing DEV1 source parts') + encoded = ''.join(path.read_text(encoding='ascii') for path in parts) + archive_bytes = base64.b64decode(encoded) + archive = Path('DEV1_R06_PLATFORM_SOURCE_TEST_SUBSTRATE.zip') + archive.write_bytes(archive_bytes) + print('exact-head test-substrate sha256=', hashlib.sha256(archive_bytes).hexdigest()) + with zipfile.ZipFile(archive) as zf: + bad = zf.testzip() + if bad: + raise SystemExit(f'corrupt DEV1 test substrate member: {bad}') + zf.extractall('.') + root = Path('r06_platform') + if not (root / 'scripture_archive_platform' / 'persistence' / 'store.py').is_file(): + raise SystemExit('DEV1 test substrate missing persistence/store.py') + shutil.copytree('lanes/dev1/repair_overlay', root, dirs_exist_ok=True) + PY + - name: Compile composed Constructor V2 surface run: >- python -m compileall -q - lanes/dev1/repair_overlay/scripture_archive_platform/authoring - lanes/dev1/repair_overlay/scripture_archive_platform/application/service.py - lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py - lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py - lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py - lanes/dev1/repair_overlay/tests/test_authoring_transport.py + r06_platform/scripture_archive_platform/authoring + r06_platform/scripture_archive_platform/application/service.py + r06_platform/scripture_archive_platform/transport/contracts.py + r06_platform/tests/test_constructor_v2_lifecycle.py + r06_platform/tests/test_constructor_v2_recovery_atomicity.py + r06_platform/tests/test_authoring_transport.py - name: Run Constructor V2 lifecycle regression - run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_lifecycle.py + run: python r06_platform/tests/test_constructor_v2_lifecycle.py - name: Run Constructor V2 crash-recovery regression - run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_recovery_atomicity.py + run: python r06_platform/tests/test_constructor_v2_recovery_atomicity.py - name: Run Constructor V2 allowlist and source-isolation regression - run: python lanes/dev1/repair_overlay/tests/test_authoring_transport.py + run: python r06_platform/tests/test_authoring_transport.py - name: Run Constructor V2 semantic frontend regression - run: python lanes/dev1/repair_overlay/tests/test_constructor_v2_frontend.py + run: python r06_platform/tests/test_constructor_v2_frontend.py - name: Verify Constructor V2 frontend module syntax - run: node --check lanes/dev1/repair_overlay/frontend/constructor-v2-ui.js + run: node --check r06_platform/frontend/constructor-v2-ui.js - name: Diff hygiene shell: bash run: git diff --check From 50b916ac25a2f7801293553eaa69e7fb719fc743 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 04:02:15 +0200 Subject: [PATCH 19/20] ci: isolate verified Constructor dependency substrate --- ...06-constructor-v2-direct-qualification.yml | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/.github/workflows/r06-constructor-v2-direct-qualification.yml b/.github/workflows/r06-constructor-v2-direct-qualification.yml index 786c762a4..7399eec40 100644 --- a/.github/workflows/r06-constructor-v2-direct-qualification.yml +++ b/.github/workflows/r06-constructor-v2-direct-qualification.yml @@ -50,29 +50,50 @@ jobs: - name: Confirm exact source checkout shell: bash run: test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - - name: Reconstruct exact-head DEV1 test substrate and apply overlay + - name: Reconstruct verified Constructor dependency substrate and apply overlay shell: bash run: | python - <<'PY' import base64, hashlib, shutil, zipfile - from pathlib import Path + from pathlib import Path, PurePosixPath parts = sorted(Path('lanes/dev1/source_parts').glob('part-*.b64')) if not parts: raise SystemExit('missing DEV1 source parts') encoded = ''.join(path.read_text(encoding='ascii') for path in parts) archive_bytes = base64.b64decode(encoded) - archive = Path('DEV1_R06_PLATFORM_SOURCE_TEST_SUBSTRATE.zip') + archive = Path('DEV1_R06_PLATFORM_SOURCE_CONSTRUCTOR_SUBSTRATE.zip') archive.write_bytes(archive_bytes) - print('exact-head test-substrate sha256=', hashlib.sha256(archive_bytes).hexdigest()) + print('exact-head source-parts sha256=', hashlib.sha256(archive_bytes).hexdigest()) + + # Shared DEV1 release qualification owns whole-archive fidelity (#146). + # Constructor qualification needs only the Python platform dependency + # subtree. Verify CRC while extracting every member of that subtree and + # fail closed on any corruption there; do not treat unrelated corrupt + # frontend members as Constructor evidence or as a release-gate pass. + prefix = PurePosixPath('r06_platform/scripture_archive_platform') + extracted = 0 with zipfile.ZipFile(archive) as zf: - bad = zf.testzip() - if bad: - raise SystemExit(f'corrupt DEV1 test substrate member: {bad}') - zf.extractall('.') + for info in zf.infolist(): + member = PurePosixPath(info.filename) + if member == prefix or prefix in member.parents: + try: + zf.extract(info, '.') + except (zipfile.BadZipFile, OSError) as exc: + raise SystemExit(f'corrupt Constructor dependency member {info.filename}: {exc}') from exc + extracted += 1 + if extracted == 0: + raise SystemExit('DEV1 source parts contain no Constructor dependency subtree') + root = Path('r06_platform') - if not (root / 'scripture_archive_platform' / 'persistence' / 'store.py').is_file(): - raise SystemExit('DEV1 test substrate missing persistence/store.py') + required = [ + root / 'scripture_archive_platform' / 'persistence' / 'store.py', + root / 'scripture_archive_platform' / 'content' / 'loader.py', + root / 'scripture_archive_platform' / 'domain' / 'registries.py', + ] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise SystemExit('Constructor dependency substrate missing: ' + ', '.join(missing)) shutil.copytree('lanes/dev1/repair_overlay', root, dirs_exist_ok=True) PY - name: Compile composed Constructor V2 surface From 7e70450985d4fae316136585e44481e902b98678 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Sun, 13 Sep 2026 04:03:22 +0200 Subject: [PATCH 20/20] ci: include verified Constructor transport fixture dependency --- ...06-constructor-v2-direct-qualification.yml | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/.github/workflows/r06-constructor-v2-direct-qualification.yml b/.github/workflows/r06-constructor-v2-direct-qualification.yml index 7399eec40..7c43eed85 100644 --- a/.github/workflows/r06-constructor-v2-direct-qualification.yml +++ b/.github/workflows/r06-constructor-v2-direct-qualification.yml @@ -67,21 +67,29 @@ jobs: print('exact-head source-parts sha256=', hashlib.sha256(archive_bytes).hexdigest()) # Shared DEV1 release qualification owns whole-archive fidelity (#146). - # Constructor qualification needs only the Python platform dependency - # subtree. Verify CRC while extracting every member of that subtree and - # fail closed on any corruption there; do not treat unrelated corrupt - # frontend members as Constructor evidence or as a release-gate pass. - prefix = PurePosixPath('r06_platform/scripture_archive_platform') + # Constructor qualification needs the Python platform dependency subtree + # plus the canonical test fixture used by the transport regression. + # CRC-verify every extracted dependency and fail closed on corruption in + # those dependencies; unrelated corrupt members are not evidence for or + # against this bounded Constructor qualification and remain #146-owned. + platform_prefix = PurePosixPath('r06_platform/scripture_archive_platform') + exact_dependencies = {PurePosixPath('r06_platform/tests/_fixture.py')} extracted = 0 with zipfile.ZipFile(archive) as zf: for info in zf.infolist(): member = PurePosixPath(info.filename) - if member == prefix or prefix in member.parents: - try: - zf.extract(info, '.') - except (zipfile.BadZipFile, OSError) as exc: - raise SystemExit(f'corrupt Constructor dependency member {info.filename}: {exc}') from exc - extracted += 1 + wanted = ( + member == platform_prefix + or platform_prefix in member.parents + or member in exact_dependencies + ) + if not wanted: + continue + try: + zf.extract(info, '.') + except (zipfile.BadZipFile, OSError) as exc: + raise SystemExit(f'corrupt Constructor dependency member {info.filename}: {exc}') from exc + extracted += 1 if extracted == 0: raise SystemExit('DEV1 source parts contain no Constructor dependency subtree') @@ -90,6 +98,7 @@ jobs: root / 'scripture_archive_platform' / 'persistence' / 'store.py', root / 'scripture_archive_platform' / 'content' / 'loader.py', root / 'scripture_archive_platform' / 'domain' / 'registries.py', + root / 'tests' / '_fixture.py', ] missing = [str(path) for path in required if not path.is_file()] if missing: