#!/usr/bin/env python3 """Prepare, publish, and verify the consolidated collection without deleting files. Run sync_centre.py first. `prepare` freezes a file inventory and SHA-256 list. `publish` uploads that exact payload through a hard-link staging directory. `verify-hf` compares every payload file with the repository's Git/LFS hashes. Operational review files, assistant state, caches, and nested Git internals are excluded. This script does not modify Centre's live production directories. """ import argparse import concurrent.futures import hashlib import json import os import re from pathlib import Path ROOT = Path(__file__).resolve().parent.parent STATE = ROOT / 'sync/review_20260922' REPO = 'davidwdw/b1k' IGNORED = {'.git', '.cache', '.claude', '.pytest_cache', '__pycache__', 'Claude outputs'} SKIP = {'sync/COLLECTION_SHA256SUMS', 'sync/COLLECTION_STATUS.json'} def files(): for parent, dirs, names in os.walk(ROOT): base = Path(parent) dirs[:] = sorted(d for d in dirs if d not in IGNORED and not (base == ROOT / 'sync' and (d.startswith('review_') or d in {'logs', '.publish-staging'}))) for name in sorted(names): path = base / name rel = path.relative_to(ROOT).as_posix() if (path.is_file() and not path.is_symlink() and rel not in SKIP and not re.match(r'^\..+\.[A-Za-z0-9]{6}$', name)): yield rel def digest(rel): p = ROOT / rel before = p.stat() sha = hashlib.sha256() git = hashlib.sha1(b'blob ' + str(before.st_size).encode() + b'\0') with p.open('rb') as stream: for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): sha.update(block) git.update(block) after = p.stat() if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns): raise RuntimeError('File changed during snapshot: ' + rel) return {'path': rel, 'size': after.st_size, 'mtime_ns': after.st_mtime_ns, 'sha256': sha.hexdigest(), 'git_blob': git.hexdigest()} def prepare(): STATE.mkdir(exist_ok=True) paths = list(files()) rows = [] with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: for n, row in enumerate(pool.map(digest, paths), 1): rows.append(row) if n % 10000 == 0: print('HASHED', n, '/', len(paths), flush=True) sums = ROOT / 'sync/COLLECTION_SHA256SUMS' sums.write_text(''.join(r['sha256'] + ' ' + r['path'] + '\n' for r in rows)) rows.append(digest('sync/COLLECTION_SHA256SUMS')) (STATE / 'payload_inventory.json').write_text(json.dumps(rows)) (STATE / 'payload_paths.null').write_bytes(b'\0'.join(r['path'].encode() for r in rows) + b'\0') print('SNAPSHOT', len(rows), 'files', sum(r['size'] for r in rows), 'bytes', flush=True) def payload(): return json.loads((STATE / 'payload_inventory.json').read_text()) def reconcile_attributes(api, commit): """Keep the frozen inventory consistent with Hub-generated LFS rules.""" from huggingface_hub import CommitOperationAdd, hf_hub_download downloaded = Path(hf_hub_download(REPO, '.gitattributes', repo_type='dataset', revision=commit.oid, local_dir=STATE / 'hf_attributes')) attributes = ROOT / '.gitattributes' if downloaded.read_bytes() == attributes.read_bytes(): return commit rows = payload() expected = {r['path']: r for r in rows} names = ['.gitattributes', 'SHA256SUMS', 'MANIFEST.tsv'] for name in names: if digest(name)['sha256'] != expected[name]['sha256']: raise RuntimeError('Local metadata changed during upload: ' + name) attributes.write_bytes(downloaded.read_bytes()) attribute_hash = digest('.gitattributes')['sha256'] sums = ROOT / 'SHA256SUMS' lines = [line for line in sums.read_text().splitlines() if line.split(' ', 1)[-1] != '.gitattributes'] sums.write_text('\n'.join(lines + [attribute_hash + ' .gitattributes']) + '\n') manifest = ROOT / 'MANIFEST.tsv' lines = [line for line in manifest.read_text().splitlines() if line.split('\t', 1)[0] != '.gitattributes'] lines.append('.gitattributes\t' + attribute_hash + '\tHub-generated LFS attributes retained after publication') manifest.write_text('\n'.join(lines) + '\n') updates = {name: digest(name) for name in names} rows = [updates.get(r['path'], r) for r in rows] collection_sums = ROOT / 'sync/COLLECTION_SHA256SUMS' collection_sums.write_text(''.join(r['sha256'] + ' ' + r['path'] + '\n' for r in rows if r['path'] != 'sync/COLLECTION_SHA256SUMS')) updates['sync/COLLECTION_SHA256SUMS'] = digest('sync/COLLECTION_SHA256SUMS') rows = [updates.get(r['path'], r) for r in rows] (STATE / 'payload_inventory.json').write_text(json.dumps(rows)) return api.create_commit( REPO, repo_type='dataset', parent_commit=commit.oid, operations=[CommitOperationAdd(path_in_repo=name, path_or_fileobj=ROOT / name) for name in ['SHA256SUMS', 'MANIFEST.tsv', 'sync/COLLECTION_SHA256SUMS']], commit_message='Align integrity manifests with Hub-generated LFS attributes') def publish(): from huggingface_hub import HfApi stage = ROOT / 'sync/.publish-staging' rows = payload() # Staging keeps upload traversal completely separate from local credentials, # assistant state, running logs, and other operational files. for row in rows: source = ROOT / row['path'] st = source.stat() if (st.st_size, st.st_mtime_ns) != (row['size'], row['mtime_ns']): raise RuntimeError('Snapshot changed; run prepare again: ' + row['path']) target = stage / row['path'] target.parent.mkdir(parents=True, exist_ok=True) if target.exists(): if not os.path.samefile(source, target): target.unlink() os.link(source, target) else: os.link(source, target) expected = {r['path'] for r in rows} stale = [p for p in stage.rglob('*') if p.is_file() and p.relative_to(stage).as_posix() not in expected] if stale: raise RuntimeError('Staging contains files outside current snapshot: ' + str(stale[:5])) api = HfApi() result = api.upload_folder(repo_id=REPO, repo_type='dataset', folder_path=stage, commit_message='Synchronize reviewed Centre and local BEHAVIOR-1K collection') result = reconcile_attributes(api, result) (STATE / 'hf_upload_result.json').write_text(json.dumps({'commit': result.oid, 'url': result.commit_url}, indent=2)) print('UPLOAD_COMPLETE', result, flush=True) def verify_hf(): from huggingface_hub import HfApi api = HfApi() info = api.dataset_info(REPO) remote = {x.path: x for x in api.list_repo_tree(REPO, repo_type='dataset', revision=info.sha, recursive=True) if hasattr(x, 'size')} missing, different = [], [] for row in payload(): item = remote.get(row['path']) if item is None: missing.append(row['path']) continue expected = row['sha256'] if item.lfs else row['git_blob'] actual = item.lfs.sha256 if item.lfs else item.blob_id if item.size != row['size'] or actual != expected: different.append(row['path']) report = {'repo': REPO, 'revision': info.sha, 'payload_files': len(payload()), 'remote_files': len(remote), 'missing': missing, 'different': different, 'verified': not missing and not different} (STATE / 'hf_verification.json').write_text(json.dumps(report, indent=2)) print(json.dumps(report, indent=2), flush=True) if missing or different: raise SystemExit(1) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('command', choices=['prepare', 'publish', 'verify-hf']) args = parser.parse_args() {'prepare': prepare, 'publish': publish, 'verify-hf': verify_hf}[args.command]()