scripts/generate_release_manifest.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/generate_release_manifest.py · SHA-256: 9b8e7a9ff4998368…
unbound_matches[key,value]=[p for p,source in normalized_sources.items() if any(shingle in source for shingle in shingles)]
for source_pmid in unbound_matches[key,value]:totals[source_pmid]+=len(value)
visit(graph)
return totals
def _verify_pinned_source(root: Path, relative_path: str, manifest: dict) -> None:
"""Never relabel changed source bytes as the pinned release during export."""
if relative_path == "manifest.json":
return # A manifest cannot contain its own digest.
if not _canonical_relative_path(relative_path):
raise ValueError(f"Unsafe manifest source path: {relative_path}")
pin = manifest.get("artifacts", {}).get(relative_path, {})
expected = pin.get("sha256")
data = _regular_file_bytes(root, relative_path)
actual = hashlib.sha256(data).hexdigest()
if expected != actual or type(pin.get("bytes")) is not int or pin["bytes"] != len(data):
raise ValueError(f"Pinned source hash mismatch for {relative_path}; regenerate the canonical manifest before export")
def manifest_integrity_errors(root: Path, manifest: dict, public: bool = False) -> list[str]:
"""Validate live identities, byte counts and exact declared public membership."""
errors=[]
artifacts=manifest.get('artifacts')
artifact_errors = _artifact_inventory_errors(artifacts)
if artifact_errors:
return sorted(artifact_errors)
inventory=manifest.get('public_export_file_inventory')
if public:
if (not isinstance(inventory,list) or not inventory or
any(not _canonical_relative_path(rel) for rel in inventory) or
len(set(inventory))!=len(inventory) or
any(rel not in artifacts or rel in ('manifest.json','.openislet_public_bundle') for rel in inventory)):
return ['invalid-public-inventory']
required=set(inventory)
errors.extend('forbidden:'+rel for rel in required if _forbidden_public_path(rel))
else:
required=set(artifacts)
for rel in sorted(required):
try:
if rel=='manifest.json': raise ValueError('self pin')
_verify_pinned_source(root,rel,manifest)
except (OSError,ValueError,TypeError,KeyError): errors.append(rel)
# Every file in a public tree must be declared. A cache directory name is
# never an exemption for an undeclared payload; verification can use -B and
# disable pytest's cache provider to keep runtime caches outside the bundle.
if public:
if (root / '.git').is_symlink():
errors.append('unsafe:.git')
for path in root.rglob('*'):
rel=path.relative_to(root).as_posix()
if rel == '.git' or rel.startswith('.git/'):
continue
if path.is_symlink() or (not path.is_dir() and (not stat.S_ISREG(path.lstat().st_mode) or path.lstat().st_nlink != 1)):
errors.append('unsafe:'+rel); continue
if not path.is_dir() and rel not in required|{'manifest.json','.openislet_public_bundle'}:
errors.append('unexpected:'+rel)
try:
if _regular_file_bytes(root, '.openislet_public_bundle') != _PUBLIC_BUNDLE_MARKER_BYTES:
errors.append('invalid-public-marker')
except (OSError, ValueError): errors.append('invalid-public-marker')
return sorted(set(errors))
def export_public_bundle(dest_dir: Path) -> list[str]:
# Snapshot imports temporarily affect Python's process-global import path
# and bytecode setting. Serialize same-process exporters as well as taking
# the destination lease used by independent processes.
with _EXPORT_PROCESS_LOCK:return _export_public_bundle_serialized(dest_dir)
def _export_public_bundle_serialized(dest_dir: Path) -> list[str]:
# Serialize publishers of the same destination without modifying source data.
destination = Path(dest_dir).absolute()
allowed_system_links = {Path('/tmp'),Path('/var'),Path('/etc')}
if any(part.is_symlink() and part not in allowed_system_links for part in [destination,*destination.parents]):
raise ValueError('Destination and ancestors may not be symbolic links')
resolved=destination.resolve(); root=ROOT.resolve()
if resolved == root or resolved in root.parents or root in resolved.parents:
raise ValueError('Public export must be outside the repository tree')
# Approved OS aliases (/var -> /private/var on macOS) were checked before
# resolution. The lease itself always receives the canonical real path.
destination=resolved
destination.parent.mkdir(parents=True, exist_ok=True)
with _publication_lock(destination.parent / ("." + destination.name + ".publish-lock")) as lease:
return _export_public_bundle_locked(destination,publication_lease=lease)
def _export_public_bundle_locked(dest_dir: Path, publication_lease=None) -> list[str]:
"""Materializes a clean, rights-aware public distribution directory containing strictly the allowlisted files
and enforcing the per-article non-OA aggregate verbatim quote ceiling (<=240 chars and <25% of abstract length)."""
import re
import shutil
import tempfile
def require_lease():
if publication_lease is not None:publication_lease.require_owned()
# Check symlink status on dest_dir and ALL ancestor components BEFORE .resolve() so symlinked destinations are rejected
raw_dest = Path(dest_dir)
allowed_sys_symlinks = {
Path("/tmp"), Path("/var"), Path("/etc"),
}
for anc in [raw_dest, *raw_dest.parents]:
if anc.is_symlink() and anc not in allowed_sys_symlinks:
raise ValueError(f"Destination or ancestor {anc} must not be a symlink.")
root_resolved = ROOT.resolve()
final_dest_dir = raw_dest.resolve()
if (
final_dest_dir == root_resolved
or final_dest_dir in root_resolved.parents
or root_resolved in final_dest_dir.parents
):
raise ValueError(
f"Refusing to export public bundle into or over repository tree: {final_dest_dir} (ROOT={root_resolved})"
)
if final_dest_dir.exists():
if not final_dest_dir.is_dir() or final_dest_dir.is_symlink():
raise ValueError(f"Destination {final_dest_dir} must be a regular directory, not a file or symlink.")
entries = list(final_dest_dir.iterdir())
if entries and not (final_dest_dir / ".openislet_public_bundle").exists():
raise ValueError(
f"Refusing to overwrite non-empty directory {final_dest_dir} lacking '.openislet_public_bundle' marker."
)
if entries:
if _regular_file_bytes(final_dest_dir, '.openislet_public_bundle') != _PUBLIC_BUNDLE_MARKER_BYTES:
raise ValueError(f"Refusing to overwrite directory {final_dest_dir} with unrecognized .openislet_public_bundle marker content.")
manifest_bytes = _regular_file_bytes(ROOT, "manifest.json")
manifest = json.loads(manifest_bytes)
artifact_errors = _artifact_inventory_errors(manifest.get('artifacts'))
if artifact_errors:
raise ValueError('Invalid release artifact inventory: ' + ', '.join(artifact_errors))
pinned_artifacts = set(manifest.get("artifacts", {}).keys()) | {"manifest.json"}
allow = manifest["public_redistribution_allowlist_spec"]
max_non_oa_chars, max_non_oa_share = public_excerpt_limits(allow)
included: set[str] = set()
# A glob is not proof that every file in the release still exists. Derive
# the required set from the pinned inventory before enumerating disk.
patterns = allow["public_package_included_paths"]
excluded = allow["local_research_cache_excluded_from_public_bundle"]
required = {rel for rel in pinned_artifacts if any(fnmatch.fnmatchcase(rel, pat) for pat in patterns)
and not any(fnmatch.fnmatchcase(rel, pat) for pat in excluded)}
if any(_forbidden_public_path(rel) for rel in required):
raise ValueError('Public policy may not include private caches, planning documents or frozen ranking artifacts')
for rel in required:
_regular_file_bytes(ROOT, rel)
for pat in allow["public_package_included_paths"]:
if Path(pat).is_absolute() or ".." in Path(pat).parts:
raise ValueError(f"Unsafe public include pattern: {pat}")
# Also check non-glob prefix directory components for symlinks before globbing
pat_parts = Path(pat).parts
cur_check = ROOT
for part in pat_parts:
if "*" in part or "?" in part or "[" in part:
break
cur_check = cur_check / part
if cur_check.is_symlink():
raise ValueError(f"Symlink directory not permitted in public bundle allowlist: {cur_check}")
for p in ROOT.glob(pat):
if _has_symlink_component(p, stop_at=ROOT):
raise ValueError(f"Symlink or symlinked ancestor not permitted in public bundle allowlist: {p}")
info = p.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
raise ValueError(f"Public include matched a non-regular or multiply-linked file: {p}")
if p.is_file():
rel_str = str(p.relative_to(ROOT))
if rel_str not in pinned_artifacts:
raise ValueError(
f"Unpinned file {rel_str!r} matched public bundle glob {pat!r} but is absent from manifest['artifacts']"
)
included.add(rel_str)
for pat in allow["local_research_cache_excluded_from_public_bundle"]:
if not isinstance(pat,str) or Path(pat).is_absolute() or ".." in Path(pat).parts:
raise ValueError("Unsafe public exclusion pattern")
for p in ROOT.glob(pat):
if p.is_file() or p.is_symlink():
included.discard(str(p.relative_to(ROOT)))
if included != required:
raise ValueError("Public allowlist does not exactly match the pinned release inventory")
# Private source text controls the quote policy, so its pins matter even
# though those dossiers never ship. Recheck on every actual read below.
if 'public_export_file_inventory' not in manifest:
for rel in manifest.get('artifacts',{}):
if rel.startswith('data/dossiers/'):
_verify_pinned_source(ROOT,rel,manifest)
dossier_inputs = sorted((ROOT / "data" / "dossiers").glob("*.json"))
for source in dossier_inputs:
_verify_pinned_source(ROOT, source.relative_to(ROOT).as_posix(), manifest)
def read_dossier(source):
rel = source.relative_to(ROOT).as_posix()
data = _regular_file_bytes(ROOT, rel)
if hashlib.sha256(data).hexdigest() != manifest["artifacts"][rel]["sha256"]:
raise ValueError("Private source changed during public export")
return json.loads(data)
# Validate source pins before creating any staging output. Unique siblings
# prevent deleting unrelated directories or colliding with another export.
for rel in sorted(included):
_verify_pinned_source(ROOT, rel, manifest)
# Sealed public bundles have already undergone full source-backed rights redaction and
# manifest pinning; re-exporting an untampered sealed bundle must be byte-preserving
# rather than re-redacting already-cleared structured labels and frozen records.
_is_sealed_pub_src = False
if (ROOT / ".openislet_public_bundle").exists() or (ROOT / ".openislet_public_bundle").is_symlink():
if _regular_file_bytes(ROOT, ".openislet_public_bundle") != _PUBLIC_BUNDLE_MARKER_BYTES:
raise ValueError("Source .openislet_public_bundle marker has unrecognized content or version")
_is_sealed_pub_src = True
if (
_is_sealed_pub_src
and "public_export_file_inventory" in manifest
and not (ROOT / "data" / "dossiers").exists()
and set(manifest["public_export_file_inventory"]) == (included - {"manifest.json"})
):
verify_public_bundle_snapshot(ROOT)
import sys as _sys_re
import types as _types_re
from jsonschema import Draft202012Validator as _Draft202012Re
final_dest_dir.parent.mkdir(parents=True, exist_ok=True)
require_lease()
staging_dir = Path(tempfile.mkdtemp(prefix=f".{final_dest_dir.name}.staging-", dir=final_dest_dir.parent))
policy_token = None
previous_bytecode = _sys_re.dont_write_bytecode
_sys_re.dont_write_bytecode = True
try:
shutil.copy2(ROOT / ".openislet_public_bundle", staging_dir / ".openislet_public_bundle")
for rel in sorted(included):
require_lease()
src = ROOT / rel
if _has_symlink_component(src, stop_at=ROOT):
raise ValueError(f"Symlink not permitted in public bundle export: {src}")
dst = staging_dir / rel
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
_verify_pinned_source(staging_dir, rel, manifest)
public_helper = _types_re.ModuleType("openislet_export_snapshot_policy")
public_helper.__file__ = str(staging_dir / "scripts/public_excerpt_policy.py")
exec(compile(_regular_file_bytes(staging_dir, "scripts/public_excerpt_policy.py"), public_helper.__file__, "exec"), public_helper.__dict__)
schema_bytes = _regular_file_bytes(staging_dir, "schemas/extraction_schema_v0.2.json")
policy_token = _PUBLIC_POLICY_SNAPSHOT.set({"helper": public_helper, "schema": schema_bytes})
if manifest_integrity_errors(staging_dir, manifest, public=True):
raise ValueError("Sealed public bundle re-export failed exact inventory and digest post-condition")
disc_re = staging_dir / "data/raw/corpus_manifest_all_sources.jsonl"
if disc_re.exists():
disc_rows_re = [json.loads(ln) for ln in disc_re.read_text(encoding="utf-8").splitlines() if ln.strip()]
if [_public_discovery_record(row) for row in disc_rows_re] != disc_rows_re:
raise ValueError("Sealed public bundle discovery metadata is not cleanly projected")
export_schema_re = _Draft202012Re(json.loads(schema_bytes))