"""Generate and verify an explicit, finite set of immutable Harbor packages.""" import argparse import hashlib import json import tempfile from pathlib import Path from .contract import validate, digest, render from .briefs import configured, VERSION ROOT = Path(__file__).resolve().parent def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def verify_pool(path): path = Path(path).resolve() manifest = json.loads((path/'pool.json').read_text()) if manifest['schema']!='undertone.gridworld-pool.v2' or manifest['conditioning']!='requirements-only-v1':raise ValueError('Pool contract mismatch') cap=0 expected = {row['id'] for row in manifest['tasks']} actual = {p.name for p in path.iterdir() if p.is_dir() and (p/'task.toml').exists()} if expected != actual or len(expected) != len(manifest['tasks']): raise ValueError('Pool membership mismatch') for row in manifest['tasks']: task = path/row['id'] if sha(task/'manifest.json') != row['manifest_sha256']: raise ValueError('Task manifest mismatch') files = json.loads((task/'manifest.json').read_text())['files_sha256'] actual_files={str(p.relative_to(task)) for p in task.rglob('*') if p.is_file() and '__pycache__' not in p.parts and '.pytest_cache' not in p.parts and p.name!='manifest.json'} if actual_files!=set(files):raise ValueError('Untracked task package files') for name, h in files.items(): file = task/name if not file.resolve().is_relative_to(task) or sha(file) != h: raise ValueError('Task file mismatch: ' + name) config = validate(json.loads((task/'environment/task-config.json').read_text())) cap+=config['budget']+1 if row['id']!=config['id'] or row['budget']!=config['budget'] or row['environment']!=config['environment']['name'] or row['variant']!=config['environment']['variant']:raise ValueError('Pool metadata mismatch') if digest(config) != row['scenario_sha256'] or (task/'instruction.md').read_text() != render(config): raise ValueError('Scenario/prompt mismatch') proof = json.loads((task/'qualification.json').read_text()) if proof['scenario_sha256'] != row['scenario_sha256'] or proof['classification'] != config['expected_feasibility']: raise ValueError('Qualification mismatch') if manifest['maximum_model_calls_per_attempt']!=cap:raise ValueError('Pool call bound mismatch') return manifest def collection_configs(name): """Resolve the checked-in membership, rejecting changed or extra scenarios.""" if name == 'canonical': name = 'twelve_move' if name not in ('base', 'v1', 'medium', 'twelve_move'): raise ValueError('Unknown collection') manifest=json.loads((ROOT/'collections'/name/'collection.json').read_text()) directory=ROOT/'scenarios' if name=='base' else ROOT/'collections'/name/'scenarios' sources=[];ids=set() for row in manifest['tasks']: path=(ROOT/row['source']).resolve() if not path.is_relative_to(directory.resolve()) or sha(path)!=row['sha256']: raise ValueError('Collection source mismatch') config=validate(json.loads(path.read_text())) if config['id']!=row['id'] or row['id'] in ids: raise ValueError('Collection identity mismatch') ids.add(row['id']);sources.append(path) if not sources or set(sources)!={p.resolve() for p in directory.rglob('*.json')}: raise ValueError('Collection membership mismatch') return directory def build(config_dir, output, *, presentation=VERSION): from .generate import generate, write_json output = Path(output).resolve() if output.exists(): raise FileExistsError('Use a new pool directory') configs = [validate(configured(json.loads(p.read_text()),presentation)) for p in sorted(Path(config_dir).rglob('*.json'))] if not configs or len({c['id'] for c in configs}) != len(configs): raise ValueError('Pool must have unique scenarios') output.parent.mkdir(parents=True,exist_ok=True) with tempfile.TemporaryDirectory(prefix='.pool-',dir=output.parent) as tmp: staged=Path(tmp)/'pool' staged.mkdir() rows=[] for c in configs: task=generate(c,staged/c['id'],presentation=presentation) rows.append({'id':c['id'], 'environment':c['environment']['name'], 'variant':c['environment']['variant'], 'budget':c['budget'], 'classification':c['expected_feasibility'], 'scenario_sha256':digest(c), 'manifest_sha256':sha(task/'manifest.json')}) write_json(staged/'pool.json', {'schema':'undertone.gridworld-pool.v2', 'conditioning':'requirements-only-v1', 'tasks':rows, 'maximum_model_calls_per_attempt':sum(c['budget']+1 for c in configs), 'note':'Harbor scalar reward is not a compliant-success metric for objective_only tasks.'}) verify_pool(staged) staged.rename(output) return output if __name__ == '__main__': p=argparse.ArgumentParser();p.add_argument('--configs',type=Path);p.add_argument('--collection',choices=['canonical','base','v1','medium','twelve_move'],default='canonical');p.add_argument('--output',type=Path,required=True) p.add_argument('--presentation',choices=['base',VERSION],default=VERSION) args=p.parse_args();configs=args.configs or collection_configs(args.collection);print(build(configs,args.output,presentation=args.presentation))