#!/usr/bin/env python3 """Preserve card inputs and exact exports once per content hash before compaction.""" import argparse import hashlib import json import os from pathlib import Path, PurePosixPath import re import shutil import tempfile VISUAL_SUFFIXES = { '.png', '.jpg', '.jpeg', '.webp', '.tif', '.tiff', '.gif', '.bmp', '.svg', '.psd', '.xcf', '.avif', '.mp4', '.webm', } CACHE_NAMES = {'__pycache__', 'font-cache', '.pytest_cache', '.mypy_cache', '.ruff_cache'} def digest(path): checksum = hashlib.sha256() with Path(path).open('rb') as stream: while chunk := stream.read(1024 * 1024): checksum.update(chunk) return checksum.hexdigest() def object_path(store, sha256): if not re.fullmatch(r'[0-9a-f]{64}', sha256): raise ValueError('Invalid archive object hash') return store / 'objects' / sha256[:2] / sha256[2:] def retain_object(path, store): """Stream a file into the store; verify existing objects instead of replacing them.""" object_root = store / 'objects' object_root.mkdir(parents=True, exist_ok=True) descriptor, temporary = tempfile.mkstemp(prefix='.pending-', dir=object_root) try: checksum = hashlib.sha256() size = 0 with os.fdopen(descriptor, 'wb') as output, path.open('rb') as source: while chunk := source.read(1024 * 1024): checksum.update(chunk) size += len(chunk) output.write(chunk) sha256 = checksum.hexdigest() target = object_path(store, sha256) target.parent.mkdir(parents=True, exist_ok=True) if target.exists(): if target.stat().st_size != size or digest(target) != sha256: raise ValueError(f'Corrupt archive object: {target}; run git lfs pull if it is a pointer') else: # A concurrent archive may have written the same object; never overwrite it. try: os.link(temporary, target) except FileExistsError: if target.stat().st_size != size or digest(target) != sha256: raise ValueError(f'Corrupt archive object: {target}') return {'sha256': sha256, 'bytes': size, 'mode': path.stat().st_mode & 0o777} finally: Path(temporary).unlink(missing_ok=True) def snapshot_id(snapshot): encoded = json.dumps(snapshot, sort_keys=True, separators=(',', ':')).encode() return hashlib.sha256(encoded).hexdigest() def archive_revision(directory, repo): """Archive originals, production exports and text evidence, excluding review renders.""" directory, repo = Path(directory).absolute(), Path(repo).resolve() manifest = json.loads((directory / 'manifest.json').read_text()) card_id, revision = manifest['cardId'], manifest['revision'] if not re.fullmatch(r'[A-Z]+-[0-9]{3,}', card_id) or not re.fullmatch(r'[a-z0-9-]+', revision): raise ValueError('Invalid archive card identity') store = repo / 'artifacts/asset-archive' files = {} for path in sorted(directory.rglob('*')): relative = path.relative_to(directory) if any(part in CACHE_NAMES for part in relative.parts): continue if relative.parts[0] == 'review' and path.suffix.lower() in VISUAL_SUFFIXES: continue if path.is_symlink() and not path.exists(): raise ValueError(f'Cannot archive a broken input link: {path}') if not path.is_file(): continue record = retain_object(path, store) if path.is_symlink(): # Store the actual bytes too, so a later deletion of the target loses no input. record['originalLink'] = str(path.readlink()) files[relative.as_posix()] = record snapshot = { 'schemaVersion': 1, 'kind': 'sanctification-card-archive', 'cardId': card_id, 'revision': revision, 'stage': manifest['stage'], 'approval': manifest.get('approval'), 'originalPath': str(directory.relative_to(repo)), 'files': files, 'retention': 'All source inputs, exact production exports and text evidence; review renders and caches excluded.', } target = store / 'snapshots' / card_id / revision / (snapshot_id(snapshot) + '.json') target.parent.mkdir(parents=True, exist_ok=True) serialized = json.dumps(snapshot, indent=2, sort_keys=True) + '\n' try: with target.open('x') as output: output.write(serialized) except FileExistsError: if target.read_text() != serialized: raise ValueError(f'Changed immutable archive snapshot: {target}') verify_snapshot(target) return {'manifest': str(target.relative_to(repo)), 'sha256': digest(target)} def verify_snapshot(path): path = Path(path).resolve() snapshot = json.loads(path.read_text()) if snapshot.get('kind') != 'sanctification-card-archive' or snapshot.get('schemaVersion') != 1: raise ValueError('Unsupported archive snapshot') if path.stem != snapshot_id(snapshot): raise ValueError('Archive snapshot hash does not match its contents') store = path.parents[3] if path.parents[2].name != 'snapshots' or store.name != 'asset-archive': raise ValueError('Snapshot must be inside an asset-archive/snapshots store') checked = set() for relative, record in snapshot['files'].items(): name = PurePosixPath(relative) if not relative or name.is_absolute() or '..' in name.parts or '\\' in relative: raise ValueError(f'Unsafe archive filename: {relative}') sha256 = record['sha256'] source = object_path(store, sha256) if not source.is_file() or source.stat().st_size != record['bytes']: raise ValueError(f'Missing or incorrect archive object: {relative}; run git lfs pull') if sha256 not in checked: if digest(source) != sha256: raise ValueError(f'Corrupt archive object: {relative}; run git lfs pull if it is a pointer') checked.add(sha256) return snapshot, store def restore_snapshot(path, output): """Restore into an empty destination; archived links become their retained bytes.""" snapshot, store = verify_snapshot(path) output = Path(output).absolute() if output.exists() and (output.is_symlink() or not output.is_dir() or any(output.iterdir())): raise ValueError('Restore destination must be an empty directory') output.mkdir(parents=True, exist_ok=True) for relative, record in snapshot['files'].items(): target = output / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(object_path(store, record['sha256']), target) target.chmod(record['mode'] & 0o777) return output def main(): parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest='command', required=True) archive = sub.add_parser('archive') archive.add_argument('--package', type=Path, required=True) archive.add_argument('--repo', type=Path, default=Path(__file__).resolve().parents[2]) for command in ['verify', 'restore']: child = sub.add_parser(command) child.add_argument('--snapshot', type=Path, required=True) if command == 'restore': child.add_argument('--output', type=Path, required=True) args = parser.parse_args() try: if args.command == 'archive': print(json.dumps(archive_revision(args.package, args.repo), indent=2)) elif args.command == 'verify': snapshot, _ = verify_snapshot(args.snapshot) print(f"Verified {snapshot['cardId']}/{snapshot['revision']}: {len(snapshot['files'])} files") else: print(restore_snapshot(args.snapshot, args.output)) except (OSError, ValueError, KeyError) as error: parser.exit(1, f'Archive error: {error}\n') if __name__ == '__main__': main()