Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/sw-bicycle/README.mdAdded+21
- tasks/sw-bicycle/RUBRIC.mdAdded+16
- tasks/sw-bicycle/environment/.dockerignoreAdded+2
- tasks/sw-bicycle/environment/DockerfileAdded+14
- tasks/sw-bicycle/environment/inkscape-autostart.desktopAdded+5
- tasks/sw-bicycle/environment/start-task.shAdded+10
- tasks/sw-bicycle/environment/terminal-blocked.shAdded+4
- tasks/sw-bicycle/environment/tutorial/index.htmlAdded+1
- tasks/sw-bicycle/instruction.mdAdded+9
- tasks/sw-bicycle/task.tomlAdded+26
- tasks/sw-bicycle/tests/VERIFIER.mdAdded+16
- tasks/sw-bicycle/tests/engine.pyAdded+175
- tasks/sw-bicycle/tests/features.pyAdded+153
- tasks/sw-bicycle/tests/grade.pyAdded+10
- tasks/sw-bicycle/tests/inspect_blend.pyAdded+40
- tasks/sw-bicycle/tests/oracle/check-examples.jsonAdded+32
- tasks/sw-bicycle/tests/oracle/config.jsonAdded+5
- tasks/sw-bicycle/tests/oracle/source-spec.jsonAdded
- tasks/sw-bicycle/tests/oracle/source.svgAdded
- tasks/sw-bicycle/tests/pre-svg-v2/RUBRIC.mdAdded+13
- tasks/sw-bicycle/tests/pre-svg-v2/instruction.mdAdded+7
- tasks/sw-bicycle/tests/pre-svg-v2/tests__VERIFIER.mdAdded+7
- tasks/sw-bicycle/tests/pre-svg-v2/tests__grade.pyAdded+121
- tasks/sw-bicycle/tests/pre-svg-v2/tests__oracle__config.jsonAdded+46
- tasks/sw-bicycle/tests/pre-svg-v2/tests__rubric.jsonAdded+34
- tasks/sw-bicycle/tests/rubric.jsonAdded+28
- tasks/sw-bicycle/tests/svg-v2.jsonAdded+146
- tasks/sw-bicycle/tests/svg_reference.pyAdded+129
- tasks/sw-bicycle/tests/test.shAdded+4
- tasks/t40-rct-onetile-1000/environment/await-assets.shAdded+14
- tasks/t40-rct-onetile-1000/environment/controller.jsAdded+336
- tasks/t40-rct-onetile-1000/environment/entrypoint.shAdded+78
- tasks/t40-rct-onetile-1000/environment/onetile-base.parkAdded
- tasks/t40-rct-onetile-1000/environment/onetile-config.jsAdded+304
- tasks/t40-rct-onetile-1000/environment/openbox-rc.xmlAdded+24
- tasks/t40-rct-onetile-1000/environment/restrict-console.pyAdded+51
- tasks/t40-rct-onetile-1000/environment/terminal-blocked.shAdded+7
- tasks/t45-bouncing-ball/README.mdAdded+14
- tasks/t45-bouncing-ball/RUBRIC.mdAdded+24
- tasks/t45-bouncing-ball/instruction.mdAdded+9
- tasks/t45-bouncing-ball/task.tomlAdded+43
- tasks/t45-bouncing-ball/tests/_vedit_verifier.pyAdded+359
- tasks/t45-bouncing-ball/tests/friction-audit-install.jsonAdded+10
- tasks/t45-bouncing-ball/tests/friction_audit/README.mdAdded+49
- tasks/t45-bouncing-ball/tests/friction_audit/T19_IMPLEMENTED.mdAdded+62
- tasks/t45-bouncing-ball/tests/friction_audit/actual-render-diagnostics.jsonAdded+66
- tasks/t45-bouncing-ball/tests/friction_audit/actual-t52-measurements.jsonAdded+401
- tasks/t45-bouncing-ball/tests/friction_audit/artifacts.pyAdded+25
- tasks/t45-bouncing-ball/tests/friction_audit/cli.pyAdded+141
- tasks/t45-bouncing-ball/tests/friction_audit/inspect_header.pyAdded+106
123456789101112131415161718192021# Bicycle Schematic
Harbor task directory for review, not yet approved for model runs.
| File | Purpose ||---|---|| instruction.md | Agent task brief || RUBRIC.md / tests/rubric.json | Criteria and draft weights || tests/grade.py / tests/VERIFIER.md | Calibrated offline SVG reference grader || tests/oracle/config.json | Calibrated hidden reference measurements || environment/Dockerfile | GUI environment build || solution/ORACLE.md | Human oracle workflow || status.json | Missing inputs and launch prerequisites |
## Missing before running
- Review extracted SVG geometry and exact labels; freeze semantic region checks/tolerances.- Review instructions/rubric, set up oracle, calibrate verifier and negative examples.- Build and smoke-test pinned GUI environment and GUI-only enforcement.
No task has been launched.12345678910111213141516# bicycle: SVG verifier v2
| Category | Weight | Measurement ||---|---:|---|| Geometry | 40% | Bidirectional rendered boundary distance; no alignment || Structure | 30% | Reference-derived features and task-specific checks; no XML counts || Appearance | 20% | Local median painted colors, independently of geometry || Delivery | 10% | Half page validity, half SVG-to-PNG correspondence |
The verifier renders the reference SVG with Inkscape, fits the visible drawing to 800px on a centered white 1000px page, and records hashes. Candidate page units and viewBox may differ if their visible output agrees. Hidden or pasted raster images are removed before candidate rendering. No VLM is used.
Boundary distance full-credit bands: mean ≤3px and 95th percentile ≤7px; scores decline to zero at 18px and 35px respectively. These are initial versioned tolerances, not proven human-quality thresholds. Independent human pen-tool calibration remains pending.
Flat vector fills are accepted for raster-backed texture. A missing feature loses its own geometry/structure credit; it does not multiply all scores. Dependencies or reference failures produce evaluation-error.json and no reward.
Details, measurements and overlay: /logs/verifier/score-report.json and /logs/verifier/artifacts/. Original files: tests/pre-svg-v2/.12__pycache__*.log1234567891011121314FROM debian:bookworm-slimENV DEBIAN_FRONTEND=noninteractiveRUN apt-get update && apt-get install -y --no-install-recommends inkscape chromium ffmpeg python3 python3-numpy python3-pil python3-pip xvfb xfce4-session xfwm4 xfce4-panel xfce4-settings xfdesktop4 x11vnc xdotool wmctrl imagemagick webp dbus-x11 thunar xdg-utils fonts-dejavu-core fonts-liberation ca-certificates libgl1-mesa-dri libglx-mesa0 libglu1-mesa pulseaudio && rm -rf /var/lib/apt/lists/*COPY media/ /root/media/COPY tutorial/ /opt/tutorial/COPY start-task.sh /usr/local/bin/start-taskCOPY terminal-blocked.sh /usr/local/bin/terminal-blockedRUN chmod 755 /usr/local/bin/start-task && mkdir -p /root/output /root/Desktop /logs/verifier \ && rm -f /usr/share/applications/*terminal*.desktop /usr/share/applications/*xterm*.desktopRUN chmod 755 /usr/local/bin/terminal-blocked && for t in xterm uxterm xfce4-terminal x-terminal-emulator xfce4-appfinder xfrun4; do rm -f /usr/bin/$t; ln -s /usr/local/bin/terminal-blocked /usr/bin/$t; doneENV LIBGL_ALWAYS_SOFTWARE=1WORKDIR /rootCOPY inkscape-autostart.desktop /root/.config/autostart/inkscape.desktopCMD ["/usr/local/bin/start-task"]12345[Desktop Entry]Type=ApplicationName=InkscapeExec=inkscape /usr/share/inkscape/templates/default.svgTerminal=false12345678910#!/bin/bashset -euo pipefailmkdir -p /root/output /logs/verifier /root/.config/autostartcat > /root/.config/autostart/task.desktop <<'EOF'[Desktop Entry]Type=ApplicationName=Bicycle SchematicExec=inkscape /usr/share/inkscape/templates/default.svgEOFexec sleep infinity1234#!/bin/shmkdir -p /logs/artifactsprintf "terminal launch attempted\n" >> /logs/artifacts/terminal-attempts.logexit 11<!doctype html><meta charset="utf-8"><title>Bicycle Schematic</title><h1>Bicycle Schematic</h1><p>Tutorial/reference media must be staged before launch.</p><p>Reproduce the supplied reference image in Inkscape using editable vector shapes. Wheel centers/radii, frame vertices, connected parts, labels and leader lines. Preserve the reference aspect ratio. Use a 1000 × 1000 white page, scale the source canvas uniformly so its longer dimension occupies 800 pixels, and center it. These output conventions override the source canvas dimensions. Do not import the source SVG, trace automatically, or use a screenshot as the drawing.</p><p>References and starting assets: /root/media</p>123456789# Bicycle Schematic
Please recreate the bicycle schematic in `/root/media/reference.png` as an editable Inkscape drawing. Keep the wheels, frame connections, and labels clear.
Use a 1000 × 1000 white page, with the reference centered and its longer side about 800 px. Draw it as vectors rather than pasting the image. Use the Inkscape GUI. In-app scripting is fine; do not open or use a terminal.
Save `final.svg` and `final.png` in `/root/output` when you are done.
Match visible outlines closely: mean boundary deviation within 3 px and 95% within 7 px earns full geometry credit. Equivalent vector constructions are accepted; the number of SVG objects is not graded.1234567891011121314151617181920212223242526schema_version = "1.4"artifacts = ["/root/output", "/logs/artifacts"][task]name = "sid/sw-bicycle"version = "0.1.0"description = "Bicycle Schematic GUI-only reference recreation"authors = []keywords = ["computer-use", "gui-only", "reference-recreation", "inkscape"][metadata]app = "inkscape"review_status = "verifier-calibrated-final-review-pending"initial_batch = trueapp_url = "file:///opt/tutorial/index.html"[verifier]timeout_sec = 1800.0[agent]timeout_sec = 21600.0network_mode = "no-network"[environment]network_mode = "no-network"build_timeout_sec = 2400.0os = "linux"mcp_servers = [][environment.env]SW_TASK_SLUG = "bicycle"[solution.env]12345678910111213141516# bicycle: SVG verifier v2
| Category | Weight | Measurement ||---|---:|---|| Geometry | 40% | Bidirectional rendered boundary distance; no alignment || Structure | 30% | Reference-derived features and task-specific checks; no XML counts || Appearance | 20% | Local median painted colors, independently of geometry || Delivery | 10% | Half page validity, half SVG-to-PNG correspondence |
The verifier renders the reference SVG with Inkscape, fits the visible drawing to 800px on a centered white 1000px page, and records hashes. Candidate page units and viewBox may differ if their visible output agrees. Hidden or pasted raster images are removed before candidate rendering. No VLM is used.
Boundary distance full-credit bands: mean ≤3px and 95th percentile ≤7px; scores decline to zero at 18px and 35px respectively. These are initial versioned tolerances, not proven human-quality thresholds. Independent human pen-tool calibration remains pending.
Flat vector fills are accepted for raster-backed texture. A missing feature loses its own geometry/structure credit; it does not multiply all scores. Dependencies or reference failures produce evaluation-error.json and no reward.
Details, measurements and overlay: /logs/verifier/score-report.json and /logs/verifier/artifacts/. Original files: tests/pre-svg-v2/.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""SVG outcome grading, version 2. No XML-count or duplicated overlap scores."""import hashlibimport jsonimport reimport shutilimport subprocessimport xml.etree.ElementTree as ETfrom pathlib import Pathimport numpy as npfrom PIL import Image, ImageFilter
VERSION='svg-outcome-v2'SLUGS=['rosette','hierarchy','rlc-circuit','four-bar','gear','bicycle','isometric-house','floor-plan','flowchart']WEIGHTS={'geometry':.40,'structure':.30,'styling':.20,'delivery':.10}def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()def tag(node):return node.tag.rsplit('}',1)[-1]def dimension(value): m=re.fullmatch(r'\s*([+]?(?:\d+(?:\.\d*)?|\.\d+))\s*(px|mm|cm|in|pt|pc|q)?\s*',value or '') if not m:return None return float(m[1])*{'px':1,'mm':96/25.4,'cm':96/2.54,'in':96,'pt':96/72,'pc':16,'q':96/101.6,None:1}[m[2]]
def sanitize(source,destination): data=Path(source).read_bytes() if len(data)>32*1024*1024:raise ValueError('SVG exceeds 32 MiB bounded parser limit') if b'<!ENTITY' in data.upper():raise ValueError('Entity declarations are unsupported') root=ET.fromstring(data) if tag(root)!='svg':raise ValueError('Not an SVG document') if len(list(root.iter()))>100000:raise ValueError('SVG exceeds bounded element limit') removed=[] def walk(node): for child in list(node): if tag(child) in {'image','foreignObject','script'}: removed.append(tag(child));node.remove(child);continue walk(child) for k,v in node.attrib.items(): if k.rsplit('}',1)[-1].lower().startswith('on'):raise ValueError('SVG event handlers unsupported') if k.rsplit('}',1)[-1]=='href' and not v.startswith('#'):raise ValueError('External references unsupported') content=' '.join(node.attrib.values())+' '+(node.text or '') if '@import' in content:raise ValueError('CSS imports unsupported') for target in re.findall(r'url\(\s*[\'\"]?([^\'\")\s]+)',content): if not target.startswith('#'):raise ValueError('External paint references unsupported') walk(root) vb=root.get('viewBox') if vb: values=[float(v) for v in re.split('[ ,]+',vb.strip())] if len(values)!=4 or not all(np.isfinite(values)) or min(values[2:])<=0:raise ValueError('Invalid viewBox') w,h=dimension(root.get('width')),dimension(root.get('height')) page=w is not None and h is not None and abs(w-1000)<.1 and abs(h-1000)<.1 # Drawing count is diagnostic only; visible raster-stripped output is decisive. count=sum(tag(n) in {'path','rect','circle','ellipse','line','polyline','polygon','text','use'} for n in root.iter()) destination.write_bytes(ET.tostring(root,encoding='utf-8',xml_declaration=True)) return {'page_1000':page,'page_css_px':[w,h],'removed_elements':removed,'drawable_count_diagnostic':count}
def render(svg,out,drawing=False): exe=shutil.which('inkscape') if not exe:raise RuntimeError('Verifier dependency missing: Inkscape') cmd=[exe,str(svg),'--export-type=png','--export-filename='+str(out),'--export-width=1000'] if drawing:cmd.append('--export-area-drawing') else:cmd.extend(['--export-area-page','--export-height=1000']) p=subprocess.run(cmd,capture_output=True,text=True,timeout=90) if p.returncode or not out.exists():raise RuntimeError('Renderer failed: '+p.stderr[-1000:]) image=Image.open(out).convert('RGBA') if drawing: bbox=image.getbbox() if not bbox:raise RuntimeError('Reference SVG has no visible drawing') image=image.crop(bbox) scale=800/max(image.size) image=image.resize(tuple(max(1,round(v*scale)) for v in image.size),Image.Resampling.LANCZOS) paper=Image.new('RGBA',(1000,1000),'white') paper.alpha_composite(image,((1000-image.width)//2,(1000-image.height)//2)) else: paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image) paper.convert('RGB').save(out)
def normalize_reference(source,destination): """Preserve source coordinate mapping; fit Inkscape's evaluated drawing bounds.""" p=subprocess.run(['inkscape',str(source),'--query-all'],capture_output=True,text=True,timeout=90) if p.returncode:raise RuntimeError('Reference bounds failed: '+p.stderr[-1000:]) try:x,y,w,h=map(float,p.stdout.splitlines()[0].split(',')[-4:]) except (ValueError,IndexError) as exc:raise RuntimeError('Reference drawing bounds unavailable') from exc if not all(np.isfinite([x,y,w,h])) or min(w,h)<=0:raise RuntimeError('Reference bounds invalid') scale=800/max(w,h) root=ET.parse(source).getroot() outer=ET.Element('{http://www.w3.org/2000/svg}svg',{'width':'1000','height':'1000','viewBox':'0 0 1000 1000'}) group=ET.SubElement(outer,'{http://www.w3.org/2000/svg}g',{'transform':f'matrix({scale},0,0,{scale},{500-scale*(x+w/2)},{500-scale*(y+h/2)})'}) group.append(root);destination.write_bytes(ET.tostring(outer))
def foreground(rgb):return np.min(rgb,axis=2)<245def boundary(mask): eroded=np.asarray(Image.fromarray(mask.astype('uint8')*255).filter(ImageFilter.MinFilter(3)))>0 return mask&~erodeddef distances(source,target,max_distance=30): remaining=source.copy();values=np.full(source.shape,max_distance,dtype=np.float32) grown=target.copy() for d in range(max_distance+1): hit=remaining&grown;values[hit]=d;remaining[hit]=False if not remaining.any():break grown=np.asarray(Image.fromarray(grown.astype('uint8')*255).filter(ImageFilter.MaxFilter(3)))>0 return values[source]def geometry(a,b): ma,mb=foreground(a),foreground(b) if not ma.any():return 0.,{'reason':'No visible editable vector drawing'} # Boundary distance at half resolution; no registration to hide placement errors. small=lambda x:np.asarray(Image.fromarray(x.astype('uint8')*255).resize((500,500),Image.Resampling.NEAREST))>0 ea,eb=boundary(small(ma)),boundary(small(mb)) ds=np.concatenate([distances(ea,eb),distances(eb,ea)])*2 mean=float(ds.mean());p95=float(np.percentile(ds,95)) ramp=lambda x,full,zero:max(0.,min(1.,(zero-x)/(zero-full))) score=.6*ramp(mean,3,18)+.4*ramp(p95,7,35) return score,{'mean_boundary_distance_px':mean,'p95_boundary_distance_px':p95,'distance_metric':'bidirectional Chebyshev raster boundary distance; no alignment','full_credit_px':[3,7],'zero_credit_px':[18,35]}
def appearance(a,b): # Local median color measures surface fills, excluding texture residual and # edge placement. Geometry/structure own missing or displaced regions. common=foreground(a)&foreground(b) support=np.asarray(Image.fromarray(common.astype('uint8')*255).filter(ImageFilter.MinFilter(5)))>0 errors=[] for y in range(0,1000,50): for x in range(0,1000,50): roi=support[y:y+50,x:x+50] if roi.sum()<20:continue ac=a[y:y+50,x:x+50][roi];bc=b[y:y+50,x:x+50][roi] errors.append(float(np.abs(np.median(ac,axis=0)-np.median(bc,axis=0)).mean()/255)) if not errors: # Thin black lines have no five-pixel interior; use shared painted samples. if common.any():errors=[float(np.abs(a[common].astype(float).mean(axis=0)-b[common].astype(float).mean(axis=0)).mean()/255)] else:return 0.,{'reason':'No corresponding painted support'} err=float(np.mean(errors)) return max(0.,min(1.,(0.20-err)/(0.20-.015))),{'local_median_rgb_error':err,'sampled_tiles':len(errors),'texture_policy':'Flat vector fills accepted; high-frequency raster texture is not required','full_credit_rgb_error':.015,'zero_credit_rgb_error':.20}
def export_match(rendered,submitted): if not submitted.exists():return 0.,{'reason':'Missing final.png'} try: image=Image.open(submitted).convert('RGBA') if image.size!=(1000,1000):return 0.,{'reason':'PNG must be 1000x1000'} paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image) a=np.asarray(Image.open(rendered).convert('RGB'),dtype=float)/255 b=np.asarray(paper.convert('RGB'),dtype=float)/255 support=np.maximum(1-a.min(axis=2),1-b.min(axis=2))>.035 err=float(np.abs(a-b).mean(axis=2)[support].mean()) if support.any() else 0. return max(0.,min(1.,(.10-err)/(.10-.005))),{'foreground_mae':err,'full_credit_mae':.005,'zero_credit_mae':.10} except (OSError,ValueError) as exc:return 0.,{'reason':str(exc)}
def run(task,output,log): from features import structure task,output,log=map(Path,(task,output,log));log.mkdir(parents=True,exist_ok=True) (log/'reward.txt').unlink(missing_ok=True) cfg=json.loads((task/'svg-v2.json').read_text());slug=cfg['task'] oracle=task/'oracle';reference=oracle/'canonical-v2.png';source=oracle/'source.svg' if sha(reference)!=cfg['reference_sha256'] or sha(source)!=cfg['source_sha256']:raise RuntimeError('Reference provenance mismatch') work=log/'artifacts';work.mkdir(exist_ok=True) svg=output/'final.svg';scores=dict.fromkeys(WEIGHTS,0.);details={} if svg.exists(): clean=work/'candidate-vector.svg';rendered=work/'candidate-render.png' try:native=sanitize(svg,clean) except (ET.ParseError,ValueError,OverflowError) as exc:details={'invalid_candidate':str(exc)} else: render(clean,rendered) a=np.asarray(Image.open(rendered).convert('RGB'));b=np.asarray(Image.open(reference).convert('RGB')) if foreground(a).any(): scores['geometry'],details['geometry']=geometry(a,b) scores['structure'],details['structure']=structure(a,b,cfg['manifest']) scores['styling'],details['styling']=appearance(a,b) export,ed=export_match(rendered,output/'final.png') scores['delivery']=.5*float(native['page_1000'])+.5*export details.update(native=native,delivery=ed) overlay=np.stack([foreground(b)*200,foreground(a)*180,np.zeros((1000,1000))],axis=2).astype('uint8') Image.fromarray(overlay).save(work/'boundary-overlay.png') else:details['reason']='Missing final.svg' report={'version':VERSION,'task':slug,'checks':[{'id':k,'weight':v,'score':float(scores[k]),'earned':float(scores[k])*v} for k,v in WEIGHTS.items()], 'reward':sum(scores[k]*v for k,v in WEIGHTS.items()),'details':details,'reference_svg_sha256':sha(source),'reference_render_sha256':sha(reference),'scorer_sha256':sha(__file__), 'calibration':'Versioned initial policy; equivalent-construction and defect fixtures tested. Human pen-tool tolerance calibration remains a limitation.'} (log/'score-report.json').write_text(json.dumps(report,indent=2,allow_nan=False)+'\n') (log/'reward.txt').write_text(f"{report['reward']:.6f}\n") return report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Reference-bound regional structure checks; no SVG element-count requirements.
Regions are human-labelled against the retained reference, then mapped to theactual canonical SVG render's foreground bounding box. They describe visibleroles, not DOM identities. Raster checks cannot prove electrical/mechanicalfunction or recover hidden geometry. Exact label recognition is not claimed."""from pathlib import Pathimport hashlibimport jsonimport mathimport numpy as npfrom PIL import Image, ImageFilter, ImageDraw
# Coordinates measured on the supplied 1000-square reference PNGs. Every ROI is# rebound to the canonical reference render's foreground box by build_manifest.ANNOTATIONS = { 'rosette': [('central junction',(.46,.46,.54,.54)),('upper petal',(.43,.16,.57,.44)),('lower petal',(.43,.56,.57,.84))], 'hierarchy': [('leaf '+s,(x-.055,.175,x+.055,.265)) for s,x in zip('abcdef',[.15,.29,.43,.57,.71,.85])] + [('bc merge',(.31,.315,.415,.405)),('de merge',(.59,.315,.70,.405)),('def merge',(.59,.46,.70,.55)),('bcdef merge',(.285,.60,.445,.68)),('root abcdef',(.13,.735,.33,.815))], 'rlc-circuit': [('resistor zigzag',(.35,.28,.51,.37)),('capacitor plates',(.58,.47,.73,.55)),('inductor coils',(.80,.43,.855,.565)),('voltage source plates',(.10,.49,.29,.55)),('R label',(.335,.38,.39,.445)),('C label',(.505,.48,.565,.57)),('L label',(.86,.47,.905,.545)),('V label',(.28,.525,.335,.59))], 'four-bar': [('drag-link mechanism',(.17,.397,.35,.526)),('crank-rocker mechanism',(.36,.395,.575,.525)),('double-rocker mechanism',(.595,.40,.735,.525)),('parallelogram mechanism',(.755,.465,.90,.525)),('four captions',(.21,.545,.90,.605)),('rotation guide',(.10,.40,.30,.56))], 'gear': [('central bore',(.39,.33,.61,.43)),('top face inner ring',(.25,.225,.75,.50)),('upper tooth lobes',(.29,.145,.72,.24)),('left tooth contour',(.10,.28,.24,.61)),('right tooth contour',(.76,.29,.90,.62)),('front extrusion',(.28,.575,.72,.845))], 'bicycle': [('rear wheel',(.22,.45,.43,.675)),('front wheel',(.585,.45,.805,.675)),('frame triangle',(.36,.40,.63,.565)),('handlebar and fork',(.59,.31,.70,.56)),('saddle',(.35,.32,.455,.365)),('crank drivetrain',(.435,.53,.555,.61)),('rear drivetrain',(.305,.56,.41,.64)),('part labels left',(.13,.345,.27,.715)),('part labels right',(.77,.51,.90,.64)),('part labels upper',(.495,.28,.83,.40))], 'isometric-house': [('roof left slope',(.20,.15,.52,.41)),('roof middle slope',(.45,.31,.65,.52)),('roof right slope',(.66,.44,.82,.58)),('front wall',(.145,.34,.44,.64)),('right facade',(.65,.60,.85,.82)),('entrance',(.30,.67,.41,.80)),('left dormer',(.24,.23,.31,.305)),('middle dormer',(.38,.33,.45,.40)),('right dormer',(.56,.43,.64,.515))], 'floor-plan': [('green side room',(.105,.47,.21,.64)),('yellow main room',(.21,.47,.69,.74)),('pink right room',(.69,.47,.90,.74)),('blue upper room',(.695,.26,.90,.47)),('toilet symbol',(.153,.56,.194,.62)),('central magenta fixture',(.37,.57,.455,.633)),('right L fixture',(.645,.54,.76,.735)),('orange right fixture',(.82,.61,.875,.735)),('upper fixtures',(.69,.26,.785,.455)),('north wall opening',(.85,.25,.885,.28)),('bottom door gap',(.27,.725,.37,.75))], 'flowchart': [('start circle',(.421,.10,.504,.184))] + [('process '+str(i),(.40,y,.525,y+.055)) for i,y in enumerate([.209,.285,.362,.44,.846],1)] + [('decision '+str(i),(.41,y,.515,y+.09)) for i,y in enumerate([.515,.625,.738],1)] + [('left branch process',(.263,.533,.388,.587)),('right branch process',(.611,.533,.734,.587)),('right second process',(.611,.61,.734,.664)),('right end circle',(.625,.688,.713,.781))],}# Connections checked along their visible middle, away from labels/nodes. Paths# represent pixel-supported strokes, not a claim that the SVG is a semantic graph.CONNECTIONS = { 'hierarchy': [('b to bc',[(.31,.266),(.35,.318)]),('c to bc',[(.411,.26),(.387,.316)]),('d to de',[(.59,.265),(.618,.315)]),('e to de',[(.69,.26),(.66,.32)]),('de to def',[(.64,.402),(.64,.461)]),('f to def',[(.825,.259),(.674,.473)]),('bc to bcdef',[(.36,.408),(.36,.598)]),('def to bcdef',[(.59,.52),(.427,.61)]),('a to root',[(.157,.266),(.220,.73)]),('bcdef to root',[(.323,.675),(.266,.739)])], 'rlc-circuit': [('top left wire',[(.20,.36),(.20,.475)]),('top resistor lead',[(.24,.329),(.342,.329)]),('upper right bus',[(.52,.329),(.813,.329)]),('capacitor upper lead',[(.656,.35),(.656,.475)]),('capacitor lower lead',[(.656,.56),(.656,.69)]),('bottom bus',[(.22,.704),(.811,.704)]),('right lower lead',[(.828,.59),(.828,.69)]),('source lower lead',[(.20,.555),(.20,.69)])], 'flowchart': [('main stem '+str(i),[(.462,y0),(.462,y1)]) for i,(y0,y1) in enumerate([(.186,.206),(.264,.284),(.34,.36),(.415,.438),(.49,.513),(.600,.625),(.715,.738),(.825,.846)],1)] + [('right branch',[(.514,.559),(.61,.559)]),('right continuation',[(.674,.589),(.674,.61)]),('right end connector',[(.673,.666),(.673,.689)]),('left decision branch',[(.414,.669),(.322,.669),(.322,.590)]),('left lower branch',[(.415,.780),(.322,.780),(.322,.67)])],}
def rgb(value): if isinstance(value,(str,Path)): im=Image.open(value).convert('RGBA'); bg=Image.new('RGBA',im.size,'white');bg.alpha_composite(im);return np.asarray(bg.convert('RGB')) return np.asarray(value,dtype=np.uint8)[...,:3]
def foreground(a): return a.min(axis=2)<242
def bbox(a): y,x=np.where(foreground(a)) if not len(x): raise ValueError('Reference has no visible foreground') return [int(x.min()),int(y.min()),int(x.max()+1),int(y.max()+1)]
def _map_point(p,old,new): return [new[0]+(p[0]*1000-old[0])/(old[2]-old[0])*(new[2]-new[0]),new[1]+(p[1]*1000-old[1])/(old[3]-old[1])*(new[3]-new[1])]
def _component_boxes(mask,min_area): seen=np.zeros_like(mask,dtype=bool);boxes=[];h,w=mask.shape for y,x in zip(*np.where(mask)): if seen[y,x]:continue stack=[(int(y),int(x))];seen[y,x]=True;pts=[] while stack: yy,xx=stack.pop();pts.append((yy,xx)) for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)): cy,cx=yy+dy,xx+dx if 0<=cy<h and 0<=cx<w and mask[cy,cx] and not seen[cy,cx]:seen[cy,cx]=True;stack.append((cy,cx)) if len(pts)>=min_area: ys,xs=zip(*pts);boxes.append([min(xs),min(ys),max(xs)+1,max(ys)+1]) return sorted(boxes,key=lambda b:(b[1],b[0]))
def build_manifest(slug,reference_svg,reference_render): if slug not in ANNOTATIONS: raise ValueError('Unknown SVG reproduction task '+slug) ref=rgb(reference_render); targetbox=bbox(ref) # Original annotations use the supplied PNG's figure bounding box, not its XML. original=Path(reference_svg).with_name('reference.png') if not original.exists(): raise ValueError('Adjacent original reference.png required for annotation mapping') oldbox=bbox(rgb(original)); regions=[] for name,r in ANNOTATIONS[slug]: a=_map_point(r[:2],oldbox,targetbox);b=_map_point(r[2:],oldbox,targetbox) regions.append({'name':name,'box':[round(v,4) for v in a+b],'method':'local_edge_profile'}) if slug=='isometric-house': # Dark blue glazing is used only to locate the reference's visible features. # Candidate scoring then uses boundary geometry, accepting different SVG code # and different colours without counting DOM nodes. navy=(ref[:,:,2].astype(int)-ref[:,:,0]>10)&(ref[:,:,1].astype(int)-ref[:,:,0]>8)&(ref.mean(axis=2)<125) for i,box in enumerate(_component_boxes(navy,min_area=100),1): regions.append({'name':'glazing region '+str(i),'box':[max(0,box[0]-5),max(0,box[1]-5),min(ref.shape[1],box[2]+5),min(ref.shape[0],box[3]+5)],'method':'local_edge_profile','grounding':'Connected navy area in reference only; not a candidate object-count requirement.'}) paths=[{'name':name,'points':[_map_point(p,oldbox,targetbox) for p in points],'method':'visible_stroke_support'} for name,points in CONNECTIONS.get(slug,[])] return {'schema':'svg-structure-v1','task':slug,'source_sha256':hashlib.sha256(Path(reference_svg).read_bytes()).hexdigest(),'reference_sha256':hashlib.sha256(Path(reference_render).read_bytes()).hexdigest(),'render_size':[ref.shape[1],ref.shape[0]],'reference_foreground_bbox':targetbox,'regions':regions,'connections':paths,'symmetry':{'order':6,'center':[(targetbox[0]+targetbox[2])/2,(targetbox[1]+targetbox[3])/2],'radius':min(targetbox[2]-targetbox[0],targetbox[3]-targetbox[1])/2} if slug=='rosette' else None,'limits':['Checks visible regional boundaries and connection stroke support; does not infer hidden topology, functional mechanics or exact text transcription.','Structure is an independent regional allocation; it does not multiply other grade categories.','No SVG object-count gate.']}
def _edges(a): # Smooth away texture and antialiasing, leaving shape/color-region boundaries. im=Image.fromarray(a).filter(ImageFilter.GaussianBlur(3)) f=np.asarray(im,dtype=np.float32);out=np.zeros(f.shape[:2],np.float32) out[:,1:]=np.maximum(out[:,1:],np.max(np.abs(f[:,1:]-f[:,:-1]),axis=2)) out[1:]=np.maximum(out[1:],np.max(np.abs(f[1:]-f[:-1]),axis=2)) return np.minimum(np.maximum(out-3,0)/8,1)
def _profile(a,box): x0,y0,x1,y1=box;x0=max(0,int(x0));y0=max(0,int(y0));x1=min(a.shape[1],int(math.ceil(x1)));y1=min(a.shape[0],int(math.ceil(y1))) if x1<=x0 or y1<=y0:return np.zeros(64) crop=a[y0:y1,x0:x1]; out=[] for yy in np.array_split(crop,8,axis=0): for cell in np.array_split(yy,8,axis=1):out.append(float(cell.mean()) if cell.size else 0) return np.asarray(out)
def _ratio(c,r): if r.sum()<1e-5:return 1. if c.sum()<1e-5 else 0. # Symmetric regional edge-mass similarity; extra boundaries are penalized. return float(2*np.minimum(c,r).sum()/(c.sum()+r.sum()+1e-12))
def _stroke_support(mask,points): vals=[];h,w=mask.shape for p,q in zip(points,points[1:]): n=max(2,int(math.hypot(q[0]-p[0],q[1]-p[1])/2)) for t in np.linspace(0,1,n): x=int(round(p[0]*(1-t)+q[0]*t));y=int(round(p[1]*(1-t)+q[1]*t));r=4 win=mask[max(0,y-r):min(h,y+r+1),max(0,x-r):min(w,x+r+1)] vals.append(float(win.any()) if win.size else 0.) return float(np.mean(vals)) if vals else 0.
def _polar(a,center,radius): # Compare six sector occupancy signatures to reference; filling white gaps, # losing a petal or making an asymmetric flower changes these signatures. h,w=a.shape;angles=np.linspace(0,2*math.pi,720,endpoint=False);radii=np.linspace(.06,.94,60)*radius xx=np.rint(center[0]+np.cos(angles)[:,None]*radii).astype(int);yy=np.rint(center[1]+np.sin(angles)[:,None]*radii).astype(int) xx=np.clip(xx,0,w-1);yy=np.clip(yy,0,h-1);return a[yy,xx].astype(float)
def structure(candidateRGB,referenceRGB,manifest): c=rgb(candidateRGB);r=rgb(referenceRGB) if c.shape!=r.shape or list(c.shape[:2][::-1])!=manifest['render_size']:raise ValueError('Canonical render dimensions differ') ce,re=_edges(c),_edges(r);regions=[] for item in manifest['regions']: a,b=_profile(ce,item['box']),_profile(re,item['box']);s=_ratio(a,b) regions.append({'name':item['name'],'score':s,'candidate_edge_mass':float(a.sum()),'reference_edge_mass':float(b.sum()),'box':item['box']}) connections=[];cf,rf=foreground(c),foreground(r) for item in manifest['connections']: a,b=_stroke_support(ce>0,item['points']),_stroke_support(re>0,item['points']) # Only positions actually grounded by the reference contribute. connections.append({'name':item['name'],'score':min(1.,a/max(b,.001)) if b>=.5 else None,'candidate_support':a,'reference_support':b,'points':item['points']}) parts=[float(np.mean([x['score'] for x in regions]))] active=[x['score'] for x in connections if x['score'] is not None] if active:parts.append(float(np.mean(active))) symmetry=None if manifest.get('symmetry'): spec=manifest['symmetry'];cp=_polar(cf,spec['center'],spec['radius']);rp=_polar(rf,spec['center'],spec['radius']) sector_scores=[float(1-np.abs(a-b).mean()) for a,b in zip(np.split(cp,6),np.split(rp,6))] symmetry={'sector_scores':sector_scores,'reference_sector_match':float(np.mean(sector_scores)),'candidate_rotation_agreement':float(1-np.abs(cp-np.roll(cp,120,axis=0)).mean()),'reference_rotation_agreement':float(1-np.abs(rp-np.roll(rp,120,axis=0)).mean())} # Joint positive and negative space comparison; symmetry alone cannot pass a disk. parts.append(symmetry['reference_sector_match']) return float(np.mean(parts)),{'method':'reference_bound_regional_structure','regions':regions,'connections':connections,'symmetry':symmetry,'limits':manifest['limits']}
def save_overlay(reference_render,manifest,path): im=Image.fromarray(rgb(reference_render));d=ImageDraw.Draw(im) for r in manifest['regions']: d.rectangle(r['box'],outline='#f000c0',width=2);d.text((r['box'][0],r['box'][1]),r['name'],fill='#b00090') for p in manifest['connections']:d.line([tuple(q) for q in p['points']],fill='red',width=2) im.save(path)12345678910import argparse,json,sysfrom pathlib import Pathfrom engine import runif __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--task',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--log',type=Path,required=True);a=p.parse_args() try:print(json.dumps(run(a.task,a.output,a.log),indent=2)) except Exception as exc: a.log.mkdir(parents=True,exist_ok=True);(a.log/'reward.txt').unlink(missing_ok=True) (a.log/'evaluation-error.json').write_text(json.dumps({'evaluation_error':str(exc),'reward':None},indent=2)) print(str(exc),file=sys.stderr);sys.exit(1)12345678910111213141516171819202122232425262728293031323334353637383940import bpy,json,sys,mathfrom pathlib import Pathout=Path(sys.argv[sys.argv.index('--')+1]);objects={}for o in bpy.data.objects: d={'type':o.type,'location':list(o.location),'rotation':list(o.rotation_euler),'scale':list(o.scale),'dimensions':list(o.dimensions),'modifiers':[{'name':m.name,'type':m.type,'target':getattr(getattr(m,'object',None),'name',None)} for m in o.modifiers],'parent':getattr(o.parent,'name',None)} if o.type=='MESH': mesh=o.data;d.update(vertices=len(mesh.vertices),polygons=len(mesh.polygons),materials=[m.name for m in mesh.materials if m],vertex_groups=[g.name for g in o.vertex_groups],shape_keys=list(mesh.shape_keys.key_blocks.keys()) if mesh.shape_keys else []) deps=bpy.context.evaluated_depsgraph_get();ev=o.evaluated_get(deps);me=ev.to_mesh();pts=[list(o.matrix_world@v.co) for v in me.vertices];d['evaluated_vertices']=len(pts);d['bounds']=[[min(p[i] for p in pts),max(p[i] for p in pts)] for i in range(3)] if pts else [];ev.to_mesh_clear() # Coarse spatial shape descriptor independent of vertex numbering. if pts: bins=[0]*216;lo=[min(p[i] for p in pts) for i in range(3)];hi=[max(p[i] for p in pts) for i in range(3)] for p in pts: q=[min(5,int(6*(p[i]-lo[i])/max(hi[i]-lo[i],1e-9))) for i in range(3)];bins[q[0]*36+q[1]*6+q[2]]+=1 d['spatial_histogram']=[v/len(pts) for v in bins] if o.type=='ARMATURE': d['bones']={b.name:{'head':list(b.head_local),'tail':list(b.tail_local),'parent':getattr(b.parent,'name',None),'deform':b.use_deform,'connected':b.use_connect} for b in o.data.bones} d['pose']={b.name:{'constraints':[{'type':c.type,'target':getattr(getattr(c,'target',None),'name',None),'subtarget':getattr(c,'subtarget',None)} for c in b.constraints],'custom_shape':getattr(b.custom_shape,'name',None),'rotation':list(b.rotation_euler)} for b in o.pose.bones} d['collections']=[{'name':c.name,'visible':c.is_visible} for c in o.data.collections] if o.type=='MESH': for m in o.modifiers: if m.type=='NODES' and m.node_group:d['node_graph']=[{'name':n.name,'type':n.bl_idname,'inputs':{i.name:str(i.default_value) for i in n.inputs if hasattr(i,'default_value')}} for n in m.node_group.nodes] ad=o.animation_data if ad and ad.action: d['action']=ad.action.name try:d['fcurves']=[{'path':f.data_path,'index':f.array_index,'keys':[[float(p.co.x),float(p.co.y),p.interpolation] for p in f.keyframe_points]} for f in ad.action.fcurves] except AttributeError:d['animation_inspection_error']='Layered actions require version-specific inspector; calibration cannot use this feature.' objects[o.name]=dscene=bpy.context.sceneresult={'objects':objects,'scene':{'frame_start':scene.frame_start,'frame_end':scene.frame_end,'fps':scene.render.fps/scene.render.fps_base,'resolution':[scene.render.resolution_x,scene.render.resolution_y],'camera':getattr(scene.camera,'name',None)},'counts':{k:sum(o.type==k for o in bpy.data.objects) for k in ['MESH','ARMATURE','CAMERA','LIGHT']}}# Pose probes are verifier-controlled, not candidate-defined.probes=Path('/tests/oracle/pose-probes.json')if probes.exists(): result['pose_probes']={} for probe in json.loads(probes.read_text()): arm=bpy.data.objects[probe['armature']];bone=arm.pose.bones[probe['bone']];old=bone.rotation_euler.copy();bone.rotation_mode='XYZ';bone.rotation_euler=probe['rotation'];bpy.context.view_layer.update() result['pose_probes'][probe['id']]={} for name in probe['meshes']: ob=bpy.data.objects[name];deps=bpy.context.evaluated_depsgraph_get();ev=ob.evaluated_get(deps);me=ev.to_mesh();p=[list(ob.matrix_world@v.co) for v in me.vertices];result['pose_probes'][probe['id']][name]=[[min(v[i] for v in p),max(v[i] for v in p)] for i in range(3)];ev.to_mesh_clear() bone.rotation_euler=old;bpy.context.view_layer.update()out.write_text(json.dumps(result,indent=2,allow_nan=False))1234567891011121314151617181920212223242526272829303132[ { "type": "svg_reference", "reference": "reference.png", "metric": "geometry", "min_vectors": 16 }, { "type": "svg_reference", "reference": "reference.png", "metric": "structure", "min_vectors": 16 }, { "type": "svg_reference", "reference": "reference.png", "metric": "styling", "min_vectors": 16 }, { "type": "svg_reference", "reference": "reference.png", "metric": "visual", "min_vectors": 16 }, { "type": "svg_reference", "reference": "reference.png", "metric": "delivery", "min_vectors": 16 }]12345{ "status": "active-v2", "configuration": "/tests/svg-v2.json", "legacy_positive_baselines": "Removed; no per-candidate reward normalization"}12345678910111213# Bicycle grading rubric
The reference drawing is centered on a 1000 × 1000 white page with its longer side about 800 px. The verifier renders `final.svg` itself, removes raster content from scoring, and checks that `final.png` matches that render.
| Criterion | Weight | Measure ||---|---:|---|| Geometry | 30% | Foreground shape placement and proportions against the approved reference. || Structure | 25% | Visible connections, repeated shapes, and overlap, with an editable-vector minimum. || Styling | 15% | Colors and fills in the matching drawing region. || Visual | 20% | Combined shape and color similarity of the verifier render. || Delivery | 10% | Correct 1000 px page and matching 1000 px PNG export. |
The frozen calibration has a source-based positive, a half-covered partial, an unrelated drawing, a raster-only SVG, and a mismatched export. Details: [verifier](tests/VERIFIER.md). This is a deterministic visual scorer; it does not prove the sequence of GUI actions or inspect semantic graph connectivity.1234567# Bicycle Schematic
Please recreate the bicycle schematic in `/root/media/reference.png` as an editable Inkscape drawing. Keep the wheels, frame connections, and labels clear.
Use a 1000 × 1000 white page, with the reference centered and its longer side about 800 px. Draw it as vectors rather than pasting the image. Use the Inkscape GUI. In-app scripting is fine; do not open or use a terminal.
Save `final.svg` and `final.png` in `/root/output` when you are done.1234567# Bicycle verifier
The verifier sanitizes and renders `final.svg` on a white 1000 × 1000 page. Raster images, scripts, foreign objects, and external SVG references cannot contribute to the drawing. It scores geometry overlap (30%), rendered/vector structure (25%), color styling (15%), overall visual similarity (20%), and page/PNG delivery (10%) against `oracle/reference.png`. The submitted PNG is checked against the verifier render, rather than used to earn visual credit.
The frozen minimum editable-vector count is 16. Calibration candidates and evidence are in `calibration/svg-reference/bicycle/` at the suite root. Docker verifier scores after positive-baseline normalization: source-based positive 1.000, shifted 20 px 0.758, faded 0.894, partial 0.666, wrong 0.018, raster-only 0.000, mismatched PNG 0.900. The source SVG is only a positive fixture; agents can use a different editable construction.
This measures visible geometry and editability, not exact SVG topology or GUI action history. Review the reference and threshold before using model scores for publication.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Offline Harbor grader. Hidden oracle configuration supplies reviewed measurements.Unconfigured criteria are evaluator errors, never candidate zeros."""import argparse,json,subprocess,sys,math,hashlib,xml.etree.ElementTree as ETfrom pathlib import Pathimport numpy as npfrom PIL import Image,ImageOps
def probe(path): r=subprocess.run(['ffprobe','-v','error','-show_format','-show_streams','-of','json',str(path)],capture_output=True,text=True) if r.returncode: return {'valid':False,'error':r.stderr[-500:]} return {'valid':True,**json.loads(r.stdout)}def xml_features(path): root=ET.parse(path).getroot();els=[] for e in root.iter(): els.append({'tag':e.tag.split('}')[-1],'attrs':dict(e.attrib),'text':''.join(e.itertext()).strip() if e.tag.split('}')[-1] in ['text','tspan','property'] else ''}) return {'root':dict(root.attrib),'elements':els,'counts':{t:sum(e['tag']==t for e in els) for t in set(e['tag'] for e in els)}}def inspect(path,kind,work): if kind=='blend': out=work/'native.json';p=subprocess.run(['blender','-b','-Y',str(path),'--python','/tests/inspect_blend.py','--',str(out)],capture_output=True,text=True,timeout=240);(work/'blender.log').write_text(p.stdout+p.stderr) if p.returncode or not out.exists():return {'valid':False,'error':p.stderr[-500:]} return {'valid':True,**json.loads(out.read_text())} if kind in ['svg','kdenlive','lmms']: try:return {'valid':True,**xml_features(path)} except ET.ParseError as e:return {'valid':False,'error':str(e)} if kind=='audacity': import sqlite3 try: db=sqlite3.connect('file:'+str(path)+'?mode=ro',uri=True);tables=[r[0] for r in db.execute("select name from sqlite_master where type='table'")];rows={t:db.execute('select count(*) from '+chr(34)+t.replace(chr(34),chr(34)*2)+chr(34)).fetchone()[0] for t in tables};db.close();return {'valid':bool(tables),'tables':tables,'row_counts':rows,'note':'AUP3 track semantics require Audacity reopening/export, not SQLite row counts.'} except sqlite3.DatabaseError as e:return {'valid':False,'error':str(e)} if kind=='xcf': b=path.read_bytes()[:64];return {'valid':b.startswith(b'gimp xcf '),'bytes':path.stat().st_size,'note':'Layer topology must be inspected with a calibrated GIMP export/inspection hook; byte count is not layer correctness.'} return {'valid':False,'error':'Unknown format'}def lookup(data,pointer): cur=data for key in pointer.split('/')[1:]:cur=cur[int(key)] if isinstance(cur,list) else cur[key.replace('~1','/').replace('~0','~')] return curdef similarity(a,b,tol): if isinstance(b,dict):return float(np.mean([similarity(a.get(k),v,tol) for k,v in b.items()])) if isinstance(a,dict) and b else float(a==b) if isinstance(b,list):return float(np.mean([similarity(x,y,tol) for x,y in zip(a,b)])) if isinstance(a,list) and len(a)==len(b) and b else float(a==b) if isinstance(b,(int,float)) and not isinstance(b,bool):return max(0,1-abs(float(a)-b)/tol) if isinstance(a,(int,float)) and tol>0 else float(a==b) return float(a==b)def image_score(a,b,cfg): a=Image.open(a).convert('RGB');b=Image.open(b).convert('RGB') if cfg.get('candidate_crop'):a=a.crop(cfg['candidate_crop']) if cfg.get('reference_crop'):b=b.crop(cfg['reference_crop']) # A frozen crop/scale policy, never per-candidate best-match search. a=ImageOps.pad(a,(512,512),color='white');b=ImageOps.pad(b,(512,512),color='white') x=np.asarray(a,dtype=float)/255;y=np.asarray(b,dtype=float)/255 error=float(np.mean(abs(x-y)));return max(0,1-error/float(cfg['max_mae']))def audio_features(p,work): out=work/'audio.wav';r=subprocess.run(['ffmpeg','-v','error','-y','-i',str(p),'-ac','1','-ar','16000',str(out)],capture_output=True,text=True) if r.returncode:return {'valid':False} import wave with wave.open(str(out)) as w:a=np.frombuffer(w.readframes(w.getnframes()),dtype='<i2').astype(float)/32768 size=1600;rms=[float(np.sqrt(np.mean(a[i:i+size]**2))) for i in range(0,len(a),size) if len(a[i:i+size])] return {'valid':True,'duration':len(a)/16000,'rms':rms,'peak':float(np.max(abs(a))) if len(a) else 0,'non_silent':bool(len(a) and np.max(abs(a))>.001),'clipped_fraction':float(np.mean(abs(a)>.999)) if len(a) else 0}def run(task,output,log): log.mkdir(parents=True,exist_ok=True);(log/'reward.txt').unlink(missing_ok=True) rubric=json.loads((task/'rubric.json').read_text());config=json.loads((task/'oracle/config.json').read_text()) if 'REVIEW_REQUIRED' in json.dumps(config) or any(v is None for v in config.get('checks',{}).values()):raise RuntimeError('Review-required oracle bindings remain.') if config.get('status')!='calibrated':raise RuntimeError('Oracle is not calibrated/reviewed. Complete /tests/oracle/config.json before running agents.') for c in rubric['criteria']: if c['id'] not in config.get('checks',{}):raise RuntimeError('Unconfigured criterion: '+c['id']) report={'rubric_version':rubric['version'],'checks':[]};work=log/'artifacts';work.mkdir(exist_ok=True) nativepath=output/rubric['native_file'];native=inspect(nativepath,rubric['kind'],work) if nativepath.exists() else {'valid':False,'missing':True} (work/'inspection.json').write_text(json.dumps(native,indent=2,allow_nan=False));data={'native':native,'files':{p.name:{'exists':True,'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in output.iterdir() if p.is_file()}} if rubric.get('media_file'): media=output/rubric['media_file'];data['media']=probe(media) if media.exists() else {'valid':False} if rubric['kind'] in ['lmms','audacity'] and media.exists():data['audio']=audio_features(media,work) svg_cache={} def evaluate(cfg,check_id): typ=cfg['type'];score=0.;detail='' if typ=='group': sub=cfg.get('checks',[]) if not sub:raise RuntimeError('Empty check group: '+check_id) results=[evaluate(v,check_id+'-'+str(i))[0] for i,v in enumerate(sub)] return float(np.mean(results)),str(results) elif typ=='feature': try:score=similarity(lookup(data,cfg['pointer']),cfg['expected'],cfg.get('tolerance',0)) except (KeyError,IndexError,TypeError):score=0.;detail='Candidate feature missing' elif typ=='svg_reference': from svg_reference import score as score_svg key=(cfg['reference'],cfg['min_vectors']) if key not in svg_cache:svg_cache[key]=score_svg(output,task/'oracle',cfg,work) scores,evidence=svg_cache[key] raw=scores[cfg['metric']] baseline=cfg.get('positive_baseline',1.) if not 0<baseline<=1:raise RuntimeError('Invalid positive baseline for '+check_id) score=min(1.,raw/baseline) detail=json.dumps({'raw_score':raw,'positive_baseline':baseline,**evidence},sort_keys=True) elif typ=='image': a=output/cfg['candidate'];b=task/'oracle'/cfg['reference'] if not b.exists():raise RuntimeError('Missing oracle reference '+str(b)) if a.exists():score=image_score(a,b,cfg) else:detail='Candidate image missing' elif typ=='video_frames': scores=[] for i,pair in enumerate(cfg['pairs']): ref=task/'oracle'/pair['reference'];img=work/f'frame-{check_id}-{i}.png' if not ref.exists():raise RuntimeError('Missing oracle frame '+str(ref)) media=output/cfg['candidate'] if media.exists(): r=subprocess.run(['ffmpeg','-v','error','-y','-ss',str(pair['time']),'-i',str(media),'-frames:v','1',str(img)],capture_output=True,text=True) scores.append(image_score(img,ref,pair) if r.returncode==0 and img.exists() else 0.) else:scores.append(0.) if not scores:raise RuntimeError('No temporal samples configured') score=float(np.mean(scores)) else:raise RuntimeError('Unsupported check type: '+typ)
return score,detail for c in rubric['criteria']: score,detail=evaluate(config['checks'][c['id']],c['id']) report['checks'].append({'id':c['id'],'description':c['description'],'weight':c['weight'],'score':score,'earned':score*c['weight'],'detail':detail}) report['reward']=sum(c['earned'] for c in report['checks']);report['evidence_only_references']=rubric.get('reference_note') (log/'score-report.json').write_text(json.dumps(report,indent=2,allow_nan=False));(log/'reward.txt').write_text(f'{report["reward"]:.6f}\n');return reportif __name__=='__main__': a=argparse.ArgumentParser();a.add_argument('--task',type=Path,default=Path('/tests'));a.add_argument('--output',type=Path,default=Path('/root/output'));a.add_argument('--log',type=Path,default=Path('/logs/verifier'));args=a.parse_args() try:print(json.dumps(run(args.task,args.output,args.log),indent=2)) except Exception as e: args.log.mkdir(parents=True,exist_ok=True);(args.log/'reward.txt').unlink(missing_ok=True);(args.log/'evaluation-error.json').write_text(json.dumps({'evaluation_error':str(e),'reward':None},indent=2));print(str(e),file=sys.stderr);sys.exit(1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "status": "calibrated", "checks": { "geometry": { "type": "svg_reference", "reference": "reference.png", "min_vectors": 16, "metric": "geometry", "positive_baseline": 0.9766483687357388, "reference_sha256": "ff8dbbd69e735124c762b4531d946206da7bf7861de3c56c8459adcc205d4599" }, "structure": { "type": "svg_reference", "reference": "reference.png", "min_vectors": 16, "metric": "structure", "positive_baseline": 0.9766483687357388, "reference_sha256": "ff8dbbd69e735124c762b4531d946206da7bf7861de3c56c8459adcc205d4599" }, "styling": { "type": "svg_reference", "reference": "reference.png", "min_vectors": 16, "metric": "styling", "positive_baseline": 0.9239408932304048, "reference_sha256": "ff8dbbd69e735124c762b4531d946206da7bf7861de3c56c8459adcc205d4599" }, "visual": { "type": "svg_reference", "reference": "reference.png", "min_vectors": 16, "metric": "visual", "positive_baseline": 0.9599575588388701, "reference_sha256": "ff8dbbd69e735124c762b4531d946206da7bf7861de3c56c8459adcc205d4599" }, "delivery": { "type": "svg_reference", "reference": "reference.png", "min_vectors": 16, "metric": "delivery", "positive_baseline": 0.9131956622004509, "reference_sha256": "ff8dbbd69e735124c762b4531d946206da7bf7861de3c56c8459adcc205d4599" } }, "calibration": "svg-reference-v1; see calibration/svg-reference/bicycle/results.json"}12345678910111213141516171819202122232425262728293031323334{ "version": "svg-reference-v1", "kind": "svg", "native_file": "final.svg", "media_file": "final.png", "criteria": [ { "id": "geometry", "weight": 0.3, "description": "Task-specific shape positions, proportions and curve geometry match." }, { "id": "structure", "weight": 0.25, "description": "Visible connectivity, repeated shapes, and overlaps match, supported by multiple editable vector primitives." }, { "id": "styling", "weight": 0.15, "description": "Line widths, colors, fills and any labels match." }, { "id": "visual", "weight": 0.2, "description": "Verifier-rendered final.svg matches the normalized 1000 px reference; the submitted PNG is not the visual authority." }, { "id": "delivery", "weight": 0.1, "description": "1000 × 1000 SVG page with editable vectors; final.png is a matching 1000 × 1000 export." } ], "reference_note": "The hidden PNG is the visual answer. The verifier renders a sanitized SVG with raster/script content removed, checks its vector primitives, and compares it to the frozen reference. It does not infer which GUI tool was used."}12345678910111213141516171819202122232425262728{ "version": "svg-outcome-v2", "native_file": "final.svg", "media_file": "final.png", "kind": "svg", "criteria": [ { "id": "geometry", "weight": 0.4, "description": "Visible boundary fidelity and placement, independently of object count" }, { "id": "structure", "weight": 0.3, "description": "Reference-grounded feature presence and task-specific symmetry/topology" }, { "id": "styling", "weight": 0.2, "description": "Local fill/stroke color appearance; raster texture excluded" }, { "id": "delivery", "weight": 0.1, "description": "Correct CSS-pixel page and submitted PNG correspondence to vector render" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146{ "task": "bicycle", "version": "svg-outcome-v2", "source_sha256": "fb46ca1c99668629b8111776031bc5b09db9e17735f95642ab933461ada52605", "reference_sha256": "745df60d9291906d8e2cc59f8b20b6716043f8b766ec4c956099c891d6753847", "weights": { "geometry": 0.4, "structure": 0.3, "styling": 0.2, "delivery": 0.1 }, "manifest": { "schema": "svg-structure-v1", "task": "bicycle", "source_sha256": "fb46ca1c99668629b8111776031bc5b09db9e17735f95642ab933461ada52605", "reference_sha256": "745df60d9291906d8e2cc59f8b20b6716043f8b766ec4c956099c891d6753847", "render_size": [ 1000, 1000 ], "reference_foreground_bbox": [ 100, 283, 900, 717 ], "regions": [ { "name": "rear wheel", "box": [ 220.0, 450.0, 430.0, 675.0 ], "method": "local_edge_profile" }, { "name": "front wheel", "box": [ 585.0, 450.0, 805.0, 675.0 ], "method": "local_edge_profile" }, { "name": "frame triangle", "box": [ 360.0, 400.0, 630.0, 565.0 ], "method": "local_edge_profile" }, { "name": "handlebar and fork", "box": [ 590.0, 310.0, 700.0, 560.0 ], "method": "local_edge_profile" }, { "name": "saddle", "box": [ 350.0, 320.0, 455.0, 365.0 ], "method": "local_edge_profile" }, { "name": "crank drivetrain", "box": [ 435.0, 530.0, 555.0, 610.0 ], "method": "local_edge_profile" }, { "name": "rear drivetrain", "box": [ 305.0, 560.0, 410.0, 640.0 ], "method": "local_edge_profile" }, { "name": "part labels left", "box": [ 130.0, 345.0, 270.0, 715.0 ], "method": "local_edge_profile" }, { "name": "part labels right", "box": [ 770.0, 510.0, 900.0, 640.0 ], "method": "local_edge_profile" }, { "name": "part labels upper", "box": [ 495.0, 280.0, 830.0, 400.0 ], "method": "local_edge_profile" } ], "connections": [], "symmetry": null, "limits": [ "Checks visible regional boundaries and connection stroke support; does not infer hidden topology, functional mechanics or exact text transcription.", "Structure is an independent regional allocation; it does not multiply other grade categories.", "No SVG object-count gate." ] }, "policy": { "mean_boundary_full_credit_px": 3, "p95_boundary_full_credit_px": 7, "texture": "Flat vector fills accepted; raster texture is not required", "object_count": "Never scored", "registration": "No candidate best-fit transform", "units": "CSS 96dpi; equivalent viewBox and units accepted" }, "calibration_status": "Initial policy validated on exact/equivalent/defect fixtures; human approximation calibration pending"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Deterministic SVG reference scoring. Candidate raster content is removed before rendering.
This is an artifact scorer, not evidence of which GUI commands were used. A candidateimage cannot substitute for the SVG, and the submitted PNG is checked against averifier render of that SVG."""import hashlib, io, json, re, shutil, subprocess, tempfileimport xml.etree.ElementTree as ETfrom pathlib import Pathimport numpy as npfrom PIL import Image, ImageFilter
DRAWABLE={'path','rect','circle','ellipse','line','polyline','polygon','text','use'}REMOVE={'image','foreignObject','script'}SVG_NS='http://www.w3.org/2000/svg'
def local(tag):return tag.rsplit('}',1)[-1]
def sanitize(source,destination): root=ET.parse(source).getroot() if local(root.tag)!='svg':raise ValueError('Not an SVG document') if '@import' in ET.tostring(root,encoding='unicode'): raise ValueError('CSS imports are not allowed in candidate SVG') vectors=0;removed=0 def check_attrs(node): for key,val in node.attrib.items(): if local(key)=='href' and not val.startswith('#'): raise ValueError('External SVG references are not allowed') for match in re.finditer(r'url\(\s*[\'\"]?([^\'\")\s]+)',val): if not match.group(1).startswith('#'): raise ValueError('External SVG URL is not allowed') check_attrs(root) def walk(node,in_defs=False): nonlocal vectors,removed for child in list(node): kind=local(child.tag) if kind in REMOVE: node.remove(child);removed+=1;continue if kind=='style' and child.text: check_attrs(ET.Element('style',{'content':child.text})) check_attrs(child) if kind in DRAWABLE and not in_defs:vectors+=1 walk(child,in_defs or kind=='defs') walk(root) destination.write_bytes(ET.tostring(root,encoding='utf-8',xml_declaration=True)) def dimension(key): value=root.attrib.get(key,'') match=re.fullmatch(r'\s*(\d+(?:\.\d+)?)\s*(?:px)?\s*',value) return float(match.group(1)) if match else None vb=[float(x) for x in re.split(r'[ ,]+',root.attrib.get('viewBox','').strip()) if x] page=dimension('width')==1000 and dimension('height')==1000 and (not vb or (len(vb)==4 and vb==[0,0,1000,1000])) return {'vectors':vectors,'removed_raster_or_script':removed,'page_1000':page}
def render(svg,out): if shutil.which('inkscape'): cmd=['inkscape',str(svg),'--export-type=png','--export-filename='+str(out),'--export-width=1000','--export-height=1000'] p=subprocess.run(cmd,capture_output=True,text=True,timeout=90) if p.returncode or not out.exists():raise RuntimeError('SVG render failed: '+p.stderr[-500:]) else: import cairosvg cairosvg.svg2png(url=str(svg),write_to=str(out),output_width=1000,output_height=1000) # Inkscape and CairoSVG may leave an unpainted page transparent; the task # specifies white paper. Flatten before every reference comparison. image=Image.open(out).convert('RGBA') paper=Image.new('RGBA',image.size,'white');paper.alpha_composite(image) paper.convert('RGB').save(out)
def images(rendered,reference): def arr(path): im=Image.open(path).convert('RGB').resize((384,384),Image.Resampling.LANCZOS) return np.asarray(im,dtype=np.float32)/255 a,b=arr(rendered),arr(reference) ma=(1-a.min(axis=2)>0.035).astype(np.float32) mb=(1-b.min(axis=2)>0.035).astype(np.float32) def blur(mask,radius): img=Image.fromarray(np.uint8(mask*255),'L').filter(ImageFilter.GaussianBlur(radius)) return np.asarray(img,dtype=np.float32)/255 geometries=[] # Two fixed blur scales give modest placement tolerance for thin lines # while missing components still lose foreground overlap. for radius in (4,10): x,y=blur(ma,radius),blur(mb,radius) geometries.append(float(2*np.minimum(x,y).sum()/(x.sum()+y.sum()+1e-9))) geometry=sum(geometries)/len(geometries) union=np.maximum(ma,mb) color_error=float((np.abs(a-b).mean(axis=2)*union).sum()/(union.sum()+1e-9)) color=max(0,1-color_error/0.42) return geometry,color
def compare_export(rendered,submitted): if not submitted.exists():return 0. try: a=Image.open(rendered).convert('RGB').resize((384,384),Image.Resampling.LANCZOS) b=Image.open(submitted).convert('RGB') if b.size!=(1000,1000):return 0. b=b.resize((384,384),Image.Resampling.LANCZOS) x=np.asarray(a,dtype=np.float32)/255;y=np.asarray(b,dtype=np.float32)/255 foreground=np.maximum(1-x.min(axis=2)>0.035,1-y.min(axis=2)>0.035) if not foreground.any():return 0. mae=float(np.abs(x-y).mean(axis=2)[foreground].mean()) return max(0.,1-mae/.25) except Exception:return 0.
def score(output,oracle,cfg,work): reference=oracle/cfg['reference'] if not reference.exists():raise RuntimeError('Missing oracle SVG reference image: '+str(reference)) if cfg.get('reference_sha256') and hashlib.sha256(reference.read_bytes()).hexdigest()!=cfg['reference_sha256']: raise RuntimeError('Oracle reference image changed after calibration') if Image.open(reference).size!=(1000,1000):raise RuntimeError('Oracle reference is not 1000x1000') svg=output/'final.svg';png=output/'final.png' if not svg.exists():return {k:0. for k in ('geometry','structure','styling','visual','delivery')}, {'reason':'Missing final.svg'} clean=work/'candidate-sanitized.svg';rendered=work/'candidate-render.png' try: native=sanitize(svg,clean) if native['vectors']==0:return {k:0. for k in ('geometry','structure','styling','visual','delivery')}, {'reason':'No editable vector objects',**native} render(clean,rendered) geom,color=images(rendered,reference) export=compare_export(rendered,png) count=min(1,native['vectors']/cfg['min_vectors']) scores={ 'geometry':geom*count, 'structure':geom*count, 'styling':color*(geom**.5)*count, 'visual':(.6*geom+.4*color)*count, 'delivery':(1. if native['page_1000'] else 0.)*export*count, } return scores,{'geometry_overlap':geom,'color_similarity':color,'export_match':export,**native} except (ET.ParseError,ValueError,OverflowError) as e: return {k:0. for k in ('geometry','structure','styling','visual','delivery')},{'reason':str(e)}1234#!/bin/bashset -euo pipefailmkdir -p /logs/verifierpython3 /tests/grade.py --task /tests --output /root/output --log /logs/verifier1234567891011121314#!/usr/bin/env bashset -euo pipefailif [[ "${ONETILE_ASSETS_MOUNTED:-0}" != 1 ]]; then until [[ -f /opt/rct2-assets/.ready ]]; do sleep 1; donefimkdir -p /logs/artifacts /logs/verifier/artifacts /artifacts /home/rct2/.config/OpenRCT2chown -R rct2:rct2 /logs /artifacts /home/rct2/.config/OpenRCT2# The guest target is the task definition, not an environment default: two tasks# share this image, so a missing value has to stop the container rather than# quietly hand out the other task's objective. It is passed on explicitly because# the run drops to the unprivileged user through runuser.: "${T39_TARGET_GUESTS:?set T39_TARGET_GUESTS (guests in the park) in compose.yaml}"exec runuser -u rct2 -- env HOME=/home/rct2 DISPLAY=:1 TMPDIR=/tmp \ T39_TARGET_GUESTS="$T39_TARGET_GUESTS" /usr/local/bin/t39-entrypoint123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336/* Trusted environment controller for the one-tile start.
It applies the scenario configuration (onetile-config.js is concatenated ahead of this file, so CONFIG and applyOneTileConfig are already defined), records evidence, draws the objective panel, and blocks cheats and any direct editing of land rights once the clock starts.
The run is three attempts, not one: a park that closes down can be started again from a pristine copy, and the in-game days every attempt burned are added up. That keeps a restart honest -- it costs exactly the time it cost -- so the ledger of attempts lives in shared storage, which survives the park being reloaded, rather than in the park save.
No gameplay help, no screenshot or model hooks. The only thing scored is whether the engine settles the objective, and how much in-game time had passed across every attempt when it did, so both clocks are stamped on every record. */registerPlugin({name:"onetile-controller",version:"1.0.0",authors:["Task environment"],type:"local",licence:"MIT",targetApiVersion:122,main:function(){ // The target is in the marker: a save from the 1,000-guest variant cannot be // handed to the calibrated task's grader and pass as its completion. var ORIGIN="onetile-v1-"+CONFIG.objective.guests+"guests-001"; var TARGET_GUESTS=CONFIG.objective.guests; // Days at a rating below 700 the engine allows before it closes the park down // (obj.cpp, CheckGuestsAndRating). Panel copy only; the engine owns the rule. var RATING_GRACE_DAYS=29; // Attempts allowed in one run. The supervisor compiles the number in ahead of // this file, the same way the guest target arrives; a missing value would be a // broken install, so it is reported rather than defaulted away. var ATTEMPTS_ALLOWED=typeof ONETILE_ATTEMPTS_ALLOWED==="number"?ONETILE_ATTEMPTS_ALLOWED:0; var store=context.getParkStorage("onetile-v1"); // Park storage dies with the park, and a restart loads a different park: the // attempt ledger has to outlive both, so it goes in shared storage. var LEDGER="onetile-v1.attempts"; var attempt=0,priorDays=0; var initialized=false,configuring=false,applying=false,started=0,lastTime=0,elapsed=0,panel=null; var startTicks=0,inGameDays=0,lastDay=-1,lastMonth=-1; var peakGuests=0,peakRating=0,peakOwned=0,peakCash=0; var tiles={owned:0,forSale:0},days=[],outcome=null,blocked=0,finalSaved=false,baseline=null;
function emit(x){x.schema=1;x.elapsed=Math.round(elapsed);x.parkOrigin=store.get("origin","");console.log("T39JSON "+JSON.stringify(x));} function note(text){park.postMessage({type:"blank",text:text});emit({kind:"notice",text:text});} function money(v){return context.formatString("{CURRENCY}",v);} function guestsInPark(){return park.guests;}
// ---- the attempt ledger ------------------------------------------------- // One entry per attempt, in order, each carrying the in-game days that attempt // burned. Written every in-game day so a crash cannot make a spent attempt look // free, and read back by a restarted park to find out which attempt it is. function ledger(){var l=context.sharedStorage.get(LEDGER,[]);return l&&l.length!==undefined?l:[];} function daysBefore(l,upto){var t=0;for(var i=0;i<upto&&i<l.length;i++)t+=l[i].inGameDays||0;return t;} function totalDays(){return priorDays+inGameDays;} function recordAttempt(result){ var l=ledger(); if(!l[attempt-1])l[attempt-1]={attempt:attempt,target:TARGET_GUESTS}; l[attempt-1].inGameDays=inGameDays;l[attempt-1].result=result; context.sharedStorage.set(LEDGER,l); } function attemptsLeft(){return ATTEMPTS_ALLOWED-attempt;} // The save the next attempt is taken from. Short names, because the load dialog // truncates its name column at seven characters -- run-supervisor.py lays these // down under the same names and explains why. function restartFile(n){return (n===2?"2nd":n===3?"3rd":n+"th")+"-try.park";}
// 2,500 surfaces is too much to walk every tick, so the count is refreshed on // the five-second reporting interval and read from the cache in between. function refreshTiles(){tiles=countOwnedTiles(); if(tiles.owned>peakOwned)peakOwned=tiles.owned; return tiles;}
function snapshot(kind){ var rides=map.rides.filter(function(r){return r.classification==="ride";}); var shops=map.rides.filter(function(r){return r.classification!=="ride";}); return {kind:kind,elapsed:Math.round(elapsed), scenarioStatus:scenario.status, objectiveType:scenario.objective.type,objectiveGuests:scenario.objective.guests, guests:guestsInPark(),targetGuests:TARGET_GUESTS,peakGuests:peakGuests, rating:park.rating,peakRating:peakRating, ratingWarningDays:scenario.parkRatingWarningDays,ratingGraceDays:RATING_GRACE_DAYS, ownedTiles:tiles.owned,tilesForSale:tiles.forSale,peakOwnedTiles:peakOwned,parkSize:park.parkSize, cash:park.cash,peakCash:peakCash,loan:park.bankLoan,maxLoan:park.maxBankLoan, landPrice:park.landPrice,entranceFee:park.entranceFee, parkOpen:park.getFlag("open"),freeParkEntry:park.getFlag("freeParkEntry"), // Which attempt this is, and the time the earlier ones already spent: the // ranked figure is the total, not this attempt's share of it. attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED, priorInGameDays:priorDays,totalInGameDays:totalDays(), // Both clocks, on every record: the reward is binary, the ranking is time. inGameDays:inGameDays,inGameTicks:date.ticksElapsed-startTicks, monthsElapsed:date.monthsElapsed,day:date.day,month:date.month,year:date.year, openRides:rides.filter(function(r){return r.status==="open";}).length, openShops:shops.filter(function(r){return r.status==="open";}).length, totalCustomers:rides.concat(shops).reduce(function(a,r){return a+r.totalCustomers;},0), blockedActions:blocked, rides:rides.map(function(r){return {id:r.id,name:r.name,type:r.type,status:r.status,excitement:r.excitement,intensity:r.intensity,totalCustomers:r.totalCustomers,totalProfit:r.totalProfit};}), shops:shops.map(function(r){return {id:r.id,name:r.name,type:r.type,status:r.status,totalCustomers:r.totalCustomers};})}; }
function recordOutcome(){ if(outcome)return; if(scenario.status!=="completed"&&scenario.status!=="failed")return; refreshTiles(); outcome={result:scenario.status==="completed"?"completed":"failed", // The speed metric. In-game days across every attempt are the ranked figure; // inGameDays is this attempt's share, ticks are the same clock at full // resolution, and the wall clock is a diagnostic only. attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED, totalInGameDays:totalDays(),priorInGameDays:priorDays, inGameDays:inGameDays,inGameTicks:date.ticksElapsed-startTicks, monthsElapsed:date.monthsElapsed,day:date.day,month:date.month,year:date.year, wallClockSeconds:Math.round(elapsed), guests:guestsInPark(),peakGuests:peakGuests,rating:park.rating, ownedTiles:tiles.owned,cash:park.cash,targetGuests:TARGET_GUESTS}; store.set("outcome",outcome); recordAttempt(outcome.result); emit({kind:outcome.result==="completed"?"objective_complete":"objective_failed", outcome:outcome,attempts:ledger(),state:snapshot("outcome_state")}); note(outcome.result==="completed" ?"OBJECTIVE COMPLETE: "+outcome.guests+" guests in the park at a rating of " +outcome.rating+", on year "+outcome.year+" month "+(outcome.month+1)+" day "+outcome.day +" ("+outcome.totalInGameDays+" in-game days over "+attempt+" attempt" +(attempt===1?"":"s")+"). The run is over." :"OBJECTIVE FAILED: the park rating stayed under 700 for "+RATING_GRACE_DAYS +" days and the park has been closed down. " +(attemptsLeft()>0 ?"You have "+attemptsLeft()+" attempt"+(attemptsLeft()===1?"":"s")+" left: open the" +" floppy-disk icon at the top left of the toolbar, choose Load Game, and load" +" "+restartFile(attempt+1)+" to start" +" attempt "+(attempt+1)+" on a fresh park. The "+totalDays()+" in-game days spent so" +" far still count towards your time." :"That was attempt "+attempt+" of "+ATTEMPTS_ALLOWED+" and the run is over." +" Save your park for review.")); // Trusted proof of how the run ended, taken at the moment it settled: the // finest autosave interval the engine offers is five minutes and would miss it. // One file per attempt, so a later attempt cannot overwrite the evidence of an // earlier one and the verifier can still take the newest. if(!finalSaved){ finalSaved=true; try{context.saveGame({filename:"t39-final-attempt"+attempt});} catch(e){emit({kind:"final_save_failed",message:String(e)});} } }
function updatePanel(){ if(typeof ui==="undefined")return; var s=snapshot("panel_state"); if(!panel){panel=ui.openWindow({classification:"onetile-progress",title:"One Tile objective", x:890,y:42,width:380,height:158,widgets:[ {type:"label",name:"guests",x:10,y:23,width:360,height:16,text:""}, {type:"label",name:"rating",x:10,y:42,width:360,height:16,text:""}, {type:"label",name:"land",x:10,y:61,width:360,height:16,text:""}, {type:"label",name:"clock",x:10,y:80,width:360,height:16,text:""}, {type:"label",name:"attempt",x:10,y:99,width:360,height:16,text:""}, {type:"label",name:"status",x:10,y:120,width:360,height:23,text:""}],onClose:function(){panel=null;}});} panel.findWidget("guests").text="Guests in park "+s.guests+" / "+TARGET_GUESTS+" (peak "+s.peakGuests+")"; panel.findWidget("rating").text="Rating "+s.rating+" (need 700)" +(s.ratingWarningDays>0?"; "+s.ratingWarningDays+" of "+RATING_GRACE_DAYS+" days under 700":""); panel.findWidget("land").text="Owned tiles "+s.ownedTiles+"; "+s.tilesForSale +" for sale at "+money(s.landPrice)+"; cash "+money(s.cash); panel.findWidget("clock").text="Year "+s.year+", month "+(s.month+1)+" of 8, day "+s.day +"; "+s.inGameDays+" in-game days this attempt"; panel.findWidget("attempt").text="Attempt "+s.attempt+" of "+ATTEMPTS_ALLOWED +"; "+s.totalInGameDays+" in-game days in total (your score)" +(s.attempt>ATTEMPTS_ALLOWED?" - over the limit, nothing here is scored":""); panel.findWidget("status").text=s.scenarioStatus==="completed"?"OBJECTIVE COMPLETE - the run is over" :s.scenarioStatus==="failed" ?(attemptsLeft()>0?"OBJECTIVE FAILED - load "+restartFile(attempt+1)+" to start attempt "+(attempt+1) :"OBJECTIVE FAILED - park closed down, no attempts left") :started?"Running. There is no deadline; your time is your score." :"Unpause to start. Faster is better."; }
function initialize(){ if(configuring)return; configuring=true; // Deliberately not paused yet. interval.tick only fires while the game is // running, so this is reached unpaused -- and it has to stay that way: the // land actions are queued and executed by the tick loop, so pausing here // would hang the configuration waiting on callbacks that never come. The // handful of ticks it costs happen before the clock starts and are not // counted. The pause is set once the last callback has landed. // // The configuration resizes the map and paints land rights, which are exactly // the actions blocked below: the guard tells the hook these are the // environment's own, and it is lowered before the agent has a park to touch. applying=true; applyOneTileConfig(function(start){ if(start===null){ applying=false; emit({kind:"controller_error",message:"Scenario configuration failed: no park entrance found"}); return; } // The land actions are queued; give the engine a tick to settle them before // the baseline is measured and handed to the grader as the starting state. context.setTimeout(function(){ applying=false; refreshTiles(); peakGuests=guestsInPark();peakRating=park.rating;peakCash=park.cash; baseline=configSummary(); baseline.startTile=start; // The objective type disables the park window's open/close control (see // onetile-config.js, CONFIG.parkOpen), so a park that is closed here can // never be opened by the agent and the run is unwinnable. That is an // environment failure, and the grader treats controller_error as one. if(!baseline.parkOpen){ emit({kind:"controller_error",message:"Scenario configuration failed: the park is closed and this objective type gives the agent no way to open it",baseline:baseline}); return; } // Without an allowance the attempt ledger has no meaning and neither does // the total the run is ranked on, so it is an install failure, not a zero. if(ATTEMPTS_ALLOWED<1){ emit({kind:"controller_error",message:"Scenario configuration failed: ONETILE_ATTEMPTS_ALLOWED was not compiled into the plugin",baseline:baseline}); return; } initialized=true; // A fresh park means a fresh attempt: this is either the hand-over or a // restart the agent chose, and the ledger is what tells the two apart. var l=ledger(); attempt=l.length+1;priorDays=daysBefore(l,l.length); l.push({attempt:attempt,inGameDays:0,result:"running",target:TARGET_GUESTS}); context.sharedStorage.set(LEDGER,l); baseline.attempt=attempt;baseline.attemptsAllowed=ATTEMPTS_ALLOWED; baseline.priorInGameDays=priorDays; store.set("initialized",true);store.set("origin",ORIGIN); store.set("baseline",baseline); lastDay=date.day;lastMonth=date.monthsElapsed;startTicks=date.ticksElapsed; if(attempt>ATTEMPTS_ALLOWED){ // The park is left playable rather than taken away -- there is no API to // unload it -- but the run is over and the grader will not credit this. emit({kind:"attempt_limit_exceeded",attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED, priorInGameDays:priorDays}); note("OVER THE LIMIT: this is attempt "+attempt+" of "+ATTEMPTS_ALLOWED+" allowed. The run" +" ended with the last one; nothing you do on this park is scored."); }else if(attempt>1){ note("ATTEMPT "+attempt+" of "+ATTEMPTS_ALLOWED+": a fresh park, and the "+priorDays +" in-game days the earlier attempt"+(attempt>2?"s":"")+" spent still count towards your" +" time. Unpause to start it."); } note("HANDOVER: One Tile. You own "+tiles.owned+" tile of a "+baseline.playable+"x" +baseline.playable+" map; the other "+tiles.forSale+" are for sale at "+money(park.landPrice) +" each. Get "+TARGET_GUESTS+" guests into the park at a rating of 700 or more."); note("OPERATIONS: cash "+money(park.cash)+", and no loan is available. The park is open" +" and admission is free: set a price on the park window's ticket tab, and switch off" +" research funding in Finances, which costs $200 a month. There is no deadline, but" +" how much in-game time you take is your score, so do it fast."); note("WARNING: an empty park rates 500. After the first month, every day under a rating of" +" 700 counts, and on day "+RATING_GRACE_DAYS+" the park is closed down and the attempt is" +" over. Any day at 700 or more resets the count."); note("ATTEMPTS: you have "+ATTEMPTS_ALLOWED+" in all. If a park is closed down, load" +" 2nd-try.park or 3rd-try.park via the floppy-disk icon at the top left (Load Game) to" +" start the next one. Every attempt's in-game days are added up, so a restart costs you" +" the time it cost. Loading any other save is not a restart and voids the run."); emit({kind:"onetile_initialized",target:TARGET_GUESTS,baseline:baseline,state:snapshot("baseline_state")}); updatePanel(); context.paused=true; },20); }); }
context.subscribe("interval.tick",function(){ if(!initialized){ if(store.get("initialized",false)){ // A park that was already played: the configuration is baked into the save, // so it is never applied twice. A restart loads a pristine copy and goes the // other way, through initialize(), so this is the verifier's path, a // restarted engine -- or an agent rewinding to a played save, which is not a // restart and which the grader refuses. Recorded either way. initialized=true;elapsed=store.get("elapsed",0);baseline=store.get("baseline",null); outcome=store.get("outcome",null);inGameDays=store.get("inGameDays",0); var back=ledger();attempt=back.length||1;priorDays=daysBefore(back,attempt-1); started=Date.now();lastTime=started;startTicks=store.get("startTicks",date.ticksElapsed); lastDay=date.day;lastMonth=date.monthsElapsed;refreshTiles(); emit({kind:"onetile_reloaded",state:snapshot("reload_state")}); }else initialize(); return; } if(!started){ started=Date.now();lastTime=started;startTicks=date.ticksElapsed; store.set("startTicks",startTicks); emit({kind:"clock_started",state:snapshot("start_state")}); note("Started. Pause and fast-forward are both yours: only in-game time is scored."); } var current=guestsInPark(); if(current>peakGuests)peakGuests=current; if(park.rating>peakRating)peakRating=park.rating; if(park.cash>peakCash)peakCash=park.cash; if(date.day!==lastDay||date.monthsElapsed!==lastMonth){ inGameDays++;store.set("inGameDays",inGameDays); // The ledger is the score's memory: written every in-game day so that a // crash, a quit or a restart cannot make a spent attempt look free. recordAttempt("running"); refreshTiles(); var record={kind:"onetile_day",inGameDays:inGameDays,monthsElapsed:date.monthsElapsed, attempt:attempt,totalInGameDays:totalDays(), day:date.day,month:date.month,year:date.year, guests:current,peakGuests:peakGuests,rating:park.rating, ratingWarningDays:scenario.parkRatingWarningDays, ownedTiles:tiles.owned,cash:park.cash,parkOpen:park.getFlag("open"), entranceFee:park.entranceFee}; days.push(record);if(days.length>64)days.shift(); store.set("days",days);emit(record); lastDay=date.day;lastMonth=date.monthsElapsed; } recordOutcome(); });
context.setInterval(function(){ if(!initialized)return; if(started){var now=Date.now();elapsed+=(now-lastTime)/1000;lastTime=now;store.set("elapsed",elapsed);} refreshTiles();recordOutcome();updatePanel(); var state=snapshot("onetile_state");state.outcome=outcome;state.days=days.length;emit(state); },5000);
context.subscribe("map.save",function(){recordOutcome();var s=snapshot("onetile_save");s.outcome=outcome;emit(s);}); context.subscribe("action.query",function(e){ // The environment's own configuration runs through these same actions, before // the agent has anything to click on; only what comes after it is blocked. if(applying)return; // landsetrights is the editor's own land-rights brush: it grants ownership // outright instead of buying it, which is the whole task. The configuration // above sets ownership by assigning cheats.sandboxMode directly rather than // through an action, so it is not affected by this hook. // Two things are deliberately NOT here. Pausing: the score is in-game time, // so stopping the clock to think costs the agent the only thing measured, and // blocking it only bought wall-clock panic. Loading a park: that is how a // restart is taken, and the attempt ledger charges it the time it cost, so it // is counted rather than forbidden -- a rewind to a played save shows up as // onetile_reloaded and the grader refuses the run. var forbidden=["cheatset","parksetdate","ridefreezerating","scenariosetsetting", "tilemodify","landsetrights","mapchangesize"]; if(forbidden.indexOf(e.action)>=0){ e.result.error=1;e.result.errorTitle="Task rules"; e.result.errorMessage="Cheats, land grants and re-dating are disabled. Pause, fast-forward and the three attempts are yours."; blocked++;emit({kind:"blocked_action",action:e.action}); } }); context.subscribe("action.execute",function(e){emit({kind:"action",action:e.action,args:e.args,result:e.result});});}});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778#!/usr/bin/env bashset -euo pipefailif [[ ! -f /opt/rct2-assets/Data/g1.dat && ! -f /opt/rct2-assets/Data/G1.DAT ]]; then echo "Mount a complete Steam RCT2 installation at /opt/rct2-assets." >&2 exit 1fimkdir -p "$HOME/.config/OpenRCT2/plugin"if [[ ! -f "$HOME/.config/OpenRCT2/config.ini" ]]; then # USD keeps the on-screen land price reading exactly $90. # allow_early_completion is set for consistency with the rest of the suite; # this objective has no deadline to complete early against. # Autosave is the shortest interval the engine offers (1 = every five # minutes); the controller also saves the moment the run settles, which is # the save the grader actually reads. cat > "$HOME/.config/OpenRCT2/config.ini" <<'EOF'[general]autosave = 1autosave_amount = 30window_width = 1280window_height = 800fullscreen_mode = 2play_intro = falsedrawing_engine = SOFTWARE_HWDuse_vsync = falsemultithreading = falseallow_early_completion = truecurrency_format = USDconfirmation_prompt = falsesave_plugin_data = true
[sound]master_sound = falseEOFfiopenrct2 set-rct2 /opt/rct2-assetsexport T39_AUDIT_DIR=/logs/artifacts/auditmkdir -p "$T39_AUDIT_DIR"pids=()cleanup() { trap - EXIT INT TERM python3 /usr/local/lib/t39/collect.py --screenshot || true kill "${pids[@]}" 2>/dev/null || true wait || true}trap cleanup EXITtrap 'exit 0' INT TERM
Xvfb "$DISPLAY" -screen 0 1280x800x24 -nolisten tcp &pids+=("$!")ready=falsefor ((attempt=0; attempt<100; attempt++)); do if xdpyinfo >/dev/null 2>&1; then ready=true; break; fi sleep 0.1done"$ready" || { echo "Virtual display failed to start." >&2; exit 1; }openbox &pids+=("$!")x11vnc -display "$DISPLAY" -localhost -rfbport 5900 -forever -shared -nopw -quiet &pids+=("$!")websockify --web=/usr/share/novnc 6080 localhost:5900 &pids+=("$!")# The supervisor owns the engine: it installs the trusted plugin and plays the# one run this task allows. Nothing else may start a scenario.python3 /usr/local/lib/t39/run-supervisor.py "$@" &pids+=("$!")
# Host-mounted checkpoints survive container removal. Screenshots and saves are# collected every two minutes, within the suite's two/five-minute limits.( while true; do sleep 120 python3 /usr/local/lib/t39/collect.py --screenshot || true done) &pids+=("$!")
# Closing the game, or failure of a desktop service, stops this container.wait -n "${pids[@]}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304// One-Tile Start: scenario configuration.//// Matched to ambiguousamphibian's "Roller Coaster Tycoon, 1 Tile Start..."// (https://www.youtube.com/watch?v=zQwWCDPFZ-E, 2026-01-02). His numbers, taken// from the video itself://// - "this entire map measures 50 tiles by 50 tiles" -> 50x50 playable// - "$90 per tile" -> land price $90// - "I do think it's in the spirit ... to begin with $0", -> $0 plus exactly// "the only thing I'm going to give myself is the most one cheap park// basic possible park advertising campaign" advertising week// - "at least 1,000 guests ... and the park rating must -> stock objective// not drop below 700 at any time" guestsAndRating//// The engine's actual rating rule is laxer than his phrasing: after the first// month, a day at rating < 700 increments a counter, and the park is closed down// only on the 29th consecutive such day. Any day at >= 700 resets it to zero.// See ScenarioObjective.cpp, Objective::CheckGuestsAndRating.//// Applied at load time, so there is no authored .park to keep in sync. Ownership// painting requires sandbox mode, which is why this is trusted code and must run// before the agent gets the keyboard.//// This file is a library, not a plugin: it defines CONFIG and// applyOneTileConfig() and registers nothing. The supervisor concatenates it// ahead of controller.js into a single installed plugin, so the controller can// call it directly and no plugin load order has to be relied on. Its own// verification harness is tests/config-selftest.js, which is concatenated the// same way.
// The guest target is the one parameter two tasks share this environment over:// t39 scores a calibrated target, and the 1,000-guest variant is video parity. The// supervisor prepends `var ONETILE_TARGET_GUESTS = <n>;` from T39_TARGET_GUESTS// before this file, so a plugin that cannot read the environment still gets it.// The fallback is the video's number, which is also what a selftest run gets.var TARGET_GUESTS = typeof ONETILE_TARGET_GUESTS === "number" ? ONETILE_TARGET_GUESTS : 1000;
var CONFIG = { // 52 technical = 50x50 playable. The engine's floor is 5 technical (3x3 // playable); a 1x1 map is not reachable, which is why "1 tile" here means one // owned tile, exactly as in the video. mapTechnical: 52,
// $90.00/tile, flat, as in the video. Money is in tenths of a dollar. landPrice: 900,
// $350 = one week of park-wide advertising (Marketing.cpp: park $350/wk, // vouchers $50/wk, single ride $200/wk). He bought the campaign and was then // at $0; we hand the agent the same money and let it find the move itself. // Set preBuyCampaign to true for literal parity: campaign already running, // cash $0, no decision to make. startCash: 3500, preBuyCampaign: false, campaignWeeks: 1,
// No borrowing. Without this an agent takes the loan and buys 111 tiles in // its first minute; every tile after the first has to come from guests. bankLoan: 0, maxBankLoan: 0,
// The gate is the only revenue source until something is built, so the agent // sets this itself. He settled on $50. entranceFee: 0,
// The park has to be handed over OPEN, and this is not a convenience. // For the guestsAndRating objective the engine disables the park window's // open/close control outright -- Park.cpp, WindowParkEntranceInvalidate: // // if (gScenarioObjective.Type == OBJECTIVE_GUESTS_AND_RATING) // disabled_widgets |= (1uLL << WIDX_OPEN_OR_CLOSE) | CLOSE_LIGHT | OPEN_LIGHT; // // Stock scenarios of this type ship open, so nobody misses it. Micro Park // ships closed, and a closed park with that objective is unwinnable through // the GUI: the flag button shows its tooltip, does nothing when clicked, and // there is no other way in. A measured run burned its whole window trying // (Opus 5.5, 2026-09-23: 48 in-game days, 0 guests, rating 0). The baseline // records parkOpen and the grader refuses a closed hand-over. parkOpen: true,
// Micro Park ships freeParkEntry (RCT1 scenarios charge per ride), which // makes an empty park earn nothing and the whole opening impossible. chargeAtGate: true,
// He charged $50 admission and priced rides ($1 on the maze). Vanilla RCT2 is // one or the other; this flag allows both, as in the video. unlockAllPrices: true,
// The engine's own success test is a single tick's conjunction (obj.cpp, // CheckGuestsAndRating): rating >= 700 AND guests in park >= the target at the // same moment. It is a capacity target, not a cumulative admissions one, and // it carries no deadline -- objective.year is not read for this type. objective: { type: 'guestsAndRating', guests: TARGET_GUESTS },
// The base plot is the converted Micro Park; nothing of its scenario text // still applies once the geometry and the economy have been rewritten. scenarioName: 'One Tile', scenarioDetails: 'You own one tile. Every other tile on this 50x50 map is for' + ' sale at $90. Get ' + TARGET_GUESTS + ' guests into the park with a' + ' rating of at least 700, as fast as you can.',};
// Ownership bits (world/MapOwnership.h, FlagHolder over OwnershipFlag):var OWNERSHIP_CONSTRUCTION_RIGHTS_OWNED = 1;var OWNERSHIP_LAND_OWNED = 2;var OWNERSHIP_CONSTRUCTION_RIGHTS_FOR_SALE = 4;var OWNERSHIP_LAND_FOR_SALE = 8;
// LandSetRightsAction settings:var SET_UNOWN_LAND = 0;var SET_UNOWN_CONSTRUCTION_RIGHTS = 1;var SET_LAND_FOR_SALE = 2;var SET_OWNERSHIP = 4;
var ADVERTISING_CAMPAIGN_PARK = 4; // Marketing.h ADVERTISING_CAMPAIGN_PARK
// An entrance element's `object` is its EntranceType, not an object index// (ScTileElement.cpp object_get): rideEntrance 0, rideExit 1, parkEntrance 2.var ENTRANCE_TYPE_PARK = 2;
function surfaceAt(x, y) { var tile = map.getTile(x, y); for (var i = 0; i < tile.numElements; i++) { var element = tile.getElement(i); if (element.type === 'surface') return element; } return null;}
// Game actions from a plugin are queued, not immediate: they run at the end of// the tick. Anything that depends on one having landed goes in its callback, or// sandbox mode will already be off by the time the land edits execute.function runActions(steps, done) { var index = 0; (function next() { if (index >= steps.length) { done(); return; } var step = steps[index++]; context.executeAction(step.action, step.args, function (result) { if (result.error !== 0) { console.log('onetile: ' + step.label + ' FAILED: ' + result.errorMessage); } next(); }); })();}
// The one owned tile is the path tile just inside the park entrance, so guests// can walk in and stand somewhere. Everything else is bought with their money.function findStartTile() { var playable = map.size.x - 2; var centre = null; for (var x = 1; x <= playable && centre === null; x++) { for (var y = 1; y <= playable; y++) { var tile = map.getTile(x, y); for (var i = 0; i < tile.numElements; i++) { var element = tile.getElement(i); // Sequence 0 is the middle of the three park entrance tiles. if (element.type === 'entrance' && element.object === ENTRANCE_TYPE_PARK && element.sequence === 0) { centre = { x: x, y: y }; break; } } if (centre !== null) break; } } if (centre === null) return null;
var neighbours = [ { x: centre.x + 1, y: centre.y }, { x: centre.x - 1, y: centre.y }, { x: centre.x, y: centre.y + 1 }, { x: centre.x, y: centre.y - 1 }, ]; var best = null; var bestEdgeDistance = -1; for (var n = 0; n < neighbours.length; n++) { var candidate = neighbours[n]; if (candidate.x < 1 || candidate.y < 1) continue; var hasFootpath = false; var neighbourTile = map.getTile(candidate.x, candidate.y); for (var j = 0; j < neighbourTile.numElements; j++) { if (neighbourTile.getElement(j).type === 'footpath') hasFootpath = true; } if (!hasFootpath) continue; // Prefer the path heading into the park, not the one out to the spawn. var edgeDistance = Math.min(candidate.x, candidate.y); if (edgeDistance > bestEdgeDistance) { bestEdgeDistance = edgeDistance; best = candidate; } } return best !== null ? best : centre;}
function applyOneTileConfig(done) { runActions([{ action: 'mapchangesize', label: 'grow map to ' + CONFIG.mapTechnical, args: { targetSizeX: CONFIG.mapTechnical, targetSizeY: CONFIG.mapTechnical, shiftX: 0, shiftY: 0 }, }], function () { var playable = map.size.x - 2; var low = 32; var high = playable * 32; var start = findStartTile(); if (start === null) { console.log('onetile: no park entrance found, refusing to configure'); done(null); return; }
cheats.sandboxMode = true; runActions([ { action: 'landsetrights', label: 'unown all land', args: { x1: low, y1: low, x2: high, y2: high, setting: SET_UNOWN_LAND, ownership: 0 }, }, { action: 'landsetrights', label: 'unown all construction rights', args: { x1: low, y1: low, x2: high, y2: high, setting: SET_UNOWN_CONSTRUCTION_RIGHTS, ownership: 0 }, }, { // Land only. Construction rights are never offered, so the agent // cannot buy the cheaper right to build on land it does not own. action: 'landsetrights', label: 'offer all land for sale', args: { x1: low, y1: low, x2: high, y2: high, setting: SET_LAND_FOR_SALE, ownership: 0 }, }, { action: 'landsetrights', label: 'own the start tile', args: { x1: start.x * 32, y1: start.y * 32, x2: start.x * 32, y2: start.y * 32, setting: SET_OWNERSHIP, ownership: OWNERSHIP_LAND_OWNED, }, }, ], function () { cheats.sandboxMode = false;
// After the land edits: owning a tile bills the $90 even in sandbox. park.landPrice = CONFIG.landPrice; park.bankLoan = CONFIG.bankLoan; park.maxBankLoan = CONFIG.maxBankLoan; park.entranceFee = CONFIG.entranceFee; park.setFlag('freeParkEntry', !CONFIG.chargeAtGate); park.setFlag('unlockAllPrices', CONFIG.unlockAllPrices); park.setFlag('open', CONFIG.parkOpen); scenario.objective.type = CONFIG.objective.type; scenario.objective.guests = CONFIG.objective.guests; scenario.name = CONFIG.scenarioName; scenario.details = CONFIG.scenarioDetails;
if (CONFIG.preBuyCampaign) { park.cash = CONFIG.startCash; runActions([{ action: 'parkmarketing', label: 'pre-buy the park advertising campaign', args: { type: ADVERTISING_CAMPAIGN_PARK, item: 0, duration: CONFIG.campaignWeeks }, }], function () { park.cash = 0; done(start); }); } else { park.cash = CONFIG.startCash; done(start); } }); });}
function countOwnedTiles() { var playable = map.size.x - 2; var owned = 0; var forSale = 0; for (var x = 1; x <= playable; x++) { for (var y = 1; y <= playable; y++) { var surface = surfaceAt(x, y); if (surface === null) continue; if (surface.ownership & OWNERSHIP_LAND_OWNED) owned++; else if (surface.ownership & OWNERSHIP_LAND_FOR_SALE) forSale++; } } return { owned: owned, forSale: forSale };}
// The applied settings, as the grader wants to see them: any of these differing// from CONFIG in a reopened save means the scenario the agent played was not the// scenario this file describes.function configSummary() { var tiles = countOwnedTiles(); return { mapSizeX: map.size.x, mapSizeY: map.size.y, playable: map.size.x - 2, ownedTiles: tiles.owned, tilesForSale: tiles.forSale, parkSize: park.parkSize, cash: park.cash, landPrice: park.landPrice, bankLoan: park.bankLoan, maxBankLoan: park.maxBankLoan, entranceFee: park.entranceFee, parkOpen: park.getFlag('open'), freeParkEntry: park.getFlag('freeParkEntry'), unlockAllPrices: park.getFlag('unlockAllPrices'), objectiveType: scenario.objective.type, objectiveGuests: scenario.objective.guests, sandboxMode: cheats.sandboxMode, };}123456789101112131415161718192021222324<?xml version="1.0" encoding="UTF-8"?><openbox_config xmlns="http://openbox.org/3.4/rc"> <focus><focusNew>yes</focusNew></focus> <keyboard> <keybind key="A-Tab"> <action name="NextWindow"> <finalactions><action name="Focus"/><action name="Raise"/></finalactions> </action> </keybind> <!-- The game is the only application on this desktop; this is the way back to it if anything else ever takes the front. --> <keybind key="W-g"> <action name="Execute"><command>wmctrl -a OpenRCT2</command></action> </keybind> </keyboard> <mouse> <context name="Desktop"> <mousebind button="Right" action="Press"> <action name="ShowMenu"><menu>root-menu</menu></action> </mousebind> </context> </mouse> <menu><file>/etc/xdg/openbox/menu.xml</file></menu></openbox_config>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""Disable the console UI in the checksum-pinned Linux 0.5.5 executable.
The official release retains ELF symbols. Replace only InGameConsole::Openwith an x86-64 return. Simulation, numeric inputs, plugin logging and theshared engine library remain untouched. Refuse other binaries/architectures.This task image is a restricted derivative, not the unmodified release."""import hashlibimport jsonfrom pathlib import Pathimport structimport sys
EXPECTED = "cf0df169bc7ff738381a3e54c8e5ecdcd6b623a4ac7f1260bc713d753d803677"SYMBOL = "_ZN8OpenRCT22Ui13InGameConsole4OpenEv"
def restrict(path): data = bytearray(path.read_bytes()) digest = hashlib.sha256(data).hexdigest() if digest != EXPECTED: raise ValueError("Console restriction requires the pinned official Linux executable") if data[:6] != b"\x7fELF\x02\x01" or struct.unpack_from("<H", data, 18)[0] != 62: raise ValueError("Expected little-endian ELF64 x86-64") offset = struct.unpack_from("<Q", data, 40)[0] size, count = struct.unpack_from("<HH", data, 58) sections = [struct.unpack_from("<IIQQQQIIQQ", data, offset + i * size) for i in range(count)] matches = [] for section in sections: if section[1] != 2: # SHT_SYMTAB continue strings_section = sections[section[6]] strings = data[strings_section[4]:strings_section[4] + strings_section[5]] for position in range(section[4], section[4] + section[5], section[9]): name, info, _, index, address, length = struct.unpack_from("<IBBHQQ", data, position) if strings[name:].split(b"\0")[0].decode() == SYMBOL: target = sections[index] assert info & 15 == 2 and target[2] & 4 and length == 346 matches.append(target[4] + address - target[3]) if len(matches) != 1: raise ValueError("Expected exactly one console entry point") position = matches[0] before = data[position] data[position] = 0xC3 # ret; no stack/register changes path.write_bytes(data) return {"original_sha256": digest, "restricted_sha256": hashlib.sha256(data).hexdigest(), "symbol": SYMBOL, "file_offset": position, "before": before, "after": 195}
if __name__ == "__main__": print(json.dumps(restrict(Path(sys.argv[1])), indent=2))1234567#!/usr/bin/env bashset -eumkdir -p /logs/artifacts /logs/verifier/artifactsentry="$(date -u +%FT%TZ) blocked terminal launcher: $0"printf '%s\n' "$entry" >> /logs/artifacts/terminal-attempts.logprintf '%s\n' "$entry" >> /logs/verifier/artifacts/terminal-attempts.logxmessage -center 'There is no terminal; use OpenRCT2 through its GUI.' || true1234567891011121314# t45-bouncing-ball
| Item | Value ||---|---|| Tutorial | [Bouncing Ball Animation - Friction Tutorial](https://www.youtube.com/watch?v=F24OzPdf9qc) || Source application | Friction || Video length | 15:46 || Effort | medium || State | Link and rubric review draft; **not launch ready** |
See [instruction.md](instruction.md) and [RUBRIC.md](RUBRIC.md). The Frictionreference, tutorial media with verified captions, detailed cross-app translationwhen needed, oracle and calibrated verifier must be added after approval.This draft reserves `t44`–`t53`; it has not been run on Daytona.123456789101112131415161718192021222324# t45-bouncing-ball scoring rubric
The deterministic verifier inspects the exported video pixels and exact media format. It writes `/logs/verifier/score.json` and a 0–1 reward. Exports and the editable project are copied to `/logs/artifacts` before scoring, including on agent timeout.
**Source composition:** 1600×1400, 24 fps, 3.750 s. **Outputs:** 1.
| Check | Points || --- | ---: || Decodable export at requested path | 5 || Exact source format | 5 || Editable project | 5 || Tutorial palette | 20 || Subject design and placement | 20 || Tutorial motion | 25 || Tutorial details | 15 || Final composition and hold | 5 |
Thresholds and per-frame measurements are implemented in `tests/score.py`. If a decodable export is found under a different filename in `/root/Desktop` or `/root/edit`, its video content is graded, but it loses the 5 delivery-path points. A missing or corrupt output receives zero for its dependent checks. Color regions, bounding boxes, movement, and holds are evaluated against the shapes and palette visible in the captioned source tutorial; the report exposes each measurement.
## Measured tutorial features
At 160×140 (aspect ratio preserved): white background over 70% of settled frames; orange ball above 20 pixels, 6–35 pixels wide and tall; vertical center moves over 15 pixels with at least two direction reversals, while horizontal travel stays below 45% of vertical travel or 12 pixels; width/height ratio exceeds 1.15 at a contact and falls below 1.10 in flight. Tutorial pose: `tests/reference/tutorial-500s.png`.
The reference stills and captioned video SHA-256 are recorded in `tests/rubric.json`; source format evidence is in `SOURCE_AUDIT.md`.123456789# Bouncing Ball Animation — video tutorial task
The captioned tutorial video is open on the desktop, paused at its first frame. **Your first action is to bring the Tutorial window forward and play the video from the beginning to the end.** Keep its captions visible. Watch the full demonstration before creating shapes or setting keyframes. Revisit relevant sections while building and compare your preview with the video before exporting. The local video at `/root/tutorial/tutorial.mp4` is the source of truth for appearance and motion.
Recreate the bouncing ball animation shown in that video. Study the design, timing, keyframes, effects and final pose demonstrated in the video, then recreate the finished animation in Friction.
Export 1600×1400, 24 fps, 90 frames (3.750 seconds). Save the editable Friction project at `/root/edit/project.friction` and the finished video at `/root/Desktop/final.mp4`. Save and export completed progress during the attempt so it can be collected if the time limit is reached.
Use only Friction's graphical interface to make the animation. Expressions typed inside Friction are allowed. The desktop has no terminal or code editor. Do not put the tutorial player, captions, pointer or Friction interface into the exported animation.12345678910111213141516171819202122232425262728293031323334353637383940414243schema_version = "1.4"artifacts = ["/root/Desktop/final.mp4", "/root/edit", "/logs/artifacts"]
[task]name = "sid/t45-bouncing-ball"version = "0.2.0"description = "Build the bouncing ball shown in the tutorial, with gravity-like timing and squash and stretch at contacts."authors = []keywords = ["friction", "motion-graphics", "tutorial", "computer-1", "video-verifier"]
[metadata]surface = "motion-graphics"app = "friction"review_status = "launch-prepared"rubric_version = "video-v1"source_application = "Friction"
output_width = 1600output_height = 1400output_fps = 24output_frames = 90output_count = 1
[verifier]timeout_sec = 1800.0
[verifier.env]
[agent]timeout_sec = 14400.0network_mode = "no-network"
[environment]network_mode = "no-network"build_timeout_sec = 1800.0os = "linux"mcp_servers = []
[environment.env]APP = "friction"SDL_AUDIODRIVER = "dummy"
[solution.env]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359# GENERATED by suite refresh from packages/verifier/vedit_verifier.py# — do not edit here; edit the source and re-run ./suite/suite.sh refresh"""Shared verifier library for the video-editing task suite.
Single source of truth for the grading primitives every task verifier uses.Task verifiers own their rubric (weights, checkpoints, calibrated thresholds);this module owns the mechanics. `suite refresh` copies this file into eachtask's tests/ dir as `_vedit_verifier.py` (a generated file — edit it HERE,never in a task dir), so the tests/ dir stays self-contained the way Harborexpects.
Grading philosophy (see fcpx.md and the task READMEs): - FRACTIONAL, artifact-only (exported MP4 + saved project, never UI state). - reward.txt gets the weighted fraction; pytest pass/fail means "fully solved" and is only the trajectory-readable signal of which dimension fell short.
GRADER CHANGE 2026-08-21 (deliberate, affects score comparability):extract_project_edl previously graded the single best MLT playlist, so asame-track mix or a V1/V2-overlap dissolve split the clips across playlistsand dropped project_structure points (the t07 opus5 run lost 0.19 to this —the on-screen timeline held both clips; the save was correct; the parserwas not). It now also considers per-tractor merges (Kdenlive models onetimeline track as TWO sub-playlists so same-track mixes can overlap) and amerge of all non-audio playlists ordered by timeline position (forcross-track dissolves). Scores from before this date under-grade multi-clipprojects that used a mix; do not compare across the boundary."""
import jsonimport osimport subprocessimport tempfileimport xml.etree.ElementTree as ET
# ------------------------------------------------------------------ rubric
class Section: """One named sub-verifier: its own checks, weights, and fraction."""
def __init__(self, name): self.name = name self.earned = 0.0 self.total = 0.0 self.lines = []
def check(self, weight, label, ok): self.total += weight try: ok = bool(ok) except Exception: ok = False if ok: self.earned += weight self.lines.append(" [%s] %.3f %s" % ("x" if ok else " ", weight, label)) return ok
def fraction(self): return (self.earned / self.total) if self.total else 1.0
class Rubric(Section): """Single-section variant for simple tasks: report() writes reward.txt."""
def __init__(self, name, reward_path="/logs/verifier/reward.txt"): super().__init__(name) self.reward_path = reward_path
def report(self): score = self.fraction() if self.total else 0.0 print("\n%s -- rubric" % self.name) print("\n".join(self.lines)) print(" score: %.4f (%.2f / %.2f)" % (score, self.earned, self.total)) write_reward(score, self.reward_path) return score
def write_reward(score, reward_path="/logs/verifier/reward.txt"): os.makedirs(os.path.dirname(reward_path), exist_ok=True) with open(reward_path, "w") as fh: fh.write("%.4f\n" % score)
def write_breakdown(breakdown, breakdown_path): os.makedirs(os.path.dirname(breakdown_path), exist_ok=True) with open(breakdown_path, "w") as fh: json.dump(breakdown, fh, indent=2)
# ----------------------------------------------------------------- ffprobe
def probe(path): """ffprobe the file; None if it does not exist or is unreadable.""" if not os.path.isfile(path): return None try: out = subprocess.run( ["ffprobe", "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], capture_output=True, check=True).stdout return json.loads(out) except Exception: return None
def duration(meta): try: return float(meta["format"]["duration"]) except Exception: return None
def has_audio(meta): return meta and any(s.get("codec_type") == "audio" for s in meta.get("streams", []))
def video_size(meta): if not meta: return None for s in meta.get("streams", []): if s.get("codec_type") == "video": return (s.get("width"), s.get("height")) return None
# ---------------------------------------------------------- frame sampling
def frame_rgb(path, t): """Mean (r, g, b) of the frame at time t; None if extraction fails.
The synthetic seed footage is solid colors with burned-in slates, so "is this the right segment" is a mean-RGB classification — deterministic, no reference render needed.""" try: out = subprocess.run( ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True, check=True).stdout n = len(out) // 3 if n == 0: return None return (sum(out[0::3]) / n, sum(out[1::3]) / n, sum(out[2::3]) / n) except Exception: return None
def gray_thumb(path, t, w, h): """Grayscale w*h pixel bytes at time t; None on failure.""" try: out = subprocess.run( ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path, "-frames:v", "1", "-vf", "scale=%d:%d" % (w, h), "-f", "rawvideo", "-pix_fmt", "gray", "-"], capture_output=True, check=True).stdout if len(out) < w * h: return None return out[:w * h] except Exception: return None
def mad(a, b, w, h, rows=None, skip_rows=None): """Mean abs diff of two thumbs over `rows` (or all rows minus `skip_rows`). rows/skip_rows are (lo, hi) half-open row ranges.""" total = n = 0 for row in range(h): if skip_rows and skip_rows[0] <= row < skip_rows[1]: continue if rows and not (rows[0] <= row < rows[1]): continue base = row * w for i in range(base, base + w): total += abs(a[i] - b[i]) n += 1 return total / n if n else 255.0
def ocr_frame(path, t): """Uppercased tesseract OCR of the frame at t; '' on any failure.""" try: with tempfile.TemporaryDirectory() as td: png = os.path.join(td, "frame.png") subprocess.run( ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path, "-frames:v", "1", png], capture_output=True, check=True) out = subprocess.run( ["tesseract", png, "stdout"], capture_output=True, check=True).stdout return out.decode("utf-8", errors="replace").upper() except Exception: return ""
# --------------------------------------------------- project (MLT XML) EDL
def project_references(path, needle): """Saved project parses as XML and references the source clip.""" if not os.path.isfile(path): return False try: ET.parse(path) except Exception: return False with open(path, "r", errors="replace") as fh: return needle in fh.read()
def parse_clock(v, fps): """MLT in/out value -> seconds. Frames int, float seconds, or hh:mm:ss.ms.""" if v is None: return None v = v.strip() try: return int(v) / fps except ValueError: pass if ":" in v: parts = v.split(":") try: sec = float(parts[-1]) for i, p in enumerate(reversed(parts[:-1]), 1): sec += int(p) * (60 ** i) return sec except ValueError: return None try: return float(v) except ValueError: return None
def extract_project_edl(path, known_clips): """ Parse a .kdenlive (MLT XML) file into candidate clip sequences.
Returns (xml_ok, referenced_clips, best_seq) where best_seq is the per-playlist entry sequence [(clip, src_in, src_dur), ...] that references the most known clips (real projects duplicate entries across audio/video tracks; we grade the best-matching track).
See the module docstring for the known V1/V2-dissolve limitation. """ if not os.path.isfile(path): return False, set(), [] try: root = ET.parse(path).getroot() except Exception: return False, set(), []
prof = root.find("profile") fps = 30.0 if prof is not None: try: fps = float(prof.get("frame_rate_num", 30)) / float(prof.get("frame_rate_den", 1)) except Exception: pass
resources = {} for tag in ("producer", "chain"): for p in root.iter(tag): res = None for prop in p.findall("property"): if prop.get("name") in ("resource", "kdenlive:originalurl"): res = os.path.basename((prop.text or "").strip()) if res in known_clips: break if res: resources[p.get("id")] = res
referenced = set(r for r in resources.values() if r in known_clips)
def playlist_entries(pl): """[(timeline_pos, clip, src_in, dur)] for one playlist, blanks walked.""" pos = 0.0 out = [] for node in pl: if node.tag == "blank": pos += parse_clock(node.get("length"), fps) or 0.0 elif node.tag == "entry": src_in = parse_clock(node.get("in"), fps) or 0.0 src_out = parse_clock(node.get("out"), fps) dur = (src_out - src_in + 1.0 / fps) if src_out is not None else None clip = resources.get(node.get("producer")) if clip in known_clips: out.append((pos, clip, src_in, dur)) pos += dur or 0.0 return out
def is_audio(pl): return any( prop.get("name") == "kdenlive:audio_track" for prop in pl.findall("property") )
playlists = {} for pl in root.iter("playlist"): if pl.get("id") == "main_bin": continue playlists[pl.get("id")] = pl
# Candidate sequences, most-specific first: # a) each playlist alone (flat saves, and the pre-2026-08-21 behaviour); # b) each tractor's sub-playlists merged by timeline position — Kdenlive # stores one timeline track as two playlists so same-track mixes can # overlap, which is how a two-clip track reads as one clip per list; # c) all non-audio playlists merged by timeline position, for dissolves # that overlap clips across two video tracks. candidates = [] for pl in playlists.values(): candidates.append(sorted(playlist_entries(pl))) for tractor in root.iter("tractor"): merged = [] for track in tractor.findall("track"): pl = playlists.get(track.get("producer")) if pl is not None and not is_audio(pl): merged.extend(playlist_entries(pl)) if merged: candidates.append(sorted(merged)) video_merge = [] for pl in playlists.values(): if not is_audio(pl): video_merge.extend(playlist_entries(pl)) if video_merge: candidates.append(sorted(video_merge))
# Best = covers the most DISTINCT known clips; ties broken by fewer # entries (less cross-track duplication), then by earlier candidate # (single playlists first, preserving legacy behaviour on flat saves). best = [] best_score = None for seq in candidates: score = (len(set(c for _, c, _, _ in seq)), -len(seq)) if best_score is None or score > best_score: best, best_score = seq, score return True, referenced, [(clip, src_in, dur) for _, clip, src_in, dur in best]
def project_has_transition(path): """A deliberate video dissolve in the project.
luma/dissolve only: real Kdenlive saves ALWAYS contain internal "mix" (audio) and "composite"/"frei0r.cairoblend" (track compositing) transitions, so counting those passes a project with no dissolve at all. Kdenlive's same-track video mix and the oracle both use "luma".""" if not os.path.isfile(path): return False try: root = ET.parse(path).getroot() except Exception: return False services = set() for t in root.iter("transition"): for prop in t.findall("property"): if prop.get("name") == "mlt_service": services.add((prop.text or "").strip()) return bool(services & {"luma", "dissolve"})12345678910{ "task": "t45-bouncing-ball", "mode": "shadow", "old_entrypoint_sha256": "c76a57e157e0dbecb805482b6ce14be60fd30a3b95f256b5c3119e808406b087", "new_entrypoint_sha256": "ff57226a1bc66bd9232c451b4ea743d23291bde224c681e087121bbb75a51cf3", "full_grading_activated": false, "reference_calibration": "pending", "native_inspector": "requires-built-runtime", "reward_policy": "Existing reward remains authoritative until full release validation"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Friction tutorial verifier implementation
This package implements the ten authorized task adapters and their pilot grading rubrics: **t19 and t44–t52**. **t18 is protected and rejected by the installer.**
| Component | Current behavior ||---|---|| Task adapters and rubrics | Executable 100-point criteria, independent subfeature scoring, grounded reference rules || Media inspection | Actual decoded frame count and presentation timestamps; missing/corrupt media distinguished from verifier-tool failures || Geometry/motion | Fitted rings, per-dot luminance, contours, progress frontiers, prefix reveal, evaluated native paths and text || T19 | Export checks, drop movement, looping/source-time speed analysis, source-grounded effect/animation criteria || Process evidence | Validates externally authenticated committed copy/paste events; equality alone earns no process credit || Native runtime | Built isolated audit runtime; actual t52 190-frame full render passes; task-specific coverage and acceptance calibration continue || Task installation | Installed alongside original grading in all ten task packages; new results are saved separately || Authoritative rollout | Full native/render integration and reference calibration must pass before replacing original reward generation |
## Run
```shpython3 cli.py --task t52 \ --project /submission/project.friction \ --desktop /submission \ --out /verifier/friction-audit```
Add `--reference <verifier-owned-reference.json>` and `--inspector <native/inspect_project.py>` for host-side native inspection. The native wrapper requires the installed Docker runtime. The task-local shadow package uses media measurements and the header fallback until a native runtime is incorporated into the release images. Extracted submission-authored JSON is not accepted as independent evidence.
A complete assessment writes `score.json` and `reward.txt`. An incomplete assessment writes score bounds and `grading-pending.json`; it does not silently convert unknown criteria into zero or normalize them away. In the installed shadow integration, the original task reward remains authoritative.
## Files
| File | Purpose ||---|---|| `cli.py` | Frozen artifact collection, inspection, task adapter and report orchestration || `media.py` | Bounded decoded media metadata/frame extraction || `metrics.py` | Concrete geometry, brightness, path and motion collectors || `tasks/engine.py` | Versioned criterion evaluation and calibrated rule validation || `tasks/t19.py`, `tasks/t44.py`–`t52.py` | Task-specific metric/criterion adapters || `rubrics/t19.json`, `rubrics/t44.json`–`t52.json` | Pilot contracts and grading weights || `references/` | Verifier-owned supplied-video evidence and annotation work || `native/` | Pinned native build, inspector wrapper and build/test evidence || `render_match.py` | Independent native/video correspondence measurements || `process_evidence.py` | Authenticated semantic action evidence validation || `install.py` | Idempotent installation; protects t18 and retains original entrypoint backup |
## Validation and limits
Tests cover numeric/temporal errors, unsupported capability handling, missing calibration, partial grading, alternative constructions, corrupted submissions, installation, native schema normalization and render comparison. The historical t52 export was also run in the Friction container: eight dots and travelling phases were detected.
A metric implementation is not the same as a calibrated visual verifier. Exact role mapping, tutorial-derived tolerances and complete source-time/effect/media coverage must be validated for each task. The original historical grades are not overwritten.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# T19 implementation status
| Component | Implemented behavior ||---|---|| `tasks/t19.py` | Checks metadata for both exports; consumes full-load/dependency facts; computes fall velocity, source-time speed and periodicity from evaluated native samples; checks text content and independent-render correspondence metrics. || `rubrics/t19.json` | Thirteen criteria totaling 100 points; explicit delivery rules plus grounded structural reference rules. Whole visual criteria remain unresolved until appearance/scope calibration is complete. || `process_evidence.py` | Validates copy/paste from externally authenticated semantic events, matching source/target/payload, commit and undo/redo. No operation inferred from equal final values or local trust flags. || `tests/test_t19.py` | Seventeen passing tests distinguish phase versus speed, static versus moving loops, reset boundaries, timestamp errors, missing calibration, unsupported native data, forbidden reference metrics, failed/mismatched/undone paste and collector trust. || Full native inspector and renderer | Source collector and wrapper exist; audit translation units compiled, shared application/runtime build still in progress at this writing. End-to-end native loading/rendering has not been verified. || Event recorder | Not implemented here. Existing trajectories cannot provide authenticated application copy/paste events retroactively. || Reference calibration | Actual supplied PartTwo cut is hash-verified; source-frame citations ground 35-frame looping, 1.5× speed, SPLASH mask scope and blue Shadow effects. Visual tolerances remain pending. |
## Input contract
Call `tasks.t19.evaluate("t19", observations, reference)`. The shared engine returns all criterion states, earned points, unresolved points and score interval; it does not fabricate a scalar score when unresolved criteria remain.
`observations` contains:
- `project_present`: actual post-run artifact collection fact.- `media.exports`: records for `scene1.mp4` and `final.mp4` with `path`, `decoded`, `width`, `height`, rational/string `fps`, optional calibrated numeric `project_match`.- `native.status`, `native.scenes`, `native.dependency_errors`, `native.capabilities` (explicit true required for supported features).- `native.roles.part1_drop.evaluated_samples` and `native.roles.drops[]`: samples use `time_seconds`, `source_seconds`, output-space `center`, `visible`, and inspector-declared `reset_from_previous`. Centers must be unclipped effective object centers, not cropped ink centroids. Seconds avoid mixing source FPS with speed.- `native.roles.text.content`.- Optional verifier-owned `reference.native_roles` binds exact object/property IDs to `project_sha256`, `composition_scene_id`, and `drop_object_ids`; raw collector source frames are translated without using object names. Raw timing remains separate until reset/visibility/geometry proof is available.- `metrics.<criterion_id>` for grounded visual/compositing measurements produced by independent native/render inspection. The adapter does not manufacture mask, glow or occlusion correctness from object names.
Reference criteria require verified local-cut hash, chronological source-frame evidence and rules naming only rubric-approved metrics. Loop evaluation needs separate pixel position, source-time and sample-time tolerances; these units must never be merged. Source resets must be inspector-declared, not guessed from candidate motion.
## Remaining work before deployment
1. Integrate trusted native observations, explicit capability coverage and independent render outputs. Untrusted submission-authored JSON cannot be used as inspector facts.2. Complete PartOne contour/fall annotations and calibrate PartTwo mask, overlap, visibility and target-specific final effect appearance on valid independent GUI outputs and confusable errors. The separate reference template remains inactive.3. Confirm mandatory methods versus equivalent outcome rules, and disclose the substituted particles/flames role mapping. Final effects have target-specific overrides: equal values are not universally expected. Actual copy credit requires a process objective and trusted recorder.4. Run retained native submissions end to end in the pinned isolated runtime. Keep historical v0/v0.1/v0.2 results separate.
No original task tests or protected t18 files were edited by this implementation.
## Grounded local-cut evidence and actual retained submission
| Requirement | Actual supplied tutorial evidence | Active check and limitation ||---|---|---|| Loop | [15:23 frame](references/t19-local-cut/part2-0923.png) shows `return frame%35` and explicitly says “every 35 frames.” | Audited native base source cycle equals integer 35; render periodicity needs tolerances. A 1.5× instance has a shorter composition period, so the adapter adjusts each period by evaluated source speed. || Different speeds | [22:30 frame](references/t19-local-cut/part2-1350.png) shows `return frame*1.5%35`. [22:10](references/t19-local-cut/part2-1330.png) demonstrates offset separately. | Exactly grounded 1.5 source-rate ratio requires a verified native timing fact; sampled rate estimates stay separate and cannot establish exact equality through an invented tolerance. Equivalent evaluated implementations qualify. || Text mask scope | [7:17 frame](references/t19-local-cut/part2-0437.png) shows text DstIn inside an isolated layer above the splash video. | Text must read SPLASH and scope must be verified. Pixel mask comparison remains pending. Object names and a DstIn flag alone cannot prove correct isolation. || Drop layering | [25:00 frame](references/t19-local-cut/part2-1500.png) shows move z-index −2 with instruction to place the drop behind SPLASH. | Require effective layering at actual overlap witnesses; ordinary layer reordering can qualify. No mandatory literal −2 proxy. || Drop and text glow | [17:15 frame](references/t19-local-cut/part2-1035.png) shows blue drop Shadow; [26:45](references/t19-local-cut/part2-1605.png) shows final blue SPLASH glow. | Enabled Shadow is a grounded subfeature. Final target-specific appearance remains pending, so enabled alone never awards full glow points. || Effect copying and overrides | [26:15 frame](references/t19-local-cut/part2-1575.png) shows SPLASH blur 156.700 and opacity 0.620 after copying. Earlier drop blur was 92.300 and opacity later changed. | The “consistency” criterion means the reference configuration for each target, not equal final parameters for every object. Copy success remains optional and requires authenticated committed events. |
[annotations.json](references/t19-local-cut/annotations.json) records absolute frame paths, SHA-256 hashes, local timestamps, observations, active rules and pending calibration. It is reference evidence from the supplied cut, not a new acceptance sheet.
The actual `ciScb9w` submission was frozen and run through the new CLI:
| Artifact | Mechanical observation ||---|---|| `scene1.mp4` | Decodes fully; 1920×1080, 30fps, 36 frames, 1.2s. || `final.mp4` | Decodes fully; 1920×1080, 30fps, 251 frames, 8.366667s. || Native project header | Two scenes, each 1920×1080 at 30fps, inclusive range 0–250 = 251 frames. Full load/assets/effects/render not established by the header. || New pilot outcome | Delivery earns 10 points; remaining 90 unresolved. Scalar reward withheld, bounds 0.10–1.00. This diagnostic is not a replacement historical score. |
The difference between the scene1 export length and scene header length is evidence to investigate using native in/out/render ranges; it is not an automatic duration failure. Historical instructions supplied no fixed 2-second or global scene-duration requirement.
Artifacts and full evidence are under `../implementation-validation/t19-pilot/`; no original t19 tests or protected t18 files were changed.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566[ { "task": "t45-bouncing-ball", "status": "missing_historical_mp4" }, { "task": "t46-linear-progress", "path": "/Users/sidsantbak/Desktop/RefreshTasks/project-fcpx/jobs/t46-linear-progress-watch-gpt6sol-20261004-224731/t46-linear-progress__xtkbmJo/verifier/artifacts/final.mp4", "frame_count": 160, "fps": 24.0, "blank_frames": [], "first_bbox": [ 30, 40, 129, 49 ], "last_bbox": [ 30, 40, 129, 49 ], "scope": "diagnostic_color_mask_only_not_score_or_confirmed_role", "max_components": 1 }, { "task": "t49-shape-morph", "path": "/Users/sidsantbak/Desktop/RefreshTasks/project-fcpx/jobs/t49-shape-morph-watch-gpt6sol-20261004-224731/t49-shape-morph__psYvVwc/verifier/artifacts/final.mp4", "frame_count": 125, "fps": 25.0, "blank_frames": [], "first_bbox": [ 21, 6, 139, 89 ], "last_bbox": [ 21, 6, 140, 89 ], "scope": "diagnostic_color_mask_only_not_score_or_confirmed_role", "max_components": 25 }, { "task": "t51-animate-lines", "path": "/Users/sidsantbak/Desktop/RefreshTasks/project-fcpx/jobs/t51-animate-lines-watch-gpt61sol-launchfix-20261005-165605/t51-animate-lines__rQVNy3b/verifier/artifacts/final.mp4", "frame_count": 150, "fps": 25.0, "blank_frames": [ 0 ], "first_bbox": null, "last_bbox": [ 19, 15, 133, 79 ], "scope": "diagnostic_color_mask_only_not_score_or_confirmed_role", "max_components": 1 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401{ "dot_count": 8, "center_error": 0.0017135478743694553, "angular_spacing_error": 0.0007673618051562414, "ring_radius": 0.08322855087909, "dot_radius_variance": 0.00021100280912432804, "pts": [ 0.0, 0.033333, 0.066667, 0.1, 0.133333, 0.166667, 0.2, 0.233333, 0.266667, 0.3, 0.333333, 0.366667, 0.4, 0.433333, 0.466667, 0.5, 0.533333, 0.566667, 0.6, 0.633333, 0.666667, 0.7, 0.733333, 0.766667, 0.8, 0.833333, 0.866667, 0.9, 0.933333, 0.966667, 1.0, 1.033333, 1.066667, 1.1, 1.133333, 1.166667, 1.2, 1.233333, 1.266667, 1.3, 1.333333, 1.366667, 1.4, 1.433333, 1.466667, 1.5, 1.533333, 1.566667, 1.6, 1.633333, 1.666667, 1.7, 1.733333, 1.766667, 1.8, 1.833333, 1.866667, 1.9, 1.933333, 1.966667, 2.0, 2.033333, 2.066667, 2.1, 2.133333, 2.166667, 2.2, 2.233333, 2.266667, 2.3, 2.333333, 2.366667, 2.4, 2.433333, 2.466667, 2.5, 2.533333, 2.566667, 2.6, 2.633333, 2.666667, 2.7, 2.733333, 2.766667, 2.8, 2.833333, 2.866667, 2.9, 2.933333, 2.966667, 3.0, 3.033333, 3.066667, 3.1, 3.133333, 3.166667, 3.2, 3.233333, 3.266667, 3.3, 3.333333, 3.366667, 3.4, 3.433333, 3.466667, 3.5, 3.533333, 3.566667, 3.6, 3.633333, 3.666667, 3.7, 3.733333, 3.766667, 3.8, 3.833333, 3.866667, 3.9, 3.933333, 3.966667, 4.0, 4.033333, 4.066667, 4.1, 4.133333, 4.166667, 4.2, 4.233333, 4.266667, 4.3, 4.333333, 4.366667, 4.4, 4.433333, 4.466667, 4.5, 4.533333, 4.566667, 4.6, 4.633333, 4.666667, 4.7, 4.733333, 4.766667, 4.8, 4.833333, 4.866667, 4.9, 4.933333, 4.966667, 5.0, 5.033333, 5.066667, 5.1, 5.133333, 5.166667, 5.2, 5.233333, 5.266667, 5.3, 5.333333, 5.366667, 5.4, 5.433333, 5.466667, 5.5, 5.533333, 5.566667, 5.6, 5.633333, 5.666667, 5.7, 5.733333, 5.766667, 5.8, 5.833333, 5.866667, 5.9, 5.933333, 5.966667, 6.0, 6.033333, 6.066667, 6.1, 6.133333, 6.166667, 6.2, 6.233333, 6.266667, 6.3 ], "support_threshold": 55, "brightest_sequence": [ 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2 ], "video_path": "/Users/sidsantbak/Desktop/RefreshTasks/project-fcpx/jobs/t52-ui-loading-watch-gpt61sol-launchfix-20261005-165605/t52-ui-loading__3nP7cbp/verifier/artifacts/final.mp4", "frame_count": 190, "fps": 30.0, "phase": { "visits": 8, "direction_consistent": true, "direction": "forward" }, "scope": "actual-render-measurements-not-a-reference-calibrated-score"}12345678910111213141516171819202122232425"""Freeze named submissions with hashes; never merge whitespace-distinct paths."""from pathlib import Pathimport jsonimport shutilfrom media import sha256
def freeze(project, videos, out): out = Path(out) out.mkdir(parents=True, exist_ok=True) records = [] for role, source in [('project', project)] + list(videos.items()): source = Path(source) row = {'role': role, 'original_path': str(source)} if not source.is_file(): row['status'] = 'missing' else: destination = out / role / source.name destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) row.update(status='ok', path=str(destination), sha256=sha256(destination), size_bytes=destination.stat().st_size) records.append(row) (out / 'manifest.json').write_text(json.dumps(records, indent=2) + '\n') return records123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141#!/usr/bin/env python3"""Run tutorial verifier diagnostics on frozen submissions.
A complete grade writes reward.txt. An unresolved grade writes explicit boundsand no scalar. Installing the pilot alongside the old grader preserves reward."""import argparseimport importlibimport jsonimport subprocessimport sysfrom pathlib import Path
from artifacts import freezefrom media import probe, sha256from report import summarize, writefrom tasks.engine import load_rubric
ALLOWED = {'t19'} | {f't{i}' for i in range(44, 53)}
def native_observation(project, inspector=None, output=None): if not Path(project).is_file(): return {'status': 'missing', 'editable': False, 'assets_resolved': False, 'capabilities': {}, 'reason': 'Required native project missing'} if inspector: # Inspector is a verifier-owned executable; no shell interpretation. try: if Path(output).exists(): Path(output).unlink() process = subprocess.run([str(inspector), '--project', str(project), '--output', str(output)], capture_output=True, text=True, timeout=300) if not Path(output).is_file(): return {'status': 'verifier_error', 'capabilities': {}, 'reason': process.stderr[-2000:] or 'Inspector produced no JSON'} from native_bridge import normalize dump=json.loads(Path(output).read_text()) dump['inspector_exit_code']=process.returncode result = normalize(dump, Path(output).parent) if process.returncode: result['inspection_error'] = process.stderr[-2000:] or 'Inspector incomplete or failed' return result except (OSError, ValueError, subprocess.TimeoutExpired) as exc: diagnostic={'status':'verifier_error','capabilities':{},'reason':str(exc)} if output is not None: Path(output).write_text(json.dumps(diagnostic,indent=2)+'\n') return diagnostic # Header parsing is useful evidence; never equivalent to a complete load. sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from inspect_header import inspect, InspectionError try: data = inspect(Path(project).read_bytes()) return {'status': 'unsupported', 'capabilities': data['capabilities'], 'scenes': data['scenes'], 'header': data, 'reason': 'Only scene header inspected; full loader unavailable'} except InspectionError as exc: return {'status': 'unsupported', 'capabilities': {}, 'reason': str(exc)}
def run(task_id, project, desktop, out, reference=None, inspector=None): task_id = task_id.split('/')[-1].split('-')[0] if task_id not in ALLOWED: raise ValueError('Only the ten authorized tasks may use this verifier; t18 is protected') rubric = load_rubric(task_id) contract = rubric['contract'] videos = {f'video-{i}': Path(desktop) / name for i, name in enumerate(contract['videos'])} out = Path(out) manifest = freeze(project, videos, out / 'submission') native_entry = manifest[0] native = native_observation(native_entry.get('path', project), inspector, out / 'native.json') media_files = [probe(row.get('path', videos[row['role']])) for row in manifest[1:]] media = dict(media_files[0]) if media_files else {'decoded': False, 'status': 'missing'} media.update(files=media_files, exports=media_files, filenames=[Path(v).name for v in videos.values()]) observations = {'native': native, 'media': media, 'metrics': {}, 'project_present': native_entry['status'] == 'ok'} reference_data = json.loads(Path(reference).read_text()) if reference else {} # Map each export to a declared native scene; never choose the best scene. scene_map = reference_data.get('scene_exports', {}) if reference_data.get('single_scene_mapping') and len(native.get('scenes',[]))!=1: scene_map={} observations['scene_mapping_error']='Single-scene contract cannot identify an export among multiple scenes' if native.get('status') == 'loaded' and scene_map: from render_match import compare scene_list = native.get('scenes', []) scenes = {s['id']: s for s in scene_list} observations['render_comparisons'] = {} for name, scene_id in scene_map.items(): # Reference packages use an explicit zero-based scene index; the # inspector emits stable string IDs. Resolve either representation. if isinstance(scene_id, int) and not isinstance(scene_id, bool): scene_id = scene_list[scene_id]['id'] if 0 <= scene_id < len(scene_list) else None matching = [m for m in media_files if Path(m['path']).name == name] if matching and scene_id in scenes: comparison = compare(matching[0]['path'], scenes[scene_id], out) observations['render_comparisons'][name] = comparison comparisons = list(observations['render_comparisons'].values()) calibrated = reference_data.get('render_correspondence', {}) if comparisons and all(c.get('status') == 'measured' for c in comparisons): error = max(c['maximum_frame_error'] for c in comparisons) observations['metrics']['render_correspondence'] = {'maximum_frame_error': error} if calibrated.get('validated') is True and isinstance(calibrated.get('maximum_frame_error'), (int, float)): media['project_match'] = error <= calibrated['maximum_frame_error'] # Dense feature extraction is optional only when adapter lacks an extractor. module = importlib.import_module(f'tasks.{task_id}') if hasattr(module, 'collect'): observations = module.collect(observations, reference_data) else: from metrics import collect_observations observations = collect_observations(task_id, observations, reference_data) checks_result = module.evaluate(task_id, observations, reference_data) checks = checks_result.get('criteria', checks_result.get('checks')) result = summarize(task_id, checks, {'rubric_version': rubric['version'], 'rubric_sha256': sha256(Path(__file__).parent / 'rubrics' / f'{task_id}.json'), 'submission': manifest, 'reference_sha256': sha256(reference) if reference else None, 'mode': 'pilot', 'native_inspector_available': bool(inspector)}) stored=dict(observations) stored['native']={k:v for k,v in native.items() if k!='scenes'} stored['native']['evidence_json']=str(out/'native.json') stored['native']['scenes']=[{k:v for k,v in scene.items() if k not in ('frames','structure')} | {'frame_count':len(scene.get('frames',[]))} for scene in native.get('scenes',[])] (out / 'observations.json').write_text(json.dumps(stored, indent=2) + '\n') write(result, out) return result
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--task', required=True) parser.add_argument('--project', type=Path, default=Path('/root/edit/project.friction')) parser.add_argument('--desktop', type=Path, default=Path('/root/Desktop')) parser.add_argument('--out', type=Path, required=True) parser.add_argument('--reference', type=Path) parser.add_argument('--inspector', type=Path) args = parser.parse_args() result = run(args.task, args.project, args.desktop, args.out, args.reference, args.inspector) print(json.dumps({k: result[k] for k in ('task_id', 'status', 'score', 'score_bounds', 'assessed_weight')}, indent=2))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python3"""Read scene metadata ONLY from Friction v34, little-endian, 64-bit-qreal files.
Does not parse layers, validate the whole project, render, or execute expressions.Unsupported/malformed input is an inspection error, not an agent score."""import argparseimport hashlibimport jsonimport mathfrom pathlib import Pathimport struct
class InspectionError(ValueError): pass
def inspect(data: bytes) -> dict: if len(data) < 61: raise InspectionError('File too short for the supported header and footer') footer = len(data) - 49 version = struct.unpack_from('<i', data, footer)[0] if data[footer + 4:footer + 19] != b'enve ev' + b'\0' * 8: raise InspectionError('Unrecognized native project footer') if version != 34: raise InspectionError(f'Unsupported format version {version}; only 34 is implemented') offset = 0
def read(fmt): nonlocal offset size = struct.calcsize('<' + fmt) if offset + size > footer: raise InspectionError('Truncated scene metadata') if fmt == '?' and data[offset] not in (0, 1): raise InspectionError('Unsupported boolean representation') value = struct.unpack_from('<' + fmt, data, offset)[0] offset += size return value
if read('q') != 0: raise InspectionError('Unexpected initial checkpoint / byte order') count = read('i') if not 0 <= count <= 10000: raise InspectionError('Invalid or unsupported scene count') scenes = [] for index in range(count): current = read('i') clip = read('?') width, height = read('i'), read('i') fps = read('d') start, end = read('i'), read('i') in_enabled, in_frame = read('?'), read('i') out_enabled, out_frame = read('?'), read('i') markers_size = read('i') if markers_size == -1: # Qt null QByteArray markers_size = 0 if markers_size < 0 or offset + markers_size > footer: raise InspectionError('Truncated or invalid marker array') markers = data[offset:offset + markers_size] offset += markers_size if width <= 0 or height <= 0 or not math.isfinite(fps) or fps <= 0 or end < start: raise InspectionError('Invalid scene settings / unsupported binary layout') try: markers_text = markers.decode('utf-8') except UnicodeDecodeError as exc: raise InspectionError('Invalid UTF-8 scene markers') from exc scenes.append({ 'scene_index': index, 'current_frame': current, 'clip_to_canvas': clip, 'width': width, 'height': height, 'fps': fps, 'frame_range_inclusive': [start, end], 'frame_count': end - start + 1, 'duration_seconds': (end - start + 1) / fps, 'in_marker': {'enabled': in_enabled, 'frame': in_frame}, 'out_marker': {'enabled': out_enabled, 'frame': out_frame}, 'markers_raw': markers_text, }) return { 'inspector': 'friction-scene-header-v1', 'scope': 'scene_metadata_only', 'full_project_validity': 'not_checked', 'format_version': version, 'binary_layout': 'little_endian_qreal64', 'artifact_sha256': hashlib.sha256(data).hexdigest(), 'scene_count': count, 'scenes': scenes, 'capabilities': {'scene_settings': True, 'layers': False, 'keyframes': False, 'expressions': False, 'effects': False, 'rendering': False, 'action_history': False}, }
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('project', type=Path) parser.add_argument('--out', type=Path) args = parser.parse_args() try: result = inspect(args.project.read_bytes()) except (OSError, InspectionError) as exc: parser.exit(2, f'Inspection error: {exc}\n') output = json.dumps(result, indent=2) + '\n' if args.out: args.out.write_text(output) else: print(output, end='')
if __name__ == '__main__': main()tasks/sw-bicycle/README.mdAdded+21
tasks/sw-bicycle/RUBRIC.mdAdded+16
tasks/sw-bicycle/environment/.dockerignoreAdded+2
tasks/sw-bicycle/environment/DockerfileAdded+14
tasks/sw-bicycle/environment/inkscape-autostart.desktopAdded+5
tasks/sw-bicycle/environment/start-task.shAdded+10
tasks/sw-bicycle/environment/terminal-blocked.shAdded+4
tasks/sw-bicycle/environment/tutorial/index.htmlAdded+1
tasks/sw-bicycle/instruction.mdAdded+9
tasks/sw-bicycle/task.tomlAdded+26
tasks/sw-bicycle/tests/VERIFIER.mdAdded+16
tasks/sw-bicycle/tests/engine.pyAdded+175
tasks/sw-bicycle/tests/features.pyAdded+153
tasks/sw-bicycle/tests/grade.pyAdded+10
tasks/sw-bicycle/tests/inspect_blend.pyAdded+40
tasks/sw-bicycle/tests/oracle/check-examples.jsonAdded+32
tasks/sw-bicycle/tests/oracle/config.jsonAdded+5
tasks/sw-bicycle/tests/oracle/source-spec.jsonAdded
tasks/sw-bicycle/tests/oracle/source.svgAdded
tasks/sw-bicycle/tests/pre-svg-v2/RUBRIC.mdAdded+13
tasks/sw-bicycle/tests/pre-svg-v2/instruction.mdAdded+7
tasks/sw-bicycle/tests/pre-svg-v2/tests__VERIFIER.mdAdded+7
tasks/sw-bicycle/tests/pre-svg-v2/tests__grade.pyAdded+121
tasks/sw-bicycle/tests/pre-svg-v2/tests__oracle__config.jsonAdded+46
tasks/sw-bicycle/tests/pre-svg-v2/tests__rubric.jsonAdded+34
tasks/sw-bicycle/tests/rubric.jsonAdded+28
tasks/sw-bicycle/tests/svg-v2.jsonAdded+146
tasks/sw-bicycle/tests/svg_reference.pyAdded+129
tasks/sw-bicycle/tests/test.shAdded+4
tasks/t40-rct-onetile-1000/environment/await-assets.shAdded+14
tasks/t40-rct-onetile-1000/environment/controller.jsAdded+336
tasks/t40-rct-onetile-1000/environment/entrypoint.shAdded+78
tasks/t40-rct-onetile-1000/environment/onetile-base.parkAdded
tasks/t40-rct-onetile-1000/environment/onetile-config.jsAdded+304
tasks/t40-rct-onetile-1000/environment/openbox-rc.xmlAdded+24
tasks/t40-rct-onetile-1000/environment/restrict-console.pyAdded+51
tasks/t40-rct-onetile-1000/environment/terminal-blocked.shAdded+7
tasks/t45-bouncing-ball/README.mdAdded+14
tasks/t45-bouncing-ball/RUBRIC.mdAdded+24
tasks/t45-bouncing-ball/instruction.mdAdded+9
tasks/t45-bouncing-ball/task.tomlAdded+43
tasks/t45-bouncing-ball/tests/_vedit_verifier.pyAdded+359
tasks/t45-bouncing-ball/tests/friction-audit-install.jsonAdded+10
tasks/t45-bouncing-ball/tests/friction_audit/README.mdAdded+49
tasks/t45-bouncing-ball/tests/friction_audit/T19_IMPLEMENTED.mdAdded+62
tasks/t45-bouncing-ball/tests/friction_audit/actual-render-diagnostics.jsonAdded+66
tasks/t45-bouncing-ball/tests/friction_audit/actual-t52-measurements.jsonAdded+401
tasks/t45-bouncing-ball/tests/friction_audit/artifacts.pyAdded+25
tasks/t45-bouncing-ball/tests/friction_audit/cli.pyAdded+141
tasks/t45-bouncing-ball/tests/friction_audit/inspect_header.pyAdded+106