OpenIslet

scripts/generate_release_manifest.py

Generate the Wave-0 / P0-8 Release & Provenance Manifest (`manifest.json`) and

script Release v0.8.0 gen-eb955f8266035aba 148 KB · 11 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/generate_release_manifest.py · SHA-256: 9b8e7a9ff4998368…

#!/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"(?<![A-Za-z0-9._-])(?:/" + r"Users/|/" + r"home/[a-z0-9_-]+/|/"
            + r"private/tmp|/" + r"var/folders|~/\.?[A-Za-z0-9_-]{2,}/)"
        ),
        "private_keys_and_tokens": (
            r"(?:-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|sk-ant-[A-Za-z0-9_-]{8,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-svcacct-[A-Za-z0-9_-]{16,}|(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_-]{20,}|hf_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})"
        ),
    }
    allowed_email_domains: set[str] = {"openislet.org", "users.noreply.github.com"}
    allowed_file_emails: dict[str, set[str]] = {
        "data/structures/pdb_00003cdg.cif": {"sw-help" + "@rcsb.rutgers.edu", "PDAdams" + "@lbl.gov"},
    }
    cfg = json.loads(guard_cfg_path.read_text(encoding="utf-8")) if guard_cfg_path.is_file() else {}
    for k, v in (cfg.get("regex_patterns") or {}).items():
        if isinstance(k, str) and isinstance(v, str):
            raw_patterns[k] = v
    for dom in cfg.get("allowed_email_domains") or ():
        if isinstance(dom, str):
            allowed_email_domains.add(dom.lower())
    for rel_k, em_list in (cfg.get("allowed_file_specific_emails") or {}).items():
        if isinstance(rel_k, str) and isinstance(em_list, list):
            allowed_file_emails.setdefault(rel_k, set()).update(str(e) for e in em_list)
    compiled_patterns = {k: _re.compile(v) for k, v in raw_patterns.items()}
    home_name = Path.home().name
    if len(home_name) >= 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()