"""Local manifest verification and explicit opt-in Hugging Face publication.""" import hashlib import json import os from pathlib import Path, PurePosixPath import re import tempfile import shutil MANIFEST = "release/MANIFEST.json" SKIP = {".git", ".venv", "venv", "__pycache__", ".pytest_cache", "build", "dist", "runs", ".ruff_cache"} TOKEN_PATTERN = re.compile(rb"hf_[A-Za-z0-9]{20,}") TEXT_SUFFIX = {".py", ".md", ".txt", ".json", ".jsonl", ".yaml", ".yml", ".bat", ".ps1", ".sh", ".toml", ".cff", ".bib", ".tex"} def eligible(path): parts=PurePosixPath(path).parts return not any(p in SKIP or p.endswith(".egg-info") for p in parts) and not ( path==MANIFEST or parts[-1].endswith((".pyc",".pyo")) or parts[-1].startswith(".env")) def _safe_relative(name): p=PurePosixPath(name) if p.is_absolute() or ".." in p.parts or not p.parts or "\\" in name: raise ValueError("manifest contains an unsafe path") return p def scan_release(root): root=Path(root).resolve();files={} for p in sorted(root.rglob("*")): rel=p.relative_to(root).as_posix() if not eligible(rel): continue if p.is_symlink(): raise ValueError(f"symlinks are forbidden in releases: {rel}") if not p.is_file(): continue data=p.read_bytes() if p.suffix.lower() in TEXT_SUFFIX and TOKEN_PATTERN.search(data): raise ValueError(f"possible Hugging Face access token in {rel}; remove it before publication") if p.name.lower() in {"id_rsa","id_ed25519","credentials.json","token","token.txt","secrets.json"} or p.suffix.lower() in {".pem",".key"}: raise ValueError(f"possible secret file: {rel}") files[rel]={"sha256":hashlib.sha256(data).hexdigest(),"bytes":len(data)} return files def build_manifest(root): root=Path(root) result={"schema":"celestis-rl-release-manifest-v1","version":"2.0.0","hash_algorithm":"SHA-256", "scope":"file byte integrity only, not authorship or scientific validity", "files":scan_release(root)} p=root/MANIFEST;p.parent.mkdir(parents=True,exist_ok=True) p.write_text(json.dumps(result,indent=2,sort_keys=True)+"\n",encoding="utf-8") return result def verify_manifest(root): """Verify every manifest-declared release file. Local *extra* files are deliberately ignored: publication stages only the manifest-declared files, so a user's screenshots, notes, replacement BAT files, or other workspace artifacts cannot leak into the Hub upload and do not invalidate an otherwise intact release. Missing or changed declared files still fail closed. """ root=Path(root).resolve() m=json.loads((root/MANIFEST).read_text(encoding="utf-8")) if m.get("schema")!="celestis-rl-release-manifest-v1": raise ValueError("unknown manifest schema") missing=[];changed=[] for rel,expected in m["files"].items(): _safe_relative(rel) p=root/rel if not p.exists() or not p.is_file() or p.is_symlink(): missing.append(rel) continue data=p.read_bytes() actual={"sha256":hashlib.sha256(data).hexdigest(),"bytes":len(data)} if actual!=expected: changed.append(rel) if missing or changed: raise ValueError(f"manifest mismatch; missing={sorted(missing)}, changed={sorted(changed)}") return m def local_extras(root, manifest=None): """Return eligible local files not declared by the release manifest. These files are never staged or uploaded by :func:`publish_release`. """ root=Path(root).resolve() m=manifest or json.loads((root/MANIFEST).read_text(encoding="utf-8")) declared=set(m["files"]) extras=[] for p in sorted(root.rglob("*")): if not p.is_file() or p.is_symlink(): continue rel=p.relative_to(root).as_posix() if rel==MANIFEST or not eligible(rel): continue if rel not in declared: extras.append(rel) return extras def publish_release(root,repo_id,*,publish=False,public=False,token=None,api=None): """Default dry run never connects. Publish stages only verified file bytes. New dataset repositories only; an existing repo is deliberately not overwritten. Public visibility requires an explicit public=True flag. Does not delete anything. Token is passed in memory, never written/logged. """ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*",repo_id): raise ValueError("repo_id must be namespace/name") root=Path(root).resolve();m=verify_manifest(root) extras=local_extras(root,m) summary={"repo_id":repo_id,"repo_type":"dataset","public":public, "files":len(m["files"])+1,"bytes":sum(x["bytes"] for x in m["files"].values()), "ignored_local_files":extras, "operation":"publish" if publish else "dry-run","uploaded":False} if not publish: return summary if api is None: if not token: raise ValueError("provide HF_TOKEN or use the interactive token prompt") from huggingface_hub import HfApi api=HfApi(token=token) # Build an immutable staging copy, check hashes again, and only then write. with tempfile.TemporaryDirectory(prefix="celestis_rl_release_") as temp: stage=Path(temp) for rel,info in m["files"].items(): data=(root/rel).read_bytes() if hashlib.sha256(data).hexdigest()!=info["sha256"]: raise ValueError("file changed during staging") target=stage/rel;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data) (stage/"release").mkdir(exist_ok=True) (stage/MANIFEST).write_text(json.dumps(m,indent=2,sort_keys=True)+"\n",encoding="utf-8") verify_manifest(stage) # exist_ok=False refuses to overwrite an already existing repository. api.create_repo(repo_id=repo_id,repo_type="dataset",private=not public,exist_ok=False) commit=api.upload_folder(repo_id=repo_id,repo_type="dataset",folder_path=str(stage), commit_message="Release Celestis-RL v2.0.0: audited research reference") summary["uploaded"]=True summary["commit_url"]=str(getattr(commit,"commit_url",commit)) return summary