#!/usr/bin/env python3 """Create an owned test-only copy of the exact non-ignored working state.""" import fcntl import hashlib import json import os from pathlib import Path import shutil import subprocess import sys import tempfile root = Path(__file__).resolve().parents[1] task = sys.argv[1] if len(sys.argv) == 2 else '' if len(task) != 3 or not task.isascii() or not task.isdigit(): sys.exit('Usage: create-test-snapshot.py 001') branch = subprocess.check_output(['git', 'branch', '--show-current'], cwd=root, text=True).strip() if branch != f'bs-{task}': sys.exit(f'Refusing snapshot: expected bs-{task}, found {branch}') parent = root / '.test-worktrees' parent.mkdir(exist_ok=True) if parent.is_symlink(): sys.exit('Refusing symlink snapshot parent') # Reuse wrapper-owned lock descriptor, or acquire it for standalone snapshot creation. lockpath = parent / 'session.lock' try: inherited = os.fstat(8) expected = lockpath.stat() if (inherited.st_dev, inherited.st_ino) != (expected.st_dev, expected.st_ino): raise OSError('unrelated descriptor') lockfd = 8 except OSError: lockfd = os.open(lockpath, os.O_CREAT | os.O_WRONLY, 0o600) try: fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: sys.exit('testtask: another test session owns this snapshot') target = parent / f'task-{task}' marker = '.roborto-test-snapshot.json' owner = {'source': str(root), 'task': task} if target.exists(): if target.is_symlink() or not (target / marker).is_file(): sys.exit('Refusing to replace an unowned snapshot') previous = json.loads((target / marker).read_text()) if previous.get('owner') != owner: sys.exit('Refusing snapshot with different owner') # git supplies tracked plus permitted untracked files, including local edits/deletions. paths = subprocess.check_output(['git', 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], cwd=root).decode().split('\0') def permitted(rel): parts = Path(rel).parts return not any(x in {'.git', '.aws', '.agents', '.codex', '.roborto-runtime', '.test-worktrees', '.task-worktrees', 'node_modules', '.venv', '__pycache__', 'instance', 'dist', 'coverage'} for x in parts) and not any(x.startswith('.env') and x != '.env.example' for x in parts) and not rel.endswith(('.db', '.sqlite', '.sqlite3', '.pem', '.key', '.pyc')) manifest = {} stage = Path(tempfile.mkdtemp(prefix=f'.task-{task}-', dir=parent)) try: for rel in sorted(set(filter(None, paths))): if not permitted(rel): continue src = root / rel if src.is_symlink(): sys.exit(f'Refusing symlink in snapshot: {rel}') if not src.is_file(): continue data = src.read_bytes() dst = stage / rel dst.parent.mkdir(parents=True, exist_ok=True) dst.write_bytes(data) shutil.copymode(src, dst) manifest[rel] = hashlib.sha256(data).hexdigest() # Detect source edits while copying; compare every included file to its snapshot. for rel, digest in manifest.items(): if hashlib.sha256((root / rel).read_bytes()).hexdigest() != digest: sys.exit(f'Source changed during snapshot: {rel}; rerun') (stage / marker).write_text(json.dumps({'owner': owner, 'branch': branch, 'files': manifest}, indent=2) + '\n') if target.exists(): shutil.rmtree(target) os.rename(stage, target) print(f'Snapshot: {target} ({len(manifest)} files verified; test-only copy, not an editing worktree)') finally: if stage.exists(): shutil.rmtree(stage)