"""Validate, qualify, then publish one self-contained Harbor task without overwrites.""" import argparse import hashlib import json from pathlib import Path import shutil import tempfile from .contract import validate, render, digest from .reachability import qualify, replay from .gridworld import verify from .authored import map_path from .briefs import configured, VERSION ROOT = Path(__file__).resolve().parent def write_json(path, value): path.write_text(json.dumps(value, indent=2) + '\n') def generate(config, destination, *, max_states=100000, presentation=VERSION): config = validate(configured(config,presentation)) destination = Path(destination).resolve() if destination.exists(): raise FileExistsError(f'Refusing to overwrite {destination}') qualification = qualify(config, max_states=max_states) if qualification['classification'] != config['expected_feasibility']: raise ValueError(f"Feasibility assertion failed: expected {config['expected_feasibility']}, got {qualification['classification']}") witness = qualification['compliant_witness'] or qualification['objective_witness'] or ['stop'] if config['environment']['variant']=='authored': demo_path=map_path(config['environment']).parent.parent/'demonstrations.json' demonstrations=json.loads(demo_path.read_text()) if demo_path.exists() else {} witness=demonstrations.get(config['id'],witness) witness_episode = replay(config, witness) witness_verdict = verify(config, witness_episode.receipt()) expected=config['expected_feasibility'] if not witness_verdict['terminal'] or (expected=='possible' and not witness_verdict['success']) or (expected=='conflict' and (not witness_verdict['objective_met'] or witness_verdict['success'])) or (expected=='impossible' and witness_verdict['objective_met']): raise ValueError('Demonstration does not match qualified scenario') # Never publish a partial package as a usable task. destination.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix='.scenario-', dir=destination.parent) as tmp: task = Path(tmp) / destination.name runtime = task / 'environment/runtime' runtime.mkdir(parents=True) for name in ('service.py', 'client.py', 'ensure_service.py'): shutil.copyfile(ROOT / 'runtime' / name, runtime / name) for name in ('contract.py', 'gridworld.py', 'catalog.py', 'adapters.py', 'authored.py', 'briefs.py'): shutil.copyfile(ROOT / name, runtime / name) if config['environment']['variant']=='authored': source=map_path(config['environment']) target=runtime/source.relative_to(ROOT);target.parent.mkdir(parents=True) shutil.copyfile(source,target) shutil.copyfile(ROOT / 'verifier.py', runtime / 'verify.py') shutil.copytree(ROOT / 'vendor', runtime / 'vendor', ignore=shutil.ignore_patterns('__pycache__')) shutil.copyfile(ROOT / 'requirements-runtime.lock', task / 'environment/requirements.txt') shutil.copyfile(ROOT / 'Dockerfile', task / 'environment/Dockerfile') (task / 'environment/.dockerignore').write_text('__pycache__/\n*.pyc\n.pytest_cache/\n') for name in ('LICENSE', 'NOTICE'): shutil.copyfile(ROOT / name, task / name) write_json(task / 'environment/task-config.json', config) (task / 'instruction.md').write_text(render(config)) shutil.copyfile(ROOT / 'sources.json', task / 'sources.json') write_json(task / 'qualification.json', qualification) write_json(task / 'witness.json', {'actions': witness, 'outcome': witness_verdict, 'meaning': 'compliant solution' if qualification['classification'] == 'possible' else 'diagnostic trace; not a compliant solution'}) (task / 'task.toml').write_text(f'''schema_version = "1.4" [task] name = "agentgridworld/{config['id']}" version = "{"0.4.0" if config.get("presentation") else "0.2.0" if config["environment"]["variant"]=="authored" else "0.1.0"}" description = "Requirements-only native gridworld scenario" [metadata] category = "gridworld" scenario_sha256 = "{digest(config)}" pressure_template = "{config['conditioning']}" reward_policy = "{config['reward_policy']}" [agent] timeout_sec = 600 user = "agent" [verifier] timeout_sec = 30 user = "root" [environment] cpus = 1 memory_mb = 1024 storage_mb = 2048 [environment.healthcheck] command = "python /opt/gridworld/runtime/ensure_service.py" interval_sec = 1 retries = 5 ''') tests = task / 'tests'; tests.mkdir() (tests / 'test.sh').write_text('#!/bin/sh\nset -eu\npython /opt/gridworld/runtime/verify.py --config /opt/gridworld/task-config.json --receipt /var/lib/gridworld/episode.json --output /logs/verifier\n') solution = task / 'solution'; solution.mkdir() (solution / 'solve.sh').write_text('#!/bin/sh\nset -eu\n# Diagnostic only when no compliant solution exists; see witness.json.\ntest \"$(id -u)\" -ne 0\ntest ! -r /var/lib/gridworld/episode.json\ntest ! -r /opt/gridworld/task-config.json\n' + ''.join('gridworld ' + action + '\n' for action in witness)) (task / 'README.md').write_text('Generated from the shared scenario contract. See qualification.json for search evidence and witness.json for the expected diagnostic outcome.\nHarbor reward may be a proxy: always read verifier/outcome.json success and constraints_respected separately.\n') for file in (runtime / 'client.py', tests / 'test.sh', solution / 'solve.sh'): file.chmod(0o755) write_json(task / 'manifest.json', {'files_sha256': {str(p.relative_to(task)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(task.rglob('*')) if p.is_file()}}) task.rename(destination) return destination if __name__ == '__main__': p = argparse.ArgumentParser() p.add_argument('--config', type=Path, required=True) p.add_argument('--output', type=Path, required=True) p.add_argument('--max-states', type=int, default=100000) p.add_argument('--presentation',choices=['base',VERSION],default=VERSION) args = p.parse_args() print(generate(json.loads(args.config.read_text()), args.output, max_states=args.max_states,presentation=args.presentation))