Record coding Job 6af66f205f2f1b7284b915db
Browse files1{"claim_nonce":"c67da3ff0eaa409fbce55a1205ba9934","input_revision":"0f0c5587a84c337839895c7829cc5407b7c44310","job_id":"6af66f205f2f1b7284b915db","job_url":"https://huggingface.co/jobs/burtenshaw/6af66f205f2f1b7284b915db","launch_spec":{"command":["python","-c","import hashlib, io, json, os, re, stat, subprocess, sys, urllib.parse, urllib.request, zipfile\nfrom pathlib import Path, PurePosixPath\nMAX_FILES = 5000\nMAX_FILE_BYTES = 16777216\nMAX_TOTAL_BYTES = 134217728\nMAX_ARCHIVE_BYTES = 167772160\nMANIFEST = 'bundle-manifest.json'\n\n\"\"\"Exact approved native blob capture; private input fixtures are never public.\n\nNew adapter only. No launch, Hub write, credentials, task filtering or image edit.\nCompile authorizations only after independent full-source/control/image intake.\n\"\"\"\nimport base64\nimport hashlib\nimport io\nimport json\nimport os\nimport re\nimport stat\nimport struct\nimport zlib\nimport zipfile\nfrom pathlib import Path, PurePosixPath\n\nADAPTER='source-bound-native-blobs-v6'\n_NC_SECRET_NAMES=('HF_TOKEN','HF_INFERENCE_TOKEN','HF_SANDBOX_TOKEN')\n_NC_FORBIDDEN={'.env','env','secrets','credentials','logs','outputs','output','runs','.git','__pycache__','.venv','.worktrees'}\n_NC_SUFFIX={'.pem','.key','.log','.zip','.tar','.gz'}\n_NC_PEM={\n 'tests/frozen/testdata/key.pem':dict(sha256='fecae623b5a0ae0a1110285c66e3e0e7f6019f49fd540ed3d9b85f65b9054f6c',git_blob_sha1='f42ec5f7c09aa9e002821d2e1dc0f31a1c0eb51f',size=1678,mode=0o644),\n 'tests/frozen/testdata/cert.pem':dict(sha256='8fb47f5e036bcb4daaeed180fa7164504a8ca43bdc010fd418618da48fdd340c',git_blob_sha1='71d285e20f0906b559a30973a649bdcbd66319fb',size=1098,mode=0o644)}\n\n\n_NC_PUBLIC_PROFILE={'repo': 'Workiva/go-datastructures', 'revision': '18d77378f834b72b39509b12f70f3f9915c56884', 'path': 'rtree/hilbert/cpu.prof', 'sha256': '16206dcd103afecd85d375c7469e4918c1ca022a5f6b70db806f5d96f0d05515', 'git_blob_sha1': '1f9258c432bf9228fd00acacb6beaddccc7fd677', 'size': 17464, 'mode': 420}\n\ndef _nc_sha(raw):return hashlib.sha256(raw).hexdigest()\ndef _nc_git(raw):return hashlib.sha1(b'blob '+str(len(raw)).encode()+b'\\0'+raw).hexdigest()\ndef _nc_pairs(rows):\n result={}\n for key,value in rows:\n if key in result:raise ValueError('duplicate native JSON key')\n result[key]=value\n return result\n\ndef _nc_json(raw):\n return json.loads(raw,object_pairs_hook=_nc_pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError('nonfinite native JSON')))\n\ndef _nc_path(name):\n if not isinstance(name,str):raise ValueError('unsafe native path')\n path=PurePosixPath(name)\n if not path.parts or path.is_absolute() or str(path)!=name or any(x in {'.','..'} for x in path.parts) or '\\\\' in name or ':' in name or any(ord(x)<32 for x in name):raise ValueError('unsafe native path')\n return path\n\ndef _nc_scan(raw,secrets=(),*,public_fixture=False):\n values=[v for v in [*secrets,*(os.environ.get(n)for n in _NC_SECRET_NAMES)]if v]\n if any(v.encode()in raw for v in values):raise ValueError('runtime credential detected in native bytes')\n if values:\n # Two bounded byte views cover MIME whitespace and JSON-escaped CR/LF,\n # including repeated JSON quoting. No recursive decoding or payload eval.\n needles={encode(v.encode()).rstrip(b'=')for v in values for encode in(base64.b64encode,base64.urlsafe_b64encode)}\n for view in(raw,re.sub(rb'\\\\+(?:r|n|u000[aAdD])',b'\\n',raw)):\n compact=re.sub(rb'[ \\t\\r\\n\\f\\v]+',b'',view)\n if any(needle and needle in compact for needle in needles):raise ValueError('encoded runtime credential detected in native bytes')\n if re.search(rb'hf_[A-Za-z0-9]{16,}|sk-ant-[A-Za-z0-9_-]{16,}',raw):raise ValueError('credential pattern detected in native bytes')\n if not public_fixture and re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----',raw):raise ValueError('unapproved private key bytes')\n\ndef _nc_record(config):\n execution=config['execution'];key=execution['expected_task_inventory_sha256'];record=_NC_AUTHORIZATIONS.get(key)\n if record is None or execution.get('expected_task_digest')!=record['task_digest'] or any(execution.get(role+'_image')!=record[role+'_image'] for role in ('agent','verifier')):raise ValueError('native full inventory/image authorization missing')\n gate=_nc_json(config['source_gate']['report_json']);inventory=gate['task_files']\n if _nc_sha(json.dumps(inventory,sort_keys=True,separators=(',',':')).encode())!=key or gate['task_digest']!=record['task_digest']:raise ValueError('native authorization source binding differs')\n return record,inventory\n\ndef _nc_check(name,raw,mode,expected,special,secrets=()):\n path=_nc_path(name)\n if mode not in (0o644,0o755) or expected!={'sha256':_nc_sha(raw),'size':len(raw),'mode':oct(mode)} or len(raw)>8*1024**2:raise ValueError('native captured bytes/modes differ')\n if any(part.lower() in _NC_FORBIDDEN for part in path.parts):raise ValueError('execution-excluded native path')\n fixture=False\n if special is not None:\n if special['sha256']!=_nc_sha(raw) or special['size']!=len(raw) or special['mode']!=mode or special['git_blob_sha1']!=_nc_git(raw):raise ValueError('native public blob readback differs')\n if name in _NC_PEM:\n if {k:special[k] for k in ('sha256','size','mode','git_blob_sha1')}!=_NC_PEM[name] or special['repo']!='go-chi/chi' or special['revision']!='23c395f8524a30334126ca16fb4d37b88745b9b9' or special['path']!='testdata/'+path.name:raise ValueError('public fixture authority differs')\n fixture=True\n elif name=='environment/source/'+_NC_PUBLIC_PROFILE['path'] and special==_NC_PUBLIC_PROFILE:\n pass # Exact immutable public upstream CPU profile; never an arbitrary .prof.\n else:\n if name!='environment/source/'+special['path'] or not (raw.startswith(b'\\x89PNG\\r\\n\\x1a\\n') or raw.startswith(b'\\xff\\xd8\\xff') or raw.startswith((b'GIF87a',b'GIF89a'))):raise ValueError('only approved public image assets supported')\n elif path.name.startswith('.env') or path.suffix.lower() in _NC_SUFFIX:raise ValueError('unapproved execution-excluded native file')\n _nc_scan(raw,secrets,public_fixture=fixture)\n if special is None:\n if b'\\0' in raw:raise ValueError('unapproved binary native file')\n raw.decode('utf8')\n\ndef _nc_fixture_materials(record,files):\n \"\"\"Only exact approved private input fixtures supply evidence deny needles.\"\"\"\n fixtures=[]\n for name,expected in _NC_PEM.items():\n if name not in record['blobs']:continue\n value=files.get(name)\n raw=value[0] if isinstance(value,tuple) and len(value)==2 else value\n if not isinstance(raw,bytes) or len(raw)!=expected['size'] or _nc_sha(raw)!=expected['sha256']:raise ValueError('verified private fixture snapshot required')\n if isinstance(value,tuple) and value[1]!=expected['mode']:raise ValueError('private fixture snapshot mode differs')\n fixtures.append(raw)\n return tuple(fixtures)\n\ndef _nc_fixture_fingerprint(raw):\n normalized=raw.replace(b'\\r\\n',b'\\n')\n known={record['sha256'] for record in _NC_PEM.values()}\n return any(_nc_sha(value) in known for value in (raw,normalized,normalized.strip()+b'\\n'))\n\ndef _nc_deny_fixture_material(raw,fixtures):\n # Fingerprints cover other task types too; fixture bytes never need embedding.\n # JSON can wrap already line-wrapped base64; its literal escaped separators\n # must be removed before decoding. Work on two bounded byte views only.\n unescaped_raw=re.sub(rb'\\\\+(?:r|n|u000[aAdD])',b'\\n',raw)\n for view in (raw,unescaped_raw):\n if _nc_fixture_fingerprint(view):raise ValueError('private input fixture material prohibited in evidence/public source')\n for block in re.findall(rb'-----BEGIN [A-Z ]+-----[\\s\\S]{1,8192}?-----END [A-Z ]+-----',view):\n if _nc_fixture_fingerprint(block):raise ValueError('embedded private input fixture material prohibited in evidence/public source')\n compact_views=tuple(re.sub(rb'\\s+',b'',view) for view in (raw,unescaped_raw))\n for compact in compact_views:\n for start in re.finditer(rb'LS0tLS1CRUdJTi',compact):\n for expected in _NC_PEM.values():\n for size in (expected['size'],expected['size']-1):\n length=4*((size+2)//3)\n candidate=compact[start.start():start.start()+length]\n try:decoded=base64.b64decode(candidate.translate(bytes.maketrans(b'-_',b'+/')),validate=True)\n except ValueError:continue\n if _nc_fixture_fingerprint(decoded):raise ValueError('encoded private input fixture material prohibited in evidence/public source')\n unescaped=compact_views[-1]\n for fixture in fixtures:\n canonical=fixture.replace(b'\\r\\n',b'\\n').strip()\n body=b''.join(canonical.splitlines()[1:-1])\n if canonical in unescaped_raw.replace(b'\\r\\n',b'\\n') or body in unescaped:raise ValueError('private input fixture material prohibited in evidence/public source')\n for value in (fixture,canonical):\n for encode in (base64.b64encode,base64.urlsafe_b64encode):\n if any(encode(value).rstrip(b'=') in compact for compact in compact_views):raise ValueError('encoded private input fixture material prohibited in evidence/public source')\n\ndef _native_capture(root,config):\n from examples.coding_audit.full_task import approved_task\n record,inventory=_nc_record(config);snapshot=approved_task(root,config['execution'])\n if snapshot.inventory!=inventory:raise ValueError('native full captured inventory differs')\n result={}\n for name,raw,mode in snapshot.iter_files():\n _nc_check(name,raw,mode,inventory[name],record['blobs'].get(name))\n result[name]=(raw,mode)\n fixtures=_nc_fixture_materials(record,result)\n for name,(raw,_) in result.items():\n if name not in _NC_PEM:_nc_deny_fixture_material(raw,fixtures)\n return result\n\ndef _native_verify_archive(manifest,files,secrets=()):\n config=_nc_json(files['coding-config.json']);record,inventory=_nc_record(config)\n actual={name.removeprefix('task/'):raw for name,raw in files.items() if name.startswith('task/')}\n if set(actual)!=set(inventory):raise ValueError('native archive full inventory differs')\n for name,raw in actual.items():_nc_check(name,raw,manifest['files']['task/'+name]['mode'],inventory[name],record['blobs'].get(name),secrets)\n fixtures=_nc_fixture_materials(record,actual)\n for name,raw in files.items():\n if name.removeprefix('task/') not in _NC_PEM:_nc_deny_fixture_material(raw,fixtures)\n if not name.startswith('task/'):\n _nc_scan(raw,secrets)\n if b'\\0' in raw:raise ValueError('operator/config binary bytes prohibited')\n raw.decode('utf8')\n\ndef _native_scan_archive(data,secrets):\n with zipfile.ZipFile(io.BytesIO(data)) as archive:files={m.filename:archive.read(m) for m in archive.infolist()}\n _native_verify_archive(_nc_json(files['bundle-manifest.json']),files,secrets)\n\ndef _native_stage_scan_archive(data,secrets):\n \"\"\"Exact decoded input exceptions; original credential gate stays strict.\n\n Raw runtime/HF credentials are always prohibited. Every decoded member is\n checked against the complete approved source/config and private-fixture\n allowlist. Original _no_secrets then checks all ZIP metadata, with only\n bounded compressed payload spans removed from that separate byte view.\n Public source and output/evidence retain their original strict scanners.\n \"\"\"\n secrets=tuple(secrets)\n if not isinstance(data,bytes)or not 0<len(data)<=160*1024**2:raise ValueError('native_stage_archive_bound')\n metadata=bytearray(data);spans=[];total=0\n with zipfile.ZipFile(io.BytesIO(data))as archive:\n infos=archive.infolist()\n if not infos or len(infos)>5000 or len({m.filename for m in infos})!=len(infos):raise ValueError('native_stage_archive_member_bound')\n for item in infos:\n total+=item.file_size\n if (item.file_size<0 or item.file_size>16*1024**2 or total>128*1024**2\n or item.compress_type not in(zipfile.ZIP_STORED,zipfile.ZIP_DEFLATED)\n or item.flag_bits&1 or item.header_offset<0 or item.header_offset+30>len(data)\n or data[item.header_offset:item.header_offset+4]!=b'PK\\x03\\x04'):\n raise ValueError('native_stage_archive_structure_bound')\n name_size,extra_size=struct.unpack_from('<HH',data,item.header_offset+26)\n start=item.header_offset+30+name_size+extra_size;end=start+item.compress_size\n if item.compress_size<0 or end>len(data)or start>end:raise ValueError('native_stage_payload_bound')\n if item.compress_type==zipfile.ZIP_STORED:\n if item.compress_size!=item.file_size:raise ValueError('native_stage_stored_payload_size')\n else:\n decoder=zlib.decompressobj(-15)\n try:decoded=decoder.decompress(data[start:end],item.file_size+1)\n except zlib.error:raise ValueError('native_stage_deflate_invalid')from None\n if len(decoded)!=item.file_size or not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:raise ValueError('native_stage_deflate_trailing_or_unbounded')\n spans.append((item.header_offset,start,end))\n previous=0\n for header,start,end in sorted(spans):\n if header<previous:raise ValueError('native_stage_payload_overlap')\n metadata[start:end]=b'\\0'*(end-start);previous=end\n # Exact supplied/environment secrets, their base64 and generic HF tokens\n # never receive the public-fixture syntax exception, even in compressed data.\n _nc_scan(data,secrets,public_fixture=True)\n _native_scan_archive(data,secrets)\n _no_secrets(bytes(metadata),secrets)\n with zipfile.ZipFile(io.BytesIO(data))as archive:\n names=set(archive.namelist());fixtures=tuple(archive.read('task/'+name)for name in _NC_PEM if 'task/'+name in names)\n _nc_deny_fixture_material(bytes(metadata),fixtures)\n\n\ndef _nc_read(path):\n before=path.lstat()\n if not stat.S_ISREG(before.st_mode) or before.st_size>16*1024**2:raise ValueError('native evidence regular-file size required')\n fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)\n try:\n current=os.fstat(fd)\n if (before.st_dev,before.st_ino,before.st_mtime_ns,before.st_size)!=(current.st_dev,current.st_ino,current.st_mtime_ns,current.st_size):raise ValueError('native evidence changed before capture')\n with os.fdopen(fd,'rb',closefd=False) as stream:raw=stream.read(16*1024**2+1)\n after=os.fstat(fd)\n if len(raw)!=before.st_size or (current.st_mtime_ns,current.st_size)!=(after.st_mtime_ns,after.st_size):raise ValueError('native evidence changed during capture')\n return raw,0o755 if before.st_mode&0o111 else 0o644\n finally:os.close(fd)\n\ndef _native_evidence_tree(root,config,secrets=(),*,input_files):\n record,inventory=_nc_record(config);evidence=_nc_json(_nc_read(root/'audit/evidence.json')[0]);references={}\n if not isinstance(input_files,dict) or set(input_files)!=set(inventory):raise ValueError('complete verified native input snapshot required')\n fixtures=_nc_fixture_materials(record,input_files)\n from openenv.validation.runtime.json_values import dumps\n normalized_config=json.loads(dumps(config))\n if evidence.get('task_inventory_sha256')!=config['execution']['expected_task_inventory_sha256'] or evidence.get('semantic_gate_configuration')!=normalized_config:raise ValueError('evidence source/config unbound')\n allowed=set(config['execution']['submission_paths']);workdir=PurePosixPath(config['execution']['workdir'])\n for trial in evidence.get('trials',[]):\n for item in trial.get('submission_files',[]):\n destination=item['destination'];relative=PurePosixPath(destination).relative_to(workdir)\n if destination not in allowed or 'environment/source/'+str(relative) not in inventory or not re.fullmatch(r'trials/[0-9]{4}/submission/[0-9]{4}',item['path']):raise ValueError('submission artifact source path unauthorized')\n name='audit/'+item['path'];_nc_path(name)\n if name in references:raise ValueError('duplicate native submission artifact')\n references[name]=(item['sha256'],'environment/source/'+str(relative))\n result={};total=0\n for directory,dirs,names in os.walk(root,followlinks=False):\n for name in dirs+names:\n if (Path(directory)/name).is_symlink():raise ValueError('native evidence symlink')\n for name in sorted(names):\n path=Path(directory)/name;relative=path.relative_to(root).as_posix();parts=_nc_path(relative).parts\n if any(p.lower() in _NC_FORBIDDEN for p in parts) or name.startswith('.env') or path.suffix.lower() in _NC_SUFFIX:raise ValueError('execution-excluded evidence path')\n raw,mode=_nc_read(path);_nc_scan(raw,secrets);_nc_deny_fixture_material(raw,fixtures)\n binary_asset=False\n if relative in references:\n expected_sha,source_name=references[relative]\n if _nc_sha(raw)!=expected_sha:raise ValueError('native submission artifact checksum differs')\n special=record['blobs'].get(source_name)\n if special is not None and source_name not in _NC_PEM:\n _nc_check(source_name,raw,mode,inventory[source_name],special,secrets)\n binary_asset=True\n if not binary_asset:\n if b'\\0' in raw:raise ValueError('nonapproved binary evidence prohibited')\n raw.decode('utf8')\n result[relative]=(raw,mode);total+=len(raw)\n if len(result)>5000 or total>128*1024**2:raise ValueError('native evidence bounds exceeded')\n if not references.keys()<=result.keys():raise ValueError('referenced native artifact missing')\n return result\n\n\n\n_NC_AUTHORIZATIONS={'0a98d243e092a5f2da0a66d97dd8db7f16076f5301addbb71e51a9011ccd4507': {'agent_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1', 'blobs': {'tests/frozen/testdata/cert.pem': {'git_blob_sha1': '71d285e20f0906b559a30973a649bdcbd66319fb', 'mode': 420, 'path': 'testdata/cert.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': '8fb47f5e036bcb4daaeed180fa7164504a8ca43bdc010fd418618da48fdd340c', 'size': 1098}, 'tests/frozen/testdata/key.pem': {'git_blob_sha1': 'f42ec5f7c09aa9e002821d2e1dc0f31a1c0eb51f', 'mode': 420, 'path': 'testdata/key.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': 'fecae623b5a0ae0a1110285c66e3e0e7f6019f49fd540ed3d9b85f65b9054f6c', 'size': 1678}}, 'task_digest': 'c55bac7b66e030eb3be03e92e992de5f4ca0fe86c558788184ccfb50653eef8f', 'task_inventory_sha256': '0a98d243e092a5f2da0a66d97dd8db7f16076f5301addbb71e51a9011ccd4507', 'verifier_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1'}, 'af6d54791494ad31631395c24ac64a9301a07bfbf1edb13507543b7dc3183ded': {'agent_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1', 'blobs': {'tests/frozen/testdata/cert.pem': {'git_blob_sha1': '71d285e20f0906b559a30973a649bdcbd66319fb', 'mode': 420, 'path': 'testdata/cert.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': '8fb47f5e036bcb4daaeed180fa7164504a8ca43bdc010fd418618da48fdd340c', 'size': 1098}, 'tests/frozen/testdata/key.pem': {'git_blob_sha1': 'f42ec5f7c09aa9e002821d2e1dc0f31a1c0eb51f', 'mode': 420, 'path': 'testdata/key.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': 'fecae623b5a0ae0a1110285c66e3e0e7f6019f49fd540ed3d9b85f65b9054f6c', 'size': 1678}}, 'task_digest': '127eb66e327b1d0e02883ecde6fc1274b5bdee8c4ecc6453df366578aa666c44', 'task_inventory_sha256': 'af6d54791494ad31631395c24ac64a9301a07bfbf1edb13507543b7dc3183ded', 'verifier_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1'}, 'cd7db0a0db281fdc1685432108361a3fe7037a5a92c71cafa51e1cb2641cd21f': {'agent_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1', 'blobs': {'tests/frozen/testdata/cert.pem': {'git_blob_sha1': '71d285e20f0906b559a30973a649bdcbd66319fb', 'mode': 420, 'path': 'testdata/cert.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': '8fb47f5e036bcb4daaeed180fa7164504a8ca43bdc010fd418618da48fdd340c', 'size': 1098}, 'tests/frozen/testdata/key.pem': {'git_blob_sha1': 'f42ec5f7c09aa9e002821d2e1dc0f31a1c0eb51f', 'mode': 420, 'path': 'testdata/key.pem', 'repo': 'go-chi/chi', 'revision': '23c395f8524a30334126ca16fb4d37b88745b9b9', 'sha256': 'fecae623b5a0ae0a1110285c66e3e0e7f6019f49fd540ed3d9b85f65b9054f6c', 'size': 1678}}, 'task_digest': '0093991c5b6dd9d36264ebae03d1ba05de08cdd677447a85ac452ebc45c4e112', 'task_inventory_sha256': 'cd7db0a0db281fdc1685432108361a3fe7037a5a92c71cafa51e1cb2641cd21f', 'verifier_image': 'registry.hf.space/harness-hub-scale800-4c935f9a1651fcba-starter-v1@sha256:bbed00cf0d9a5a2069d8473257b0e669cdf51b8fee4b724ec869acdfcada8fe1'}}\n\ndef _loads(data):\n from decimal import Decimal\n\n def pairs(items):\n result = {}\n for key, value in items:\n if key in result:\n raise ValueError(\"Duplicate JSON key\")\n result[key] = value\n return result\n\n def invalid(value):\n raise ValueError(\"Nonfinite JSON number\")\n\n return json.loads(\n data, object_pairs_hook=pairs, parse_constant=invalid, parse_float=Decimal\n )\n\ndef _safe_name(name):\n if not isinstance(name, str):\n raise ValueError(\"Unsafe bundle path\")\n path = PurePosixPath(name)\n if (\n not path.parts\n or path.is_absolute()\n or path.as_posix() != name\n or any(part in (\".\", \"..\") for part in path.parts)\n or any(ord(char) < 32 for char in name)\n or \"\\\\\" in name\n or \":\" in name\n ):\n raise ValueError(\"Unsafe bundle path\")\n return path\n\ndef _checked_archive(data, expected_sha=None):\n \"\"\"Check every archive member before writing or executing any payload.\"\"\"\n if len(data) > MAX_ARCHIVE_BYTES:\n raise ValueError(\"Archive size limit exceeded\")\n if expected_sha is not None and hashlib.sha256(data).hexdigest() != expected_sha:\n raise ValueError(\"Bundle SHA256 mismatch\")\n with zipfile.ZipFile(io.BytesIO(data)) as archive:\n members = archive.infolist()\n if not 1 < len(members) <= MAX_FILES + 1:\n raise ValueError(\"Bundle file count limit exceeded\")\n names = set()\n folded = set()\n total = 0\n for member in members:\n name = str(_safe_name(member.filename))\n mode = member.external_attr >> 16\n if stat.S_IFMT(mode) != stat.S_IFREG or member.flag_bits & 1:\n raise ValueError(\"Bundle members must be unencrypted regular files\")\n if name in names or name.casefold() in folded:\n raise ValueError(\"Bundle path collision\")\n names.add(name)\n folded.add(name.casefold())\n total += member.file_size\n if member.file_size > MAX_FILE_BYTES or total > MAX_TOTAL_BYTES:\n raise ValueError(\"Bundle size limit exceeded\")\n for name in names:\n if any(\n str(parent).casefold() in folded\n for parent in PurePosixPath(name).parents\n if str(parent) != \".\"\n ):\n raise ValueError(\"Bundle file/directory collision\")\n if MANIFEST not in names:\n raise ValueError(\"Bundle inventory missing\")\n manifest = _loads(archive.read(MANIFEST))\n inventory = manifest[\"files\"]\n if not isinstance(inventory, dict) or set(inventory) != names - {MANIFEST}:\n raise ValueError(\"Bundle inventory is incomplete\")\n files = {}\n for member in members:\n if member.filename == MANIFEST:\n continue\n content = archive.read(member)\n record = inventory[member.filename]\n if (\n not isinstance(record, dict)\n or record.get(\"size\") != len(content)\n or record.get(\"sha256\") != hashlib.sha256(content).hexdigest()\n or record.get(\"mode\") not in (0o644, 0o755)\n or stat.S_IMODE(member.external_attr >> 16) != record[\"mode\"]\n ):\n raise ValueError(\"Bundle inventory hash, size or mode mismatch\")\n files[member.filename] = content\n files[MANIFEST] = archive.read(MANIFEST)\n for name,digest in {'examples/coding_audit/hf.py': 'b549137d1f34b91228fdc4a5f7d64fb78d2c9ca974854e096202843dc1973edc', 'examples/coding_audit/runner.py': '502bae61429b98096490cf21a1925a1eccf7a1e88048d48bed54379ec51d608c', 'examples/coding_audit/scoring.py': '49a5c721f7e1973fa918296c5fe9a6367ebc37d692461139937dfdd836834111', 'examples/coding_audit/sdk_extension.py': '1553cedfcdda9ea06d2d21ff9cabdcfd34287c561f4d471ec4517a4b70e247c8', 'examples/coding_audit/public_source.py': '58bbaceb279671f13bd558b897485ecce570404261e0b2724037f7ed04c93fe4', 'examples/coding_audit/full_task.py': 'eb860fd81715524b18a97b7869cae63feaf71cd2614dd640d21b9eb6486f51da', 'examples/coding_audit/protocol_gate.py': 'f829eedb46f544358cf749effe152fd49e580d41b505bced179574218b4773a9', 'examples/coding_audit/request_retry.py': 'bb2fa904683a01f20c33e0b6bbf9aeb8e93f0192c577ead0235134b8f77ca9cf', 'examples/coding_audit/target_only_cost.py': '1836cf281f2be242e06cf2fdedd7da7327e90023b1f17ebf3d48ab7fc2f1a625', 'examples/coding_audit/cost-projection.json': 'f491f1841bd47ce671d5f6d1a1fb0d7105716d852e72c55d55690fd42f3cb9f2', 'examples/hub_validation_pipeline/full_run.py': 'aacea96bc3065b03f54e4e4aec0a6d475cfd04d04584628f76a55265db53f40f', 'examples/coding_audit/native_capture_v6.py': '4fbf6edd53d6b32f22ecf6442dab616f7432130277c1ade27cc6731a3ac19159'}.items():\n if hashlib.sha256(files[name]).hexdigest()!=digest:raise ValueError(\"captured target-only runtime/helper/projection changed\")\n if hashlib.sha256(files[\"examples/coding_audit/native_capture_v6.py\"]).hexdigest()!='4fbf6edd53d6b32f22ecf6442dab616f7432130277c1ade27cc6731a3ac19159':raise ValueError(\"captured native helper changed\")\n _native_verify_archive(manifest,files)\n return manifest, files\n\ndef extract_bundle(data, destination, expected_sha):\n \"\"\"Extract a fully verified bundle into a fresh directory, without extractall.\"\"\"\n manifest, files = _checked_archive(data, expected_sha)\n destination = Path(destination)\n destination.mkdir(parents=True, exist_ok=False)\n for name, content in files.items():\n path = destination.joinpath(*_safe_name(name).parts)\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"xb\") as stream:\n stream.write(content)\n path.chmod(manifest[\"files\"].get(name, {}).get(\"mode\", 0o644))\n return manifest\n\nclass _HubRedirect(urllib.request.HTTPRedirectHandler):\n def redirect_request(self, req, fp, code, msg, headers, newurl):\n if urllib.parse.urlsplit(newurl).scheme != \"https\":\n raise ValueError(\"Hub download redirect requires HTTPS\")\n redirected = super().redirect_request(req, fp, code, msg, headers, newurl)\n if (\n urllib.parse.urlsplit(req.full_url).netloc\n != urllib.parse.urlsplit(newurl).netloc\n ):\n redirected.remove_header(\"Authorization\")\n return redirected\n\ndef _bootstrap_main(uv_version, hub_version):\n import base64\n import tempfile\n\n revision = os.environ[\"OPENENV_BUNDLE_REVISION\"]\n sha = os.environ[\"OPENENV_BUNDLE_SHA256\"]\n repo = os.environ[\"OPENENV_RESULTS_REPO\"]\n token = os.environ[\"HF_TOKEN\"]\n if (\n not re.fullmatch(r\"[0-9a-f]{40}\", revision)\n or not re.fullmatch(r\"[0-9a-f]{64}\", sha)\n or not re.fullmatch(r\"[\\w.-]+/[\\w.-]+\", repo)\n ):\n raise ValueError(\"Invalid immutable input identity\")\n opener = urllib.request.build_opener(_HubRedirect())\n headers = {\"Authorization\": \"Bearer \" + token}\n stage = \"download\"\n try:\n url = (\n \"https://huggingface.co/datasets/\"\n + repo\n + \"/resolve/\"\n + revision\n + \"/inputs/\"\n + sha\n + \"/bundle.zip\"\n )\n with opener.open(\n urllib.request.Request(url, headers=headers), timeout=120\n ) as response:\n data = response.read(MAX_ARCHIVE_BYTES + 1)\n root = Path(tempfile.mkdtemp(prefix=\"openenv-coding-\")) / \"bundle\"\n stage = \"integrity\"\n extract_bundle(data, root, sha)\n stage = \"install_uv\"\n subprocess.run(\n [sys.executable, \"-m\", \"pip\", \"install\", \"uv==\" + uv_version], check=True\n )\n stage = \"sync\"\n subprocess.run([\"uv\", \"sync\", \"--frozen\", \"--no-dev\"], cwd=root, check=True)\n python = str(root / \".venv/bin/python\")\n stage = \"install_sdk\"\n subprocess.run(\n [\n \"uv\",\n \"pip\",\n \"install\",\n \"--python\",\n python,\n \"huggingface_hub==\" + hub_version,\n ],\n cwd=root,\n check=True,\n )\n stage = \"verify_sdk\"\n subprocess.run(\n [\n python,\n \"-c\",\n \"from importlib.metadata import version\\n\"\n f\"if version('huggingface_hub') != {hub_version!r}:\\n\"\n \" raise RuntimeError('Installed Hugging Face SDK differs from declared pin')\\n\",\n ],\n cwd=root,\n check=True,\n )\n stage = \"worker\"\n subprocess.run(\n [\n python,\n \"-m\",\n \"examples.hub_validation_pipeline.cloud\",\n \"worker\",\n \"--root\",\n str(root),\n \"--bundle-sha\",\n sha,\n ],\n cwd=root,\n check=True,\n )\n except BaseException as error:\n # Stdlib fallback also covers dependency failures before HfApi is installed.\n report = {\n \"status\": \"error\",\n \"accepted\": False,\n \"stage\": stage,\n \"error_type\": type(error).__name__,\n \"bundle_sha256\": sha,\n }\n try:\n info_url = \"https://huggingface.co/api/datasets/\" + repo\n with opener.open(\n urllib.request.Request(info_url, headers=headers), timeout=30\n ) as response:\n info = _loads(response.read(1024 * 1024))\n if info.get(\"private\") is not True:\n raise ValueError(\"Results repository is not private\")\n records = [\n {\n \"key\": \"header\",\n \"value\": {\n \"summary\": \"Persist coding bootstrap error\",\n \"description\": \"\",\n },\n },\n {\n \"key\": \"file\",\n \"value\": {\n \"path\": \"runs/coding-\" + sha + \"/bootstrap-error.json\",\n \"encoding\": \"base64\",\n \"content\": base64.b64encode(\n json.dumps(report).encode()\n ).decode(),\n },\n },\n ]\n payload = \"\".join(json.dumps(row) + \"\\n\" for row in records).encode()\n request = urllib.request.Request(\n info_url + \"/commit/main\",\n data=payload,\n headers={**headers, \"Content-Type\": \"application/x-ndjson\"},\n method=\"POST\",\n )\n with opener.open(request, timeout=60) as response:\n response.read(1024 * 1024)\n except Exception:\n print(\"Bootstrap error evidence upload failed\", file=sys.stderr)\n raise RuntimeError(\n \"Coding bootstrap failed during \" + stage + \"; inspect runs/coding-\" + sha\n ) from None\n\n_bootstrap_main('0.9.3', '1.33.0')\n"],"env":{"OPENENV_BUNDLE_REVISION":"0f0c5587a84c337839895c7829cc5407b7c44310","OPENENV_BUNDLE_SHA256":"1739ff949203146d333e62326bfad0b160ae3fab5551923c793c009588709987","OPENENV_RESULTS_REPO":"harness-hub/agentic-coding-envs","PYTHONUNBUFFERED":"1"},"flavor":"cpu-basic","image":"docker.io/library/python@sha256:48d884813cf44e927cf64c5529dd630dd3b18338c6dc727991eef9b71e934a20","labels":{"openenv_bundle":"1739ff949203146d333e62326bfad0b160ae3fab5551923c793c009588709987","openenv_profile":"coding-audit-v1"},"timeout":"14400s"},"run_id":"coding-1739ff949203146d333e62326bfad0b160ae3fab5551923c793c009588709987","secret_names":["HF_TOKEN","HF_INFERENCE_TOKEN","HF_SANDBOX_TOKEN"],"status":"submitted"}runs/coding-1739ff949203146d333e62326bfad0b160ae3fab5551923c793c009588709987/submission.jsonAdded+1