#!/usr/bin/env python3 """ Generate the Wave-0 / P0-8 Release & Provenance Manifest (`manifest.json`) and synchronize the three brief-referenced JSONL/JSON artifact aliases (`AT-00`): - data/extracted/ring1_study_dossiers_v0.5.jsonl - data/extracted/ring1_atomic_effects_v0.5.jsonl - data/extracted/islet1_stack_ranking_v0.5.json """ from __future__ import annotations import hashlib import json import os import stat import fnmatch import threading from functools import lru_cache from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path ROOT = Path(__file__).resolve().parent.parent EXTRACTED_DIR = ROOT / "data" / "extracted" DOSSIERS_DIR = ROOT / "data" / "dossiers" OMICS_DIR = ROOT / "data" / "omics" RAW_DIR = ROOT / "data" / "raw" GRAVEYARD_PATH = ROOT / "data" / "graveyard" / "idea_graveyard_v0.5.json" _PUBLIC_POLICY_SNAPSHOT = ContextVar('openislet_public_policy_snapshot', default=None) _GENERATION_LEASE = ContextVar('openislet_manifest_generation_lease', default=None) _GENERATION_JOURNAL = ContextVar('openislet_manifest_generation_journal', default=None) _EXPORT_PROCESS_LOCK = threading.RLock() _PUBLIC_BUNDLE_MARKER_BYTES = b"openislet_public_bundle_v0.8.0\n" _NEVER_PUBLIC = ( 'data/dossiers/*', 'data/curated/*', # DEC-011 keeps detailed downstream plans private. The decisions log also # embeds those plans; neither file is a public blueprint artifact. 'docs/OPENISLET-2026-2030-MASTER-TIMELINE.md', 'docs/PROJECT-DECISIONS-LOG.md', 'data/raw/alphagenome_avi_3118_snvs_full_archive.json', 'data/raw/alphagenome_avi_26_seed_anchors.json', 'data/raw/alphagenome_avi_live_receipt_2026_10_28.json', 'data/raw/private_export_guard_patterns.json', 'data/extracted/islet1_candidate_stack_rankings.json', 'data/extracted/islet1_stack_ranking_v0.5.json', 'CLAUDE.md', '.git', '.git/*', '.claude', '.claude/*', '.claude/**', '.env', '.env.*', ) PUBLIC_PACKAGE_INCLUDED_PATHS: tuple[str, ...] = ( "LICENSE", "LICENSE-DATA", "CODE_OF_CONDUCT.md", "CONTRIBUTING.md", "SECURITY.md", ".gitignore", ".github/openislet-mark.svg", ".github/openislet-mark-dark.svg", ".github/ISSUE_TEMPLATE/config.yml", ".github/ISSUE_TEMPLATE/files-problem.yml", "requirements.txt", "pyproject.toml", ".licenses/*.txt", "ISLET-1-BLUEPRINT.md", "README.md", "manifest.json", "docs/*.md", "schemas/extraction_schema_v0.2.json", "scripts/*.py", "tests/*.py", "data/raw/ring1_platinum_queue.json", "data/raw/corpus_manifest_all_sources.jsonl", "data/raw/corpus_stratification_manifest.json", "data/raw/doc_citation_metadata_cache.json", "data/raw/layer2_genomic_and_jaspar_reference.json", "data/raw/layer5_dbsnp_clinvar_reference.json", "data/constructs/*.fasta", "data/extracted/*.json", "data/extracted/*.jsonl", "data/graveyard/idea_graveyard_v0.5.json", "data/omics/*.json", "data/protocols/*.json", "data/structures/*.cif", "data/structures/*.pdb", "data/structures/*.json", "data/structures/*.md", "data/structures/pymol/*", ) def _forbidden_public_path(relative): # Match portable identities too: a case alias can address the same private # file on APFS even when the manifest spells its name differently. key = relative.casefold() return any(part in {'__pycache__','.pytest_cache','.claude','.git'} or part == '.env' or part.startswith('.env.') for part in key.split('/')) or any(fnmatch.fnmatchcase(key, pattern.casefold()) for pattern in _NEVER_PUBLIC) def verify_public_bundle_privacy_guard( bundle_root: Path, included_paths: list[str] | tuple[str, ...] | None = None, *, source_root: Path | None = None, require_private_pattern_file: bool | None = None, ) -> dict[str, int | bool]: """Fail-closed privacy and credential scan over a staged public bundle or allowlisted file set.""" import re as _re base = source_root if source_root is not None else ROOT if require_private_pattern_file is None: require_private_pattern_file = not (base / ".openislet_public_bundle").exists() guard_cfg_path = base / "data" / "raw" / "private_export_guard_patterns.json" if not guard_cfg_path.is_file() and require_private_pattern_file: raise RuntimeError( "PRIVACY GUARD FAILED: Missing required private policy file data/raw/private_export_guard_patterns.json" ) raw_patterns: dict[str, str] = { "home_and_temp_paths": ( r"(?= 4 and home_name.lower() not in ("root", "admin", "user", "runner", "ubuntu"): compiled_patterns["local_account_name"] = _re.compile(_re.escape(home_name), _re.I) email_re = _re.compile(r"\b([A-Za-z0-9._%+-]+@([A-Za-z0-9.-]+\.[A-Za-z]{2,}))\b") candidate_files: list[tuple[Path, bool]] = [] if included_paths is None: candidate_files = [(fp, False) for fp in sorted(bundle_root.rglob("*")) if fp.is_file()] else: seen_paths: set[Path] = set() for pat in included_paths: is_glob = any(ch in pat for ch in ("*", "?", "[")) for fp in sorted(bundle_root.glob(pat)): if fp.is_file() and fp not in seen_paths: seen_paths.add(fp) candidate_files.append((fp, is_glob)) files_scanned = 0 for fp, from_glob in candidate_files: rel = fp.relative_to(bundle_root).as_posix() if rel != ".openislet_public_bundle" and _forbidden_public_path(rel): if from_glob: continue raise RuntimeError(f"PRIVACY GUARD FAILED: Public export privacy guard blocked forbidden path: {rel}") is_binary = rel.lower().endswith((".png", ".pse", ".jpg", ".jpeg", ".gif", ".webp", ".ico")) if is_binary: text = b"\n".join(_re.findall(rb"[ -~]{6,}", fp.read_bytes())).decode("ascii", errors="ignore") else: text = fp.read_text(encoding="utf-8", errors="ignore") for label, rx in compiled_patterns.items(): if rx.search(text): raise RuntimeError(f"PRIVACY GUARD FAILED: Public export privacy guard blocked {label} in {rel}") if not is_binary: file_allowed = {e.lower() for e in allowed_file_emails.get(rel, set())} for full_email, domain in email_re.findall(text): if domain.lower() not in allowed_email_domains and full_email.lower() not in file_allowed: raise RuntimeError(f"PRIVACY GUARD FAILED: Public export privacy guard blocked unauthorized email in {rel}") files_scanned += 1 return {"passed": True, "violation_count": 0, "files_scanned": files_scanned} def _canonical_relative_path(value: str) -> bool: import re return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9._/-]+", value) is not None and all(part not in ("", ".", "..") for part in value.split("/")) def _artifact_inventory_errors(artifacts) -> list[str]: """Validate even retained private pins before any path is dereferenced.""" if not isinstance(artifacts, dict) or not artifacts: return ['invalid-or-empty-artifact-inventory'] errors = [] identities = set() for relative, pin in artifacts.items(): if not _canonical_relative_path(relative) or relative in ('manifest.json', '.openislet_public_bundle'): errors.append('invalid-artifact-path:' + str(relative)) continue identity = relative.casefold() if identity in identities: errors.append('duplicate-portable-artifact:' + relative) identities.add(identity) if (not isinstance(pin, dict) or not isinstance(pin.get('sha256'), str) or _re.fullmatch('[0-9a-f]{64}', pin['sha256']) is None or type(pin.get('bytes')) is not int or pin['bytes'] < 0): errors.append('invalid-artifact-pin:' + relative) return errors def public_excerpt_limits(allow) -> tuple[int, float]: """Resolve one validated policy for exporter and acceptance verification.""" import math characters = allow.get('non_oa_per_article_aggregate_verbatim_ceiling_characters', 240) share = allow.get('non_oa_per_article_max_abstract_share', .25) if type(characters) is not int or not 0 <= characters <= 240: raise ValueError('Public non-OA character policy may not exceed 240 characters') if isinstance(share, bool) or not isinstance(share, (int, float)) or not math.isfinite(share) or not 0 < share <= .25: raise ValueError('Public non-OA abstract share policy must be finite in (0, .25]') return characters, share def _regular_file_bytes(root: Path, relative: str) -> bytes: """Read one single-link regular file without following release-tree links.""" if not _canonical_relative_path(relative): raise ValueError("Release file path must be canonical and relative") current = root parts = relative.split("/") for i, part in enumerate(parts): current = current / part info = current.lstat() if stat.S_ISLNK(info.st_mode): raise ValueError("Release files and their parents may not be symbolic links") if i < len(parts)-1 and not stat.S_ISDIR(info.st_mode): raise ValueError("Release parent must be a directory") if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("Release input must be a regular file with one hard link") fd = os.open(current, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) try: opened = os.fstat(fd) if not stat.S_ISREG(opened.st_mode) or opened.st_nlink != 1 or (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino): raise ValueError("Release input identity changed while opening") with os.fdopen(fd, "rb", closefd=False) as stream: data = stream.read() after = os.fstat(fd) if (after.st_size, after.st_mtime_ns, after.st_ctime_ns) != (len(data), opened.st_mtime_ns, opened.st_ctime_ns): raise ValueError("Release input changed while reading") return data finally: os.close(fd) def sha256_file(path: Path) -> str: base = ROOT if path.is_relative_to(ROOT) else path.parent return hashlib.sha256(_regular_file_bytes(base, path.relative_to(base).as_posix())).hexdigest()