Upload folder using huggingface_hub (part 20)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- L295-y-0054-r5/task.tomlAdded+31
- L295-y-0054-r5/tests/test.shAdded+30
- L295-y-0054-r5/tests/test_state.pyAdded+232
- L295-y-0054-r6/environment/DockerfileAdded+275
- L295-y-0054-r6/instruction.mdAdded+3
- L295-y-0054-r6/metadata.jsonAdded+1
- L295-y-0054-r6/solution/solve.shAdded+523
- L295-y-0054-r6/stats.jsonAdded+38
- L295-y-0054-r6/task.tomlAdded+31
- L295-y-0054-r6/tests/test.shAdded+30
- L295-y-0054-r6/tests/test_state.pyAdded+322
- L296-y-0313-r0/bootstrap_report.jsonAdded+15
- L296-y-0313-r0/environment/DockerfileAdded+3
- L296-y-0313-r0/instruction.mdAdded+62
- L296-y-0313-r0/metadata.jsonAdded+1
- L296-y-0313-r0/solution/solve.shAdded+140
- L296-y-0313-r0/stats.jsonAdded+18
- L296-y-0313-r0/task.tomlAdded+31
- L296-y-0313-r0/tests/test.shAdded+30
- L296-y-0313-r0/tests/test_state.pyAdded+50
- L296-y-0313-r1/environment/DockerfileAdded+44
- L296-y-0313-r1/instruction.mdAdded+3
- L296-y-0313-r1/metadata.jsonAdded+1
- L296-y-0313-r1/round_report.jsonAdded+161
- L296-y-0313-r1/solution/solve.shAdded+325
- L296-y-0313-r1/stats.jsonAdded+48
- L296-y-0313-r1/task.tomlAdded+31
- L296-y-0313-r1/tests/test.shAdded+30
- L296-y-0313-r1/tests/test_state.pyAdded+338
- L296-y-0313-r2/environment/DockerfileAdded+44
- L296-y-0313-r2/instruction.mdAdded+3
- L296-y-0313-r2/metadata.jsonAdded+1
- L296-y-0313-r2/round_report.jsonAdded+158
- L296-y-0313-r2/solution/solve.shAdded+244
- L296-y-0313-r2/stats.jsonAdded+48
- L296-y-0313-r2/task.tomlAdded+31
- L296-y-0313-r2/tests/test.shAdded+30
- L296-y-0313-r2/tests/test_state.pyAdded+360
- L296-y-0313-r3/environment/DockerfileAdded+70
- L296-y-0313-r3/instruction.mdAdded+5
- L296-y-0313-r3/metadata.jsonAdded+1
- L296-y-0313-r3/round_report.jsonAdded+169
- L296-y-0313-r3/solution/solve.shAdded+304
- L296-y-0313-r3/stats.jsonAdded+48
- L296-y-0313-r3/task.tomlAdded+31
- L296-y-0313-r3/tests/test.shAdded+30
- L296-y-0313-r3/tests/test_state.pyAdded+488
- L296-y-0313-r4/environment/DockerfileAdded+72
- L296-y-0313-r4/instruction.mdAdded+3
- L296-y-0313-r4/metadata.jsonAdded+1
12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0054"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232import json,os,pathlib,re,subprocess,sysimport numpy as npimport xarray as xrdef R(): for b in [pathlib.Path.cwd(),pathlib.Path('/app')]: try: if (b/'docs'/'grid_spec.md').is_file():return b if (b/'tools'/'validate_grid.py').is_file():return b except:pass return pathlib.Path('/app')def F(r): p=R()/r if p.is_file():return p q=pathlib.Path('/app')/r return q if q.is_file() else Nonedef LD(): for s in [str(R()),'/app']: if s not in sys.path:sys.path.insert(0,s) for m in ['app.pygmt.datasets','pygmt.datasets']: try: a=__import__(m,fromlist=['load_earth_relief']) f=getattr(a,'load_earth_relief',None) if callable(f):return f except:continue raise AssertionError('loader missing')def EX(): for s in [str(R()),'/app']: if s not in sys.path:sys.path.insert(0,s) for m in ['app.pygmt.exceptions','pygmt.exceptions']: try: a=__import__(m,fromlist=['GMTInvalidInput']) e=getattr(a,'GMTInvalidInput',None) if e is not None:return e except:continue raise AssertionError('GMTInvalidInput missing')def CLI(a,timeout=25): v=F('tools/validate_grid.py') assert v is not None,'validator missing' e=dict(os.environ);b=str(R()) p=e.get('PYTHONPATH','') for s in [b,'/app']: if s not in p:p=s+':'+p if p else s e['PYTHONPATH']=p return subprocess.run([sys.executable,str(v)]+list(a),capture_output=True,text=True,timeout=timeout,cwd=b,env=e)def J(r): p=F(r) assert p is not None,r+' missing' t=p.read_text(errors='replace') assert len(t.strip())>20,r+' empty' d=json.loads(t) assert isinstance(d,(dict,list)),r+' bad json' return d,tdef G(d): if isinstance(d,dict) and isinstance(d.get('grids'),dict):return d['grids'] if isinstance(d,dict) and isinstance(d.get('results'),dict):return d['results'] if isinstance(d,dict): c={k:v for k,v in d.items() if isinstance(v,dict) and ('checks' in v or 'status' in v or 'result' in v or 'verdict' in v)} if c:return c if isinstance(d,list):return {str(e.get('resolution','g'+str(i))):e for i,e in enumerate(d) if isinstance(e,dict)} return {}def GP(g): if not isinstance(g,dict):return False for k in ['status','result','verdict']: v=g.get(k) if isinstance(v,str) and v.strip().lower() in ('pass','passed','ok','success'):return True ch=g.get('checks') if isinstance(ch,dict) and ch: ok=True for x in ch.values(): if isinstance(x,str): if x.lower() not in ('pass','passed','ok','success'):ok=False elif isinstance(x,dict): if str(x.get('status',x.get('result',''))).lower() not in ('pass','passed','ok','success'):ok=False else:ok=False if ok:return True return Falsedef OP(d): if isinstance(d,dict): for k in ['overall','status','result','verdict']: v=d.get(k) if isinstance(v,str) and v.strip().lower() in ('pass','passed','ok','success'):return True g=G(d) if g and len(g)>=2 and all(GP(x) for x in g.values()):return True return Falsedef SEM(res): f=LD();sh=(181,361) if res=='01d' else (361,721) mn,mx=(-1000.0,1000.0) if res=='01d' else (-500.0,500.0) da=f(res) assert isinstance(da,xr.DataArray),res+' DataArray' assert tuple(da.dims)==('lat','lon'),res+' dims' assert tuple(da.shape)==sh,res+' shape '+str(tuple(da.shape)) a=np.asarray(da.data,dtype=float) assert np.all(np.isfinite(a)),res+' finite' assert abs(float(a.min())-mn)<1e-6 and abs(float(a.max())-mx)<1e-6,res+' bounds' assert np.allclose(a,a[:,[0]]*np.ones((1,a.shape[1]))),res+' lon-invariant' return dadef test_check_01_required_evidence(): s=F('docs/grid_spec.md') assert s is not None,'spec missing' t=s.read_text(errors='replace') assert len(t)>500,'spec small' for k in ['01d','30m','gridline','lat','lon']: assert k in t,'spec '+k assert '181' in t and '361' in t,'shapes' assert '-1000' in t and '-500' in t,'bounds' h=F('tools/validate_grid.py') assert h is not None,'validator missing' ht=h.read_text(errors='replace') assert '--resolution' in ht and '--output' in ht,'flags' compile(ht,str(h),'exec') l=F('app/pygmt/datasets.py') or F('pygmt/datasets.py') assert l is not None,'loader missing' assert 'load_earth_relief' in l.read_text(errors='replace'),'fn' for r in ['reports/toolchain.json','reports/validation.json','reports/summary.json']: assert F(r) is not None,r+' missing' h2=CLI(['--help']) assert h2.returncode==0,'help exit 0' assert 'resolution' in (h2.stdout+h2.stderr).lower(),'help text'def test_check_01_cli_stdio_exit_codes(): import tempfile;d=tempfile.mkdtemp();o1=os.path.join(d,'a.json') r1=CLI(['--resolution','01d','--output',o1]) assert r1.returncode==0,'01d exit 0:'+r1.stderr[:200] assert os.path.isfile(o1),'output written' rb=CLI(['--resolution','bogus','--output',os.path.join(d,'b.json')]) assert rb.returncode==2,'bad res exit 2 got '+str(rb.returncode) assert len(rb.stderr.strip())>0,'stderr on error'def test_check_01_env_doc(): p=F('docs/environment.md') assert p is not None,'docs/environment.md missing' t=p.read_text(errors='replace') assert 'PYTHONPATH' in t,'env doc PYTHONPATH' assert '/app' in t,'env doc /app' assert any(k in t.lower() for k in ['bashrc','profile','.env','export']),'persistence' home=pathlib.Path.home() found=False for c in [home/'.bashrc',home/'.profile',home/'.bash_profile',R()/'.env',pathlib.Path('/app')/'.env']: try: if c.is_file(): x=c.read_text(errors='replace') if 'PYTHONPATH' in x and '/app' in x:found=True except:pass assert found,'no persisted PYTHONPATH with /app'def test_check_01_fresh_shell_env(): cmd='python3 -c "from app.pygmt.datasets import load_earth_relief;print(tuple(load_earth_relief(\'01d\').shape))"' clean=dict(os.environ);clean.pop('PYTHONPATH',None) ok=False;msg='' for fl in (['bash','-l','-c',cmd],['bash','-i','-c',cmd]): try: r=subprocess.run(fl,capture_output=True,text=True,timeout=20,cwd='/tmp',env=clean) msg+=str(fl[1])+':'+str(r.returncode)+':'+(r.stdout.strip()[:60] or r.stderr.strip()[:60])+ '|' if r.returncode==0 and '181' in r.stdout and '361' in r.stdout:ok=True;break except Exception as e:msg+=str(e)[:60] assert ok,'fresh shell import failed, persist export: '+msgdef test_check_02_intermediate_artifact(): d,t=J('reports/toolchain.json') low=t.lower() assert 'numpy' in low and 'xarray' in low,'numpy+xarray' assert re.search(r'\d+\.\d+',t),'versions' assert '/app' in t and 'PYTHONPATH' in t,'env evidence' import numpy as _np import xarray as _xr assert _np.__version__ in t,'numpy stale' assert _xr.__version__ in t,'xarray stale' SEM('01d');SEM('30m') dc=LD()('01d',region=[-45.0,45.0,-30.0,30.0]) assert tuple(dc.shape)==(61,91),'region shape'def test_check_02_loader_errors(): f=LD();e=EX() for bad in ['1d','',None,123]: try: f(bad);raise AssertionError('bad res') except e:pass try: f('01d',registration='pixel');raise AssertionError('bad reg') except e:pass for br in [[0,1,2],[0,1,2,3,4]]: try: f('01d',region=br);raise AssertionError('bad region') except e:passdef test_check_03_final_semantics(): d,t=J('reports/validation.json') assert '01d' in t and '30m' in t,'both res' assert OP(d),'overall pass' g=G(d) assert len(g)>=2,'per-grid' for res in ['01d','30m']: k=[x for x in g if res in str(x)] assert k,'missing '+res assert GP(g[k[0]]),res+' pass'def test_check_03_summary_aggregates(): vd,vt=J('reports/validation.json') sd,st=J('reports/summary.json') vg=G(vd);tot=len(vg);ps=sum(1 for v in vg.values() if GP(v)) assert tot>=2 and ps==tot,'validation all pass' assert isinstance(sd,dict),'summary dict' assert sd.get('total_grids',sd.get('total'))==tot,'total' assert sd.get('passed',sd.get('num_passed'))==ps,'passed' assert sd.get('failed',sd.get('num_failed'))==(tot-ps),'failed' pr=sd.get('pass_rate',sd.get('rate')) assert pr is not None,'pass_rate' assert abs(float(pr)-(ps/tot))<1e-6,'rate calc' prs=sd.get('per_resolution',sd.get('resolutions')) assert isinstance(prs,dict),'per_resolution' assert '01d' in st and '30m' in st,'both res' assert str(sd.get('overall',sd.get('verdict',sd.get('status','')))).lower() in ('pass','passed','ok','success'),'overall pass'def test_check_04_no_shortcut(): for rel in ['reports/toolchain.json','reports/validation.json','reports/summary.json']: p=F(rel) t=p.read_text(errors='replace') assert len(t.strip())>50,rel+' placeholder' assert 'placeholder' not in t.lower() and 'todo' not in t.lower(),rel+' todo' json.loads(t) vd,vt=J('reports/validation.json') assert '181' in vt and '361' in vt,'stale 01d' assert '721' in vt,'stale 30m' sd,st=J('reports/summary.json') vg=G(vd);tot=len(vg);ps=sum(1 for v in vg.values() if GP(v)) assert sd.get('total_grids',sd.get('total'))==tot,'hardcoded total' assert OP(vd),'genuine pass' f=LD() for res,mn,mx in [('01d',-1000.0,1000.0),('30m',-500.0,500.0)]: a=np.asarray(f(res).data,dtype=float) assert abs(float(a.min())-mn)<1e-6 and abs(float(a.max())-mx)<1e-6,res+' bounds' dr=np.asarray(f(res,region=[-10.0,10.0,-5.0,5.0]).data,dtype=float) assert np.all(np.isfinite(dr)),res+' region finite' lp=F('app/pygmt/datasets.py') assert lp is not None,'loader path' src=lp.read_text(errors='replace') assert 'sys.path' not in src,'no sys.path hack' assert 'requests' not in src.lower() and 'urlopen' not in src.lower(),'no-network' a1=np.asarray(f('01d').data);a2=np.asarray(f('01d').data) assert np.array_equal(a1,a2),'deterministic'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytest numpy xarrayRUN mkdir -p docs tools reports app/pygmtRUN cat > docs/grid_spec.md <<'EOF'# Earth Relief Grid Specification (local schema)
This document is the authoritative local schema for `load_earth_relief` grids.Loader and validator MUST satisfy these rules. No network I/O.
## 1. Loader contract- Function: `app/pygmt/datasets.py::load_earth_relief(resolution, region=None, registration="gridline", use_srtm=False)`- `resolution`: str, one of {"01d", "30m"} only. Else raise `GMTInvalidInput`.- `region`: None or length-4 sequence `[west, east, south, north]` of finite numbers. Else raise `GMTInvalidInput`.- `registration`: must be `"gridline"`. Else raise `GMTInvalidInput`.- `use_srtm`: bool, accepted but ignored for data generation.
## 2. Resolutions, steps, default extents- `01d`: step 1.0 deg; default lat -90 to 90, lon -180 to 180.- `30m`: step 0.5 deg; default lat -90 to 90, lon -180 to 180.- Coordinate construction: `lat = arange(lat_min, lat_max+1e-9, step)`, `lon = arange(lon_min, lon_max+1e-9, step)`.- If `region` is None use defaults above. If provided map `[west,east,south,north]` to `lon_min=west, lon_max=east, lat_min=south, lat_max=north` and rebuild arrays with same step.- Empty grid (zero-size lat or lon) must raise `GMTInvalidInput`.
## 3. Dimensions and shapes- Data is `xarray.DataArray` with `dims == ("lat", "lon")` in that order.- Shape is `(n_lat, n_lon)` where `n_lat=len(lat)`, `n_lon=len(lon)`.- Default shapes: `01d -> (181, 361)`; `30m -> (361, 721)`.- Region shape formula: `n_lat = len(arange(south, north+1e-9, step))`, `n_lon = len(arange(west, east+1e-9, step))`.- Coords named `lat` and `lon`; `data.coords["lat"].data` and `data.coords["lon"].data` match 1D arrays; `data.lat` / `data.lon` accessible.
## 4. Dtypes- Data dtype must be floating (`kind == 'f'`, e.g. float64). Integer dtype fails.- Coord dtypes must be floating as well.
## 5. Coordinate ranges and ordering- `lat` values monotonic strictly increasing with fixed `step` (tolerance 1e-8).- `lon` values monotonic strictly increasing with fixed `step`.- All `lat` in [-90, 90], all `lon` in [-180, 180] (inclusive, tolerance 1e-8).- All coords finite (no NaN/Inf).
## 6. Value model (min/max) and completeness- Deterministic latitude-linear model: `data = alpha * lat_grid + gamma` where `lat_grid` broadcasts `lat` across lon columns.- `alpha = (max_val-min_val)/(lat_max-lat_min)` if `lat_max>lat_min` else 0; `gamma = min_val - alpha*lat_min`.- Per-resolution bounds: - `01d`: `min_val=-1000.0`, `max_val=1000.0`. - `30m`: `min_val=-500.0`, `max_val=500.0`.- Corrected bounds actually enforced: `01d: min -1000.0 max 1000.0`; `30m: min -500.0 max 500.0`.- `data.min() == min_val` and `data.max() == max_val` within 1e-8 for any extents (including regions). Single-lat edge case fills constant `min_val`.- All values finite, no NaN/Inf; count of finite cells == n_lat*n_lon (completeness).- Data independent of longitude (each row constant across columns) for this simplified model.
## 7. Validation report- `tools/validate_grid.py` checks sampled grids against sections 3-6 and writes `reports/validation.json`.- Report is non-empty parseable JSON with per-grid per-check pass/fail and overall status.EOFRUN cat > docs/reporting.md <<'EOF'# Summary Reporting Note
Source for aggregation is `reports/validation.json` per-grid per-check results.Destination is `reports/summary.json` parseable JSON.
Summary fields derived from validation output:- `total_grids`: number of grids found in validation report.- `passed`: number of grids with passing status.- `failed`: total minus passed.- `pass_rate`: passed divided by total_grids (0 to 1).- `per_resolution`: object keyed by resolution (01d, 30m), each with `status`, `checks_passed`, `checks_total`, and grid `shape` stats from the loader.- `overall`: `pass` if every grid passes, else `fail`; must agree with validation overall status.
Totals and verdict must be computed from actual validation content and loader grid stats, not hardcoded.EOFRUN cat > docs/environment.md <<'EOF'# Runtime Environment
`PYTHONPATH` must include `/app` so the loader `app.pygmt.datasets::load_earth_relief` imports in a fresh terminal without ad-hoc `sys.path` hacks.
Persist the runtime environment for fresh shells:- Add `export PYTHONPATH="/app:${PYTHONPATH:-}"` to `~/.bashrc` and `~/.profile` (and `~/.bash_profile` if present) so both login (`bash -l`) and interactive (`bash -i`) shells resolve the import.- Also write `PYTHONPATH=/app` to `/app/.env` for file-based env evidence.- Verify with `bash -lc 'python3 -c "from app.pygmt.datasets import load_earth_relief"'` using a clean environment.
See `docs/grid_spec.md` and `docs/reporting.md` for grid and aggregation rules. Use `tools/validate_grid.py --help` for CLI flags.EOFRUN cat > tools/validate_grid.py <<'PYEOF'#!/usr/bin/env python3"""Local grid validator per docs/grid_spec.md - writes reports/validation.json."""import argparseimport jsonimport pathlibimport sysimport numpy as npdef _load_fn(): for mod in ("app.pygmt.datasets", "pygmt.datasets"): try: m = __import__(mod, fromlist=["load_earth_relief"]) return m.load_earth_relief except Exception: continue raise RuntimeError("loader app/pygmt/datasets.py::load_earth_relief not importable")STEPS = {"01d": 1.0, "30m": 0.5}BOUNDS = {"01d": (-1000.0, 1000.0), "30m": (-500.0, 500.0)}def check_grid(da, resolution, step, min_val, max_val): checks = {} try: import xarray as xr checks["is_dataarray"] = "pass" if isinstance(da, xr.DataArray) else "fail" except Exception: checks["is_dataarray"] = "fail" return checks, False if checks["is_dataarray"] != "pass": return checks, False try: checks["dims"] = "pass" if tuple(da.dims) == ("lat", "lon") else "fail" except Exception: checks["dims"] = "fail" try: lat = np.asarray(da.coords["lat"].data, dtype=float) lon = np.asarray(da.coords["lon"].data, dtype=float) checks["coords_present"] = "pass" except Exception: checks["coords_present"] = "fail" return checks, False try: checks["shape"] = "pass" if tuple(da.shape) == (len(lat), len(lon)) else "fail" except Exception: checks["shape"] = "fail" try: checks["data_dtype_float"] = "pass" if np.asarray(da.data).dtype.kind == "f" else "fail" except Exception: checks["data_dtype_float"] = "fail" try: cLat = np.asarray(da.coords["lat"].data) cLon = np.asarray(da.coords["lon"].data) checks["coord_dtype_float"] = "pass" if (cLat.dtype.kind == "f" and cLon.dtype.kind == "f") else "fail" except Exception: checks["coord_dtype_float"] = "fail" try: checks["lat_monotonic"] = "pass" if (len(lat) < 2 or bool(np.all(np.diff(lat) > 0))) else "fail" except Exception: checks["lat_monotonic"] = "fail" try: checks["lon_monotonic"] = "pass" if (len(lon) < 2 or bool(np.all(np.diff(lon) > 0))) else "fail" except Exception: checks["lon_monotonic"] = "fail" try: if len(lat) < 2: checks["lat_step"] = "pass" else: checks["lat_step"] = "pass" if bool(np.allclose(np.diff(lat), step, atol=1e-8)) else "fail" except Exception: checks["lat_step"] = "fail" try: if len(lon) < 2: checks["lon_step"] = "pass" else: checks["lon_step"] = "pass" if bool(np.allclose(np.diff(lon), step, atol=1e-8)) else "fail" except Exception: checks["lon_step"] = "fail" try: checks["lat_range"] = "pass" if (bool(np.all(lat >= -90.0 - 1e-8)) and bool(np.all(lat <= 90.0 + 1e-8))) else "fail" except Exception: checks["lat_range"] = "fail" try: checks["lon_range"] = "pass" if (bool(np.all(lon >= -180.0 - 1e-8)) and bool(np.all(lon <= 180.0 + 1e-8))) else "fail" except Exception: checks["lon_range"] = "fail" try: checks["coords_finite"] = "pass" if (bool(np.all(np.isfinite(lat))) and bool(np.all(np.isfinite(lon)))) else "fail" except Exception: checks["coords_finite"] = "fail" try: data = np.asarray(da.data, dtype=float) checks["data_finite"] = "pass" if bool(np.all(np.isfinite(data))) else "fail" except Exception: checks["data_finite"] = "fail" data = None try: if data is None: checks["completeness"] = "fail" else: checks["completeness"] = "pass" if int(np.sum(np.isfinite(data))) == int(data.size) else "fail" except Exception: checks["completeness"] = "fail" try: if data is None: checks["data_min"] = "fail" checks["data_max"] = "fail" else: checks["data_min"] = "pass" if abs(float(np.min(data)) - float(min_val)) < 1e-6 else "fail" checks["data_max"] = "pass" if abs(float(np.max(data)) - float(max_val)) < 1e-6 else "fail" except Exception: checks["data_min"] = "fail" checks["data_max"] = "fail" try: if data is None: checks["lon_invariant"] = "fail" else: exp = np.broadcast_to(data[:, [0]], data.shape) checks["lon_invariant"] = "pass" if bool(np.allclose(data, exp, atol=1e-8)) else "fail" except Exception: checks["lon_invariant"] = "fail" try: if data is None or len(lat) < 2: checks["value_model"] = "pass" if (data is not None and abs(float(np.min(data)) - float(min_val)) < 1e-6) else ("pass" if data is not None else "fail") else: lat_max = float(np.max(lat)) lat_min = float(np.min(lat)) alpha = (float(max_val) - float(min_val)) / (lat_max - lat_min) if lat_max > lat_min else 0.0 gamma = float(min_val) - alpha * lat_min expected = (alpha * lat[:, None] * np.ones((1, len(lon))) + gamma).astype(float) checks["value_model"] = "pass" if bool(np.allclose(data, expected, atol=1e-6)) else "fail" except Exception: checks["value_model"] = "fail" passed = all(v == "pass" for v in checks.values()) return checks, passeddef validate_one(resolution): fn = _load_fn() step = STEPS[resolution] mn, mx = BOUNDS[resolution] da = fn(resolution) checks, passed = check_grid(da, resolution, step, mn, mx) return {"resolution": resolution, "shape": list(tuple(da.shape)) if hasattr(da, "shape") else [], "checks": checks, "status": "pass" if passed else "fail"}def main(): p = argparse.ArgumentParser(description="Validate earth relief grids per docs/grid_spec.md") p.add_argument("--resolution", default="all", help="resolution: 01d, 30m or all (also supports comma-separated)") p.add_argument("--output", required=True, help="output JSON path for validation report") args = p.parse_args() raw = args.resolution if isinstance(raw, list): parts = raw else: parts = [raw] expanded = [] for r in parts: rs = str(r).strip() if rs == "all": expanded.extend(["01d", "30m"]) elif "," in rs: for x in rs.split(","): x = x.strip() if x == "all": expanded.extend(["01d", "30m"]) elif x: expanded.append(x) elif rs: expanded.append(rs) if not expanded: expanded = ["01d", "30m"] for r in expanded: if r not in STEPS: print(f"error: invalid resolution '{r}' (must be one of 01d, 30m, all)", file=sys.stderr) sys.exit(2) try: fn_check = _load_fn() except Exception as e: print(f"error: {e}", file=sys.stderr) sys.exit(1) grids = {} for r in expanded: try: grids[r] = validate_one(r) except Exception as e: grids[r] = {"resolution": r, "shape": [], "checks": {"load": "fail"}, "status": "fail", "error": str(e)} overall = "pass" if all(g.get("status") == "pass" for g in grids.values()) else "fail" out = {"grids": grids, "results": grids, "overall": overall, "status": overall} op = pathlib.Path(args.output) op.parent.mkdir(parents=True, exist_ok=True) op.write_text(json.dumps(out, indent=2)) print(f"validated {', '.join(expanded)}: {overall.upper()} -> {op}") sys.exit(0 if overall == "pass" else 1)if __name__ == "__main__": main()PYEOFRUN chmod +x tools/validate_grid.py123Build a deterministic no-network earth-relief loader in /app following docs/grid_spec.md and prove it through the terminal with a correctly configured runtime using only local dependencies without network access.
Inspect the interpreter and dependency toolchain and validator CLI behavior following the local docs in docs/ and the validator help, persist PYTHONPATH so the loader imports in a fresh shell, save parseable toolchain and validation evidence in reports/, then aggregate loader stats and validation results into a verdict at /app/reports/summary.json consistent with validation.1{"metadata": {"lineage": "L295-y-0054", "round": "r6", "generation_method": "recursive-task-synthesis", "stats": {"stages": {"affordance_ranking": {"seconds": 278.339, "cost_usd": 0.001186, "llm_calls": 1}, "contract": {"seconds": 255.703, "cost_usd": 0.001377, "llm_calls": 1}, "solution": {"seconds": 252.992, "cost_usd": 0.003056, "llm_calls": 1}, "verifier": {"seconds": 477.713, "cost_usd": 0.006717, "llm_calls": 2}, "instruction": {"seconds": 170.969, "cost_usd": 0.00115, "llm_calls": 1}, "env_align": {"seconds": 150.084, "cost_usd": 0.000848, "llm_calls": 1}}, "lineage_id": "L295-y-0054", "round": 6, "total_seconds": 1585.8, "total_cost_usd": 0.014334}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523#!/bin/bashset -ecd /appexport PYTHONPATH="/app:${PYTHONPATH:-}"mkdir -p reports app/pygmt pygmt# ===== inspect: local docs, validator flags, toolchain =====echo "[inspect] workspace layout"ls -R . 2>&1 | head -n 100 || trueecho "[inspect] grid_spec"cat docs/grid_spec.md | head -n 200echo "[inspect] reporting"cat docs/reporting.md | head -n 80echo "[inspect] environment"cat docs/environment.md 2>&1 | head -n 80 || trueecho "[inspect] validator source head"cat tools/validate_grid.py | head -n 120echo "[inspect] toolchain versions"python3 --versionpython3 -c 'import sys,numpy,xarray; print(sys.version.split()[0], numpy.__version__, xarray.__version__)'echo "PYTHONPATH=$PYTHONPATH"echo "[inspect] validator help"python3 tools/validate_grid.py --help 2>&1 | head -n 40python3 tools/validate_grid.py --help > /tmp/help.txt 2>&1 || truecat /tmp/help.txt | head -n 40grep -n "resolution\|output\|add_argument" tools/validate_grid.py | head -n 20 || true# ===== derive: steps, shapes, bounds, registration, probe expectations =====echo "[derive] inferring contract"python3 <<'PY'import pathlib, subprocess, sysspec = pathlib.Path('docs/grid_spec.md').read_text()assert '01d' in spec and '30m' in spec, 'resolutions missing'assert 'gridline' in spec, 'registration missing'assert '-1000' in spec and '-500' in spec, 'bounds missing'assert '181' in spec and '361' in spec, 'shapes missing'rep = pathlib.Path('docs/reporting.md').read_text()assert 'total_grids' in rep and 'overall' in rep, 'reporting fields missing'try: envt = pathlib.Path('docs/environment.md').read_text() assert 'PYTHONPATH' in envt print('env doc ok')except FileNotFoundError: print('env doc missing, will create in execute')h = subprocess.run([sys.executable, 'tools/validate_grid.py', '--help'], capture_output=True, text=True)assert h.returncode == 0, 'help must exit 0'combined = h.stdout + h.stderrassert '--resolution' in combined and '--output' in combined, 'flags missing'print('derive ok: steps 1.0/0.5 shapes (181,361)/(361,721) bounds enforced')PY# ===== execute: loader implementation + env persistence + toolchain + validation runs =====echo "[execute] ensure environment doc"if [ ! -f docs/environment.md ]; thenprintf '%s\n' '# Runtime Environment' '' 'PYTHONPATH must include /app so loader imports in fresh shell.' 'export PYTHONPATH="/app:${PYTHONPATH:-}" to ~/.bashrc and ~/.profile.' 'Also write PYTHONPATH=/app to /app/.env.' > docs/environment.mdfigrep -q PYTHONPATH docs/environment.mdecho "[execute] implement loader"touch app/__init__.pytouch app/pygmt/__init__.pytouch pygmt/__init__.pyprintf '%s\n' 'class GMTInvalidInput(Exception):' ' pass' > app/pygmt/exceptions.pycp -f app/pygmt/exceptions.py pygmt/exceptions.pycat > app/pygmt/datasets.py <<'EOF'import mathimport numpy as npimport xarray as xrfrom .exceptions import GMTInvalidInput_ALLOWED = ('01d', '30m')_STEPS = {'01d': 1.0, '30m': 0.5}_BOUNDS = {'01d': (-1000.0, 1000.0), '30m': (-500.0, 500.0)}def load_earth_relief(resolution, region=None, registration='gridline', use_srtm=False): if resolution not in _ALLOWED: raise GMTInvalidInput(f'Invalid resolution {resolution!r}') if registration != 'gridline': raise GMTInvalidInput(f'Invalid registration {registration!r}') step = _STEPS[resolution] mn, mx = _BOUNDS[resolution] if region is None: x0, x1, y0, y1 = -180.0, 180.0, -90.0, 90.0 else: try: r = list(region) except Exception: raise GMTInvalidInput('region must be length-4 sequence') if len(r) != 4: raise GMTInvalidInput('region must have length 4') for v in r: if isinstance(v, bool): raise GMTInvalidInput('region values must be numbers') try: import numpy as _np if isinstance(v, (_np.integer, _np.floating)): fv = float(v) elif isinstance(v, (int, float)): fv = float(v) else: raise GMTInvalidInput('region values must be numbers') except GMTInvalidInput: raise except Exception: raise GMTInvalidInput('region values must be numbers') if not math.isfinite(fv): raise GMTInvalidInput('region values must be finite') x0, x1, y0, y1 = float(r[0]), float(r[1]), float(r[2]), float(r[3]) lat = np.arange(y0, y1 + 1e-9, step, dtype=float).astype(float) lon = np.arange(x0, x1 + 1e-9, step, dtype=float).astype(float) if lat.size == 0 or lon.size == 0: raise GMTInvalidInput('empty grid') nl, ng = int(lat.size), int(lon.size) if nl == 1: data = np.full((1, ng), float(mn), dtype=float) else: d = float(y1 - y0) if d == 0: data = np.full((nl, ng), float(mn), dtype=float) else: alpha = (float(mx) - float(mn)) / float(d) gamma = float(mn) - alpha * float(y0) data = (alpha * lat[:, None] * np.ones((1, ng)) + gamma).astype(float) return xr.DataArray(data, dims=('lat', 'lon'), coords={'lat': lat, 'lon': lon})EOFcp -f app/pygmt/datasets.py pygmt/datasets.pypython3 -c 'from app.pygmt.datasets import load_earth_relief; print(load_earth_relief("01d").shape)'python3 <<'PY'from app.pygmt.datasets import load_earth_reliefassert tuple(load_earth_relief('01d').shape) == (181, 361)assert tuple(load_earth_relief('30m').shape) == (361, 721)assert tuple(load_earth_relief('01d', region=[-45.0, 45.0, -30.0, 30.0]).shape) == (61, 91)print('loader shapes ok')PYecho "[execute] persist PYTHONPATH for fresh shells"LINE='export PYTHONPATH="/app:${PYTHONPATH:-}"'touch ~/.bashrc ~/.profiletouch ~/.bash_profile 2>/dev/null || trueif ! grep -Fq 'PYTHONPATH' ~/.bashrc 2>/dev/null || ! grep -Fq '/app' ~/.bashrc 2>/dev/null; then echo "$LINE" >> ~/.bashrc; fiif ! grep -Fq 'PYTHONPATH' ~/.profile 2>/dev/null || ! grep -Fq '/app' ~/.profile 2>/dev/null; then echo "$LINE" >> ~/.profile; fiif [ -f ~/.bash_profile ]; then if ! grep -Fq '/app' ~/.bash_profile 2>/dev/null; then echo "$LINE" >> ~/.bash_profile; fielse echo "$LINE" > ~/.bash_profilefiprintf 'PYTHONPATH=/app\n' > .envprintf 'PYTHONPATH=/app\n' > /app/.envcat .envgrep -H 'PYTHONPATH' ~/.bashrc ~/.profile .env || truegrep -H 'PYTHONPATH' ~/.bash_profile /app/.env || trueecho "[execute] probe validator CLI for toolchain evidence"set +epython3 tools/validate_grid.py --help > /tmp/vhelp.txt 2>&1HELP_EXIT=$?python3 tools/validate_grid.py --resolution 01d --output /tmp/probe01.json > /tmp/probe01.log 2>&1PROBE01_EXIT=$?python3 tools/validate_grid.py --resolution 30m --output /tmp/probe30.json > /tmp/probe30.log 2>&1PROBE30_EXIT=$?python3 tools/validate_grid.py --resolution bogus --output /tmp/probeBogus.json > /tmp/probeBogus.log 2>&1BOGUS_EXIT=$?set -eecho "help=$HELP_EXIT probe01=$PROBE01_EXIT probe30=$PROBE30_EXIT bogus=$BOGUS_EXIT"cat /tmp/probe01.log | head -n 20 || trueecho "[execute] write reports/toolchain.json"python3 <<'PY'import json, sys, os, platform, pathlib, subprocessimport numpy, xarrayfrom app.pygmt.datasets import load_earth_reliefpp = os.environ.get('PYTHONPATH', '')home = pathlib.Path.home()def read(p): try: return pathlib.Path(p).read_text() except Exception: return ''b = read(home / '.bashrc')pr = read(home / '.profile')bp = read(home / '.bash_profile')de = read(pathlib.Path('.env'))help_txt = read('/tmp/vhelp.txt')probe01_log = read('/tmp/probe01.log')# re-probe help exit parseablyimport subprocess as sph = sp.run([sys.executable, 'tools/validate_grid.py', '--help'], capture_output=True, text=True)try: p01 = int(pathlib.Path('/tmp/probe01.log').read_text()[:0] and '0')except Exception: pass# read exits from files created by shell? recompute quicklydef exit_of(args): r = sp.run([sys.executable, 'tools/validate_grid.py'] + args, capture_output=True, text=True) return r.returncode, (r.stdout + r.stderr)[:500]_, help_out = exit_of(['--help'])# loader shapes derived from actual loadershapes = { '01d': list(load_earth_relief('01d').shape), '30m': list(load_earth_relief('30m').shape), '01d_region': list(load_earth_relief('01d', region=[-45.0, 45.0, -30.0, 30.0]).shape),}info = { 'python': sys.version.split()[0], 'python_full': sys.version, 'platform': platform.platform(), 'numpy': numpy.__version__, 'xarray': xarray.__version__, 'env': { 'PYTHONPATH': pp, 'bashrc_contains_pythonpath': ('/app' in b and 'PYTHONPATH' in b), 'profile_contains_pythonpath': ('/app' in pr and 'PYTHONPATH' in pr), 'bash_profile_contains_pythonpath': ('/app' in bp and 'PYTHONPATH' in bp) if bp else False, 'dotenv': de.strip(), 'profile_persisted': (('/app' in b) or ('/app' in pr)), }, 'resolved': {'PYTHONPATH_resolved': pp}, 'validator_cli': { 'help_exit': h.returncode, 'help_contains_resolution': ('--resolution' in (h.stdout + h.stderr)), 'help_contains_output': ('--output' in (h.stdout + h.stderr)), 'help_text_excerpt': (h.stdout + h.stderr)[:800], 'probe_01d_exit': sp.run([sys.executable, 'tools/validate_grid.py', '--resolution', '01d', '--output', '/tmp/probe01b.json'], capture_output=True, text=True).returncode, 'probe_bogus_exit': sp.run([sys.executable, 'tools/validate_grid.py', '--resolution', 'bogus', '--output', '/tmp/probeBogusb.json'], capture_output=True, text=True).returncode, 'validator_path': 'tools/validate_grid.py', }, 'loader_shapes': shapes,}pathlib.Path('reports/toolchain.json').write_text(json.dumps(info, indent=2))print('toolchain written')print(json.dumps({k: info[k] for k in ['python','numpy','xarray']}, indent=2))PYcat reports/toolchain.jsonecho "[execute] run validator CLI to produce reports/validation.json"rm -f reports/validation.jsonset +epython3 tools/validate_grid.py --resolution all --output reports/validation.json > /tmp/val_all.log 2>&1ALL_EXIT=$?set -ecat /tmp/val_all.log | head -n 40 || trueecho "all exit=$ALL_EXIT"if [ ! -f reports/validation.json ]; then echo "fallback: try default output without resolution" python3 tools/validate_grid.py --output reports/validation.json 2>&1 | head -n 40 || truefi# if still missing or single-grid, build from per-resolution runs by merging validator outputspython3 <<'PY'import json, pathlib, subprocess, sysp = pathlib.Path('reports/validation.json')need_merge = Trueif p.is_file(): try: d = json.loads(p.read_text()) txt = p.read_text() has01 = '01d' in txt has30 = '30m' in txt print(f'existing validation has01={has01} has30={has30}') if has01 and has30 and len(txt.strip()) > 50: need_merge = False except Exception as e: print(f'parse fail {e}') need_merge = Trueif need_merge: print('merging per-resolution validator outputs') import os for res in ['01d', '30m']: out = f'/tmp/v_{res}.json' r = subprocess.run([sys.executable, 'tools/validate_grid.py', '--resolution', res, '--output', out], capture_output=True, text=True) print(res, r.returncode) assert r.returncode == 0, f'validator {res} failed: {r.stderr[:300]}' # generic merge preserving validator structure d01 = json.loads(pathlib.Path('/tmp/v_01d.json').read_text()) d30 = json.loads(pathlib.Path('/tmp/v_30m.json').read_text()) def grids_of(d): if isinstance(d, dict) and isinstance(d.get('grids'), dict): return d['grids'] if isinstance(d, dict) and isinstance(d.get('results'), dict): return d['results'] if isinstance(d, dict): c = {k: v for k, v in d.items() if isinstance(v, dict) and ('checks' in v or 'status' in v or 'result' in v)} if c: return c if isinstance(d, list): return {str(e.get('resolution', f'g{i}')): e for i, e in enumerate(d) if isinstance(e, dict)} return {} g = {} g.update(grids_of(d01)) g.update(grids_of(d30)) # determine overall def is_pass(v): if not isinstance(v, dict): return False for k in ['status', 'result', 'verdict']: if isinstance(v.get(k), str) and v[k].strip().lower() in ('pass', 'passed', 'ok', 'success'): return True ch = v.get('checks') if isinstance(ch, dict) and ch: ok = True for x in ch.values(): if isinstance(x, str): if x.lower() not in ('pass', 'passed', 'ok', 'success'): ok = False elif isinstance(x, dict): if str(x.get('status', x.get('result', ''))).lower() not in ('pass', 'passed', 'ok', 'success'): ok = False else: ok = False if ok: return True return False overall = 'pass' if g and all(is_pass(v) for v in g.values()) else 'fail' # preserve validator envelope if possible base = d01 if isinstance(d01, dict) else {} merged = dict(base) if 'grids' in merged or 'results' not in merged: merged['grids'] = g else: merged['results'] = g # set overall keys consistently for k in ['overall', 'status', 'result', 'verdict']: if k in merged: merged[k] = overall if isinstance(merged[k], str) else merged[k] if 'overall' not in merged and 'status' not in merged: merged['overall'] = overall else: if 'overall' in merged and isinstance(merged['overall'], str): merged['overall'] = overall pathlib.Path('reports/validation.json').write_text(json.dumps(merged, indent=2)) print(f'merged {list(g.keys())} overall={overall}')PYcat reports/validation.json | head -n 100ls -lh reports/# ===== validate: exit codes, stdio, JSON parseability, fresh-shell probe =====echo "[validate] CLI stdout/stderr and exit codes"TMPD=$(mktemp -d)python3 tools/validate_grid.py --resolution 01d --output "$TMPD/a.json"test -f "$TMPD/a.json"echo "01d exit 0 ok"set +epython3 tools/validate_grid.py --resolution bogus --output "$TMPD/b.json" > "$TMPD/bogus_out.txt" 2> "$TMPD/bogus_err.txt"BEXIT=$?set -eecho "bogus exit=$BEXIT"test "$BEXIT" -eq 2test -s "$TMPD/bogus_err.txt"echo "bogus stderr non-empty ok"cat "$TMPD/bogus_err.txt" | head -n 10python3 tools/validate_grid.py --help > "$TMPD/help_out.txt" 2>&1test $? -eq 0grep -qi resolution "$TMPD/help_out.txt"echo "help ok"echo "[validate] JSON parseability"python3 <<'PY'import json, pathlibfor f in ['reports/toolchain.json', 'reports/validation.json']: t = pathlib.Path(f).read_text() assert len(t.strip()) > 20, f'{f} empty' d = json.loads(t) assert isinstance(d, (dict, list)), f'{f} bad json' print(f'{f} parseable len={len(t)}')# validation must have per-grid checks and overall passingimport subprocess, sysv = json.loads(pathlib.Path('reports/validation.json').read_text())def grids(d): if isinstance(d, dict) and isinstance(d.get('grids'), dict): return d['grids'] if isinstance(d, dict) and isinstance(d.get('results'), dict): return d['results'] if isinstance(d, dict): c = {k: v for k, v in d.items() if isinstance(v, dict) and ('checks' in v or 'status' in v)} if c: return c if isinstance(d, list): return {str(e.get('resolution', f'g{i}')): e for i, e in enumerate(d) if isinstance(e, dict)} return {}g = grids(v)assert len(g) >= 2, f'need >=2 grids got {list(g.keys())}'print(f'grids={list(g.keys())}')PYecho "[validate] fresh-shell import probe (clean env, login + interactive)"set +eenv -u PYTHONPATH bash -l -c 'python3 -c "from app.pygmt.datasets import load_earth_relief; print(tuple(load_earth_relief(\04701d\047).shape))"' > /tmp/fresh_l.log 2>&1L_EXIT=$?env -u PYTHONPATH bash -i -c 'python3 -c "from app.pygmt.datasets import load_earth_relief; print(tuple(load_earth_relief(\04701d\047).shape))"' > /tmp/fresh_i.log 2>&1I_EXIT=$?set -ecat /tmp/fresh_l.log | head -n 10cat /tmp/fresh_i.log | head -n 10echo "login exit=$L_EXIT interactive exit=$I_EXIT"python3 <<'PY'import pathlibl = pathlib.Path('/tmp/fresh_l.log').read_text()i = pathlib.Path('/tmp/fresh_i.log').read_text()print('login:', l.strip()[:100])print('interactive:', i.strip()[:100])assert ('181' in l and '361' in l) or ('181' in i and '361' in i), 'fresh-shell import must succeed in at least one shell'print('fresh-shell probe ok')PY# ===== finalize: aggregate summary.json from validation + loader stats =====echo "[finalize] aggregate reports/summary.json"python3 <<'PY'import json, pathlibfrom app.pygmt.datasets import load_earth_reliefval = json.loads(pathlib.Path('reports/validation.json').read_text())# flexible grid extractiondef grids(d): if isinstance(d, dict) and isinstance(d.get('grids'), dict): return d['grids'] if isinstance(d, dict) and isinstance(d.get('results'), dict): return d['results'] if isinstance(d, dict): c = {k: v for k, v in d.items() if isinstance(v, dict) and ('checks' in v or 'status' in v or 'result' in v or 'verdict' in v)} if c: return c if isinstance(d, list): return {str(e.get('resolution', f'g{i}')): e for i, e in enumerate(d) if isinstance(e, dict)} return {}def is_pass(v): if not isinstance(v, dict): return False for k in ['status', 'result', 'verdict']: vv = v.get(k) if isinstance(vv, str) and vv.strip().lower() in ('pass', 'passed', 'ok', 'success'): return True ch = v.get('checks') if isinstance(ch, dict) and ch: ok = True for x in ch.values(): if isinstance(x, str): if x.lower() not in ('pass', 'passed', 'ok', 'success'): ok = False elif isinstance(x, dict): if str(x.get('status', x.get('result', ''))).lower() not in ('pass', 'passed', 'ok', 'success'): ok = False elif isinstance(x, bool): if not x: ok = False else: ok = False if ok: return True return Falsedef checks_counts(v): ch = v.get('checks') if isinstance(v, dict) else None if isinstance(ch, dict): total = len(ch) passed = sum(1 for x in ch.values() if (x.lower() in ('pass','passed','ok','success') if isinstance(x, str) else (str(x.get('status', x.get('result',''))).lower() in ('pass','passed','ok','success') if isinstance(x, dict) else (bool(x) if isinstance(x,bool) else False)))) return passed, total return (1 if is_pass(v) else 0), 1g = grids(val)assert len(g) >= 2, 'need >=2 grids'total = len(g)passed = sum(1 for v in g.values() if is_pass(v))failed = total - passedpass_rate = passed / total if total else 0# validation overalldef overall_of(d): for k in ['overall', 'status', 'result', 'verdict']: vv = d.get(k) if isinstance(d, dict) else None if isinstance(vv, str) and vv.strip().lower() in ('pass','passed','ok','success','fail','failed','error'): return vv.strip().lower() return Nonevo = overall_of(val)# map to pass/failif vo in ('passed','ok','success'): vo = 'pass'if vo in ('failed','error'): vo = 'fail'overall = 'pass' if passed == total else 'fail'# must agree with validation overall if validation says passif vo == 'pass': assert overall == 'pass', 'summary must agree with validation pass'per = {}for res, entry in g.items(): # normalize key to 01d/30m where possible key = str(res) # try to infer resolution from entry for cand in ['01d', '30m']: if cand in key or cand == str(entry.get('resolution', '')): key = cand break cp, ct = checks_counts(entry) try: shape = list(load_earth_relief(key).shape) if key in ('01d','30m') else None except Exception: shape = None status = 'pass' if is_pass(entry) else 'fail' per[key] = {'status': status, 'checks_passed': cp, 'checks_total': ct, 'shape': shape}# ensure both resolutions presentfor cand in ['01d', '30m']: if cand not in per: shape = list(load_earth_relief(cand).shape) # find entry containing cand found = None for k, v in g.items(): if cand in str(k) or cand == str(v.get('resolution','')): found = v break if found is not None: cp, ct = checks_counts(found) per[cand] = {'status': 'pass' if is_pass(found) else 'fail', 'checks_passed': cp, 'checks_total': ct, 'shape': shape} else: per[cand] = {'status': overall, 'checks_passed': 1, 'checks_total': 1, 'shape': shape}summary = { 'total_grids': total, 'passed': passed, 'failed': failed, 'pass_rate': pass_rate, 'per_resolution': per, 'overall': overall,}pathlib.Path('reports/summary.json').write_text(json.dumps(summary, indent=2))print(json.dumps(summary, indent=2))PYcat reports/summary.jsonecho "[finalize] bounded validation of summary"python3 <<'PY'import json, pathlibs = json.loads(pathlib.Path('reports/summary.json').read_text())v = json.loads(pathlib.Path('reports/validation.json').read_text())assert s['total_grids'] >= 2assert s['passed'] + s['failed'] == s['total_grids']assert abs(s['pass_rate'] - s['passed']/s['total_grids']) < 1e-9assert s['overall'] in ('pass','fail')assert s['overall'] == 'pass', 'all grids must pass'assert '01d' in s['per_resolution'] and '30m' in s['per_resolution']assert list(s['per_resolution']['01d']['shape']) == [181, 361]assert list(s['per_resolution']['30m']['shape']) == [361, 721]print('summary validated')PYls -lh reports/ app/pygmt/echo "DONE"1234567891011121314151617181920212223242526272829303132333435363738{ "stages": { "affordance_ranking": { "seconds": 278.339, "cost_usd": 0.001186, "llm_calls": 1 }, "contract": { "seconds": 255.703, "cost_usd": 0.001377, "llm_calls": 1 }, "solution": { "seconds": 252.992, "cost_usd": 0.003056, "llm_calls": 1 }, "verifier": { "seconds": 477.713, "cost_usd": 0.006717, "llm_calls": 2 }, "instruction": { "seconds": 170.969, "cost_usd": 0.00115, "llm_calls": 1 }, "env_align": { "seconds": 150.084, "cost_usd": 0.000848, "llm_calls": 1 } }, "lineage_id": "L295-y-0054", "round": 6, "total_seconds": 1585.8, "total_cost_usd": 0.014334}12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0054"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322import jsonimport osimport pathlibimport subprocessimport sysimport tempfileimport numpy as npimport xarray as xrdef R(): for b in [pathlib.Path.cwd(), pathlib.Path('/app')]: if (b / 'docs' / 'grid_spec.md').is_file(): return b if (b / 'tools' / 'validate_grid.py').is_file(): return b return pathlib.Path('/app')def F(p): a = R() / p if a.is_file(): return a b = pathlib.Path('/app') / p return b if b.is_file() else Nonedef LD(): for s in [str(R()), '/app']: if s not in sys.path: sys.path.insert(0, s) for m in ['app.pygmt.datasets', 'pygmt.datasets']: try: mod = __import__(m, fromlist=['load_earth_relief']) fn = getattr(mod, 'load_earth_relief', None) if callable(fn): return fn except Exception: continue raise AssertionError('loader missing')def EX(): for s in [str(R()), '/app']: if s not in sys.path: sys.path.insert(0, s) for m in ['app.pygmt.exceptions', 'pygmt.exceptions']: try: mod = __import__(m, fromlist=['GMTInvalidInput']) e = getattr(mod, 'GMTInvalidInput', None) if e is not None: return e except Exception: continue raise AssertionError('exc missing')def CLI(args, timeout=25): v = F('tools/validate_grid.py') assert v is not None, 'validator missing' e = dict(os.environ) b = str(R()) p = e.get('PYTHONPATH', '') for s in [b, '/app']: if s not in p: p = s + ':' + p if p else s e['PYTHONPATH'] = p return subprocess.run([sys.executable, str(v)] + list(args), capture_output=True, text=True, timeout=timeout, cwd=b, env=e)def J(p): f = F(p) assert f is not None, p + ' missing' t = f.read_text(errors='replace') assert len(t.strip()) > 20, p + ' empty' d = json.loads(t) assert isinstance(d, (dict, list)), p + ' json type' return d, tdef G(d): if isinstance(d, dict) and isinstance(d.get('grids'), dict): return d['grids'] if isinstance(d, dict) and isinstance(d.get('results'), dict): return d['results'] if isinstance(d, dict): c = {k: v for k, v in d.items() if isinstance(v, dict) and ('checks' in v or 'status' in v or 'verdict' in v)} if c: return c if isinstance(d, list): return {str(e.get('resolution', 'g')): e for e in d if isinstance(e, dict)} return {}def is_pass(g): if not isinstance(g, dict): return False for k in ['status', 'result', 'verdict', 'overall']: v = g.get(k) if isinstance(v, str) and v.strip().lower() in ('pass', 'passed', 'ok', 'success'): return True ch = g.get('checks') if isinstance(ch, dict) and ch: ok = True for x in ch.values(): if isinstance(x, str): if x.lower() not in ('pass', 'passed', 'ok', 'success'): ok = False elif isinstance(x, dict): s = str(x.get('status', x.get('result', ''))).lower() if s not in ('pass', 'passed', 'ok', 'success'): ok = False else: ok = False if ok: return True return Falsedef overall_pass(d): if isinstance(d, dict): for k in ['overall', 'status', 'result', 'verdict']: v = d.get(k) if isinstance(v, str) and v.strip().lower() in ('pass', 'passed', 'ok', 'success'): return True g = G(d) if g and len(g) >= 2 and all(is_pass(x) for x in g.values()): return True return Falsedef check_grid(res): f = LD() sh = (181, 361) if res == '01d' else (361, 721) mn, mx = (-1000.0, 1000.0) if res == '01d' else (-500.0, 500.0) da = f(res) assert isinstance(da, xr.DataArray), res + ' DataArray' assert tuple(da.dims) == ('lat', 'lon'), res + ' dims' assert tuple(da.shape) == sh, res + ' shape' a = np.asarray(da.data, dtype=float) assert np.all(np.isfinite(a)), res + ' finite' assert abs(float(a.min()) - mn) < 1e-6, res + ' min' assert abs(float(a.max()) - mx) < 1e-6, res + ' max' assert np.allclose(a, a[:, [0]] * np.ones((1, a.shape[1]))), res + ' lon invariant' return dadef test_check_01_required_evidence(): s = F('docs/grid_spec.md') assert s is not None, 'spec missing' t = s.read_text(errors='replace') assert len(t) > 500, 'spec small' for k in ['01d', '30m', 'gridline', 'lat', 'lon']: assert k in t, 'spec ' + k assert '181' in t and '361' in t, 'shapes' assert '-1000' in t and '-500' in t, 'bounds' h = F('tools/validate_grid.py') assert h is not None, 'validator missing' ht = h.read_text(errors='replace') assert '--resolution' in ht and '--output' in ht, 'flags' compile(ht, str(h), 'exec') l = F('app/pygmt/datasets.py') if l is None: l = F('pygmt/datasets.py') assert l is not None, 'loader missing' assert 'load_earth_relief' in l.read_text(errors='replace'), 'fn missing' for r in ['reports/toolchain.json', 'reports/validation.json', 'reports/summary.json']: assert F(r) is not None, r + ' missing' hh = CLI(['--help']) assert hh.returncode == 0, 'help exit' assert 'resolution' in (hh.stdout + hh.stderr).lower(), 'help text'def test_check_01_cli_stdio_exit_codes(): d = tempfile.mkdtemp() o1 = os.path.join(d, 'a.json') r1 = CLI(['--resolution', '01d', '--output', o1]) assert r1.returncode == 0, '01d exit 0' assert os.path.isfile(o1), 'output written' assert len(pathlib.Path(o1).read_text(errors='replace').strip()) > 20, 'output empty' rb = CLI(['--resolution', 'bogus', '--output', os.path.join(d, 'b.json')]) assert rb.returncode == 2, 'bad res exit 2' assert len(rb.stderr.strip()) > 0, 'stderr needed'def test_check_01_env_doc(): p = F('docs/environment.md') assert p is not None, 'env doc missing' t = p.read_text(errors='replace') assert 'PYTHONPATH' in t, 'env PYTHONPATH' assert '/app' in t, 'env app' low = t.lower() assert 'bashrc' in low or 'profile' in low or '.env' in low or 'export' in low, 'persistence' home = pathlib.Path.home() found = False for c in [home / '.bashrc', home / '.profile', home / '.bash_profile', R() / '.env', pathlib.Path('/app') / '.env']: try: if c.is_file(): x = c.read_text(errors='replace') if 'PYTHONPATH' in x and '/app' in x: found = True except Exception: pass assert found, 'persisted PYTHONPATH missing'def test_check_01_fresh_shell_env(): cmd = "python3 -c 'from app.pygmt.datasets import load_earth_relief; print(tuple(load_earth_relief(chr(48)+chr(49)+chr(100)).shape))'" clean = dict(os.environ) clean.pop('PYTHONPATH', None) ok = False msg = '' for flag in ['-l', '-i']: try: r = subprocess.run(['bash', flag, '-c', cmd], capture_output=True, text=True, timeout=20, cwd='/tmp', env=clean) msg = msg + flag + str(r.returncode) + (r.stdout.strip() or r.stderr.strip()) if r.returncode == 0 and '181' in r.stdout and '361' in r.stdout: ok = True except Exception as e: msg = msg + str(e) assert ok, 'fresh shell import failed'def test_check_02_toolchain_artifact(): d, t = J('reports/toolchain.json') assert isinstance(d, dict), 'toolchain dict' assert len(t.strip()) > 50, 'toolchain small' low = t.lower() cur = str(sys.version_info.major) + '.' + str(sys.version_info.minor) assert cur in t, 'python version' assert np.__version__ in t, 'numpy version' assert xr.__version__ in t, 'xarray version' assert 'validator' in low or 'validate' in low or 'cli' in low, 'probe' assert 'resolution' in low or 'validate_grid' in low or 'exit' in low, 'probe detail' assert '181' in t and '361' in t, 'shapes' assert '721' in t, '30m shape'def test_check_02_validation_artifact(): d, t = J('reports/validation.json') assert len(t.strip()) > 50, 'validation small' g = G(d) assert isinstance(g, dict) and len(g) >= 2, 'grids' keys = ' '.join(list(g.keys())).lower() + ' ' + t.lower() assert '01d' in keys and '30m' in keys, 'cover' for k, v in g.items(): assert is_pass(v), 'grid pass ' + str(k) assert overall_pass(d), 'overall pass'def test_check_03_loader_semantics(): for res in ['01d', '30m']: da = check_grid(res) assert str(da.dtype.kind) == 'f', res + ' dtype' assert str(da.coords['lat'].dtype.kind) == 'f', res + ' lat dtype' assert str(da.coords['lon'].dtype.kind) == 'f', res + ' lon dtype' lat = np.asarray(da.coords['lat'].data, dtype=float) lon = np.asarray(da.coords['lon'].data, dtype=float) assert np.all(lat >= -90 - 1e-8) and np.all(lat <= 90 + 1e-8), res + ' lat range' assert np.all(lon >= -180 - 1e-8) and np.all(lon <= 180 + 1e-8), res + ' lon range' assert np.all(np.diff(lat) > 0), res + ' lat mono' assert np.all(np.diff(lon) > 0), res + ' lon mono' step = 1.0 if res == '01d' else 0.5 assert np.allclose(np.diff(lat), step, atol=1e-8), res + ' lat step' assert np.allclose(np.diff(lon), step, atol=1e-8), res + ' lon step' f = LD() sub = f('01d', region=[-45.0, 45.0, -30.0, 30.0]) assert tuple(sub.shape) == (61, 91), 'region shape' assert tuple(sub.dims) == ('lat', 'lon'), 'region dims' a = np.asarray(sub.data, dtype=float) assert abs(float(a.min()) + 1000.0) < 1e-6, 'region min' assert abs(float(a.max()) - 1000.0) < 1e-6, 'region max'def test_check_03_loader_errors(): f = LD() E = EX() for bad in ['bogus', '', '1d']: try: f(bad) raise AssertionError('bad res must raise') except E: pass try: f(None) raise AssertionError('none must raise') except E: pass try: f('01d', registration='pix') raise AssertionError('reg must raise') except E: pass for br in [[0, 1, 2], [0, 1, 2, 3, 4]]: try: f('01d', region=br) raise AssertionError('bad region must raise') except E: pass da = f('01d', use_srtm=True) assert tuple(da.shape) == (181, 361), 'srtm'def test_check_03_summary_semantics(): s, st = J('reports/summary.json') v, vt = J('reports/validation.json') assert isinstance(s, dict), 'summary dict' g = G(v) n = len(g) assert n >= 2, 'grids' total = s.get('total_grids', s.get('total', 0)) assert total == n, 'total' passed = s.get('passed', -1) failed = s.get('failed', -1) assert isinstance(passed, int) and isinstance(failed, int), 'counts int' assert passed + failed == n, 'counts sum' assert passed == n and failed == 0, 'all pass' pr = s.get('pass_rate', s.get('rate', -1)) assert isinstance(pr, (int, float)), 'rate' assert abs(float(pr) - 1.0) < 1e-6, 'rate 1' ov = str(s.get('overall', s.get('verdict', s.get('status', '')))).lower() assert ov in ('pass', 'passed', 'ok', 'success'), 'overall pass' per = s.get('per_resolution', s.get('resolutions', {})) assert isinstance(per, dict) and len(per) >= 2, 'per res' lowp = json.dumps(per).lower() assert '01d' in lowp and '30m' in lowp, 'per keys' for res, exp0, exp1 in [('01d', 181, 361), ('30m', 361, 721)]: e = per.get(res) assert isinstance(e, dict), res + ' entry' assert 'pass' in str(e).lower() or 'ok' in str(e).lower(), res + ' pass' assert str(exp0) in json.dumps(e) and str(exp1) in json.dumps(e), res + ' shape'def test_check_04_no_shortcut(): for r in ['reports/toolchain.json', 'reports/validation.json', 'reports/summary.json']: p = F(r) assert p is not None, r + ' missing' t = p.read_text(errors='replace') assert len(t.strip()) > 50, r + ' small' low = t.lower() assert 'placeholder' not in low and 'todo' not in low, r + ' placeholder' json.loads(t) lp = F('app/pygmt/datasets.py') if lp is None: lp = F('pygmt/datasets.py') assert lp is not None, 'loader missing' src = lp.read_text(errors='replace') assert len(src) > 400, 'loader small' assert 'DataArray' in src, 'DataArray' assert 'arange' in src, 'arange' assert 'GMTInvalidInput' in src, 'exc' d, _ = J('reports/toolchain.json') jt = json.dumps(d) assert np.__version__ in jt, 'stale numpy' assert xr.__version__ in jt, 'stale xarray' tmp = tempfile.mkdtemp() out = os.path.join(tmp, 'rerun.json') rr = CLI(['--resolution', '01d', '--output', out]) assert rr.returncode == 0, 'rerun exit' assert os.path.isfile(out), 'rerun file' dd = json.loads(pathlib.Path(out).read_text(errors='replace')) assert overall_pass(dd) or len(json.dumps(dd)) > 50, 'rerun pass'123456789101112131415{ "seed_dir": "/ansh/data/tasktrove/tasktrove-exp-rpt-curriculum-easy/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313", "test_file": "/ansh/data/tasktrove/tasktrove-exp-rpt-curriculum-easy/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313/tests/test_curriculum.py", "attempts": 1, "precheck": { "ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 1.9 }, "repair_log": []}123FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytest1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162## Easier task: small, single-file VCF header parser
Goal- Create a tiny Python module at /app/vcfparser.py that provides: - a MetaDataParser class - a split_to_dict helper function
Public API- from vcfparser import MetaDataParser- from vcfparser import split_to_dict
What to implement- A single file: /app/vcfparser.py - class MetaDataParser: - __init__(self, header_file: str) - store the path to the VCF header file - def _parse_gvcf_block(self, line: str) -> dict - input: one line from the meta-header that might describe a GVCF block - output: a dict with parsed key-value pairs or {} if not a recognizable block - def _parse_gatk_commands(self, line: str) -> dict - input: a line containing GATK command information in the header - output: a dict of parsed key-value pairs or {} - def parse_lines(self) -> list - read the header_file - collect relevant lines (e.g., lines starting with "##" that contain a block) - return a list of dictionaries parsed from those lines - if the file cannot be read, raise FileNotFoundError- The split_to_dict function: - def split_to_dict(string: str) -> dict - Expected behavior for input like: - "<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>" - Return: { "ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality" } - Parsing rules (keep things simple but robust): - Remove surrounding "<" and ">" if present - Split inner content into key=value pairs by commas - Trim whitespace around keys and values - Remove surrounding single quotes around values if present - Convert purely numeric values to int (e.g., "2" -> 2) - If the input is malformed or empty, return an empty dict - Do not raise for well-formed inputs
Implementation tips (for you)- The current tests will exercise split_to_dict with a representative sample string, so ensure that function passes that scenario reliably.- MetaDataParser methods can be implemented with sensible, small, robust behavior (a minimal, future-proof scaffold), but you only need the above surface for now.- Keep the code robust to extra spaces and simple quoted values.
Notes- The tests are designed to be lenient now, so focus on getting split_to_dict correct and making MetaDataParser return reasonable data if parse_lines is called.- Do not modify tests. Place the file at: - /app/vcfparser.py
Summary- Move to a single-file approach for ease: - Public API: MetaDataParser and split_to_dict - Location: /app/vcfparser.py - Minimal, robust parsing with sensible defaults and clear behavior for the stated example.1{"metadata": {"lineage": "L296-y-0313", "round": "r0", "generation_method": "recursive-task-synthesis", "stats": {"stages": {"bootstrap": {"seconds": 59.72, "cost_usd": 0.001205, "llm_calls": 1}, "precheck": {"seconds": 2.157, "cost_usd": 0.0, "llm_calls": 0}}, "lineage_id": "L296-y-0313", "round": 0, "total_seconds": 61.877, "total_cost_usd": 0.001205}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140#!/bin/bashset -ecat > /app/vcfparser.py <<'PYEOF'"""Tiny single-file VCF header parser."""
def split_to_dict(string: str) -> dict: """Parse a VCF meta block like <ID=HQ,Number=2,...> into a dict.""" if not isinstance(string, str): return {} if not string or not string.strip(): return {} s = string.strip() if s.startswith("<"): s = s[1:] if s.endswith(">"): s = s[:-1] s = s.strip() if not s: return {} # Split by commas respecting single/double quotes parts = [] current = "" in_single = False in_double = False for ch in s: if ch == "'" and not in_double: in_single = not in_single current += ch elif ch == '"' and not in_single: in_double = not in_double current += ch elif ch == "," and not in_single and not in_double: parts.append(current) current = "" else: current += ch parts.append(current) result = {} for part in parts: part = part.strip() if not part: return {} if "=" not in part: return {} k, v = part.split("=", 1) k = k.strip() v = v.strip() if not k: return {} if len(v) >= 2 and ((v[0] == "'" and v[-1] == "'") or (v[0] == '"' and v[-1] == '"')): v = v[1:-1] # Convert purely numeric values to int if isinstance(v, str): vs = v.strip() if vs.isdigit(): v = int(vs) elif vs.startswith("-") and vs[1:].isdigit() and len(vs) > 1: v = int(vs) elif vs.startswith("+") and vs[1:].isdigit() and len(vs) > 1: v = int(vs) else: v = v result[k] = v if not result: return {} return result
class MetaDataParser: """Parse VCF header files for meta blocks."""
def __init__(self, header_file: str): self.header_file = header_file
def _parse_gvcf_block(self, line: str) -> dict: if not isinstance(line, str): return {} if "<" not in line or ">" not in line: return {} try: start = line.find("<") end = line.rfind(">") if start < 0 or end < 0 or start >= end: return {} block = line[start:end + 1] parsed = split_to_dict(block) return parsed if isinstance(parsed, dict) else {} except Exception: return {}
def _parse_gatk_commands(self, line: str) -> dict: if not isinstance(line, str): return {} if "gatk" not in line.lower(): return {} try: if "<" in line and ">" in line: start = line.find("<") end = line.rfind(">") if start >= 0 and end > start: block = line[start:end + 1] parsed = split_to_dict(block) if parsed: return parsed return {} except Exception: return {}
def parse_lines(self) -> list: try: fh = open(self.header_file, "r") except FileNotFoundError: raise except OSError as e: raise FileNotFoundError(str(e)) from e results = [] with fh: for raw in fh: line = raw.strip() if not line.startswith("##"): continue if "<" not in line or ">" not in line: continue d = self._parse_gvcf_block(line) if not d: d = self._parse_gatk_commands(line) if not d: try: start = line.find("<") end = line.rfind(">") block = line[start:end + 1] d = split_to_dict(block) except Exception: d = {} if d: results.append(d) return resultsPYEOFpython3 -c "from vcfparser import MetaDataParser, split_to_dict; print(split_to_dict(\"<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\"))"123456789101112131415161718{ "stages": { "bootstrap": { "seconds": 59.72, "cost_usd": 0.001205, "llm_calls": 1 }, "precheck": { "seconds": 2.157, "cost_usd": 0.0, "llm_calls": 0 } }, "lineage_id": "L296-y-0313", "round": 0, "total_seconds": 61.877, "total_cost_usd": 0.001205}12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import osimport syssys.path.insert(0, "/app")sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))import pytestfrom vcfparser import MetaDataParser, split_to_dict
def test_split_to_dict_basic(): input_str = "<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>" expected = { "ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality", } assert split_to_dict(input_str) == expected
def test_split_to_dict_with_spaces_and_quotes(): input_str = "< ID = HQ , Number = 2 , Type = Integer , Description = 'Haplotype Quality' >" expected = { "ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality", } assert split_to_dict(input_str) == expected
def test_split_to_dict_malformed_returns_empty(): assert split_to_dict("") == {} assert split_to_dict("<>") == {}
def test_metadata_parser_parse_lines(tmp_path): content = ( "##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\n" "##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>\n" ) header_path = tmp_path / "header.vcf" header_path.write_text(content)
parser = MetaDataParser(str(header_path)) parsed = parser.parse_lines() assert isinstance(parsed, list) assert len(parsed) == 2 ids = [d.get("ID") for d in parsed] assert "HQ" in ids assert "SB" in ids1234567891011121314151617181920212223242526272829303132333435363738394041424344FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytestRUN mkdir -p /app/docs /app/dataRUN cat > /app/docs/HEADER_SCHEMA.md <<'MDEOF'# VCF Header Schema — Meta Entries
This document defines validation rules for parsed VCF meta header dicts produced by `vcfparser.split_to_dict` / `MetaDataParser.parse_lines`.
## Required fields (completeness)Every parsed entry must contain all four keys:- `ID`- `Number`- `Type`- `Description`
Missing any required key => invalid. Extra keys are allowed and ignored.
## Field types and constraints- `ID`: must be a non-empty string matching `^[A-Za-z0-9_.\-]+$` (letters, digits, underscore, dot, hyphen). Empty or missing => invalid.- `Number`: must be either: - a non-negative integer (`0`, `1`, `2`, ...) with value `>= 0`, OR - one of the symbolic values `A`, `R`, `G`, `.` Anything else (negative integers, other strings like `two`, empty) => invalid. This covers type + range.- `Type`: must be exactly one of `Integer`, `Float`, `Flag`, `String`, `Character` (case-sensitive). Anything else => invalid.- `Description`: must be a non-empty string after stripping whitespace. Empty or missing => invalid.
## Examples- Valid: `<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>` => `{"ID":"HQ","Number":2,"Type":"Integer","Description":"Haplotype Quality"}`- Invalid: missing `Description`, `Number=-1` (out of range), `Type=BadType` (not allowed), `ID=` (empty).
## Validation reportValidators must emit per-entry `valid` boolean and `errors` list mentioning the offending field(s).MDEOFRUN cat > /app/data/sample_header.vcf <<'VCFEOF'##fileformat=VCFv4.2##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>##INFO=<ID=DP,Number=1,Type=Integer,Description='Total Depth'>##INFO=<ID=BAD_NUM,Number=-1,Type=Integer,Description='Negative number out of range'>##INFO=<ID=BAD_TYPE,Number=1,Type=BadType,Description='Invalid type value'>##INFO=<ID=BAD_MISSING,Number=1,Type=String>##INFO=<ID=,Number=1,Type=String,Description='Empty ID fails'>VCFEOF123Build a tiny single-file VCF header parser at /app/vcfparser.py providing MetaDataParser and split_to_dict. split_to_dict must parse blocks like <ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'> into dicts with trimmed keys, unquoted values and numeric conversion, returning {} for malformed input; MetaDataParser must read a header file via parse_lines and raise FileNotFoundError if unreadable.
Then inspect the workspace schema doc and sample header under docs/ and data/ to derive required fields, types and completeness rules, run the parser over the sample header, validate every entry, and write a machine-readable JSON validation report to /app/validation_report.json marking each entry valid with field-specific errors.1{"metadata": {"lineage": "L296-y-0313", "round": "r1", "generation_method": "recursive-task-synthesis", "rounds": {"lineage_id": "L296-y-0313", "round": 1, "operator": "schema_content_validation", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": {"status": "ok", "ranked_operators": [{"operator": "schema_content_validation", "fit": "high", "reason": "VCF dicts have clear schema ID/Number/Type/Description ideal for validation subgoal"}, {"operator": "format_conversion_validation", "fit": "high", "reason": "Parsed header list naturally converts to JSON with semantic preservation checks"}, {"operator": "aggregation_summary_report", "fit": "high", "reason": "parse_lines list naturally supports counts and summary report artifact"}, {"operator": "toolchain_availability_check", "fit": "medium", "reason": "Python/pytest check possible but low exploration value for stdlib parser"}, {"operator": "container_build_alignment", "fit": "low", "reason": "Trivial single-FROM Dockerfile offers little build-context work"}, {"operator": "environment_variable_resolution", "fit": "low", "reason": "No env vars, locale, or shell profiles in seed; would need forced injection"}], "blocked_operators": [{"operator": "environment_variable_resolution", "reason": "Artificial for pure VCF parser with no env/locale/timezone affordance"}], "rationale": "Env resolution is artificial; data validation/conversion/report operators fit parser workflow directly."}, "contract": {"status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "schema_content_validation", "operator_fit": "fallback", "why_fit": "Preferred env-var resolution has no affordance in pure stdlib VCF parser; VCF meta dicts with ID/Number/Type/Description give natural schema-validation subgoal.", "goal": "Build tiny VCF header parser and validate parsed headers against schema to produce a validation report", "preserved_workflow": "Create /app/vcfparser.py with MetaDataParser and split_to_dict that parses VCF meta blocks like <ID=HQ,Number=2,...> and parse_lines over header file", "new_requirement": "Validate every parsed header dict for required fields, types, ranges and completeness per workspace schema doc and emit a machine-readable JSON validation report distinguishing valid and invalid entries", "task_chain": [{"stage": "inspect", "artifact_or_state": "sample VCF header fixture and local schema doc to inspect via filesystem/CLI"}, {"stage": "derive", "artifact_or_state": "required fields, types, ranges and completeness rules inferred from local docs and fixture"}, {"stage": "execute", "artifact_or_state": "vcfparser.py implementation executed via python CLI to produce parsed intermediate output"}, {"stage": "validate", "artifact_or_state": "local validation run producing parseable JSON report with per-entry status and errors"}, {"stage": "finalize", "artifact_or_state": "final validation report artifact checked for semantic correctness"}], "expected_artifacts": [{"path": "/app/vcfparser.py", "role": "final", "requirement": "provides MetaDataParser and split_to_dict with robust parsing and FileNotFoundError on missing file"}, {"path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "discoverable doc defining required fields, types, and validation rules for VCF meta entries"}, {"path": "/app/data/sample_header.vcf", "role": "evidence", "requirement": "fixture header with mix of valid and invalid meta lines for parsing and validation"}, {"path": "/app/validation_report.json", "role": "final", "requirement": "JSON report listing each parsed entry, valid flag, and errors for missing/invalid fields, non-empty and parseable"}, {"path": "/app/parsed_output.json", "role": "intermediate", "requirement": "parsed list of dicts from parse_lines, present parseable and non-empty"}], "reward_checks": [{"name": "check_01_required_evidence", "checks": "schema doc and sample header fixture exist and parser output references their content"}, {"name": "check_02_intermediate_artifact", "checks": "parsed intermediate JSON/list is present, parseable, non-empty with expected IDs"}, {"name": "check_03_final_semantics", "checks": "validation report correctly marks valid vs invalid entries per schema types/ranges/completeness"}, {"name": "check_04_no_shortcut", "checks": "reject empty, placeholder, hardcoded, or stale report that does not reflect actual parser output"}], "instruction_boundary": {"mention": ["public goal to build parser and validation report", "fair starting points in workspace docs and sample header", "main deliverables and completion signal", "only undiscoverable hard constant like example HQ block"], "hide": ["step-by-step commands", "path/field inventories", "schema/format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable validation details that belong in local docs"]}, "environment_changes": ["add docs/HEADER_SCHEMA.md with ID/Number/Type/Description rules and allowed types", "add data/sample_header.vcf with valid and invalid meta lines"], "rationale": "Schema validation fits parser output directly, adds inspect-derive-execute-validate-finalize depth with observable report while staying local, deterministic, and verifiable without new dependencies."}, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": {"ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.4}, "repair_log": []}, "stats": {"stages": {"affordance_ranking": {"seconds": 49.927, "cost_usd": 0.000916, "llm_calls": 1}, "contract": {"seconds": 46.866, "cost_usd": 0.000956, "llm_calls": 1}, "solution": {"seconds": 118.423, "cost_usd": 0.002256, "llm_calls": 1}, "verifier": {"seconds": 81.28, "cost_usd": 0.002095, "llm_calls": 1}, "instruction": {"seconds": 35.779, "cost_usd": 0.000873, "llm_calls": 1}, "env_align": {"seconds": 41.098, "cost_usd": 0.00092, "llm_calls": 1}, "consistency_repair": {"seconds": 68.88, "cost_usd": 0.001316, "llm_calls": 1}, "precheck": {"seconds": 2.712, "cost_usd": 0.0, "llm_calls": 0}}, "lineage_id": "L296-y-0313", "round": 1, "total_seconds": 444.965, "total_cost_usd": 0.009332}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161{ "lineage_id": "L296-y-0313", "round": 1, "operator": "schema_content_validation", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": { "status": "ok", "ranked_operators": [ { "operator": "schema_content_validation", "fit": "high", "reason": "VCF dicts have clear schema ID/Number/Type/Description ideal for validation subgoal" }, { "operator": "format_conversion_validation", "fit": "high", "reason": "Parsed header list naturally converts to JSON with semantic preservation checks" }, { "operator": "aggregation_summary_report", "fit": "high", "reason": "parse_lines list naturally supports counts and summary report artifact" }, { "operator": "toolchain_availability_check", "fit": "medium", "reason": "Python/pytest check possible but low exploration value for stdlib parser" }, { "operator": "container_build_alignment", "fit": "low", "reason": "Trivial single-FROM Dockerfile offers little build-context work" }, { "operator": "environment_variable_resolution", "fit": "low", "reason": "No env vars, locale, or shell profiles in seed; would need forced injection" } ], "blocked_operators": [ { "operator": "environment_variable_resolution", "reason": "Artificial for pure VCF parser with no env/locale/timezone affordance" } ], "rationale": "Env resolution is artificial; data validation/conversion/report operators fit parser workflow directly." }, "contract": { "status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "schema_content_validation", "operator_fit": "fallback", "why_fit": "Preferred env-var resolution has no affordance in pure stdlib VCF parser; VCF meta dicts with ID/Number/Type/Description give natural schema-validation subgoal.", "goal": "Build tiny VCF header parser and validate parsed headers against schema to produce a validation report", "preserved_workflow": "Create /app/vcfparser.py with MetaDataParser and split_to_dict that parses VCF meta blocks like <ID=HQ,Number=2,...> and parse_lines over header file", "new_requirement": "Validate every parsed header dict for required fields, types, ranges and completeness per workspace schema doc and emit a machine-readable JSON validation report distinguishing valid and invalid entries", "task_chain": [ { "stage": "inspect", "artifact_or_state": "sample VCF header fixture and local schema doc to inspect via filesystem/CLI" }, { "stage": "derive", "artifact_or_state": "required fields, types, ranges and completeness rules inferred from local docs and fixture" }, { "stage": "execute", "artifact_or_state": "vcfparser.py implementation executed via python CLI to produce parsed intermediate output" }, { "stage": "validate", "artifact_or_state": "local validation run producing parseable JSON report with per-entry status and errors" }, { "stage": "finalize", "artifact_or_state": "final validation report artifact checked for semantic correctness" } ], "expected_artifacts": [ { "path": "/app/vcfparser.py", "role": "final", "requirement": "provides MetaDataParser and split_to_dict with robust parsing and FileNotFoundError on missing file" }, { "path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "discoverable doc defining required fields, types, and validation rules for VCF meta entries" }, { "path": "/app/data/sample_header.vcf", "role": "evidence", "requirement": "fixture header with mix of valid and invalid meta lines for parsing and validation" }, { "path": "/app/validation_report.json", "role": "final", "requirement": "JSON report listing each parsed entry, valid flag, and errors for missing/invalid fields, non-empty and parseable" }, { "path": "/app/parsed_output.json", "role": "intermediate", "requirement": "parsed list of dicts from parse_lines, present parseable and non-empty" } ], "reward_checks": [ { "name": "check_01_required_evidence", "checks": "schema doc and sample header fixture exist and parser output references their content" }, { "name": "check_02_intermediate_artifact", "checks": "parsed intermediate JSON/list is present, parseable, non-empty with expected IDs" }, { "name": "check_03_final_semantics", "checks": "validation report correctly marks valid vs invalid entries per schema types/ranges/completeness" }, { "name": "check_04_no_shortcut", "checks": "reject empty, placeholder, hardcoded, or stale report that does not reflect actual parser output" } ], "instruction_boundary": { "mention": [ "public goal to build parser and validation report", "fair starting points in workspace docs and sample header", "main deliverables and completion signal", "only undiscoverable hard constant like example HQ block" ], "hide": [ "step-by-step commands", "path/field inventories", "schema/format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable validation details that belong in local docs" ] }, "environment_changes": [ "add docs/HEADER_SCHEMA.md with ID/Number/Type/Description rules and allowed types", "add data/sample_header.vcf with valid and invalid meta lines" ], "rationale": "Schema validation fits parser output directly, adds inspect-derive-execute-validate-finalize depth with observable report while staying local, deterministic, and verifiable without new dependencies." }, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": { "ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.4 }, "repair_log": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325#!/bin/bashset -e# Oracle workflow: inspect -> derive -> execute -> validate -> finalizeAPP=/appmkdir -p /app/docs /app/data
# --- Evidence: schema doc ---cat > /app/docs/HEADER_SCHEMA.md <<'MDEOF'# VCF Header Schema — Meta Entries
This document defines validation rules for parsed VCF meta header dicts produced by `vcfparser.split_to_dict` / `MetaDataParser.parse_lines`.
## Required fields (completeness)Every parsed entry must contain all four keys:- `ID`- `Number`- `Type`- `Description`
Missing any required key => invalid. Extra keys are allowed and ignored.
## Field types and constraints- `ID`: must be a non-empty string matching `^[A-Za-z0-9_.\-]+$` (letters, digits, underscore, dot, hyphen). Empty or missing => invalid.- `Number`: must be either: - a non-negative integer (`0`, `1`, `2`, ...) with value `>= 0`, OR - one of the symbolic values `A`, `R`, `G`, `.` Anything else (negative integers, other strings like `two`, empty) => invalid. This covers type + range.- `Type`: must be exactly one of `Integer`, `Float`, `Flag`, `String`, `Character` (case-sensitive). Anything else => invalid.- `Description`: must be a non-empty string after stripping whitespace. Empty or missing => invalid.
## Examples- Valid: `<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>` => `{"ID":"HQ","Number":2,"Type":"Integer","Description":"Haplotype Quality"}`- Invalid: missing `Description`, `Number=-1` (out of range), `Type=BadType` (not allowed), `ID=` (empty).
## Validation reportValidators must emit per-entry `valid` boolean and `errors` list mentioning the offending field(s).MDEOF
# --- Evidence: sample header fixture (mix valid + invalid) ---cat > /app/data/sample_header.vcf <<'VCFEOF'##fileformat=VCFv4.2##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>##INFO=<ID=DP,Number=1,Type=Integer,Description='Total Depth'>##INFO=<ID=BAD_NUM,Number=-1,Type=Integer,Description='Negative number out of range'>##INFO=<ID=BAD_TYPE,Number=1,Type=BadType,Description='Invalid type value'>##INFO=<ID=BAD_MISSING,Number=1,Type=String>##INFO=<ID=,Number=1,Type=String,Description='Empty ID fails'>VCFEOF
# --- Stage: inspect inputs before transforming ---echo "[inspect] workspace layout"ls -R /app echo "[inspect] schema doc"cat /app/docs/HEADER_SCHEMA.mdecho "[inspect] sample header"cat /app/data/sample_header.vcfwc -l /app/data/sample_header.vcfgrep -c "^##" /app/data/sample_header.vcf || true
# --- Stage: derive rules inferred from docs + fixture ---echo "[derive] required fields and allowed values from schema doc"grep -E "ID|Number|Type|Description" /app/docs/HEADER_SCHEMA.md | head -20grep -E "Integer|Float|Flag|String|Character" /app/docs/HEADER_SCHEMA.md | head -20echo "[derive] fixture IDs present:"grep -o "ID=[^,>]*" /app/data/sample_header.vcf || true
# --- Stage: execute parser implementation ---cat > /app/vcfparser.py <<'PYEOF'"""Tiny single-file VCF header parser."""
def split_to_dict(string: str) -> dict: """Parse a VCF meta block like <ID=HQ,Number=2,...> into a dict.""" if not isinstance(string, str): return {} if not string or not string.strip(): return {} s = string.strip() if s.startswith("<"): s = s[1:] if s.endswith(">"): s = s[:-1] s = s.strip() if not s: return {} parts = [] current = "" in_single = False in_double = False for ch in s: if ch == "'" and not in_double: in_single = not in_single current += ch elif ch == '"' and not in_single: in_double = not in_double current += ch elif ch == "," and not in_single and not in_double: parts.append(current) current = "" else: current += ch parts.append(current) result = {} for part in parts: part = part.strip() if not part: return {} if "=" not in part: return {} k, v = part.split("=", 1) k = k.strip() v = v.strip() if not k: return {} if len(v) >= 2 and ((v[0] == "'" and v[-1] == "'") or (v[0] == '"' and v[-1] == '"')): v = v[1:-1] if isinstance(v, str): vs = v.strip() if vs.isdigit(): v = int(vs) elif vs.startswith("-") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) elif vs.startswith("+") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) else: v = v result[k] = v if not result: return {} return result
class MetaDataParser: """Parse VCF header files for meta blocks."""
def __init__(self, header_file: str): self.header_file = header_file
def _parse_gvcf_block(self, line: str) -> dict: if not isinstance(line, str): return {} if "<" not in line or ">" not in line: return {} try: start = line.find("<") end = line.rfind(">") if start < 0 or end < 0 or start >= end: return {} block = line[start:end + 1] parsed = split_to_dict(block) return parsed if isinstance(parsed, dict) else {} except Exception: return {}
def _parse_gatk_commands(self, line: str) -> dict: if not isinstance(line, str): return {} if "gatk" not in line.lower(): return {} try: if "<" in line and ">" in line: start = line.find("<") end = line.rfind(">") if start >= 0 and end > start: block = line[start:end + 1] parsed = split_to_dict(block) if parsed: return parsed return {} except Exception: return {}
def parse_lines(self) -> list: try: fh = open(self.header_file, "r") except FileNotFoundError: raise except OSError as e: raise FileNotFoundError(str(e)) from e results = [] with fh: for raw in fh: line = raw.strip() if not line.startswith("##"): continue if "<" not in line or ">" not in line: continue d = self._parse_gvcf_block(line) if not d: d = self._parse_gatk_commands(line) if not d: try: start = line.find("<") end = line.rfind(">") block = line[start:end + 1] d = split_to_dict(block) except Exception: d = {} if d: results.append(d) return resultsPYEOF
echo "[execute] smoke test split_to_dict"python3 -c "from vcfparser import MetaDataParser, split_to_dict; print(split_to_dict(\"<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\"))"
# Produce parsed intermediate via CLIecho "[execute] parsing sample header to parsed_output.json"python3 <<'PYEOF'import jsonfrom vcfparser import MetaDataParserparser = MetaDataParser("/app/data/sample_header.vcf")parsed = parser.parse_lines()print(f"parsed {len(parsed)} entries: {[d.get('ID') for d in parsed]}")with open("/app/parsed_output.json", "w") as f: json.dump(parsed, f, indent=2)print(open("/app/parsed_output.json").read())PYEOF
# Bounded validation of intermediate before final outputs echo "[execute-check] validating intermediate artifact"python3 <<'PYEOF'import json, sysparsed = json.load(open("/app/parsed_output.json"))assert isinstance(parsed, list), "parsed must be list"assert len(parsed) >= 5, f"expected >=5 entries got {len(parsed)}"ids = [d.get("ID") for d in parsed if isinstance(d, dict)]assert "HQ" in ids, "HQ missing"assert "SB" in ids, "SB missing"print(f"intermediate OK: {len(parsed)} entries, IDs={ids}")PYEOF
# --- Stage: validate per schema and emit JSON report ---echo "[validate] running schema validation to validation_report.json"python3 <<'PYEOF'import json, reparsed = json.load(open("/app/parsed_output.json"))allowed_types = ("Integer", "Float", "Flag", "String", "Character")allowed_numbers = ("A", "R", "G", ".")id_pat = re.compile(r"^[A-Za-z0-9_.\-]+$")entries = []for idx, entry in enumerate(parsed): errors = [] for field in ("ID", "Number", "Type", "Description"): if field not in entry: errors.append(f"missing required field: {field}") if "ID" in entry: v = entry["ID"] if not isinstance(v, str) or not v.strip() or not id_pat.match(str(v)): errors.append(f"invalid ID: {v!r} must match ^[A-Za-z0-9_.\\-]+$ and be non-empty") if "Number" in entry: n = entry["Number"] if isinstance(n, int) and not isinstance(n, bool): if n < 0: errors.append(f"invalid Number: {n} must be >= 0 or one of A,R,G,.") elif isinstance(n, str): ns = n.strip() if ns in allowed_numbers: pass elif ns.lstrip("+-").isdigit() and ns != "": try: iv = int(ns) if iv < 0: errors.append(f"invalid Number: {n} must be >= 0 or one of A,R,G,.") # non-negative numeric string would have been int; treat as ok range but flag type inconsistency? except Exception: errors.append(f"invalid Number: {n} must be non-negative integer or one of A,R,G,.") else: errors.append(f"invalid Number: {n!r} must be non-negative integer or one of A,R,G,.") else: errors.append(f"invalid Number: {n!r} must be non-negative integer or one of A,R,G,.") if "Type" in entry: if entry["Type"] not in allowed_types: errors.append(f"invalid Type: {entry['Type']!r} must be one of {', '.join(allowed_types)}") if "Description" in entry: d = entry["Description"] if not isinstance(d, str) or not d.strip(): errors.append(f"invalid Description: {d!r} must be non-empty string") valid = len(errors) == 0 entries.append({"index": idx, "parsed": entry, "valid": valid, "errors": errors})valid_n = sum(1 for e in entries if e["valid"])invalid_n = len(entries) - valid_nreport = {"entries": entries, "summary": {"total": len(entries), "valid": valid_n, "invalid": invalid_n}}with open("/app/validation_report.json", "w") as f: json.dump(report, f, indent=2)print(json.dumps(report, indent=2))# bounded check: must have both valid and invalid to reflect mixed fixtureassert valid_n >= 1 and invalid_n >= 1, "report must distinguish valid and invalid"PYEOF
# --- Stage: finalize semantic checks ---echo "[finalize] checking final artifacts"ls -lh /app/vcfparser.py /app/docs/HEADER_SCHEMA.md /app/data/sample_header.vcf /app/parsed_output.json /app/validation_report.jsonpython3 <<'PYEOF'import jsonparsed = json.load(open("/app/parsed_output.json"))report = json.load(open("/app/validation_report.json"))assert isinstance(report, dict) and "entries" in report, "report needs entries"assert isinstance(report["entries"], list) and len(report["entries"]) == len(parsed), "entries must mirror parsed output"for e in report["entries"]: assert "parsed" in e and "valid" in e and "errors" in e, "each entry needs parsed/valid/errors" assert isinstance(e["valid"], bool), "valid must be bool" assert isinstance(e["errors"], list), "errors must be list" if e["valid"]: assert e["errors"] == [], f"valid entry must have no errors: {e}" else: assert len(e["errors"]) > 0, f"invalid entry must list errors: {e}" assert any(k in ";".join(e["errors"]) for k in ("ID","Number","Type","Description")), "errors must name field"# spot-check known semanticsby_id = {}for e in report["entries"]: pid = e["parsed"].get("ID") by_id.setdefault(pid, []).append(e)assert by_id.get("HQ", [{}])[0].get("valid") is True, "HQ must be valid"assert by_id.get("SB", [{}])[0].get("valid") is True, "SB must be valid"# invalid onesfor bad in ("BAD_NUM", "BAD_TYPE", "BAD_MISSING", ""): if bad in by_id: assert by_id[bad][0]["valid"] is False, f"{bad!r} must be invalid"print(f"finalize OK: total={report['summary']['total']} valid={report['summary']['valid']} invalid={report['summary']['invalid']}")PYEOF
echo "[done] all stages complete"cat /app/validation_report.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "stages": { "affordance_ranking": { "seconds": 49.927, "cost_usd": 0.000916, "llm_calls": 1 }, "contract": { "seconds": 46.866, "cost_usd": 0.000956, "llm_calls": 1 }, "solution": { "seconds": 118.423, "cost_usd": 0.002256, "llm_calls": 1 }, "verifier": { "seconds": 81.28, "cost_usd": 0.002095, "llm_calls": 1 }, "instruction": { "seconds": 35.779, "cost_usd": 0.000873, "llm_calls": 1 }, "env_align": { "seconds": 41.098, "cost_usd": 0.00092, "llm_calls": 1 }, "consistency_repair": { "seconds": 68.88, "cost_usd": 0.001316, "llm_calls": 1 }, "precheck": { "seconds": 2.712, "cost_usd": 0.0, "llm_calls": 0 } }, "lineage_id": "L296-y-0313", "round": 1, "total_seconds": 444.965, "total_cost_usd": 0.009332}12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338import osimport sysimport jsonimport reimport pathlibsys.path.insert(0, "/app")sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))import pytestfrom vcfparser import MetaDataParser, split_to_dict
SCHEMA_PATH = "/app/docs/HEADER_SCHEMA.md"HEADER_PATH = "/app/data/sample_header.vcf"PARSED_PATH = "/app/parsed_output.json"REPORT_PATH = "/app/validation_report.json"PARSER_PATH = "/app/vcfparser.py"ALLOWED_TYPES = {"Integer", "Float", "Flag", "String", "Character"}SYMBOLIC_NUMBERS = {"A", "R", "G", "."}ID_RE = re.compile(r"^[A-Za-z0-9_.\-]+$")
def _load_json(path): with open(path, "r") as f: return json.load(f)
def _as_entry_list(data): if isinstance(data, list): return data if isinstance(data, dict): for k in ("entries", "results", "report", "validations", "data", "items"): v = data.get(k) if isinstance(v, list): return v if isinstance(v, dict): # maybe mapping id -> result looks = [vv for vv in v.values() if isinstance(vv, dict) and any(x in vv for x in ("valid", "is_valid", "passed", "errors", "error"))] if looks: out = [] for kk, vv in v.items(): c = dict(vv) c.setdefault("ID", kk) c.setdefault("id", kk) out.append(c) return out # mapping form at top level: {"HQ": {"valid":..}, ...} vals = list(data.values()) if vals and all(isinstance(v, dict) for v in vals) and any(any(x in v for x in ("valid", "is_valid", "passed", "errors", "error")) for v in vals): out = [] for kk, vv in data.items(): c = dict(vv) c.setdefault("ID", kk) out.append(c) return out # single entry dict if any(x in data for x in ("valid", "is_valid", "passed", "ID", "id", "errors")): return [data] return None
def _get_valid(entry): for k in ("valid", "is_valid", "isValid", "passed", "ok"): if k in entry: v = entry[k] if isinstance(v, bool): return v if isinstance(v, (int, float)): return bool(v) if isinstance(v, str): s = v.strip().lower() if s in ("true", "1", "yes", "valid", "pass"): return True if s in ("false", "0", "no", "invalid", "fail"): return False return bool(v) return None
def _get_errors(entry): for k in ("errors", "error", "messages", "issues", "problems"): if k in entry: v = entry[k] if v is None: return [] if isinstance(v, list): return [str(x) for x in v] if isinstance(v, str): return [v] if v.strip() else [] return [str(v)] return None
def _get_entry_data(entry): for k in ("entry", "parsed", "record", "data", "input", "row", "item"): v = entry.get(k) if isinstance(v, dict) and any(x in v for x in ("ID", "id", "Number", "Type", "Description")): return v return entry
def _get_id(entry, entry_data): for src in (entry_data, entry): for k in ("ID", "id", "name"): if k in src and isinstance(src[k], (str, int)): return str(src[k]) return None
def _recompute(entry_data): bad = [] for f in ("ID", "Number", "Type", "Description"): if f not in entry_data: bad.append(f) if "ID" in entry_data: v = entry_data["ID"] if not isinstance(v, str) or not v.strip() or not ID_RE.match(str(v).strip()): if "ID" not in bad: bad.append("ID") if "Number" in entry_data: v = entry_data["Number"] ok = False if isinstance(v, bool): ok = False elif isinstance(v, int): ok = v >= 0 elif isinstance(v, float): ok = v.is_integer() and v >= 0 elif isinstance(v, str): s = v.strip() if s in SYMBOLIC_NUMBERS: ok = True elif re.fullmatch(r"\+?\d+", s): try: ok = int(s) >= 0 except Exception: ok = False else: ok = False else: ok = False if not ok and "Number" not in bad: bad.append("Number") if "Type" in entry_data: v = entry_data["Type"] if v not in ALLOWED_TYPES: if "Type" not in bad: bad.append("Type") if "Description" in entry_data: v = entry_data["Description"] if not isinstance(v, str) or not v.strip(): if "Description" not in bad: bad.append("Description") return (len(bad) == 0, bad)
def _live_ids(): p = MetaDataParser(HEADER_PATH) parsed = p.parse_lines() ids = [] for d in parsed: if isinstance(d, dict): v = d.get("ID", d.get("id")) ids.append("" if v is None else str(v)) return parsed, ids
def test_split_to_dict_basic(): input_str = "<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>" expected = { "ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality", } assert split_to_dict(input_str) == expected
def test_split_to_dict_with_spaces_and_quotes(): input_str = "< ID = HQ , Number = 2 , Type = Integer , Description = 'Haplotype Quality' >" expected = { "ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality", } assert split_to_dict(input_str) == expected
def test_split_to_dict_malformed_returns_empty(): assert split_to_dict("") == {} assert split_to_dict("<>") == {}
def test_metadata_parser_parse_lines(tmp_path): content = ( "##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\n" "##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>\n" ) header_path = tmp_path / "header.vcf" header_path.write_text(content) parser = MetaDataParser(str(header_path)) parsed = parser.parse_lines() assert isinstance(parsed, list) assert len(parsed) == 2 ids = [d.get("ID") for d in parsed] assert "HQ" in ids assert "SB" in ids
def test_parser_api_and_missing_file(): assert os.path.exists(PARSER_PATH), "parser module file missing" assert hasattr(MetaDataParser, "parse_lines"), "MetaDataParser.parse_lines missing" assert hasattr(MetaDataParser, "_parse_gvcf_block"), "MetaDataParser helper missing" assert callable(split_to_dict), "split_to_dict not callable" with pytest.raises(FileNotFoundError): MetaDataParser("/app/data/__definitely_missing_12345.vcf").parse_lines()
def test_check_01_required_evidence(): assert os.path.exists(SCHEMA_PATH), "schema doc not found" text = pathlib.Path(SCHEMA_PATH).read_text(errors="replace") assert len(text.strip()) > 100, "schema doc empty or trivial" for kw in ("ID", "Number", "Type", "Description"): assert kw in text, f"schema doc missing field {kw}" assert any(t in text for t in ("Integer", "Float", "String")), "schema doc missing allowed types" assert os.path.exists(HEADER_PATH), "sample header fixture not found" htext = pathlib.Path(HEADER_PATH).read_text(errors="replace") assert "##" in htext, "header fixture has no meta lines" assert "ID=" in htext, "header fixture has no meta entries" fixture_ids = re.findall(r"ID=([^,>\s]*)", htext) assert len(fixture_ids) >= 3, "header fixture should contain several entries" found_ref = False for p in (PARSED_PATH, REPORT_PATH): if os.path.exists(p): try: raw = pathlib.Path(p).read_text(errors="replace") except Exception: continue for fid in fixture_ids: if fid and fid in raw: found_ref = True break if found_ref: break assert found_ref, "parsed/report artifacts do not reference fixture content"
def test_check_02_intermediate_artifact(): assert os.path.exists(PARSED_PATH), "intermediate parsed output missing" data = _load_json(PARSED_PATH) lst = _as_entry_list(data) assert lst is not None, "intermediate output not a list or wrapping dict" assert len(lst) >= 3, f"intermediate output too small: {len(lst)}" ids = [] for e in lst: assert isinstance(e, dict), "intermediate entry not a dict" d = _get_entry_data(e) assert isinstance(d, dict), "intermediate entry data not a dict" v = d.get("ID", d.get("id")) assert v is not None, "intermediate entry missing ID" ids.append(str(v)) assert "HQ" in ids, "intermediate output missing expected HQ entry" live, live_ids = _live_ids() assert len(lst) == len(live), f"intermediate length {len(lst)} != live parser {len(live)}, possibly stale" for lid in live_ids: if lid == "": continue assert lid in ids, f"live parser ID {lid!r} missing from intermediate output"
def test_check_03_final_semantics(): assert os.path.exists(REPORT_PATH), "validation report missing" data = _load_json(REPORT_PATH) entries = _as_entry_list(data) assert entries is not None, "report is not a list of per-entry results" assert len(entries) >= 4, f"report too small: {len(entries)}" valids = [] invalids = [] id_to_valid = {} for e in entries: assert isinstance(e, dict), "report entry not a dict" v = _get_valid(e) assert v is not None, "report entry missing valid flag" d = _get_entry_data(e) eid = _get_id(e, d) if eid is not None: id_to_valid[eid] = v exp, _ = _recompute(d if isinstance(d, dict) else {}) assert v == exp, f"entry {eid!r} reported valid={v} but recomputed {exp} for {d}" (valids if v else invalids).append(eid) assert len(valids) >= 1 and len(invalids) >= 1, "report must contain both valid and invalid entries" if "HQ" in id_to_valid: assert id_to_valid["HQ"] is True, "HQ entry should be valid" for bad_id in ("BAD_NUM", "BAD_TYPE", "BAD_MISSING"): if bad_id in id_to_valid: assert id_to_valid[bad_id] is False, f"{bad_id} should be invalid" if "" in id_to_valid: assert id_to_valid[""] is False, "empty ID should be invalid"
def test_check_03b_error_details(): data = _load_json(REPORT_PATH) entries = _as_entry_list(data) assert entries is not None, "report unreadable" for e in entries: d = _get_entry_data(e) eid = _get_id(e, d) v = _get_valid(e) errs = _get_errors(e) assert errs is not None, f"entry {eid!r} missing errors list" exp_valid, bad_fields = _recompute(d) if exp_valid: assert v is True, f"entry {eid!r} should be valid" assert len(errs) == 0, f"valid entry {eid!r} should have empty errors" else: assert v is False, f"entry {eid!r} should be invalid" assert len(errs) >= 1, f"invalid entry {eid!r} must list errors" joined = " ".join(errs).lower() mentioned = any(bf.lower() in joined for bf in bad_fields) assert mentioned, f"errors for {eid!r} should name offending field {bad_fields}"
def test_check_04_no_shortcut(): assert os.path.exists(REPORT_PATH), "report missing" raw = pathlib.Path(REPORT_PATH).read_text(errors="replace") assert len(raw.strip()) > 50, "report empty or trivial" try: data = json.loads(raw) except Exception: pytest.fail("report is not parseable JSON") entries = _as_entry_list(data) assert entries is not None and len(entries) >= 4, "report too small, possible placeholder" low = raw.lower() assert "todo" not in low or len(entries) >= 4, "report looks like placeholder" assert "placeholder" not in low, "report contains placeholder" assert "lorem" not in low, "report contains filler" _, live_ids = _live_ids() live_set = set(x for x in live_ids if x != "") rep_ids = set() for e in entries: d = _get_entry_data(e) eid = _get_id(e, d) if eid is not None and eid != "": rep_ids.add(eid) assert len(rep_ids) >= 3, "report has too few distinct IDs" missing = live_set - rep_ids assert not missing, f"report stale: missing live IDs {missing}" extra_only_one = len(rep_ids) == 1 and len(live_set) > 1 assert not extra_only_one, "report hardcoded to single entry" vals = set(_get_valid(e) for e in entries) assert True in vals and False in vals, "report must show mixed valid/invalid, not hardcoded uniform" if os.path.exists(PARSED_PATH): praw = pathlib.Path(PARSED_PATH).read_text(errors="replace") assert len(praw.strip()) > 20, "intermediate output trivial" pdata = json.loads(praw) plst = _as_entry_list(pdata) assert plst is not None and len(plst) >= 3, "intermediate output too small"1234567891011121314151617181920212223242526272829303132333435363738394041424344FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytestRUN mkdir -p /app/docs /app/dataRUN cat > /app/docs/HEADER_SCHEMA.md <<'MDEOF'# VCF Header Schema — Meta Entries
This document defines validation rules for parsed VCF meta header dicts produced by `vcfparser.split_to_dict` / `MetaDataParser.parse_lines`.
## Required fields (completeness)Every parsed entry must contain all four keys:- `ID`- `Number`- `Type`- `Description`
Missing any required key => invalid. Extra keys are allowed and ignored.
## Field types and constraints- `ID`: must be a non-empty string matching `^[A-Za-z0-9_.\-]+$` (letters, digits, underscore, dot, hyphen). Empty or missing => invalid.- `Number`: must be either: - a non-negative integer (`0`, `1`, `2`, ...) with value `>= 0`, OR - one of the symbolic values `A`, `R`, `G`, `.` Anything else (negative integers, other strings like `two`, empty) => invalid. This covers type + range.- `Type`: must be exactly one of `Integer`, `Float`, `Flag`, `String`, `Character` (case-sensitive). Anything else => invalid.- `Description`: must be a non-empty string after stripping whitespace. Empty or missing => invalid.
## Examples- Valid: `<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>` => `{"ID":"HQ","Number":2,"Type":"Integer","Description":"Haplotype Quality"}`- Invalid: missing `Description`, `Number=-1` (out of range), `Type=BadType` (not allowed), `ID=` (empty).
## Validation reportValidators must emit per-entry `valid` boolean and `errors` list mentioning the offending field(s).MDEOFRUN cat > /app/data/sample_header.vcf <<'VCFEOF'##fileformat=VCFv4.2##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>##INFO=<ID=DP,Number=1,Type=Integer,Description='Total Depth'>##INFO=<ID=BAD_NUM,Number=-1,Type=Integer,Description='Negative number out of range'>##INFO=<ID=BAD_TYPE,Number=1,Type=BadType,Description='Invalid type value'>##INFO=<ID=BAD_MISSING,Number=1,Type=String>##INFO=<ID=,Number=1,Type=String,Description='Empty ID fails'>VCFEOF123Build a tiny single-file VCF header parser at /app/vcfparser.py providing MetaDataParser and split_to_dict. Keep block parsing faithful with trimmed keys, unquoted values and numeric conversion, returning {} for malformed input, and support reading a header file via parse_lines with FileNotFoundError if unreadable.
Then follow the schema doc and sample header under docs/ and data/ to derive completeness rules, run the parser over the sample header to save the raw conversion at /app/parsed_output.json, and validate every entry into a machine-readable report at /app/validation_report.json marking each entry valid with field-specific errors while preserving IDs and semantics without loss or invention.1{"metadata": {"lineage": "L296-y-0313", "round": "r2", "generation_method": "recursive-task-synthesis", "rounds": {"lineage_id": "L296-y-0313", "round": 2, "operator": "format_conversion_validation", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": {"status": "ok", "ranked_operators": [{"operator": "format_conversion_validation", "fit": "high", "reason": "Seed converts VCF header blocks to dicts and JSON report; validating semantic preservation is direct extension"}, {"operator": "aggregation_summary_report", "fit": "high", "reason": "Seed already emits per-entry valid/errors JSON; adding aggregate counts/summary is natural verifiable artifact"}, {"operator": "toolchain_availability_check", "fit": "medium", "reason": "Python/pytest/pip in Dockerfile exist so check is feasible but peripheral to parser workflow"}, {"operator": "container_build_alignment", "fit": "medium", "reason": "Dockerfile FROM python exists so alignment possible but tangential to validation goal"}, {"operator": "compile_link_package_workflow", "fit": "low", "reason": "Single-file pure-Python parser has no compile/link step; packaging would be forced"}, {"operator": "environment_variable_resolution", "fit": "low", "reason": "No .env, locale, timezone or shell init affordances in seed; would need invented env wiring"}], "blocked_operators": [{"operator": "schema_content_validation", "reason": "Would duplicate core HEADER_SCHEMA.md validation already central to task, not a new terminal subgoal"}, {"operator": "environment_variable_resolution", "reason": "Artificial for this seed: no env vars or runtime substrate signals to infer or configure"}], "rationale": "Preferred env-var operator lacks seed support; data/report operators best fit VCF-to-JSON validation workflow."}, "contract": {"status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "format_conversion_validation", "operator_fit": "fallback", "why_fit": "Seed parses VCF <...> blocks to dicts and JSON report; requiring validated format conversion directly extends that workflow", "goal": "Build VCF header parser and produce semantically faithful JSON conversion with validation report", "preserved_workflow": "Implement single-file vcfparser.py with split_to_dict and MetaDataParser, parse sample header, validate per schema doc, emit machine-readable validation_report.json", "new_requirement": "Also emit intermediate parsed_output.json raw conversion and prove validation_report.json preserves IDs, fields and semantics with no loss or invention", "task_chain": [{"stage": "inspect", "artifact_or_state": "docs/HEADER_SCHEMA.md and data/sample_header.vcf layout and rules to inspect"}, {"stage": "derive", "artifact_or_state": "required fields, types and completeness rules inferred from schema doc and fixture"}, {"stage": "execute", "artifact_or_state": "vcfparser.py implementation and parsed_output.json intermediate created by running parser"}, {"stage": "validate", "artifact_or_state": "local validation of every parsed entry with per-entry valid and field-specific errors"}, {"stage": "finalize", "artifact_or_state": "validation_report.json final deliverable semantically aligned to parsed conversion"}], "expected_artifacts": [{"path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "exists and defines required fields and type constraints"}, {"path": "/app/vcfparser.py", "role": "intermediate", "requirement": "provides split_to_dict and MetaDataParser with specified parsing behavior"}, {"path": "/app/parsed_output.json", "role": "intermediate", "requirement": "non-empty parseable JSON list of parsed dicts matching live parser output"}, {"path": "/app/validation_report.json", "role": "final", "requirement": "parseable per-entry valid boolean plus field-specific errors preserving IDs and semantics"}], "reward_checks": [{"name": "check_01_required_evidence", "checks": "schema doc and sample header exist and parser output covers their entries"}, {"name": "check_02_intermediate_artifact", "checks": "parsed_output.json present, parseable, non-empty and matches live parser results"}, {"name": "check_03_final_semantics", "checks": "validation_report.json valid flags and errors match recomputed schema rules per entry"}, {"name": "check_04_no_shortcut", "checks": "reject empty, placeholder, stale, hardcoded or semantically diverged conversion outputs"}], "instruction_boundary": {"mention": ["public goal", "fair starting docs and sample location", "main final deliverable and completion signal"], "hide": ["step-by-step commands", "path and field inventories", "schema and format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable details that belong in local docs"]}, "environment_changes": ["none"], "rationale": "Preferred env-var operator has no seed affordance; format conversion fits VCF-to-JSON workflow and adds verifiable preservation depth without new dependencies"}, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": {"ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.1}, "repair_log": []}, "stats": {"stages": {"affordance_ranking": {"seconds": 43.268, "cost_usd": 0.000955, "llm_calls": 1}, "contract": {"seconds": 38.547, "cost_usd": 0.001071, "llm_calls": 1}, "solution": {"seconds": 77.793, "cost_usd": 0.001852, "llm_calls": 1}, "verifier": {"seconds": 95.839, "cost_usd": 0.002314, "llm_calls": 1}, "instruction": {"seconds": 46.662, "cost_usd": 0.000858, "llm_calls": 1}, "env_align": {"seconds": 22.107, "cost_usd": 0.000564, "llm_calls": 1}, "consistency_repair": {"seconds": 128.572, "cost_usd": 0.002929, "llm_calls": 1}, "precheck": {"seconds": 2.353, "cost_usd": 0.0, "llm_calls": 0}}, "lineage_id": "L296-y-0313", "round": 2, "total_seconds": 455.141, "total_cost_usd": 0.010544}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158{ "lineage_id": "L296-y-0313", "round": 2, "operator": "format_conversion_validation", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": { "status": "ok", "ranked_operators": [ { "operator": "format_conversion_validation", "fit": "high", "reason": "Seed converts VCF header blocks to dicts and JSON report; validating semantic preservation is direct extension" }, { "operator": "aggregation_summary_report", "fit": "high", "reason": "Seed already emits per-entry valid/errors JSON; adding aggregate counts/summary is natural verifiable artifact" }, { "operator": "toolchain_availability_check", "fit": "medium", "reason": "Python/pytest/pip in Dockerfile exist so check is feasible but peripheral to parser workflow" }, { "operator": "container_build_alignment", "fit": "medium", "reason": "Dockerfile FROM python exists so alignment possible but tangential to validation goal" }, { "operator": "compile_link_package_workflow", "fit": "low", "reason": "Single-file pure-Python parser has no compile/link step; packaging would be forced" }, { "operator": "environment_variable_resolution", "fit": "low", "reason": "No .env, locale, timezone or shell init affordances in seed; would need invented env wiring" } ], "blocked_operators": [ { "operator": "schema_content_validation", "reason": "Would duplicate core HEADER_SCHEMA.md validation already central to task, not a new terminal subgoal" }, { "operator": "environment_variable_resolution", "reason": "Artificial for this seed: no env vars or runtime substrate signals to infer or configure" } ], "rationale": "Preferred env-var operator lacks seed support; data/report operators best fit VCF-to-JSON validation workflow." }, "contract": { "status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "format_conversion_validation", "operator_fit": "fallback", "why_fit": "Seed parses VCF <...> blocks to dicts and JSON report; requiring validated format conversion directly extends that workflow", "goal": "Build VCF header parser and produce semantically faithful JSON conversion with validation report", "preserved_workflow": "Implement single-file vcfparser.py with split_to_dict and MetaDataParser, parse sample header, validate per schema doc, emit machine-readable validation_report.json", "new_requirement": "Also emit intermediate parsed_output.json raw conversion and prove validation_report.json preserves IDs, fields and semantics with no loss or invention", "task_chain": [ { "stage": "inspect", "artifact_or_state": "docs/HEADER_SCHEMA.md and data/sample_header.vcf layout and rules to inspect" }, { "stage": "derive", "artifact_or_state": "required fields, types and completeness rules inferred from schema doc and fixture" }, { "stage": "execute", "artifact_or_state": "vcfparser.py implementation and parsed_output.json intermediate created by running parser" }, { "stage": "validate", "artifact_or_state": "local validation of every parsed entry with per-entry valid and field-specific errors" }, { "stage": "finalize", "artifact_or_state": "validation_report.json final deliverable semantically aligned to parsed conversion" } ], "expected_artifacts": [ { "path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "exists and defines required fields and type constraints" }, { "path": "/app/vcfparser.py", "role": "intermediate", "requirement": "provides split_to_dict and MetaDataParser with specified parsing behavior" }, { "path": "/app/parsed_output.json", "role": "intermediate", "requirement": "non-empty parseable JSON list of parsed dicts matching live parser output" }, { "path": "/app/validation_report.json", "role": "final", "requirement": "parseable per-entry valid boolean plus field-specific errors preserving IDs and semantics" } ], "reward_checks": [ { "name": "check_01_required_evidence", "checks": "schema doc and sample header exist and parser output covers their entries" }, { "name": "check_02_intermediate_artifact", "checks": "parsed_output.json present, parseable, non-empty and matches live parser results" }, { "name": "check_03_final_semantics", "checks": "validation_report.json valid flags and errors match recomputed schema rules per entry" }, { "name": "check_04_no_shortcut", "checks": "reject empty, placeholder, stale, hardcoded or semantically diverged conversion outputs" } ], "instruction_boundary": { "mention": [ "public goal", "fair starting docs and sample location", "main final deliverable and completion signal" ], "hide": [ "step-by-step commands", "path and field inventories", "schema and format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable details that belong in local docs" ] }, "environment_changes": [ "none" ], "rationale": "Preferred env-var operator has no seed affordance; format conversion fits VCF-to-JSON workflow and adds verifiable preservation depth without new dependencies" }, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": { "ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.1 }, "repair_log": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244#!/bin/bashset -eAPP=/appSCHEMA_DOC="$APP/docs/HEADER_SCHEMA.md"SAMPLE_VCF="$APP/data/sample_header.vcf"PARSER_PY="$APP/vcfparser.py"PARSED_JSON="$APP/parsed_output.json"REPORT_JSON="$APP/validation_report.json"
echo "[inspect] workspace layout"ls -R "$APP"echo "[inspect] schema doc"cat "$SCHEMA_DOC"echo "[inspect] sample header"cat "$SAMPLE_VCF"wc -l "$SAMPLE_VCF"grep -c "^##" "$SAMPLE_VCF" || trueecho "[inspect] existing parser if any"ls -l "$PARSER_PY" 2>&1 || echo "no parser yet"
echo "[derive] required fields and constraints from schema doc"grep -E "ID|Number|Type|Description" "$SCHEMA_DOC" | head -20grep -E "Integer|Float|Flag|String|Character" "$SCHEMA_DOC" | head -20grep -E "Required|Missing|Invalid|valid" "$SCHEMA_DOC" | head -20echo "[derive] fixture IDs present"grep -o "ID=[^,>]*" "$SAMPLE_VCF" || trueecho "[derive] raw blocks"grep -o "<[^>]*>" "$SAMPLE_VCF" || true
cat > "$PARSER_PY" <<'PYEOF'"""Tiny single-file VCF header parser."""
def split_to_dict(string: str) -> dict: """Parse a VCF meta block like <ID=HQ,Number=2,...> into a dict.""" if not isinstance(string, str): return {} if not string or not string.strip(): return {} s = string.strip() if s.startswith("<"): s = s[1:] if s.endswith(">"): s = s[:-1] s = s.strip() if not s: return {} parts = [] current = "" in_single = False in_double = False for ch in s: if ch == "'" and not in_double: in_single = not in_single current += ch elif ch == '"' and not in_single: in_double = not in_double current += ch elif ch == "," and not in_single and not in_double: parts.append(current) current = "" else: current += ch parts.append(current) result = {} for part in parts: part = part.strip() if not part: return {} if "=" not in part: return {} k, v = part.split("=", 1) k = k.strip() v = v.strip() if not k: return {} if len(v) >= 2 and ((v[0] == "'" and v[-1] == "'") or (v[0] == '"' and v[-1] == '"')): v = v[1:-1] if isinstance(v, str): vs = v.strip() if vs.isdigit(): v = int(vs) elif vs.startswith("-") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) elif vs.startswith("+") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) else: v = v result[k] = v if not result: return {} return result
class MetaDataParser: """Parse VCF header files for meta blocks.""" def __init__(self, header_file: str): self.header_file = header_file def _parse_block(self, line: str) -> dict: if not isinstance(line, str): return {} if "<" not in line or ">" not in line: return {} try: start = line.find("<") end = line.rfind(">") if start < 0 or end < 0 or start >= end: return {} block = line[start:end+1] parsed = split_to_dict(block) return parsed if isinstance(parsed, dict) else {} except Exception: return {} def parse_lines(self): try: fh = open(self.header_file, "r") except FileNotFoundError: raise except OSError as e: raise FileNotFoundError(str(e)) from e results = [] with fh: for line in fh: line = line.strip() if not line: continue if "<" not in line or ">" not in line: continue d = self._parse_block(line) if d: results.append(d) return resultsPYEOFecho "[execute] parser written"python3 -c "import vcfparser; print(vcfparser.split_to_dict(\"<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\"))"
echo "[execute] running parser over sample header to create intermediate"python3 <<'PYEOF'import jsonfrom vcfparser import MetaDataParserparser = MetaDataParser("/app/data/sample_header.vcf")parsed = parser.parse_lines()print(f"parsed {len(parsed)} entries")for d in parsed: print(d)with open("/app/parsed_output.json", "w") as f: json.dump(parsed, f, indent=2)print("wrote /app/parsed_output.json")PYEOFcat "$PARSED_JSON"python3 -c "import json; d=json.load(open('$PARSED_JSON')); assert isinstance(d,list) and len(d)>0, 'intermediate empty'; print(f'intermediate ok: {len(d)} entries')"
echo "[validate] bounded validation of intermediate artifacts"python3 <<'PYEOF'import jsonparsed = json.load(open("/app/parsed_output.json"))assert isinstance(parsed, list), "parsed_output must be list"assert len(parsed) > 0, "parsed_output must be non-empty"from vcfparser import MetaDataParserlive = MetaDataParser("/app/data/sample_header.vcf").parse_lines()assert parsed == live, "parsed_output must match live parser output"print(f"validated intermediate: {len(parsed)} entries match live parser")for d in parsed: assert isinstance(d, dict) and len(d) > 0 for k, v in d.items(): assert k == k.strip(), f"key not trimmed: {k!r}" if isinstance(v, str): assert not (len(v) >= 2 and v[0]=="'" and v[-1]=="'"), f"value still quoted: {v!r}"print("intermediate field hygiene ok")PYEOF
echo "[finalize] building validation_report.json preserving IDs and semantics"python3 <<'PYEOF'import json, reparsed = json.load(open("/app/parsed_output.json"))ALLOWED = {"Integer", "Float", "Flag", "String", "Character"}SYMBOLIC = {"A", "R", "G", "."}ID_RE = re.compile(r"^[A-Za-z0-9_.\-]+$")report = []for entry in parsed: errors = [] for f in ("ID", "Number", "Type", "Description"): if f not in entry: errors.append(f"{f}: missing required field") if "ID" in entry: v = entry["ID"] if not isinstance(v, str) or not v.strip() or not ID_RE.match(v.strip()): if not any(e.startswith("ID") for e in errors): errors.append("ID: invalid ID must match ^[A-Za-z0-9_.\\-]+$ and be non-empty") if "Number" in entry: v = entry["Number"] ok = False if isinstance(v, bool): ok = False elif isinstance(v, int): ok = v >= 0 elif isinstance(v, float): ok = v.is_integer() and v >= 0 elif isinstance(v, str): s = v.strip() if s in SYMBOLIC: ok = True elif re.fullmatch(r"\+?\d+", s): try: ok = int(s) >= 0 except Exception: ok = False else: ok = False else: ok = False if not ok and not any(e.startswith("Number") for e in errors): errors.append("Number: invalid must be non-negative integer or one of A,R,G,.") if "Type" in entry: if entry["Type"] not in ALLOWED and not any(e.startswith("Type") for e in errors): errors.append("Type: invalid must be one of Integer,Float,Flag,String,Character") if "Description" in entry: v = entry["Description"] if not isinstance(v, str) or not v.strip(): if not any(e.startswith("Description") for e in errors): errors.append("Description: invalid must be non-empty string") valid = len(errors) == 0 rec = dict(entry) rec["valid"] = valid rec["errors"] = errors report.append(rec)with open("/app/validation_report.json", "w") as f: json.dump(report, f, indent=2)print(f"wrote /app/validation_report.json with {len(report)} entries")PYEOFcat "$REPORT_JSON"python3 <<'PYEOF'import jsonfrom vcfparser import MetaDataParserparsed = json.load(open("/app/parsed_output.json"))report = json.load(open("/app/validation_report.json"))assert isinstance(report, list) and len(report) == len(parsed), "report must align 1:1 with parsed"for r, p in zip(report, parsed): assert isinstance(r, dict) assert "valid" in r and isinstance(r["valid"], bool) assert "errors" in r and isinstance(r["errors"], list) assert str(r.get("ID")) == str(p.get("ID")), f"ID not preserved: {r} vs {p}"print("finalize semantics ok")PYEOFecho "done"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "stages": { "affordance_ranking": { "seconds": 43.268, "cost_usd": 0.000955, "llm_calls": 1 }, "contract": { "seconds": 38.547, "cost_usd": 0.001071, "llm_calls": 1 }, "solution": { "seconds": 77.793, "cost_usd": 0.001852, "llm_calls": 1 }, "verifier": { "seconds": 95.839, "cost_usd": 0.002314, "llm_calls": 1 }, "instruction": { "seconds": 46.662, "cost_usd": 0.000858, "llm_calls": 1 }, "env_align": { "seconds": 22.107, "cost_usd": 0.000564, "llm_calls": 1 }, "consistency_repair": { "seconds": 128.572, "cost_usd": 0.002929, "llm_calls": 1 }, "precheck": { "seconds": 2.353, "cost_usd": 0.0, "llm_calls": 0 } }, "lineage_id": "L296-y-0313", "round": 2, "total_seconds": 455.141, "total_cost_usd": 0.010544}12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360import osimport sysimport jsonimport reimport pathlibimport tempfilesys.path.insert(0, "/app")import pytestfrom vcfparser import MetaDataParser, split_to_dict
SCHEMA_PATH = "/app/docs/HEADER_SCHEMA.md"HEADER_PATH = "/app/data/sample_header.vcf"PARSED_PATH = "/app/parsed_output.json"REPORT_PATH = "/app/validation_report.json"PARSER_PATH = "/app/vcfparser.py"ALLOWED_TYPES = {"Integer", "Float", "Flag", "String", "Character"}SYMBOLIC_NUMBERS = {"A", "R", "G", "."}ID_RE = re.compile(r"^[A-Za-z0-9_.\-]+$")
def _load_json(path): with open(path, "r") as f: return json.load(f)
def _as_entry_list(data): if isinstance(data, list): return data if isinstance(data, dict): for k in ("entries", "results", "report", "validations", "data", "items"): v = data.get(k) if isinstance(v, list): return v if isinstance(v, dict): looks = [vv for vv in v.values() if isinstance(vv, dict) and any(x in vv for x in ("valid", "is_valid", "passed", "errors", "error"))] if looks: out = [] for kk, vv in v.items(): c = dict(vv) c.setdefault("ID", kk) c.setdefault("id", kk) out.append(c) return out vals = list(data.values()) if vals and all(isinstance(v, dict) for v in vals) and any(any(x in v for x in ("valid", "is_valid", "passed", "errors", "error")) for v in vals): out = [] for kk, vv in data.items(): c = dict(vv) c.setdefault("ID", kk) out.append(c) return out if any(x in data for x in ("valid", "is_valid", "passed", "ID", "id", "errors")): return [data] return None
def _get_valid(entry): for k in ("valid", "is_valid", "isValid", "passed", "ok"): if k in entry: v = entry[k] if isinstance(v, bool): return v if isinstance(v, (int, float)): return bool(v) if isinstance(v, str): s = v.strip().lower() if s in ("true", "1", "yes", "valid", "pass"): return True if s in ("false", "0", "no", "invalid", "fail"): return False return bool(v) return None
def _get_errors(entry): for k in ("errors", "error", "messages", "issues", "problems"): if k in entry: v = entry[k] if v is None: return [] if isinstance(v, list): return [str(x) for x in v] if isinstance(v, str): return [v] if v.strip() else [] return [str(v)] return None
def _get_entry_data(entry): for k in ("entry", "parsed", "record", "data", "input", "row", "item", "source"): v = entry.get(k) if isinstance(v, dict) and any(x in v for x in ("ID", "id", "Number", "Type", "Description")): return v return entry
def _get_id(entry, entry_data): for src in (entry_data, entry): for k in ("ID", "id", "name"): if k in src and isinstance(src[k], (str, int)): return str(src[k]) return None
def _recompute(entry_data): bad = [] for f in ("ID", "Number", "Type", "Description"): if f not in entry_data and f.lower() not in {k.lower() for k in entry_data.keys()}: # check case-insensitive presence for robustness, but require canonical has = any(k == f or k.lower() == f.lower() for k in entry_data.keys()) if not has: bad.append(f) # normalize lookup case-sensitively first lookup = dict(entry_data) # allow lowercase id fallback if "ID" not in lookup and "id" in lookup: lookup["ID"] = lookup["id"] if "ID" in lookup: v = lookup["ID"] if not isinstance(v, str) or not v.strip() or not ID_RE.match(str(v).strip()): if "ID" not in bad: bad.append("ID") if "Number" in lookup: v = lookup["Number"] ok = False if isinstance(v, bool): ok = False elif isinstance(v, int): ok = v >= 0 elif isinstance(v, float): ok = v.is_integer() and v >= 0 elif isinstance(v, str): s = v.strip() if s in SYMBOLIC_NUMBERS: ok = True elif re.fullmatch(r"\+?\d+", s): try: ok = int(s) >= 0 except Exception: ok = False else: ok = False else: ok = False if not ok and "Number" not in bad: bad.append("Number") if "Type" in lookup: v = lookup["Type"] if v not in ALLOWED_TYPES: if "Type" not in bad: bad.append("Type") if "Description" in lookup: v = lookup["Description"] if not isinstance(v, str) or not v.strip(): if "Description" not in bad: bad.append("Description") return (len(bad) == 0, bad)
def _live_parsed(): return MetaDataParser(HEADER_PATH).parse_lines()
# ---- reward check 01 ----def test_check_01_required_evidence(): assert os.path.isfile(SCHEMA_PATH), "schema doc missing" assert os.path.isfile(HEADER_PATH), "sample header missing" assert os.path.isfile(PARSER_PATH), "parser file missing" text = pathlib.Path(SCHEMA_PATH).read_text(errors="replace") for field in ("ID", "Number", "Type", "Description"): assert field in text, f"schema doc must define {field}" header_text = pathlib.Path(HEADER_PATH).read_text(errors="replace") assert "##" in header_text, "sample header must contain ## lines" assert "ID=" in header_text, "sample header must contain ID entries" live = _live_parsed() assert isinstance(live, list) and len(live) > 0, "live parser must yield entries from sample" raw_ids = re.findall(r"ID=([^,>]*)", header_text) assert len(live) >= max(1, len([r for r in raw_ids if r.strip() != ""])) - 2, "parser output must cover sample entries" parsed_file_ids = set() if os.path.isfile(PARSED_PATH): try: d = _load_json(PARSED_PATH) assert isinstance(d, list), "parsed output must be list" for e in d: if isinstance(e, dict): v = e.get("ID", e.get("id")) if v is not None: parsed_file_ids.add(str(v)) except Exception: pass live_ids = set(str(e.get("ID", e.get("id", ""))) for e in live if isinstance(e, dict)) if parsed_file_ids: assert len(set(live_ids) & parsed_file_ids) > 0, "parsed file must cover live IDs"
# ---- reward check 02 ----def test_check_02_intermediate_artifact(): assert os.path.isfile(PARSED_PATH), "parsed_output.json missing" assert os.path.getsize(PARSED_PATH) > 10, "parsed_output.json empty" data = _load_json(PARSED_PATH) assert isinstance(data, list), "parsed_output.json must be JSON list" assert len(data) > 0, "parsed_output.json must be non-empty" for e in data: assert isinstance(e, dict) and len(e) > 0, "each parsed entry must be non-empty dict" live = _live_parsed() assert len(data) == len(live), f"parsed file length {len(data)} != live {len(live)}, stale or diverged" assert data == live, "parsed_output.json must equal live parser output"
def test_check_02_intermediate_hygiene(): data = _load_json(PARSED_PATH) assert isinstance(data, list) and len(data) > 0, "intermediate missing" for e in data: for k, v in e.items(): assert k == k.strip(), f"key not trimmed: {k!r}" assert k != "", "empty key" for f in ("ID", "Type", "Description"): if f in e and isinstance(e[f], str): v = e[f] assert not (len(v) >= 2 and ((v[0] == "'" and v[-1] == "'") or (v[0] == '"' and v[-1] == '"'))), f"value still quoted for {f}: {v!r}" nums = [e.get("Number") for e in data if isinstance(e, dict) and "Number" in e] assert len(nums) > 0, "no Number fields found" int_like = [n for n in nums if isinstance(n, int) and not isinstance(n, bool)] assert len(int_like) > 0, "numeric conversion missing: expected int Number values"
# ---- reward check 03 ----def test_check_03_final_semantics(): assert os.path.isfile(REPORT_PATH), "validation_report.json missing" assert os.path.getsize(REPORT_PATH) > 10, "validation report empty" raw = _load_json(REPORT_PATH) entries = _as_entry_list(raw) assert entries is not None, "report must contain entry list" assert isinstance(entries, list) and len(entries) > 0, "report entry list empty" live = _live_parsed() assert len(entries) == len(live), f"report length {len(entries)} != parsed {len(live)}" for i, entry in enumerate(entries): assert isinstance(entry, dict), f"report entry {i} must be dict" valid = _get_valid(entry) assert valid is not None and isinstance(valid, bool), f"entry {i} missing boolean valid flag" errs = _get_errors(entry) assert errs is not None, f"entry {i} missing errors list" assert isinstance(errs, list), f"entry {i} errors must be list" edata = _get_entry_data(entry) # resolve full parsed dict for recompute: prefer embedded data if complete else live candidate = None if isinstance(edata, dict) and all(k in edata or "id" in edata for k in ("ID",)) and len([k for k in ("ID", "Number", "Type", "Description") if k in edata or k.lower() in {x.lower() for x in edata}]) >= 3: # if embedded looks complete use live-aligned check: use live entry when IDs match else embedded eid = _get_id(entry, edata) lid = str(live[i].get("ID", live[i].get("id", ""))) if isinstance(live[i], dict) else None if eid == lid: candidate = live[i] else: candidate = edata else: candidate = live[i] if i < len(live) else edata exp_valid, bad = _recompute(candidate) assert valid == exp_valid, f"entry {i} valid={valid} expected {exp_valid} bad={bad} data={candidate}" if exp_valid: assert len(errs) == 0, f"valid entry {i} must have empty errors, got {errs}" else: assert len(errs) > 0, f"invalid entry {i} must list errors, bad={bad}" joined = " ".join(errs) for f in bad: assert f.lower() in joined.lower(), f"entry {i} errors must mention {f}, got {errs}"
def test_check_03_final_ids_preserved(): raw = _load_json(REPORT_PATH) entries = _as_entry_list(raw) assert entries is not None and len(entries) > 0, "report missing" live = _live_parsed() live_ids = [str(d.get("ID", d.get("id", ""))) if isinstance(d, dict) else "" for d in live] rep_ids = [] for e in entries: ed = _get_entry_data(e) rid = _get_id(e, ed) assert rid is not None, f"report entry missing ID: {e}" rep_ids.append(str(rid)) assert len(rep_ids) == len(live_ids), f"ID count mismatch report {len(rep_ids)} vs live {len(live_ids)}" assert set(rep_ids) == set(live_ids), f"IDs diverged: report {set(rep_ids)} vs live {set(live_ids)}" # no loss: every live ID present for lid in live_ids: assert lid in rep_ids, f"live ID {lid!r} lost in report" # order preserved when report is positional list if len(rep_ids) == len(live_ids): # allow dict-mapping wrappers to differ in order, but list reports should align raw_is_list = isinstance(raw, list) if raw_is_list: assert rep_ids == live_ids, f"report order diverged: {rep_ids} vs {live_ids}"
# ---- reward check 04 ----def test_check_04_no_shortcut(): pdata = _load_json(PARSED_PATH) assert isinstance(pdata, list) and len(pdata) > 0, "parsed empty" rraw = _load_json(REPORT_PATH) rentries = _as_entry_list(rraw) assert rentries is not None and len(rentries) > 0, "report empty" # reject placeholder strings for blob, name in [(json.dumps(pdata), "parsed"), (json.dumps(rraw), "report")]: low = blob.lower() for ph in ("todo", "placeholder", "lorem", "example output"): assert ph not in low, f"{name} contains placeholder {ph}" # reject trivial all-valid / all-invalid report (fixture has both) flags = [_get_valid(e) for e in rentries] assert all(isinstance(f, bool) for f in flags), "report flags missing" assert any(flags) and not all(flags), "report must contain both valid and invalid entries for this fixture" # reject empty-string IDs invented or dropped: parsed IDs must include known goods and bads pids = set(str(e.get("ID", e.get("id", ""))) for e in pdata if isinstance(e, dict)) assert "HQ" in pids, "parsed must preserve HQ" assert "BAD_NUM" in pids or "BAD_TYPE" in pids or "BAD_MISSING" in pids, "parsed must preserve invalid fixture IDs" # stale check: live re-execution must match file live = _live_parsed() assert pdata == live, "parsed stale vs live parser" # hardcoded parser check: novel block must parse correctly probe = split_to_dict("<ID=PROBE_X1,Number=A,Type=Float,Description='Probe desc'>") assert probe.get("ID") == "PROBE_X1", "parser looks hardcoded" assert probe.get("Number") == "A", "symbolic Number must stay string" assert probe.get("Type") == "Float", "parser diverged on novel input" # diverged semantics: report flags must match recompute (already strict, spot-check HQ valid) hq_idx = next((i for i, d in enumerate(live) if isinstance(d, dict) and d.get("ID") == "HQ"), None) assert hq_idx is not None, "live HQ missing" assert _get_valid(rentries[hq_idx]) is True, "HQ must be valid" bad_idx = next((i for i, d in enumerate(live) if isinstance(d, dict) and d.get("ID") == "BAD_TYPE"), None) if bad_idx is not None: assert _get_valid(rentries[bad_idx]) is False, "BAD_TYPE must be invalid" # report must not be mere copy of parsed (must add valid/errors) for e in rentries: assert _get_valid(e) is not None and _get_errors(e) is not None, "report missing valid/errors"
# ---- preserved seed behavior ----def test_split_to_dict_basic(): s = "<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>" exp = {"ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality"} assert split_to_dict(s) == exp
def test_split_to_dict_with_spaces_and_quotes(): s = "< ID = HQ , Number = 2 , Type = Integer , Description = 'Haplotype Quality' >" exp = {"ID": "HQ", "Number": 2, "Type": "Integer", "Description": "Haplotype Quality"} assert split_to_dict(s) == exp
def test_split_to_dict_malformed_returns_empty(): assert split_to_dict("") == {} assert split_to_dict(" ") == {} assert split_to_dict("no-equals-here") == {} assert split_to_dict("<IDHQ,Number>") == {} assert split_to_dict("<,>") == {}
def test_split_to_dict_numeric_and_unquote(): d = split_to_dict("<ID=X,Number=0,Type=String,Description=\"hello\">") assert d["Number"] == 0 and isinstance(d["Number"], int), "numeric conversion required" assert d["Description"] == "hello", "unquoting required" d2 = split_to_dict("<ID=Y,Number=A,Type=Float,Description='d'>") assert d2["Number"] == "A", "symbolic Number must remain string"
def test_metadata_parser_parse_lines(): p = MetaDataParser(HEADER_PATH) lines = p.parse_lines() assert isinstance(lines, list) and len(lines) >= 5, "expected multiple parsed entries" for d in lines: assert isinstance(d, dict) and "ID" in d, f"each entry needs ID: {d}" ids = [d.get("ID") for d in lines] assert "HQ" in ids, "HQ missing from parse_lines" assert "DP" in ids or "SB" in ids, "expected fixture IDs missing"
def test_metadata_parser_missing_file(): with pytest.raises(FileNotFoundError): MetaDataParser("/app/data/does_not_exist_12345.vcf").parse_lines() with tempfile.NamedTemporaryFile(mode="w", suffix=".vcf", delete=True) as tf: tf.write("##INFO=<ID=T1,Number=1,Type=String,Description='t'>\n") tf.flush() out = MetaDataParser(tf.name).parse_lines() assert out == [{"ID": "T1", "Number": 1, "Type": "String", "Description": "t"}]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytestRUN mkdir -p /app/docs /app/dataRUN cat > /app/docs/HEADER_SCHEMA.md <<'MDEOF'# VCF Header Schema — Meta Entries
This document defines validation rules for parsed VCF meta header dicts produced by `vcfparser.split_to_dict` / `MetaDataParser.parse_lines`.
## Required fields (completeness)Every parsed entry must contain all four keys:- `ID`- `Number`- `Type`- `Description`
Missing any required key => invalid. Extra keys are allowed and ignored.
## Field types and constraints- `ID`: must be a non-empty string matching `^[A-Za-z0-9_.\-]+$` (letters, digits, underscore, dot, hyphen). Empty or missing => invalid.- `Number`: must be either: - a non-negative integer (`0`, `1`, `2`, ...) with value `>= 0`, OR - one of the symbolic values `A`, `R`, `G`, `.` Anything else (negative integers, other strings like `two`, empty) => invalid. This covers type + range.- `Type`: must be exactly one of `Integer`, `Float`, `Flag`, `String`, `Character` (case-sensitive). Anything else => invalid.- `Description`: must be a non-empty string after stripping whitespace. Empty or missing => invalid.
## Examples- Valid: `<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>` => `{"ID":"HQ","Number":2,"Type":"Integer","Description":"Haplotype Quality"}`- Invalid: missing `Description`, `Number=-1` (out of range), `Type=BadType` (not allowed), `ID=` (empty).
## Validation reportValidators must emit per-entry `valid` boolean and `errors` list mentioning the offending field(s).MDEOFRUN cat > /app/data/sample_header.vcf <<'VCFEOF'##fileformat=VCFv4.2##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>##INFO=<ID=DP,Number=1,Type=Integer,Description='Total Depth'>##INFO=<ID=BAD_NUM,Number=-1,Type=Integer,Description='Negative number out of range'>##INFO=<ID=BAD_TYPE,Number=1,Type=BadType,Description='Invalid type value'>##INFO=<ID=BAD_MISSING,Number=1,Type=String>##INFO=<ID=,Number=1,Type=String,Description='Empty ID fails'>VCFEOFRUN cat > /app/docs/SUMMARY_SPEC.md <<'MDEOF'# Summary Report Spec — Aggregation over validation_report.json
This document defines the machine-readable aggregate at `/app/summary.json`.
## Source- Input is `validation_report.json`: list of per-entry objects each with `valid` boolean and `errors` list mentioning offending field(s).- Entry identity preserved via `ID` (or `entry.ID`).
## Required summary fields- `total` (int): total number of validation entries. Alias `total_entries`.- `valid` (int): count of entries where `valid` is true. Alias `valid_count`.- `invalid` (int): count of entries where `valid` is false. Alias `invalid_count`. Must equal `total - valid`.- `errors_by_field` (object): map of field name -> count of entries whose `errors` mention that field. Aliases `error_breakdown`, `by_field`. - Keys cover `ID`, `Number`, `Type`, `Description` (include all four with 0 default). - Counting rule: for each entry, if an error string contains the field name substring (case-sensitive), increment that field once per entry (deduplicated per entry).- `source` (string, optional): name of input file aggregated (`validation_report.json`).
## Aggregation rules- `total` equals length of validation report list.- `valid` equals number of entries with `valid` true; `invalid` equals number with `valid` false.- Reconciliation: `total == valid + invalid` and `invalid == total - valid`.- `errors_by_field` counts are derived from `errors` strings per entry, one increment per field per entry at most.- Output must be JSON object written to `/app/summary.json` and parseable with `python3 -m json.tool` or `jq`.- Counts must reconcile with the live `validation_report.json` when checked via terminal CLI composition (e.g. `jq`, `python3 -c`, `grep -c`).MDEOF12345Build a tiny single-file VCF header parser in /app providing MetaDataParser and split_to_dict. Keep block parsing faithful with trimmed keys, unquoted values and numeric conversion, returning {} for malformed input, and support reading a header file via parse_lines with FileNotFoundError if unreadable.
Then follow the schema doc and sample header under docs/ and data/ to derive completeness rules, run the parser over the sample header to save the raw conversion and validate every entry into a machine-readable validation report marking each entry valid with field-specific errors while preserving IDs without loss.
Aggregate the validation report into a machine-readable summary at /app/summary.json following docs/SUMMARY_SPEC.md for totals and field-level error breakdown, using terminal CLI composition to reconcile counts.1{"metadata": {"lineage": "L296-y-0313", "round": "r3", "generation_method": "recursive-task-synthesis", "rounds": {"lineage_id": "L296-y-0313", "round": 3, "operator": "aggregation_summary_report", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": {"status": "ok", "ranked_operators": [{"operator": "config_data_consistency", "fit": "high", "reason": "Seed core reconciles docs/HEADER_SCHEMA.md rules with data/sample_header.vcf into parsed_output and validation_report; directly supported."}, {"operator": "aggregation_summary_report", "fit": "high", "reason": "Seed already produces JSON artifacts; aggregate valid/invalid counts and error breakdown via CLI is natural verifiable extension."}, {"operator": "container_build_alignment", "fit": "medium", "reason": "Dockerfile FROM python:3.10-slim exists, alignment check feasible with small addition but peripheral to VCF workflow."}, {"operator": "toolchain_availability_check", "fit": "medium", "reason": "pip/python/pytest signals exist, check feasible via terminal but superficial versus data validation goal."}, {"operator": "environment_variable_resolution", "fit": "low", "reason": "No .env or env-var-dependent parser behavior; would require inventing unrelated locale/profile substrate."}, {"operator": "compile_link_package_workflow", "fit": "low", "reason": "Single-file Python parser has no compile/link/package affordance; artificial for this seed."}], "blocked_operators": [{"operator": "schema_content_validation", "reason": "Would duplicate existing schema-driven validation as narrow check without new terminal exploration."}, {"operator": "format_conversion_validation", "reason": "Isolated JSON conversion check is superficial; seed JSON handling already covered by report artifacts."}], "rationale": "Preferred env-var operator lacks affordance; config-data consistency and aggregation report best fit existing schema/data/report workflow."}, "contract": {"status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "aggregation_summary_report", "operator_fit": "fallback", "why_fit": "preferred environment_variable_resolution has no .env, locale, timezone or profile affordance in VCF parser seed and would be invented; aggregation naturally extends existing parsed_output and validation_report JSON workflow", "goal": "Build VCF header parser, validate sample header, and produce aggregate summary report", "preserved_workflow": "single-file vcfparser.py with split_to_dict and MetaDataParser.parse_lines, raw conversion to parsed_output.json, per-entry validation_report.json per docs/HEADER_SCHEMA.md and data/sample_header.vcf", "new_requirement": "compute valid/invalid totals and field-level error breakdown from validation results via terminal CLI composition into a machine-readable summary report", "task_chain": [{"stage": "inspect", "artifact_or_state": "workspace layout, docs/HEADER_SCHEMA.md, data/sample_header.vcf and vcfparser.py source/build output to inspect via ls/cat/grep"}, {"stage": "derive", "artifact_or_state": "completeness rules and aggregation keys to infer from local schema doc and sample header evidence"}, {"stage": "execute", "artifact_or_state": "parser, parsed_output.json, validation_report.json and summary report to create by editing and running python/CLI"}, {"stage": "validate", "artifact_or_state": "local JSON parseability, count reconciliation and CLI output evidence to validate"}, {"stage": "finalize", "artifact_or_state": "final summary report with totals and breakdown as checked deliverable"}], "expected_artifacts": [{"path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "exists and defines required ID/Number/Type/Description rules"}, {"path": "/app/data/sample_header.vcf", "role": "evidence", "requirement": "exists with ## header lines and ID entries for parsing"}, {"path": "/app/vcfparser.py", "role": "intermediate", "requirement": "provides split_to_dict and MetaDataParser.parse_lines with faithful block parsing"}, {"path": "/app/parsed_output.json", "role": "intermediate", "requirement": "non-empty list matching live parser output over sample header"}, {"path": "/app/validation_report.json", "role": "intermediate", "requirement": "per-entry valid boolean and field-specific errors preserving IDs without loss"}, {"path": "/app/summary.json", "role": "final", "requirement": "machine-readable aggregates with totals and error breakdown reconciling validation_report"}], "reward_checks": [{"name": "check_01_required_evidence", "checks": "schema doc and sample header exist and parser honors discoverable rules"}, {"name": "check_02_intermediate_artifact", "checks": "parsed_output and validation_report present, parseable, non-empty and consistent with live parser"}, {"name": "check_03_final_semantics", "checks": "summary totals and error breakdown semantically reconcile with validation_report entries"}, {"name": "check_04_no_shortcut", "checks": "reject empty, placeholder, stale, hardcoded or verifier-only outputs with no real derivation"}], "instruction_boundary": {"mention": ["public goal", "at most 1-2 fair starting points", "main final deliverable or completion signal", "only undiscoverable hard acceptance constants"], "hide": ["step-by-step commands", "path/field inventories", "schema/format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable details that belong in local docs"]}, "environment_changes": ["add docs/SUMMARY_SPEC.md defining summary fields and aggregation rules as discoverable workspace evidence"], "rationale": "aggregation_summary_report extends parser plus validation workflow with terminal-native counting and reporting depth while staying verifiable via JSON reconciliation and rejecting shortcuts, harder but controllable"}, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": {"ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.6}, "repair_log": []}, "stats": {"stages": {"affordance_ranking": {"seconds": 44.705, "cost_usd": 0.001018, "llm_calls": 1}, "contract": {"seconds": 58.987, "cost_usd": 0.001358, "llm_calls": 1}, "solution": {"seconds": 88.397, "cost_usd": 0.002307, "llm_calls": 1}, "verifier": {"seconds": 190.066, "cost_usd": 0.005746, "llm_calls": 2}, "instruction": {"seconds": 34.835, "cost_usd": 0.00094, "llm_calls": 1}, "env_align": {"seconds": 39.06, "cost_usd": 0.001037, "llm_calls": 1}, "consistency_repair": {"seconds": 86.509, "cost_usd": 0.002471, "llm_calls": 1}, "precheck": {"seconds": 2.953, "cost_usd": 0.0, "llm_calls": 0}}, "lineage_id": "L296-y-0313", "round": 3, "total_seconds": 545.512, "total_cost_usd": 0.014878}}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169{ "lineage_id": "L296-y-0313", "round": 3, "operator": "aggregation_summary_report", "family": "data_artifact_report_processing", "operator_fit": "fallback", "affordance_ranking": { "status": "ok", "ranked_operators": [ { "operator": "config_data_consistency", "fit": "high", "reason": "Seed core reconciles docs/HEADER_SCHEMA.md rules with data/sample_header.vcf into parsed_output and validation_report; directly supported." }, { "operator": "aggregation_summary_report", "fit": "high", "reason": "Seed already produces JSON artifacts; aggregate valid/invalid counts and error breakdown via CLI is natural verifiable extension." }, { "operator": "container_build_alignment", "fit": "medium", "reason": "Dockerfile FROM python:3.10-slim exists, alignment check feasible with small addition but peripheral to VCF workflow." }, { "operator": "toolchain_availability_check", "fit": "medium", "reason": "pip/python/pytest signals exist, check feasible via terminal but superficial versus data validation goal." }, { "operator": "environment_variable_resolution", "fit": "low", "reason": "No .env or env-var-dependent parser behavior; would require inventing unrelated locale/profile substrate." }, { "operator": "compile_link_package_workflow", "fit": "low", "reason": "Single-file Python parser has no compile/link/package affordance; artificial for this seed." } ], "blocked_operators": [ { "operator": "schema_content_validation", "reason": "Would duplicate existing schema-driven validation as narrow check without new terminal exploration." }, { "operator": "format_conversion_validation", "reason": "Isolated JSON conversion check is superficial; seed JSON handling already covered by report artifacts." } ], "rationale": "Preferred env-var operator lacks affordance; config-data consistency and aggregation report best fit existing schema/data/report workflow." }, "contract": { "status": "ok", "rewrite_family": "data_artifact_report_processing", "rewrite_operator": "aggregation_summary_report", "operator_fit": "fallback", "why_fit": "preferred environment_variable_resolution has no .env, locale, timezone or profile affordance in VCF parser seed and would be invented; aggregation naturally extends existing parsed_output and validation_report JSON workflow", "goal": "Build VCF header parser, validate sample header, and produce aggregate summary report", "preserved_workflow": "single-file vcfparser.py with split_to_dict and MetaDataParser.parse_lines, raw conversion to parsed_output.json, per-entry validation_report.json per docs/HEADER_SCHEMA.md and data/sample_header.vcf", "new_requirement": "compute valid/invalid totals and field-level error breakdown from validation results via terminal CLI composition into a machine-readable summary report", "task_chain": [ { "stage": "inspect", "artifact_or_state": "workspace layout, docs/HEADER_SCHEMA.md, data/sample_header.vcf and vcfparser.py source/build output to inspect via ls/cat/grep" }, { "stage": "derive", "artifact_or_state": "completeness rules and aggregation keys to infer from local schema doc and sample header evidence" }, { "stage": "execute", "artifact_or_state": "parser, parsed_output.json, validation_report.json and summary report to create by editing and running python/CLI" }, { "stage": "validate", "artifact_or_state": "local JSON parseability, count reconciliation and CLI output evidence to validate" }, { "stage": "finalize", "artifact_or_state": "final summary report with totals and breakdown as checked deliverable" } ], "expected_artifacts": [ { "path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "exists and defines required ID/Number/Type/Description rules" }, { "path": "/app/data/sample_header.vcf", "role": "evidence", "requirement": "exists with ## header lines and ID entries for parsing" }, { "path": "/app/vcfparser.py", "role": "intermediate", "requirement": "provides split_to_dict and MetaDataParser.parse_lines with faithful block parsing" }, { "path": "/app/parsed_output.json", "role": "intermediate", "requirement": "non-empty list matching live parser output over sample header" }, { "path": "/app/validation_report.json", "role": "intermediate", "requirement": "per-entry valid boolean and field-specific errors preserving IDs without loss" }, { "path": "/app/summary.json", "role": "final", "requirement": "machine-readable aggregates with totals and error breakdown reconciling validation_report" } ], "reward_checks": [ { "name": "check_01_required_evidence", "checks": "schema doc and sample header exist and parser honors discoverable rules" }, { "name": "check_02_intermediate_artifact", "checks": "parsed_output and validation_report present, parseable, non-empty and consistent with live parser" }, { "name": "check_03_final_semantics", "checks": "summary totals and error breakdown semantically reconcile with validation_report entries" }, { "name": "check_04_no_shortcut", "checks": "reject empty, placeholder, stale, hardcoded or verifier-only outputs with no real derivation" } ], "instruction_boundary": { "mention": [ "public goal", "at most 1-2 fair starting points", "main final deliverable or completion signal", "only undiscoverable hard acceptance constants" ], "hide": [ "step-by-step commands", "path/field inventories", "schema/format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable details that belong in local docs" ] }, "environment_changes": [ "add docs/SUMMARY_SPEC.md defining summary fields and aggregation rules as discoverable workspace evidence" ], "rationale": "aggregation_summary_report extends parser plus validation workflow with terminal-native counting and reporting depth while staying verifiable via JSON reconciliation and rejecting shortcuts, harder but controllable" }, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": { "ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 2.6 }, "repair_log": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304#!/bin/bashset -eAPP=/appSCHEMA_DOC="$APP/docs/HEADER_SCHEMA.md"SAMPLE_VCF="$APP/data/sample_header.vcf"PARSER_PY="$APP/vcfparser.py"PARSED_JSON="$APP/parsed_output.json"REPORT_JSON="$APP/validation_report.json"SUMMARY_JSON="$APP/summary.json"SUMMARY_SPEC="$APP/docs/SUMMARY_SPEC.md"
echo "[inspect] workspace layout"ls -R "$APP"echo "[inspect] schema doc"cat "$SCHEMA_DOC"echo "[inspect] sample header"cat "$SAMPLE_VCF"wc -l "$SAMPLE_VCF"grep -c "^##" "$SAMPLE_VCF" || trueecho "[inspect] existing parser if any"ls -l "$PARSER_PY" 2>&1 || echo "no parser yet"cat "$PARSER_PY" 2>/dev/null | head -100 || trueecho "[inspect] existing artifacts if any"ls -l "$PARSED_JSON" "$REPORT_JSON" "$SUMMARY_JSON" 2>&1 || truecat "$PARSED_JSON" 2>/dev/null | head -50 || echo "no parsed_output yet"cat "$REPORT_JSON" 2>/dev/null | head -50 || echo "no validation_report yet"cat "$SUMMARY_JSON" 2>/dev/null | head -50 || echo "no summary yet"cat "$SUMMARY_SPEC" 2>/dev/null || echo "no summary spec yet"
echo "[derive] required fields and constraints from schema doc"grep -E "ID|Number|Type|Description" "$SCHEMA_DOC" | head -20grep -E "Integer|Float|Flag|String|Character" "$SCHEMA_DOC" | head -20grep -E "Required|Missing|Invalid|valid" "$SCHEMA_DOC" | head -20echo "[derive] fixture IDs present"grep -o "ID=[^,>]*" "$SAMPLE_VCF" || trueecho "[derive] raw blocks"grep -o "<[^>]*>" "$SAMPLE_VCF" || trueecho "[derive] header line count via CLI"grep -c "^##INFO" "$SAMPLE_VCF" || truewc -l "$SAMPLE_VCF"
echo "[execute] writing parser"cat > "$PARSER_PY" <<'PYEOF'"""Tiny single-file VCF header parser."""
def split_to_dict(string: str) -> dict: """Parse a VCF meta block like <ID=HQ,Number=2,...> into a dict.""" if not isinstance(string, str): return {} if not string or not string.strip(): return {} s = string.strip() if s.startswith("<"): s = s[1:] if s.endswith(">"): s = s[:-1] s = s.strip() if not s: return {} parts = [] current = "" in_single = False in_double = False for ch in s: if ch == "'" and not in_double: in_single = not in_single current += ch elif ch == '"' and not in_single: in_double = not in_double current += ch elif ch == "," and not in_single and not in_double: parts.append(current) current = "" else: current += ch parts.append(current) result = {} for part in parts: part = part.strip() if not part: return {} if "=" not in part: return {} k, v = part.split("=", 1) k = k.strip() v = v.strip() if not k: return {} if len(v) >= 2 and ((v[0] == "'" and v[-1] == "'") or (v[0] == '"' and v[-1] == '"')): v = v[1:-1] if isinstance(v, str): vs = v.strip() if vs.isdigit(): v = int(vs) elif vs.startswith("-") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) elif vs.startswith("+") and len(vs) > 1 and vs[1:].isdigit(): v = int(vs) else: v = v result[k] = v if not result: return {} return result
class MetaDataParser: """Parse VCF header files for meta blocks.""" def __init__(self, header_file: str): self.header_file = header_file def _parse_block(self, line: str) -> dict: if not isinstance(line, str): return {} if "<" not in line or ">" not in line: return {} try: start = line.find("<") end = line.rfind(">") if start < 0 or end < 0 or start >= end: return {} block = line[start:end+1] parsed = split_to_dict(block) return parsed if isinstance(parsed, dict) else {} except Exception: return {} def parse_lines(self): try: fh = open(self.header_file, "r") except FileNotFoundError: raise except OSError as e: raise FileNotFoundError(str(e)) from e results = [] with fh: for line in fh: line = line.strip() if not line: continue if "<" not in line or ">" not in line: continue d = self._parse_block(line) if d: results.append(d) return resultsPYEOFecho "[execute] parser written"python3 -c "import vcfparser; print(vcfparser.split_to_dict(\"<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>\"))"
echo "[execute] ensuring summary spec exists (discoverable workspace evidence)"if [ ! -f "$SUMMARY_SPEC" ]; thencat > "$SUMMARY_SPEC" <<'MDEOF'# Summary Report Spec — Aggregation over validation_report.json
This document defines the machine-readable aggregate at `/app/summary.json`.
## Source- Input is `validation_report.json`: list of per-entry objects each with `valid` boolean and `errors` list mentioning offending field(s).- Entry identity preserved via `ID` (or `entry.ID`).
## Required summary fields- `total` (int): total number of validation entries. Alias `total_entries`.- `valid` (int): count of entries where `valid` is true. Alias `valid_count`.- `invalid` (int): count of entries where `valid` is false. Alias `invalid_count`. Must equal `total - valid`.- `errors_by_field` (object): map of field name -> count of entries whose `errors` mention that field. Aliases `error_breakdown`, `by_field`. - Keys cover `ID`, `Number`, `Type`, `Description` (include all four with 0 default). - Counting rule: for each entry, if an error string contains the field name substring (case-sensitive), increment that field once per entry (deduplicated per entry).- `source` (string, optional): name of input file aggregated (`validation_report.json`).
## Aggregation rules- `total` equals length of validation report list.- `valid` equals number of entries with `valid` true; `invalid` equals number with `valid` false.- Reconciliation: `total == valid + invalid` and `invalid == total - valid`.- `errors_by_field` counts are derived from `errors` strings per entry, one increment per field per entry at most.- Output must be JSON object written to `/app/summary.json` and parseable with `python3 -m json.tool` or `jq`.- Counts must reconcile with the live `validation_report.json` when checked via terminal CLI composition (e.g. `jq`, `python3 -c`, `grep -c`).MDEOFficat "$SUMMARY_SPEC"
echo "[execute] raw conversion via live parser to parsed_output.json"python3 -c "from vcfparser import MetaDataParser; import json; data=MetaDataParser('$SAMPLE_VCF').parse_lines(); open('$PARSED_JSON','w').write(json.dumps(data, indent=2)); print(f'parsed {len(data)} entries')"cat "$PARSED_JSON"python3 -m json.tool "$PARSED_JSON" > /dev/null && echo "parsed_output parseable"
echo "[execute] validate every entry to validation_report.json"python3 <<'PYEOF'import json, reparsed=json.load(open('/app/parsed_output.json'))if isinstance(parsed, dict): for k in ['entries','results','parsed','data','items','output','parsed_output']: if isinstance(parsed.get(k), list): parsed=parsed[k] breakALLOWED={'Integer','Float','Flag','String','Character'}SYM={'A','R','G','.'}IDRE=re.compile(r'^[A-Za-z0-9_.\-]+$')def num_ok(v): if type(v) is bool: return False if type(v) is int: return v>=0 if type(v) is float: return v.is_integer() and v>=0 if isinstance(v,str): s=v.strip() if s in SYM: return True try: n=int(s) return n>=0 and (str(n)==s or (s.startswith('+') and str(n)==s[1:])) except Exception: return False return Falsereport=[]for e in parsed: errs=[] lookup=dict(e) for f in ['ID','Number','Type','Description']: found=any(k==f or k.lower()==f.lower() for k in lookup.keys()) if not found: errs.append(f"Missing {f}") if 'ID' in lookup or 'id' in lookup: iv=lookup.get('ID', lookup.get('id')) if not isinstance(iv,str) or not iv.strip() or not IDRE.match(iv.strip()): if not any('ID' in x for x in errs): errs.append(f"Invalid ID: {iv!r}") if 'Number' in lookup: if not num_ok(lookup['Number']): if not any('Number' in x for x in errs): errs.append(f"Invalid Number: {lookup['Number']!r}") if 'Type' in lookup: if lookup['Type'] not in ALLOWED: if not any('Type' in x for x in errs): errs.append(f"Invalid Type: {lookup['Type']!r}") if 'Description' in lookup: dv=lookup['Description'] if not isinstance(dv,str) or not dv.strip(): if not any('Description' in x for x in errs): errs.append("Invalid Description: empty") valid=len(errs)==0 eid=e.get('ID', e.get('id', '')) report.append({"ID": eid, "entry": e, "valid": valid, "errors": errs})json.dump(report, open('/app/validation_report.json','w'), indent=2)print(f"validated {len(report)} entries valid={sum(1 for r in report if r['valid'])}")PYEOFcat "$REPORT_JSON"python3 -m json.tool "$REPORT_JSON" > /dev/null && echo "validation_report parseable"
echo "[execute] aggregate via terminal CLI composition to summary.json"python3 <<'PYEOF'import jsonrep=json.load(open('/app/validation_report.json'))if isinstance(rep, dict): for k in ['entries','results','report','validations','data','items']: v=rep.get(k) if isinstance(v,list): rep=v breaktotal=len(rep)valid=sum(1 for e in rep if e.get('valid') is True)invalid=total-validfields=['ID','Number','Type','Description']by={f:0 for f in fields}for e in rep: errs=e.get('errors', e.get('error', e.get('messages', e.get('issues', [])))) if errs is None: errs=[] if isinstance(errs,str): errs=[errs] if errs.strip() else [] strs=[str(x) for x in errs] for f in fields: if any(f in s for s in strs): by[f]+=1summary={"total": total, "total_entries": total, "valid": valid, "valid_count": valid, "invalid": invalid, "invalid_count": invalid, "errors_by_field": by, "error_breakdown": by, "by_field": by, "source": "validation_report.json"}json.dump(summary, open('/app/summary.json','w'), indent=2)print(json.dumps(summary, indent=2))PYEOFcat "$SUMMARY_JSON"
echo "[validate] JSON parseability via CLI"python3 -m json.tool "$PARSED_JSON" > /dev/null && echo "parsed_output json ok"python3 -m json.tool "$REPORT_JSON" > /dev/null && echo "report json ok"python3 -m json.tool "$SUMMARY_JSON" > /dev/null && echo "summary json ok"if command -v jq >/dev/null 2>&1; then jq . "$PARSED_JSON" > /dev/null && echo "jq parsed ok" jq . "$REPORT_JSON" > /dev/null && echo "jq report ok" jq . "$SUMMARY_JSON" > /dev/null && echo "jq summary ok" echo "[validate] jq totals" jq '{total, valid, invalid, errors_by_field}' "$SUMMARY_JSON" jq -r '.[] | select(.valid==true) | .ID' "$REPORT_JSON" | wc -l jq -r '.[] | select(.valid==false) | .ID' "$REPORT_JSON" | wc -lelse echo "jq not available, using python3 -c"fiecho "[validate] count reconciliation via CLI"python3 -c "import json; r=json.load(open('$REPORT_JSON')); s=json.load(open('$SUMMARY_JSON')); t=s.get('total',s.get('total_entries')); v=s.get('valid',s.get('valid_count')); iv=s.get('invalid',s.get('invalid_count')); assert t==len(r), (t,len(r)); assert v==sum(1 for e in r if e.get('valid') is True); assert iv==t-v; assert t==v+iv; print(f'reconciled total={t} valid={v} invalid={iv}')"grep -c '"valid": true' "$REPORT_JSON" || truegrep -c '"valid": false' "$REPORT_JSON" || truegrep -E '"total"|"valid"|"invalid"|errors_by_field' "$SUMMARY_JSON" || truewc -l "$PARSED_JSON" "$REPORT_JSON" "$SUMMARY_JSON"
echo "[finalize] summary deliverable"ls -l "$PARSER_PY" "$PARSED_JSON" "$REPORT_JSON" "$SUMMARY_JSON" "$SUMMARY_SPEC"cat "$SUMMARY_JSON"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "stages": { "affordance_ranking": { "seconds": 44.705, "cost_usd": 0.001018, "llm_calls": 1 }, "contract": { "seconds": 58.987, "cost_usd": 0.001358, "llm_calls": 1 }, "solution": { "seconds": 88.397, "cost_usd": 0.002307, "llm_calls": 1 }, "verifier": { "seconds": 190.066, "cost_usd": 0.005746, "llm_calls": 2 }, "instruction": { "seconds": 34.835, "cost_usd": 0.00094, "llm_calls": 1 }, "env_align": { "seconds": 39.06, "cost_usd": 0.001037, "llm_calls": 1 }, "consistency_repair": { "seconds": 86.509, "cost_usd": 0.002471, "llm_calls": 1 }, "precheck": { "seconds": 2.953, "cost_usd": 0.0, "llm_calls": 0 } }, "lineage_id": "L296-y-0313", "round": 3, "total_seconds": 545.512, "total_cost_usd": 0.014878}12345678910111213141516171819202122232425262728293031schema_version = "1.1"artifacts = [][task]name = "openthoughts/tasktrove-exp-rpt-curriculum-easy-curriculum-easy-0313"description = ""authors = []keywords = [][metadata]author_name = "Sandboxes"author_email = "sandboxes@sandboxes.com"difficulty = "medium"category = "sandbox"tags = [ "sandbox",][verifier]timeout_sec = 720.0
[verifier.env][agent]timeout_sec = 900.0[environment]build_timeout_sec = 600.0os = "linux"cpus = 1memory_mb = 2048storage_mb = 10240gpus = 0allow_internet = truemcp_servers = []
[environment.env][solution.env]123456789101112131415161718192021222324252627282930#!/bin/bash# rst: fixed partial-credit runner. Reward = fraction of pytest tests in# test_state.py that passed (not a binary all-or-nothing gate).set -uo pipefailmkdir -p /logs/verifiercd "/app" 2>/dev/null || cd /export PYTHONPATH="/app:${PYTHONPATH:-}"
pytest /tests/test_state.py -v --tb=short > /logs/verifier/test_output.txt 2>&1PYTEST_STATUS=$?cp /logs/verifier/test_output.txt /logs/verifier/test_output_copy.txt 2>/dev/null || true
python3 - "$PYTEST_STATUS" <<'PYEOF'import re, sys, pathlibtext = pathlib.Path("/logs/verifier/test_output.txt").read_text(errors="replace")passed = len(re.findall(r"^tests/test_state\.py::\S+ PASSED", text, re.M)) or len(re.findall(r" PASSED\b", text))failed = len(re.findall(r"^tests/test_state\.py::\S+ FAILED", text, re.M)) or len(re.findall(r" FAILED\b", text))errored = len(re.findall(r"^tests/test_state\.py::\S+ ERROR", text, re.M)) or len(re.findall(r" ERROR\b", text))total = passed + failed + erroredif total == 0: # pytest itself couldn't collect/run -- hard zero, not "no checks" == 1.0 reward = 0.0else: reward = passed / totalpathlib.Path("/logs/verifier/reward.txt").write_text(f"{reward:.4f}")pathlib.Path("/logs/verifier/reward_detail.json").write_text( __import__("json").dumps({"passed": passed, "failed": failed, "errored": errored, "total": total, "reward": reward}))PYEOFexit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488import osimport sysimport jsonimport pathlibimport tempfilesys.path.insert(0, '/app')import pytestfrom vcfparser import MetaDataParser, split_to_dictSCHEMA_PATH = '/app/docs/HEADER_SCHEMA.md'HEADER_PATH = '/app/data/sample_header.vcf'PARSED_PATH = '/app/parsed_output.json'REPORT_PATH = '/app/validation_report.json'SUMMARY_PATH = '/app/summary.json'PARSER_PATH = '/app/vcfparser.py'ALLOWED_TYPES = ['Integer', 'Float', 'Flag', 'String', 'Character']SYMBOLIC_NUMBERS = ['A', 'R', 'G', '.']REQUIRED_FIELDS = ['ID', 'Number', 'Type', 'Description']ID_ALLOWED = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'def _load_json(path): with open(path, 'r') as f: return json.load(f)def _as_parsed_list(data): if isinstance(data, list): return data if isinstance(data, dict): for k in ['entries', 'results', 'parsed', 'data', 'items', 'output', 'parsed_output']: v = data.get(k) if isinstance(v, list): return v if 'ID' in data or 'id' in data or 'Number' in data: return [data] return Nonedef _as_entry_list(data): if isinstance(data, list): return data if isinstance(data, dict): for k in ['entries', 'results', 'report', 'validations', 'data', 'items']: v = data.get(k) if isinstance(v, list): return v vals = list(data.values()) if vals and all(isinstance(v, dict) for v in vals): out = [] for kk, vv in data.items(): c = dict(vv) c.setdefault('ID', kk) out.append(c) return out if 'valid' in data or 'is_valid' in data or 'errors' in data: return [data] return Nonedef _get_valid(entry): for k in ['valid', 'is_valid', 'isValid', 'passed', 'ok']: if k in entry: v = entry[k] if isinstance(v, bool): return v if type(v) is int or type(v) is float: return bool(v) if isinstance(v, str): s = v.strip().lower() if s in ['true', '1', 'yes', 'valid', 'pass']: return True if s in ['false', '0', 'no', 'invalid', 'fail']: return False return bool(v) return Nonedef _get_errors(entry): for k in ['errors', 'error', 'messages', 'issues', 'problems']: if k in entry: v = entry[k] if v is None: return [] if isinstance(v, list): return [str(x) for x in v] if isinstance(v, str): if v.strip() == '': return [] return [v] return [str(v)] return Nonedef _get_entry_data(entry): for k in ['entry', 'parsed', 'record', 'data', 'input', 'row', 'item', 'source']: v = entry.get(k) if isinstance(v, dict): if 'ID' in v or 'id' in v or 'Number' in v or 'Type' in v: return v return entrydef _get_id(entry, ed): for src in [ed, entry]: for k in ['ID', 'id', 'name']: if k in src and isinstance(src[k], (str, int)): return str(src[k]) return Nonedef _valid_id(s): if not isinstance(s, str): return False t = s.strip() if t == '': return False for ch in t: if ch not in ID_ALLOWED: return False return Truedef _valid_number(v): if type(v) is bool: return False if type(v) is int: return v >= 0 if type(v) is float: return v.is_integer() and v >= 0 if isinstance(v, str): s = v.strip() if s in SYMBOLIC_NUMBERS: return True try: n = int(s) if str(n) == s or ('+' in s and int(s[1:]) >= 0): return n >= 0 return False except Exception: return False return Falsedef _recompute(ed): lookup = dict(ed) if 'ID' not in lookup and 'id' in lookup: lookup['ID'] = lookup['id'] bad = [] for f in REQUIRED_FIELDS: found = False for k in lookup.keys(): if k == f or k.lower() == f.lower(): found = True break if not found: bad.append(f) if 'ID' in lookup: if not _valid_id(lookup['ID']): if 'ID' not in bad: bad.append('ID') if 'Number' in lookup: if not _valid_number(lookup['Number']): if 'Number' not in bad: bad.append('Number') if 'Type' in lookup: if lookup['Type'] not in ALLOWED_TYPES: if 'Type' not in bad: bad.append('Type') if 'Description' in lookup: dv = lookup['Description'] if not isinstance(dv, str) or dv.strip() == '': if 'Description' not in bad: bad.append('Description') return (len(bad) == 0, bad)def _live_parsed(): return MetaDataParser(HEADER_PATH).parse_lines()def _header_block_count(): text = pathlib.Path(HEADER_PATH).read_text(errors='replace') n = 0 for line in text.splitlines(): s = line.strip() if s.startswith('##') and '<' in s and '>' in s: n += 1 return ndef _find_key(d, aliases): for a in aliases: if a in d: return d[a] return Nonedef _extract_summary(data): cands = [] if isinstance(data, dict): cands.append(data) for v in data.values(): if isinstance(v, dict): cands.append(v) else: return (None, None, None, None) best = (None, None, None, None) best_score = -1 for cand in cands: t = _find_key(cand, ['total', 'total_entries', 'count', 'n_total', 'num_entries']) vv = _find_key(cand, ['valid', 'valid_count', 'n_valid', 'num_valid']) iv = _find_key(cand, ['invalid', 'invalid_count', 'n_invalid', 'num_invalid']) br = _find_key(cand, ['errors_by_field', 'error_breakdown', 'by_field', 'breakdown', 'field_errors', 'error_counts']) score = 0 for x in [t, vv, iv, br]: if x is not None: score += 1 if score > best_score: best_score = score best = (t, vv, iv, br) return bestdef _coerce_int(v): if type(v) is bool: return None if type(v) is int: return v if type(v) is float: if v.is_integer(): return int(v) return None if isinstance(v, str): s = v.strip() try: return int(s) except Exception: return None return Nonedef _expected_breakdown(entries): exp = {} for f in REQUIRED_FIELDS: exp[f] = 0 for e in entries: errs = _get_errors(e) if errs is None: errs = [] for f in REQUIRED_FIELDS: hit = False for s in errs: if f in s: hit = True break if hit: exp[f] += 1 return expdef _sample_ids(): text = pathlib.Path(HEADER_PATH).read_text(errors='replace') ids = set() start = 0 while True: i = text.find('ID=', start) if i < 0: break j = i + 3 buf = '' while j < len(text) and text[j] not in [',', '>', chr(10), chr(13)]: buf += text[j] j += 1 ids.add(buf) start = j + 1 return idsdef test_check_01_required_evidence(): assert os.path.isfile(SCHEMA_PATH), 'schema doc missing' assert os.path.isfile(HEADER_PATH), 'sample header missing' assert os.path.isfile(PARSER_PATH), 'parser file missing' text = pathlib.Path(SCHEMA_PATH).read_text(errors='replace') for field in REQUIRED_FIELDS: assert field in text, 'schema must define field' htext = pathlib.Path(HEADER_PATH).read_text(errors='replace') assert '##' in htext, 'header must have meta lines' assert 'ID=' in htext, 'header must have ID entries' live = _live_parsed() assert isinstance(live, list) and len(live) > 0, 'live parser must return non-empty list' exp_n = _header_block_count() assert len(live) == exp_n, 'live parser count must match header blocks' for d in live: assert isinstance(d, dict), 'each live entry must be dict'def test_check_01_parser_faithful(): assert callable(split_to_dict), 'split_to_dict must be callable' assert hasattr(MetaDataParser, 'parse_lines'), 'parse_lines missing' d = split_to_dict('<ID=HQ,Number=2,Type=Integer,Description=Haplotype Quality>') assert isinstance(d, dict) and d.get('ID') == 'HQ', 'basic ID parse failed' assert d.get('Number') == 2 and type(d.get('Number')) is int, 'numeric conversion failed' d2 = split_to_dict('< ID = DP , Number = 1 , Type = String , Description = Total Depth >') assert d2.get('ID') == 'DP', 'trimmed keys failed' assert d2.get('Number') == 1, 'numeric with spaces failed' assert split_to_dict('') == {}, 'empty must yield empty dict' assert split_to_dict(' ') == {}, 'spaces must yield empty dict' assert split_to_dict('no-equals-here') == {}, 'missing equals must yield empty dict' assert split_to_dict('<>') == {}, 'empty block must yield empty dict' assert split_to_dict('<ID>') == {}, 'block without equals must yield empty dict' with pytest.raises(FileNotFoundError): MetaDataParser('/app/data/does_not_exist_12345.vcf').parse_lines() live = _live_parsed() assert all(isinstance(x, dict) and len(x) > 0 for x in live), 'parse_lines must skip bad lines'def test_check_02_intermediate_artifact_parsed(): assert os.path.isfile(PARSED_PATH), 'parsed_output missing' raw = pathlib.Path(PARSED_PATH).read_text(errors='replace') assert len(raw.strip()) > 10, 'parsed_output empty' data = json.loads(raw) plist = _as_parsed_list(data) assert plist is not None, 'parsed_output must be list or wrapped list' assert len(plist) > 0, 'parsed_output must be non-empty' live = _live_parsed() assert len(plist) == len(live), 'parsed_output length must match live parser' for i in range(len(live)): assert isinstance(plist[i], dict), 'parsed entry must be dict' assert plist[i] == live[i], 'parsed entry must match live parser'def test_check_02_intermediate_artifact_validation(): assert os.path.isfile(REPORT_PATH), 'validation_report missing' raw = pathlib.Path(REPORT_PATH).read_text(errors='replace') assert len(raw.strip()) > 10, 'validation_report empty' data = json.loads(raw) entries = _as_entry_list(data) assert entries is not None, 'validation_report must be list or wrapped' assert len(entries) > 0, 'validation_report must be non-empty' live = _live_parsed() assert len(entries) == len(live), 'report length must match live count' live_ids = [] for dd in live: vv = dd.get('ID', dd.get('id')) if isinstance(vv, (str, int)): live_ids.append(str(vv)) else: live_ids.append(None) rep_ids = [] for e in entries: assert isinstance(e, dict), 'report entry must be dict' v = _get_valid(e) assert isinstance(v, bool), 'report entry must have bool valid' errs = _get_errors(e) assert errs is not None and isinstance(errs, list), 'report entry must have errors list' ed = _get_entry_data(e) rep_ids.append(_get_id(e, ed)) for lid in live_ids: assert lid in rep_ids, 'report lost an ID' for e in entries: ed = _get_entry_data(e) reported = _get_valid(e) errs = _get_errors(e) exp_valid, bad = _recompute(ed) assert reported == exp_valid, 'valid flag mismatch' if exp_valid: assert len(errs) == 0, 'valid entry must have empty errors' else: assert len(errs) > 0, 'invalid entry must list errors' for f in bad: found = False for s in errs: if f in s: found = True break assert found, 'errors must mention offending field' vals = [_get_valid(e) for e in entries] assert any(vals) and not all(vals), 'report must mix valid and invalid'def test_check_03_final_semantics_totals(): assert os.path.isfile(SUMMARY_PATH), 'summary missing' raw = pathlib.Path(SUMMARY_PATH).read_text(errors='replace') assert len(raw.strip()) > 10, 'summary empty' data = json.loads(raw) assert isinstance(data, dict), 'summary must be object' t_raw, v_raw, iv_raw, br = _extract_summary(data) assert t_raw is not None, 'summary must expose total' assert v_raw is not None, 'summary must expose valid' assert iv_raw is not None, 'summary must expose invalid' total = _coerce_int(t_raw) valid = _coerce_int(v_raw) invalid = _coerce_int(iv_raw) assert total is not None and valid is not None and invalid is not None, 'totals must be ints' rep = _load_json(REPORT_PATH) entries = _as_entry_list(rep) assert entries is not None and len(entries) > 0, 'need report for reconcile' exp_total = len(entries) exp_valid = 0 exp_invalid = 0 for e in entries: if _get_valid(e) is True: exp_valid += 1 else: exp_invalid += 1 assert total == exp_total, 'total must equal report count' assert valid == exp_valid, 'valid must equal report valid' assert invalid == exp_invalid, 'invalid must equal report invalid' assert invalid == total - valid, 'invalid must equal total minus valid' assert total > 0 and valid > 0 and invalid > 0, 'summary must reflect mixed sample'def test_check_03_final_semantics_breakdown(): assert os.path.isfile(SUMMARY_PATH), 'summary missing' data = _load_json(SUMMARY_PATH) t_raw, v_raw, iv_raw, br = _extract_summary(data) assert br is not None, 'summary must expose breakdown' assert isinstance(br, dict), 'breakdown must be object' for f in REQUIRED_FIELDS: assert f in br, 'breakdown must include field' cv = _coerce_int(br[f]) assert cv is not None and cv >= 0, 'breakdown counts must be non-negative ints' rep = _load_json(REPORT_PATH) entries = _as_entry_list(rep) exp = _expected_breakdown(entries) for f in REQUIRED_FIELDS: got = _coerce_int(br[f]) assert got == exp[f], 'breakdown value mismatch' total = _coerce_int(t_raw) invalid = _coerce_int(iv_raw) for f in REQUIRED_FIELDS: got = _coerce_int(br[f]) assert got <= total, 'field count exceeds total' assert got <= invalid, 'field count exceeds invalid' s = 0 for f in REQUIRED_FIELDS: s += _coerce_int(br[f]) es = 0 for f in REQUIRED_FIELDS: es += exp[f] assert es > 0, 'expected breakdown must be non-zero' assert s == es, 'breakdown sum mismatch'def test_check_04_no_shortcut(): for p in [PARSED_PATH, REPORT_PATH, SUMMARY_PATH]: assert os.path.isfile(p), 'artifact missing' sz = os.path.getsize(p) assert sz > 20, 'artifact too small' txt = pathlib.Path(p).read_text(errors='replace') low = txt.lower() assert 'todo' not in low, 'placeholder found' assert 'fixme' not in low, 'placeholder found' assert 'placeholder' not in low, 'placeholder found' assert 'lorem ipsum' not in low, 'placeholder found' obj = json.loads(txt) if isinstance(obj, list): assert len(obj) > 0, 'artifact must not be empty list' else: assert len(obj) > 0, 'artifact must not be empty' data = _load_json(SUMMARY_PATH) t_raw, v_raw, iv_raw, br = _extract_summary(data) assert _coerce_int(t_raw) not in [None, 0], 'total must be non-zero' assert isinstance(br, dict), 'breakdown required' anypos = False for f in REQUIRED_FIELDS: if _coerce_int(br.get(f, 0)) not in [None, 0]: anypos = True assert anypos, 'breakdown must not be all zeros' sample_ids = _sample_ids() rep = _load_json(REPORT_PATH) entries = _as_entry_list(rep) rep_ids = set() for e in entries: rep_ids.add(str(_get_id(e, _get_entry_data(e)))) inter = 0 for x in rep_ids: if x in sample_ids: inter += 1 assert inter >= 3, 'report IDs must overlap sample' parsed = _load_json(PARSED_PATH) plist = _as_parsed_list(parsed) pids = set() for dd in plist: if isinstance(dd, dict): pids.add(str(dd.get('ID', dd.get('id', '')))) pinter = 0 for x in pids: if x in sample_ids: pinter += 1 assert pinter >= 3, 'parsed IDs must overlap sample'def test_check_04_no_shortcut_derivation(): live = _live_parsed() parsed = _load_json(PARSED_PATH) plist = _as_parsed_list(parsed) assert plist is not None and len(plist) == len(live), 'parsed stale' for a, b in zip(plist, live): assert a == b, 'parsed content diverges from live' rep = _load_json(REPORT_PATH) entries = _as_entry_list(rep) for e in entries: ed = _get_entry_data(e) exp_valid, bad = _recompute(ed) assert _get_valid(e) == exp_valid, 'report stale' summ = _load_json(SUMMARY_PATH) t_raw, v_raw, iv_raw, br = _extract_summary(summ) exp_total = len(entries) exp_valid = 0 for e in entries: if _get_valid(e) is True: exp_valid += 1 exp_invalid = exp_total - exp_valid assert _coerce_int(t_raw) == exp_total, 'summary total stale' assert _coerce_int(v_raw) == exp_valid, 'summary valid stale' assert _coerce_int(iv_raw) == exp_invalid, 'summary invalid stale' exp_br = _expected_breakdown(entries) for f in REQUIRED_FIELDS: assert _coerce_int(br[f]) == exp_br[f], 'summary breakdown stale' synth = split_to_dict('<ID=SYNTH1,Number=A,Type=Float,Description=Synthetic check>') assert synth.get('ID') == 'SYNTH1', 'parser must handle symbolic Number' assert synth.get('Number') == 'A', 'parser must keep symbolic value' nl = chr(10) tf = tempfile.NamedTemporaryFile(mode='w', suffix='.vcf', delete=False) tfname = tf.name tf.write('##INFO=<ID=TMP1,Number=1,Type=String,Description=Tmp>' + nl) tf.write('#CHROM' + nl) tf.close() try: out = MetaDataParser(tfname).parse_lines() assert isinstance(out, list) and len(out) == 1, 'parser must derive from file' assert out[0].get('ID') == 'TMP1', 'parser must not be hardcoded' finally: try: os.unlink(tfname) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172FROM python:3.10-slimWORKDIR /appRUN pip install --no-cache-dir pytestRUN mkdir -p /app/docs /app/dataRUN cat > /app/docs/HEADER_SCHEMA.md <<'MDEOF'# VCF Header Schema — Meta Entries
This document defines validation rules for parsed VCF meta header dicts produced by `vcfparser.split_to_dict` / `MetaDataParser.parse_lines`.
## Required fields (completeness)Every parsed entry must contain all four keys:- `ID`- `Number`- `Type`- `Description`
Missing any required key => invalid. Extra keys are allowed and ignored.
## Field types and constraints- `ID`: must be a non-empty string matching `^[A-Za-z0-9_.\-]+$` (letters, digits, underscore, dot, hyphen). Empty or missing => invalid.- `Number`: must be either: - a non-negative integer (`0`, `1`, `2`, ...) with value `>= 0`, OR - one of the symbolic values `A`, `R`, `G`, `.` Anything else (negative integers, other strings like `two`, empty) => invalid. This covers type + range.- `Type`: must be exactly one of `Integer`, `Float`, `Flag`, `String`, `Character` (case-sensitive). Anything else => invalid.- `Description`: must be a non-empty string after stripping whitespace. Empty or missing => invalid.
## Examples- Valid: `<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>` => `{"ID":"HQ","Number":2,"Type":"Integer","Description":"Haplotype Quality"}`- Invalid: missing `Description`, `Number=-1` (out of range), `Type=BadType` (not allowed), `ID=` (empty).
## Validation reportValidators must emit per-entry `valid` boolean and `errors` list mentioning the offending field(s).MDEOFRUN cat > /app/data/sample_header.vcf <<'VCFEOF'##fileformat=VCFv4.2##INFO=<ID=HQ,Number=2,Type=Integer,Description='Haplotype Quality'>##INFO=<ID=SB,Number=1,Type=String,Description='Sample Block'>##INFO=<ID=DP,Number=1,Type=Integer,Description='Total Depth'>##INFO=<ID=BAD_NUM,Number=-1,Type=Integer,Description='Negative number out of range'>##INFO=<ID=BAD_TYPE,Number=1,Type=BadType,Description='Invalid type value'>##INFO=<ID=BAD_MISSING,Number=1,Type=String>##INFO=<ID=,Number=1,Type=String,Description='Empty ID fails'>VCFEOFRUN cat > /app/docs/SUMMARY_SPEC.md <<'MDEOF'# Summary Report Spec — Aggregation over validation_report.json
This document defines the machine-readable aggregate at `/app/summary.json`.
## Source- Input is `validation_report.json`: list of per-entry objects each with `valid` boolean and `errors` list mentioning offending field(s).- Entry identity preserved via `ID` (or `entry.ID`).- Raw conversion artifact `parsed_output.json` holds the list of parsed dicts from `sample_header.vcf` (one per `##...<...>` block, IDs preserved).- Per-entry validation artifact `validation_report.json` holds the list validated from `parsed_output.json`.
## Required summary fields- `total` (int): total number of validation entries. Alias `total_entries`.- `valid` (int): count of entries where `valid` is true. Alias `valid_count`.- `invalid` (int): count of entries where `valid` is false. Alias `invalid_count`. Must equal `total - valid`.- `errors_by_field` (object): map of field name -> count of entries whose `errors` mention that field. Aliases `error_breakdown`, `by_field`. - Keys cover `ID`, `Number`, `Type`, `Description` (include all four with 0 default). - Counting rule: for each entry, if an error string contains the field name substring (case-sensitive), increment that field once per entry (deduplicated per entry).- `source` (string, optional): name of input file aggregated (`validation_report.json`).
## Aggregation rules- `total` equals length of validation report list.- `valid` equals number of entries with `valid` true; `invalid` equals number with `valid` false.- Reconciliation: `total == valid + invalid` and `invalid == total - valid`.- `errors_by_field` counts are derived from `errors` strings per entry, one increment per field per entry at most.- Output must be JSON object written to `/app/summary.json` and parseable with `python3 -m json.tool` or `jq`.- Counts must reconcile with the live `validation_report.json` when checked via terminal CLI composition (e.g. `jq`, `python3 -c`, `grep -c`).MDEOF123Build a single-file VCF header parser in /app exposing MetaDataParser and split_to_dict with faithful block handling. Consult docs/HEADER_SCHEMA.md and data/sample_header.vcf for expected behavior and completeness rules, and docs/SUMMARY_SPEC.md for aggregation rules.
Run the parser over the sample header to produce the raw conversion and per-entry validation report preserving IDs without loss, then aggregate the live validation report into a reconciled machine-readable summary at /app/summary.json. Use standard terminal tools to verify JSON validity and that totals and field error counts reconcile, keeping all derived counts consistent with live parser output rather than static copies.1{"metadata": {"lineage": "L296-y-0313", "round": "r4", "generation_method": "recursive-task-synthesis", "rounds": {"lineage_id": "L296-y-0313", "round": 4, "operator": "config_data_consistency", "family": "configuration_state_migration", "operator_fit": "fallback", "affordance_ranking": {"status": "ok", "ranked_operators": [{"operator": "config_data_consistency", "fit": "high", "reason": "Seed core is reconciling HEADER_SCHEMA.md rules against sample_header.vcf via parser into validation report; direct fit."}, {"operator": "toolchain_availability_check", "fit": "medium", "reason": "Seed depends on python3, pytest, jq/grep composition; checking tools is natural terminal exploration."}, {"operator": "cli_argument_behavior", "fit": "medium", "reason": "Seed requires jq/python3-c/grep reconciliation; validating flags, stdio and exit codes is plausible extension."}, {"operator": "container_build_alignment", "fit": "low", "reason": "Dockerfile exists but workflow never builds images; alignment would need artificial new build goal."}, {"operator": "compile_link_package_workflow", "fit": "low", "reason": "Single-file interpreted Python has no compile/link/package artifact; forced build step would be artificial."}, {"operator": "environment_variable_resolution", "fit": "low", "reason": "No .env, locale, timezone, or shell profile handling in seed; only generic APP= vars in solve.sh."}], "blocked_operators": [{"operator": "schema_content_validation", "reason": "Pipeline-blocked for diversity despite natural fit; excluded this cycle."}, {"operator": "format_conversion_validation", "reason": "Pipeline-blocked for diversity despite natural fit; excluded this cycle."}, {"operator": "aggregation_summary_report", "reason": "Pipeline-blocked for diversity despite natural fit; excluded this cycle."}], "rationale": "Preferred env-var operator lacks seed affordances; config_data_consistency best fits schema-vs-data validation workflow, with toolchain/CLI as medium fallbacks."}, "contract": {"status": "ok", "rewrite_family": "configuration_state_migration", "rewrite_operator": "config_data_consistency", "operator_fit": "fallback", "why_fit": "Seed core is schema-doc vs sample-header vs parser-output reconciliation; preferred env-var has no .env/locale/profile affordances so config_data_consistency is natural fit.", "goal": "Build VCF header parser and reconcile schema, header data, and reports into validated summary", "preserved_workflow": "Single-file vcfparser.py with MetaDataParser/split_to_dict faithful block parsing, raw conversion of sample header, and per-entry validation report marking valid with field-specific errors", "new_requirement": "Reconcile configuration (HEADER_SCHEMA.md + SUMMARY_SPEC.md) against data (sample_header.vcf) and derived artifacts via terminal CLI composition, preserving IDs without loss and reconciling totals and field error counts in machine-readable summary", "task_chain": [{"stage": "inspect", "artifact_or_state": "workspace layout and local evidence: docs/HEADER_SCHEMA.md, data/sample_header.vcf, docs/SUMMARY_SPEC.md, existing vcfparser.py via ls/cat/grep/wc"}, {"stage": "derive", "artifact_or_state": "completeness and aggregation rules inferred from local docs: required ID/Number/Type/Description constraints and summary totals/errors_by_field counting rules"}, {"stage": "execute", "artifact_or_state": "create vcfparser.py and run it over sample header to produce parsed_output.json and validation_report.json preserving IDs"}, {"stage": "validate", "artifact_or_state": "local CLI validation result: json parseable via python3-m-json.tool/jq and counts reconciled via jq/python3-c/grep-c"}, {"stage": "finalize", "artifact_or_state": "final /app/summary.json aggregate reconciled to live validation report"}], "expected_artifacts": [{"path": "/app/docs/HEADER_SCHEMA.md", "role": "evidence", "requirement": "exists and defines required fields and field constraints used as reconciliation source"}, {"path": "/app/data/sample_header.vcf", "role": "evidence", "requirement": "exists with ## meta blocks; source for live parsing and ID preservation check"}, {"path": "/app/docs/SUMMARY_SPEC.md", "role": "evidence", "requirement": "exists and defines summary totals and errors_by_field aggregation rules"}, {"path": "/app/vcfparser.py", "role": "intermediate", "requirement": "provides MetaDataParser and split_to_dict with faithful block parsing, trimmed keys, unquoted values, numeric conversion"}, {"path": "/app/parsed_output.json", "role": "intermediate", "requirement": "parseable non-empty JSON conversion of sample header preserving IDs"}, {"path": "/app/validation_report.json", "role": "intermediate", "requirement": "parseable per-entry list with valid boolean and errors mentioning offending fields preserving IDs"}, {"path": "/app/summary.json", "role": "final", "requirement": "parseable JSON with totals reconciling valid+invalid and errors_by_field derived from live report"}], "reward_checks": [{"name": "check_01_required_evidence", "checks": "schema doc, sample header, and summary spec exist locally and parser exposes required APIs"}, {"name": "check_02_intermediate_artifact", "checks": "parsed_output and validation_report present, parseable, non-empty and preserve header IDs"}, {"name": "check_03_final_semantics", "checks": "summary totals equal live report counts and errors_by_field matches per-entry error mentions per spec rules"}, {"name": "check_04_no_shortcut", "checks": "reject empty, placeholder, stale, hardcoded or verifier-only outputs; require live reconciliation not static copy"}], "instruction_boundary": {"mention": ["public goal", "fair starting workspace docs/data", "main final deliverable and completion signal", "only undiscoverable hard constants"], "hide": ["step-by-step commands", "path/field inventories", "schema/format dumps", "oracle repair recipe", "anti-shortcut implementation details", "private harness paths under tests/", "discoverable details that belong in local docs"]}, "environment_changes": ["none - reuse existing docs/, data/, specs; no new dependencies, network, or services"], "rationale": "Preferred environment_variable_resolution has no seed affordances (no .env/locale/timezone); config_data_consistency directly extends schema-vs-data validation plus summary aggregation with CLI reconciliation, adding depth while remaining controllable and verifiable."}, "gate_generation_quality": [], "gate_static_preflight": [], "precheck_attempts": 1, "precheck": {"ok": true, "verdict": "validated", "build_ok": true, "nop_reward": 0.0, "oracle_reward": 1.0, "detail": "nop=0.0, oracle=1.0", "seconds": 3.7}, "repair_log": []}, "stats": {"stages": {"affordance_ranking": {"seconds": 42.741, "cost_usd": 0.001019, "llm_calls": 1}, "contract": {"seconds": 47.921, "cost_usd": 0.001282, "llm_calls": 1}, "solution": {"seconds": 138.046, "cost_usd": 0.003081, "llm_calls": 1}, "verifier": {"seconds": 111.279, "cost_usd": 0.002878, "llm_calls": 1}, "instruction": {"seconds": 37.116, "cost_usd": 0.000868, "llm_calls": 1}, "env_align": {"seconds": 30.021, "cost_usd": 0.000639, "llm_calls": 1}, "consistency_repair": {"seconds": 116.192, "cost_usd": 0.003029, "llm_calls": 1}, "precheck": {"seconds": 4.08, "cost_usd": 0.0, "llm_calls": 0}}, "lineage_id": "L296-y-0313", "round": 4, "total_seconds": 527.396, "total_cost_usd": 0.012796}}}L295-y-0054-r5/task.tomlAdded+31
L295-y-0054-r5/tests/test.shAdded+30
L295-y-0054-r5/tests/test_state.pyAdded+232
L295-y-0054-r6/environment/DockerfileAdded+275
L295-y-0054-r6/instruction.mdAdded+3
L295-y-0054-r6/metadata.jsonAdded+1
L295-y-0054-r6/solution/solve.shAdded+523
L295-y-0054-r6/stats.jsonAdded+38
L295-y-0054-r6/task.tomlAdded+31
L295-y-0054-r6/tests/test.shAdded+30
L295-y-0054-r6/tests/test_state.pyAdded+322
L296-y-0313-r0/bootstrap_report.jsonAdded+15
L296-y-0313-r0/environment/DockerfileAdded+3
L296-y-0313-r0/instruction.mdAdded+62
L296-y-0313-r0/metadata.jsonAdded+1
L296-y-0313-r0/solution/solve.shAdded+140
L296-y-0313-r0/stats.jsonAdded+18
L296-y-0313-r0/task.tomlAdded+31
L296-y-0313-r0/tests/test.shAdded+30
L296-y-0313-r0/tests/test_state.pyAdded+50
L296-y-0313-r1/environment/DockerfileAdded+44
L296-y-0313-r1/instruction.mdAdded+3
L296-y-0313-r1/metadata.jsonAdded+1
L296-y-0313-r1/round_report.jsonAdded+161
L296-y-0313-r1/solution/solve.shAdded+325
L296-y-0313-r1/stats.jsonAdded+48
L296-y-0313-r1/task.tomlAdded+31
L296-y-0313-r1/tests/test.shAdded+30
L296-y-0313-r1/tests/test_state.pyAdded+338
L296-y-0313-r2/environment/DockerfileAdded+44
L296-y-0313-r2/instruction.mdAdded+3
L296-y-0313-r2/metadata.jsonAdded+1
L296-y-0313-r2/round_report.jsonAdded+158
L296-y-0313-r2/solution/solve.shAdded+244
L296-y-0313-r2/stats.jsonAdded+48
L296-y-0313-r2/task.tomlAdded+31
L296-y-0313-r2/tests/test.shAdded+30
L296-y-0313-r2/tests/test_state.pyAdded+360
L296-y-0313-r3/environment/DockerfileAdded+70
L296-y-0313-r3/instruction.mdAdded+5
L296-y-0313-r3/metadata.jsonAdded+1
L296-y-0313-r3/round_report.jsonAdded+169
L296-y-0313-r3/solution/solve.shAdded+304
L296-y-0313-r3/stats.jsonAdded+48
L296-y-0313-r3/task.tomlAdded+31
L296-y-0313-r3/tests/test.shAdded+30
L296-y-0313-r3/tests/test_state.pyAdded+488
L296-y-0313-r4/environment/DockerfileAdded+72
L296-y-0313-r4/instruction.mdAdded+3
L296-y-0313-r4/metadata.jsonAdded+1