StudentTang commited on
Commit
5a9b3df
·
verified ·
1 Parent(s): d2dfe87

Upload Skill-Venus Data as released (part 9)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy.json +16 -0
  2. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy.py +133 -0
  3. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy_guard.py +86 -0
  4. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/autograde_task_check.py +54 -0
  5. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/candidate_artifacts.py +24 -0
  6. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/check.py +2 -0
  7. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/dependency_scan.py +14 -0
  8. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/old_check.py +93 -0
  9. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/repair_manifest.json +69 -0
  10. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/workspace_support.py +33 -0
  11. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/grading/verified_config.json +45 -0
  12. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/inputs/config. +8 -0
  13. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/inputs/detections.log +12 -0
  14. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/instruction.md +7 -0
  15. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/skill/SKILL.md +56 -0
  16. benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/task.json +77 -0
  17. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_contract.json +8 -0
  18. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_entry.py +38 -0
  19. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_policy.py +133 -0
  20. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_policy_guard.py +86 -0
  21. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/autograde_task_check.py +14 -0
  22. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/check.py +2 -0
  23. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy-task.json +146 -0
  24. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/evaluate.py +159 -0
  25. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/objective_evaluators.py +1329 -0
  26. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/shell_invocations.py +265 -0
  27. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/test.sh +8 -0
  28. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/verifiers.py +554 -0
  29. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/repair_equivalences.py +240 -0
  30. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/grading/verified_config.json +100 -0
  31. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/instruction.md +1 -0
  32. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/skill/SKILL.md +146 -0
  33. benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/task.json +46 -0
  34. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_contract.json +26 -0
  35. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_entry.py +38 -0
  36. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy.json +16 -0
  37. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy.py +133 -0
  38. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy_guard.py +86 -0
  39. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/autograde_task_check.py +109 -0
  40. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/check.py +2 -0
  41. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/dependency_scan.py +14 -0
  42. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/r10_support.py +31 -0
  43. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/grading/verified_config.json +91 -0
  44. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/asset_inventory.json +1 -0
  45. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/dns_data.json +1 -0
  46. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/repo_history.txt +14 -0
  47. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/subdomains.txt +8 -0
  48. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/instruction.md +20 -0
  49. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/skill/SKILL.md +3 -0
  50. benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/skill/members/M000/LICENSE +19 -0
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "stdlib_only": true,
3
+ "forbid_network": true,
4
+ "forbid_subprocess": false,
5
+ "forbid_native": true,
6
+ "owner_ids": [
7
+ "6"
8
+ ],
9
+ "require_execution": true,
10
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
11
+ "execution_budget_seconds": 60,
12
+ "runtime_owner_ids": [
13
+ "6"
14
+ ],
15
+ "total_evaluation_budget_seconds": 420
16
+ }
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted bounded-invocation policy; never infer whole-program properties."""
2
+ from pathlib import Path
3
+ import hashlib,json,os,subprocess,sys,tempfile,time,uuid
4
+
5
+ HERE=Path(__file__).resolve().parent
6
+ ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
7
+ DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
8
+ class PolicyInfrastructureError(RuntimeError): pass
9
+ _installed=False
10
+ _original_popen=subprocess.Popen
11
+ _original_run=subprocess.run
12
+
13
+ def _config():
14
+ p=HERE/'auto_policy.json'
15
+ if not p.is_file():return None
16
+ value=json.loads(p.read_text())
17
+ if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
18
+ return value
19
+
20
+ def _folder():
21
+ if ENV not in os.environ:
22
+ os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
23
+ p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
24
+
25
+ def _python_target(command,cwd):
26
+ if not isinstance(command,(list,tuple))or not command:return None
27
+ argv=[os.fspath(x)for x in command]
28
+ if 'python'not in Path(argv[0]).name.lower():return None
29
+ i=1;flags=[]
30
+ while i<len(argv)and argv[i].startswith('-'):
31
+ flag=argv[i]
32
+ if flag=='-m':
33
+ if i+1>=len(argv):return None
34
+ name=argv[i+1];p=Path(cwd)/name.replace('.','/')
35
+ if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
36
+ return argv[0],flags,'module',name,argv[i+2:]
37
+ if flag in ['-c','-']:return None
38
+ flags.append(flag);i+=1
39
+ if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
40
+ if i>=len(argv)or not argv[i].endswith('.py'):return None
41
+ path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
42
+ path=path.resolve()
43
+ if path==HERE or HERE in path.parents:
44
+ if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
45
+ for value in argv[i+1:]:
46
+ if not value.endswith('.py')or value.startswith('-'):continue
47
+ subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
48
+ subject=subject.resolve()
49
+ if HERE not in subject.parents:
50
+ return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
51
+ return None
52
+ return argv[0],flags,'script',str(path),argv[i+1:]
53
+
54
+ def install():
55
+ global _installed
56
+ if _installed:return
57
+ _installed=True
58
+ cfg=_config()
59
+ if cfg is None:return
60
+ _folder()
61
+ os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
62
+ class GuardedPopen(_original_popen):
63
+ def __init__(self,args,*pos,**kwargs):
64
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
65
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
66
+ receipt=None
67
+ if target:
68
+ executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
69
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
70
+ if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
71
+ args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
72
+ env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
73
+ if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
74
+ try:super().__init__(args,*pos,**kwargs)
75
+ except OSError as error:
76
+ if receipt:
77
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
78
+ raise
79
+ subprocess.Popen=GuardedPopen
80
+ def bounded_run(*pos,**kwargs):
81
+ command=pos[0]if pos else kwargs.get('args')
82
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
83
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
84
+ if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
85
+ if target is not None and cfg.get('execution_budget_seconds')is not None:
86
+ budget=cfg['execution_budget_seconds']
87
+ if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
88
+ kwargs['timeout']=budget
89
+ remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
90
+ if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
91
+ try:
92
+ if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
93
+ result=_original_run(*pos,**kwargs)
94
+ if target is not None and result.returncode<0:
95
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
96
+ return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
97
+ return result
98
+ except subprocess.TimeoutExpired as error:
99
+ if target is None:raise
100
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
101
+ textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
102
+ empty=''if textual else b''
103
+ def output(value):
104
+ if value is None:return empty
105
+ return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
106
+ return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
107
+ subprocess.run=bounded_run
108
+
109
+ def status(require_execution=True):
110
+ install();p=_folder();rows=[]
111
+ for receipt in sorted(p.glob('*.json')):
112
+ try:row=json.loads(receipt.read_text())
113
+ except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
114
+ if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
115
+ raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
116
+ rows.append(row)
117
+ if require_execution and not any(r.get('target_present')for r in rows):return False
118
+ return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
119
+
120
+ def finalize(body,owner_ids,require_execution=True):
121
+ observed=status(require_execution=require_execution)
122
+ wanted=set(map(str,owner_ids))
123
+ for row in body.get('checks',[]):
124
+ if str(row['id'])in wanted:
125
+ if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
126
+ row['passed']=row['passed']and observed
127
+ row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
128
+ body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
129
+ body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
130
+ return body
131
+
132
+ def run(*args,**kwargs):
133
+ install();return subprocess.run(*args,**kwargs)
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/auto_policy_guard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child-side observer for the exact public bounded-invocation policy."""
2
+ from pathlib import Path
3
+ import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
4
+
5
+ receipt,config_file,kind,target,*arguments=sys.argv[1:]
6
+ subject=arguments.pop(0)if kind=='probe'else target
7
+ subject_filename=os.path.abspath(subject)
8
+ receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
9
+ local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
10
+ if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
11
+ if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
12
+ candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
13
+ observer_filename=__file__
14
+ stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
15
+ stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
16
+ if not getattr(sys,'stdlib_module_names',None):
17
+ for p in stdlib_root.iterdir():
18
+ if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
19
+ state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
20
+ busy=False
21
+ def save():
22
+ global busy
23
+ was=busy;busy=True
24
+ try:
25
+ temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
26
+ finally:busy=was
27
+ def violation(code,detail):
28
+ state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
29
+ def local_module(name):
30
+ first=name.partition('.')[0]
31
+ roots=list(local_roots)
32
+ for value in sys.path:
33
+ try:p=Path(value or cwd).resolve()
34
+ except (OSError,TypeError,ValueError):continue
35
+ if any(p==r or r in p.parents for r in local_roots):roots.append(p)
36
+ return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
37
+ def subject_active():
38
+ if kind!='probe':return True
39
+ frame=sys._getframe(1)
40
+ while frame:
41
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
42
+ if isinstance(filename,str):
43
+ absolute=os.path.abspath(filename)
44
+ if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
45
+ frame=frame.f_back
46
+ return False
47
+ def audit(event,args):
48
+ relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
49
+ if busy or not relevant or not subject_active():return
50
+ if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
51
+ check_import(str(args[0]))
52
+ if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
53
+ if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
54
+ if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
55
+ def check_import(name):
56
+ if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
57
+ base=name.partition('.')[0]
58
+ if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
59
+ def import_requested_by_candidate():
60
+ frame=sys._getframe(1)
61
+ while frame:
62
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
63
+ if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
64
+ absolute=os.path.abspath(filename)
65
+ return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
66
+ return False
67
+ original_import=builtins.__import__;original_import_module=importlib.import_module
68
+ def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
69
+ if not busy and subject_active()and import_requested_by_candidate():
70
+ absolute=name
71
+ if level:
72
+ package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
73
+ try:absolute=importlib.util.resolve_name('.'*level+name,package)
74
+ except(ImportError,ValueError):absolute=name
75
+ check_import(absolute)
76
+ return original_import(name,globals,locals,fromlist,level)
77
+ def bounded_import_module(name,package=None):
78
+ if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
79
+ return original_import_module(name,package)
80
+ save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
81
+ @atexit.register
82
+ def finish():state['state']='finished';save()
83
+ for p in reversed(local_roots):sys.path.insert(0,str(p))
84
+ sys.argv=[target,*arguments]
85
+ if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
86
+ else:runpy.run_path(target,run_name='__main__')
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json
2
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
3
+ import json,math,subprocess,sys
4
+ from pathlib import Path
5
+ from dependency_scan import scan_stdlib
6
+ from workspace_support import mirrored,remove_exact
7
+ CONFIG={'voice': {'enabled': True, 'wakeWord': 'hey jarvis', 'openaiTtsVoice': 'alloy', 'wakewordThreshold': 0.5}};LOG='2024-05-01T10:00:01\they jarvis\t0.82\n2024-05-01T10:00:45\they jarvis\t0.61\n2024-05-01T10:01:30\they jarvis\t0.44\n2024-05-01T10:02:10\they jarvis\t0.93\n2024-05-01T10:03:00\they jarvis\t0.55\n2024-05-01T10:04:12\they jarvis\t0.71\n2024-05-01T10:05:33\they jarvis\t0.38\n2024-05-01T10:06:20\they jarvis\t0.66\n2024-05-01T10:07:01\tcorrupted line\n2024-05-01T10:08:00\they jarvis\tnot_a_number\n\n2024-05-01T10:09:00\they jarvis\t0.9'
8
+ def conjunction(values):return False if False in values else None if None in values else True
9
+ def number(value):return type(value)in[int,float]and(type(value)is int or math.isfinite(value))
10
+ def oracle(config,log):
11
+ threshold=config.get('voice',{}).get('wakewordThreshold',.5);scores=[]
12
+ for line in log.splitlines():
13
+ parts=line.split('\t')
14
+ if not line.strip()or len(parts)!=3:continue
15
+ try:scores.append(float(parts[2]))
16
+ except ValueError:continue
17
+ triggers=sum(score>=threshold for score in scores);total=len(scores)
18
+ return dict(threshold=threshold,total=total,triggers=triggers,misses=total-triggers,recommended_threshold=min(.9,threshold+.2)if 2*triggers>total else threshold)
19
+ def assess(o,config,log):
20
+ want=oracle(config,log)
21
+ if not isinstance(o,dict):return[False]*6
22
+ numeric={key:number(o.get(key))for key in want};shape=all(numeric.values())
23
+ def equal(key):
24
+ if not numeric[key]:return False
25
+ try:return abs(o[key]-want[key])<=1e-10
26
+ except OverflowError:return False
27
+ return[shape,equal('threshold'),equal('total'),equal('triggers')and equal('misses'),all(numeric[key]for key in('total','triggers','misses'))and o['total']==o['triggers']+o['misses'],equal('recommended_threshold')]
28
+ def run(c,config,log):
29
+ results=[]
30
+ with mirrored(c)as roots:
31
+ for ws in roots:
32
+ for site in roots:remove_exact(site,'report.');(site/'config.').write_text(json.dumps(config));(site/'detections.log').write_text(log)
33
+ try:
34
+ p=subprocess.run([sys.executable,'tune.py'],cwd=ws,capture_output=True,text=True,timeout=30);paths=[site/'report.'for site in roots if(site/'report.').is_file()]
35
+ for path in paths:
36
+ try:results.append((p.returncode,_co_loads(_co_text(path))))
37
+ except(ValueError,UnicodeError,OSError):results.append((p.returncode,None))
38
+ if not paths:results.append((p.returncode,None))
39
+ except subprocess.TimeoutExpired:results.append((124,None))
40
+ except OSError as error:raise RuntimeError("Trusted voice tuning launcher failed") from error
41
+ return results
42
+
43
+ def evaluate(c):
44
+ c=Path(c)
45
+ try:actual=_co_loads(_co_text(c/'report.'))
46
+ except(OSError,UnicodeError,ValueError):actual=None
47
+ views=[assess(actual,CONFIG,LOG)];runtime=[]
48
+ panels=[(CONFIG,LOG),({},'t\tmodel-A\t0.5\nt\tmodel-B\t0.49999\n'),({'wakewordThreshold':.9,'voice':{'enabled':False}},'\t\t5e-1\n x\tnew model\t0.9\ninvalid\nwrong\tfields\t0.7\textra\nt\tm\tnonnumeric\n\n'),({'voice':{'wakewordThreshold':0}},'t\tquiet\t0\nt\tother\t0.1\n'),({'voice':{'wakewordThreshold':.85}},'t\tnew\t0.85\nt\tnew\t0.99\nt\tnew\t0.9\nt\tnew\t0.1\n'),({'voice':{'wakewordThreshold':.95}},'t\tnew\t1.0\nt\tnew\t0.95\n'),({'voice':{'wakewordThreshold':.31}},''),({'voice':{}},'\nwrong field count\n1\t2\t3\t4\nt\tany\tbad\n')]
49
+ for config,log in panels:
50
+ for rc,o in run(c,config,log):runtime.append(None if rc is None else isinstance(o,dict));views.append([None]*6 if rc is None else assess(o,config,log))
51
+ dependency,_,why=scan_stdlib(c,['tune.py']);dependency=None if why.startswith('unknown:')else dependency
52
+ bits=[conjunction([v[i]for v in views])for i in range(6)]+[dependency,conjunction(runtime)]
53
+ return{'scoreable':None not in bits,'checks':[{'id':str(i),'passed':v,'reason':['Actual required report and clean full numeric JSON report with five fields, extra diagnostics allowed','Effective nested threshold including explicit0 and absent voice/key fallback, no top-level substitution','All and only three-field numeric-score nonblank events across arbitrary models and malformed/empty logs','Threshold-inclusive trigger/miss counts across exact boundary/half/zero/cap panels','Counts are finite numeric nonbool values and triggers+misses equals total','Strict trigger fraction>0.5, current threshold unchanged at equality/empty, min0.9 cap','Reachable public stdlib graph with namespaces/PEP263/local shadows/dynamic literal loaders; unknown perIDnull','Named Python program creates parseable fresh public output; independent of the saved artifact and no prescribed exit code in either supported runtime root'][i]}for i,v in enumerate(bits)]}
54
+ if __name__=='__main__':print(json.dumps(evaluate('/candidate')))
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/candidate_artifacts.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read only ordinary candidate artifacts after a bounded child completes.
2
+ No launch/setup/monitor exceptions are caught here. Symlinks to regular files
3
+ remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from
4
+ blocking the trusted grader. Malformed text/JSON is an absent invalid value.
5
+ """
6
+ import json, os, stat
7
+
8
+ def read_text(path, encoding=None, errors=None):
9
+ fd=None
10
+ try:
11
+ fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK)
12
+ if not stat.S_ISREG(os.fstat(fd).st_mode):return ''
13
+ with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream:
14
+ fd=None
15
+ return stream.read()
16
+ except (OSError,UnicodeError):return ''
17
+ finally:
18
+ if fd is not None:os.close(fd)
19
+
20
+ def loads(text, **kwargs):
21
+ try:return json.loads(text,**kwargs)
22
+ except (ValueError,TypeError,RecursionError):return None
23
+
24
+ def load(path, **kwargs):return loads(read_text(path),**kwargs)
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/dependency_scan.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private static dependency validation, including local Python namespace packages.
2
+
3
+ This module only parses source. It never imports or runs candidate modules.
4
+ """
5
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
6
+ import _imp
7
+ import ast
8
+ import sys
9
+ import tokenize
10
+ from pathlib import Path
11
+
12
+
13
+ def scan_stdlib(root, entries, external=()):
14
+ return True, [], 'Deferred to public bounded runtime policy; no whole-source inference'
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/old_check.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ import json, os, shutil, subprocess, sys, tempfile, ast
3
+
4
+ CONFIG = '{\n "voice": {\n "enabled": true,\n "wakeWord": "hey jarvis",\n "openaiTtsVoice": "alloy",\n "wakewordThreshold": 0.5\n }\n}'
5
+ LOG = '2024-05-01T10:00:01\they jarvis\t0.82\n2024-05-01T10:00:45\they jarvis\t0.61\n2024-05-01T10:01:30\they jarvis\t0.44\n2024-05-01T10:02:10\they jarvis\t0.93\n2024-05-01T10:03:00\they jarvis\t0.55\n2024-05-01T10:04:12\they jarvis\t0.71\n2024-05-01T10:05:33\they jarvis\t0.38\n2024-05-01T10:06:20\they jarvis\t0.66\n2024-05-01T10:07:01\tcorrupted line\n2024-05-01T10:08:00\they jarvis\tnot_a_number\n\n2024-05-01T10:09:00\they jarvis\t0.9\n'
6
+
7
+ def is_stdlib(name):
8
+ try:
9
+ m = __import__(name)
10
+ except Exception:
11
+ return False
12
+ spec = getattr(m, '__spec__', None)
13
+ if spec is None:
14
+ return True
15
+ origin = getattr(spec, 'origin', None)
16
+ if origin is None:
17
+ return True
18
+ return ('stdlib' in origin) or ('python3.' in origin and 'site-packages' not in origin)
19
+
20
+ def main():
21
+ cand = '/candidate'
22
+ checks = [None]*8
23
+ tmp = tempfile.mkdtemp(dir='/tmp')
24
+ try:
25
+ with open(os.path.join(tmp, 'config.'), 'w') as f: f.write(CONFIG)
26
+ with open(os.path.join(tmp, 'detections.log'), 'w') as f: f.write(LOG)
27
+ src = os.path.join(cand, 'tune.py')
28
+ have_src = os.path.isfile(src)
29
+ run_ok = False
30
+ report = None
31
+ if have_src:
32
+ shutil.copy(src, os.path.join(tmp, 'tune.py'))
33
+ try:
34
+ r = subprocess.run([sys.executable, 'tune.py'], cwd=tmp,
35
+ capture_output=True, text=True, timeout=60)
36
+ run_ok = (r.returncode == 0)
37
+ except Exception:
38
+ run_ok = False
39
+ rp = os.path.join(tmp, 'report.')
40
+ if os.path.isfile(rp):
41
+ try:
42
+ report = json.load(open(rp))
43
+ except Exception:
44
+ report = None
45
+ # 0: report. exists and valid JSON
46
+ checks[0] = (report is not None, 'report. exists and parses as JSON' if report is not None else 'report. missing or not valid JSON')
47
+ # 7: script runs successfully producing report.
48
+ checks[7] = (have_src and run_ok and report is not None,
49
+ 'python3 tune.py ran and produced report.' if (have_src and run_ok and report is not None) else 'tune.py missing, crashed, or did not produce report.')
50
+ def num(rep, key):
51
+ try:
52
+ v = rep[key]
53
+ return float(v)
54
+ except Exception:
55
+ return None
56
+ if report is not None:
57
+ th = num(report, 'threshold')
58
+ tot = num(report, 'total')
59
+ trg = num(report, 'triggers')
60
+ mis = num(report, 'misses')
61
+ rec = num(report, 'recommended_threshold')
62
+ else:
63
+ th = tot = trg = mis = rec = None
64
+ checks[1] = (th == 0.5, 'threshold == 0.5 from voice.wakewordThreshold' if th == 0.5 else 'threshold is %r, expected 0.5' % th)
65
+ checks[2] = (tot == 9, 'total == 9 valid events' if tot == 9 else 'total is %r, expected 9' % tot)
66
+ checks[3] = (trg == 7 and mis == 2, 'triggers == 7 and misses == 2' if (trg == 7 and mis == 2) else 'triggers=%r misses=%r, expected 7 and 2' % (trg, mis))
67
+ checks[4] = (tot is not None and trg is not None and mis is not None and trg + mis == tot,
68
+ 'triggers + misses == total' if (tot is not None and trg is not None and mis is not None and trg + mis == tot) else 'triggers + misses != total')
69
+ checks[5] = (rec == 0.7, 'recommended_threshold == 0.7' if rec == 0.7 else 'recommended_threshold is %r, expected 0.7' % rec)
70
+ # 6: stdlib-only imports
71
+ stdlib_ok = False
72
+ reason = 'tune.py missing'
73
+ if have_src:
74
+ try:
75
+ tree = ast.parse(open(src).read())
76
+ mods = set()
77
+ for node in ast.walk(tree):
78
+ if isinstance(node, ast.Import):
79
+ for a in node.names: mods.add(a.name.split('.')[0])
80
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
81
+ mods.add(node.module.split('.')[0])
82
+ bad = [m for m in sorted(mods) if not is_stdlib(m)]
83
+ stdlib_ok = not bad
84
+ reason = 'only stdlib imports' if stdlib_ok else 'non-stdlib imports: %s' % ', '.join(bad)
85
+ except Exception as e:
86
+ reason = 'could not parse tune.py: %s' % e
87
+ checks[6] = (stdlib_ok, reason)
88
+ out = {'checks': [{'id': str(i), 'passed': bool(c[0]), 'reason': c[1]} for i, c in enumerate(checks)]}
89
+ finally:
90
+ shutil.rmtree(tmp, ignore_errors=True)
91
+ print(json.dumps(out))
92
+
93
+ main()
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/repair_manifest.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "query_id": "70b4b7a3dc1f941435e5dffe",
3
+ "sample_index": 433,
4
+ "scope_ordinal": 294,
5
+ "canonical_check_ids": [
6
+ "0",
7
+ "1",
8
+ "2",
9
+ "3",
10
+ "4",
11
+ "5",
12
+ "6",
13
+ "7"
14
+ ],
15
+ "original_count": 8,
16
+ "modified_check_ids": [
17
+ "0",
18
+ "1",
19
+ "2",
20
+ "3",
21
+ "4",
22
+ "5",
23
+ "6",
24
+ "7"
25
+ ],
26
+ "root_cause": "Whole-schema failure erased independently valid fields; fresh runtime duplicated saved artifact and imposed exit0",
27
+ "public_semantics": "Each numeric field is evaluated independently of schema0; fresh artifact7 is separate from actual saved report and accepts any completed exit with valid output",
28
+ "source_hashes": {
29
+ "instruction.md": "5e5ee19d55f90a497f7236abe66f4f92b7536808b6cffded5d0717331538cd2b",
30
+ "evaluator/check.py": "5dbe091545eb7df05e8c4d0095908df9c4e59569944be6696df508e25a09f678",
31
+ "skill/SKILL.md": "487433b580bb4e6d64e9cc9077c5d2975bfe4a6daf4b80c4d501ea32126b4585",
32
+ "reference/answer.txt": "7d9ce3b9a12ba9d5393f7217e785b73edfc353a5c23422707a73fede13b6eff6",
33
+ "inputs/config.": "33b5c23f06dc47f838671f8718ed3f9329bc80e9985f85beefbe4b21c051ba39",
34
+ "inputs/detections.log": "3fc7be50cb35a69da101d2519f038fec3295bfb71afaa5e4b64265cb5de27da4",
35
+ "reference/workspace/config.": "33b5c23f06dc47f838671f8718ed3f9329bc80e9985f85beefbe4b21c051ba39",
36
+ "reference/workspace/detections.log": "3fc7be50cb35a69da101d2519f038fec3295bfb71afaa5e4b64265cb5de27da4",
37
+ "reference/workspace/instruction.md": "5e5ee19d55f90a497f7236abe66f4f92b7536808b6cffded5d0717331538cd2b",
38
+ "reference/workspace/report.": "1f7f80d3d4e15e4b6ffe2103e80e6f2961cd7371bea4296d7e9acec27fabec9d",
39
+ "reference/workspace/tune.py": "c2be1964c091133718ef98c65486f6ffa1801e305057823813703e88bf759598"
40
+ },
41
+ "reviewed_files": [
42
+ "instruction.md",
43
+ "evaluator/check.py",
44
+ "skill/SKILL.md",
45
+ "reference/answer.txt",
46
+ "inputs/config.",
47
+ "inputs/detections.log",
48
+ "reference/workspace/config.",
49
+ "reference/workspace/detections.log",
50
+ "reference/workspace/instruction.md",
51
+ "reference/workspace/report.",
52
+ "reference/workspace/tune.py"
53
+ ],
54
+ "required_historical_artifacts": [],
55
+ "checker_sha256": "200df8277929aedf035645dadb0242f52fb6059889cf90de9bf15a9e4a93de12",
56
+ "all_logic_sha256": {
57
+ "check.py": "200df8277929aedf035645dadb0242f52fb6059889cf90de9bf15a9e4a93de12",
58
+ "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9",
59
+ "old_check.py": "5dbe091545eb7df05e8c4d0095908df9c4e59569944be6696df508e25a09f678",
60
+ "workspace_support.py": "5fdb5a170551f96795fcebc315cbf87d40048075d71ebeeece63a65af31bf387"
61
+ },
62
+ "solver_or_arm_conditioned": false,
63
+ "status": "implemented_pending_independent_review",
64
+ "validation": "Authored checker parsed and compiled only; no source/candidate/checker runtime locally; no new solver; no historical rescoring by author.",
65
+ "notes": "Full public/old/voice skill/input/reference/current and all20 controls read. Preserve missing-actual entity as0-5False/6-7True, add malformed threshold/missing recommendation/boolean count field maps, nonzero valid equivalent and unknown6 mixed known0/1False. Three-value scanner API verified, AST only",
66
+ "repair_scope": "grader_only_second_round",
67
+ "historical_scores_seen": false,
68
+ "new_solver_executions": 0
69
+ }
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/evaluator/workspace_support.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private Docker-only mirrored runtime roots; importing performs no mutation."""
2
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
3
+ import contextlib
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ def _clear(root):
8
+ root.mkdir(exist_ok=True)
9
+ for path in root.iterdir():
10
+ if path.is_dir() and not path.is_symlink():
11
+ shutil.rmtree(path)
12
+ else:
13
+ path.unlink()
14
+
15
+ @contextlib.contextmanager
16
+ def mirrored(candidate):
17
+ roots = [Path('/workspace'), Path('/app')]
18
+ try:
19
+ for root in roots:
20
+ _clear(root)
21
+ shutil.copytree(candidate, root, dirs_exist_ok=True, symlinks=True,
22
+ ignore=shutil.ignore_patterns('__pycache__', '.git', '.venv'))
23
+ yield roots
24
+ finally:
25
+ for root in roots:
26
+ _clear(root)
27
+
28
+ def remove_exact(root, relative):
29
+ path = root / relative
30
+ if path.is_file() or path.is_symlink():
31
+ path.unlink()
32
+ elif path.is_dir():
33
+ shutil.rmtree(path)
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/grading/verified_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "70b4b7a3dc1f941435e5dffe",
4
+ "runtime_requirements": {
5
+ "expected_check_ids": [
6
+ "0",
7
+ "1",
8
+ "2",
9
+ "3",
10
+ "4",
11
+ "5",
12
+ "6",
13
+ "7"
14
+ ],
15
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
16
+ "network": "none",
17
+ "criterion_weights": {
18
+ "0": 1,
19
+ "1": 1,
20
+ "2": 1,
21
+ "3": 1,
22
+ "4": 1,
23
+ "5": 1,
24
+ "6": 1,
25
+ "7": 1
26
+ },
27
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair."
28
+ },
29
+ "engine": "verified514_offline_v1",
30
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
31
+ "grader_file_sha256": {
32
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
33
+ "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185",
34
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
35
+ "auto_policy.json": "c9740d4478341dceb7b36171f5fb4f4d228974705d59f9ff227e7532c4021c47",
36
+ "old_check.py": "4322b8c2fb3d8789405035ee3e1288e4647c29b8bb5103f278dd535b3f314f78",
37
+ "repair_manifest.json": "6375104d1a7f2468f35a3faca39b92721c60223ab411d8caf6ffc36134a61191",
38
+ "dependency_scan.py": "aff23360095bcb8289ad65e861c5fe29ae8b9c355ae7cab23f306d1e20c81f67",
39
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
40
+ "autograde_task_check.py": "419b908127a2a5d690416c975183db3362493eff2b8fc28dcd07653f4e8b0861",
41
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
42
+ "workspace_support.py": "374d2be38b386a83cc0b6210cd0552499ea971dc4683431594322125376b125e",
43
+ "auto_contract.json": "1973ab59d6c798839dc76976e2cf6ec72facd1f60b833ebabefed0e297a7ccd7"
44
+ }
45
+ }
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/inputs/config. ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "voice": {
3
+ "enabled": true,
4
+ "wakeWord": "hey jarvis",
5
+ "openaiTtsVoice": "alloy",
6
+ "wakewordThreshold": 0.5
7
+ }
8
+ }
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/inputs/detections.log ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2024-05-01T10:00:01 hey jarvis 0.82
2
+ 2024-05-01T10:00:45 hey jarvis 0.61
3
+ 2024-05-01T10:01:30 hey jarvis 0.44
4
+ 2024-05-01T10:02:10 hey jarvis 0.93
5
+ 2024-05-01T10:03:00 hey jarvis 0.55
6
+ 2024-05-01T10:04:12 hey jarvis 0.71
7
+ 2024-05-01T10:05:33 hey jarvis 0.38
8
+ 2024-05-01T10:06:20 hey jarvis 0.66
9
+ 2024-05-01T10:07:01 corrupted line
10
+ 2024-05-01T10:08:00 hey jarvis not_a_number
11
+
12
+ 2024-05-01T10:09:00 hey jarvis 0.9
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/instruction.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ You are configuring a local wake-word voice assistant on a Raspberry Pi. The workspace contains `config.` (the assistant's configuration) and `detections.log` (a log of raw wake-word detection events, one per line, format: `timestamp<TAB>model<TAB>score` where score is a float between 0 and 1). Write a Python script `tune.py` that: (1) reads `config.` and determines the effective wake-word threshold — it must use `voice.wakewordThreshold` if present, otherwise default to 0.5; (2) reads `detections.log`, ignores blank lines and malformed lines (wrong field count or non-numeric score), and classifies each valid event as `trigger` if score >= threshold, else `miss`; (3) writes `report.` containing: `threshold` (the effective threshold as a number), `total` (number of valid events), `triggers` (count of triggers), `misses` (count of misses), and `recommended_threshold` — if the fraction of triggers among valid events is greater than 0.5, the config is too sensitive and `recommended_threshold` must be min(0.9, threshold + 0.2); otherwise it must equal the current threshold. Run the script so `report.` is created in the workspace. Use only the Python standard library.
2
+ Bounded automatic resource contract: During the actual grader-launched Python invocations, Python imports must resolve to the standard library or submitted local modules/packages (including namespace packages and computed imports). Unused/dead source code and strings are not rejected by static import inference. Do not perform network operations during graded invocations. Do not load or call foreign native libraries through FFI during graded invocations. Child processes are not forbidden solely because they exist; all original output and interface requirements still apply. A launcher or instrumentation failure is an infrastructure error, not a wrong-answer score.
3
+
4
+ Execution budget: every grader-launched candidate Python invocation must complete within 60 seconds. A timeout after candidate startup fails this bounded-completion requirement; a trusted observer or launcher failure is an infrastructure error.
5
+
6
+
7
+ Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score.
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/skill/SKILL.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: voice-assistant
3
+ description: Run the local wake-word voice assistant ("hey jarvis") with OpenAI voice + TTS.
4
+ homepage: https://github.com/HKUDS/nanobot
5
+ metadata: {"nanobot":{"emoji":"🎙️"}}
6
+ ---
7
+
8
+ # Voice Assistant (Wake Word)
9
+
10
+ This skill enables a local, always-on voice assistant for nanobot with the wake word **"hey jarvis"**. It runs on-device for wake word detection and uses OpenAI audio models for transcription + TTS.
11
+
12
+ ## Install (Raspberry Pi 4)
13
+
14
+ ```bash
15
+ # System deps for audio I/O
16
+ sudo apt-get update
17
+ sudo apt-get install -y portaudio19-dev libsndfile1
18
+
19
+ # Python deps
20
+ pip install 'nanobot-ai[voice]'
21
+ ```
22
+
23
+ ## Configure
24
+
25
+ Edit `~/.nanobot/config.json` and enable voice:
26
+
27
+ ```json
28
+ {
29
+ "voice": {
30
+ "enabled": true,
31
+ "wakeWord": "hey jarvis",
32
+ "openaiTtsVoice": "alloy"
33
+ }
34
+ }
35
+ ```
36
+
37
+ Notes:
38
+ - "hey jarvis" is included as a built-in openwakeword model. You only need `wakewordModels` for a custom wake phrase.
39
+ - Set `voice.openaiApiKey` or `providers.openai.apiKey` in config.
40
+ - Default sample rate is 16kHz for Raspberry Pi 4 efficiency.
41
+
42
+ ## Run
43
+
44
+ ```bash
45
+ # Run standalone voice assistant
46
+ nanobot voice
47
+
48
+ # Or run with the full gateway (channels + voice)
49
+ nanobot gateway
50
+ ```
51
+
52
+ ## Tips
53
+
54
+ - If the wake word is too sensitive, raise `voice.wakewordThreshold` (0.5 → 0.7).
55
+ - If recordings cut off, increase `voice.preRollMs` or `voice.silenceMs`.
56
+ - Use `voice.inputDevice` and `voice.outputDevice` if you have multiple audio devices.
benchmarks/skillbench-venus-e/tasks/70b4b7a3dc1f941435e5dffe/task.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "70b4b7a3dc1f941435e5dffe",
4
+ "environment": {
5
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
6
+ "network": "none"
7
+ },
8
+ "query_id": "70b4b7a3dc1f941435e5dffe",
9
+ "outputs": [
10
+ "tune.py",
11
+ "report."
12
+ ],
13
+ "success_criteria": [
14
+ "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.",
15
+ "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md."
16
+ ],
17
+ "evaluation": {
18
+ "kind": "python",
19
+ "type": "verified"
20
+ },
21
+ "source_skill": {
22
+ "sha256": "ac38d37d57f893a9402bb6751925b88697245252893fb6f1f8d22eb12e751161",
23
+ "files": {
24
+ "SKILL.md": "487433b580bb4e6d64e9cc9077c5d2975bfe4a6daf4b80c4d501ea32126b4585"
25
+ }
26
+ },
27
+ "workspace": {
28
+ "candidate_mode": "workspace",
29
+ "input_mappings": [
30
+ {
31
+ "source": "inputs/config.",
32
+ "workspace_target": "config.",
33
+ "sha256": "33b5c23f06dc47f838671f8718ed3f9329bc80e9985f85beefbe4b21c051ba39"
34
+ },
35
+ {
36
+ "source": "inputs/detections.log",
37
+ "workspace_target": "detections.log",
38
+ "sha256": "3fc7be50cb35a69da101d2519f038fec3295bfb71afaa5e4b64265cb5de27da4"
39
+ }
40
+ ],
41
+ "skill_packages": [
42
+ {
43
+ "package_path": "skill",
44
+ "content_hash": "ac38d37d57f893a9402bb6751925b88697245252893fb6f1f8d22eb12e751161"
45
+ }
46
+ ]
47
+ },
48
+ "autograde_runtime_contract": {
49
+ "stdlib_only": true,
50
+ "forbid_network": true,
51
+ "forbid_subprocess": false,
52
+ "forbid_native": true,
53
+ "owner_ids": [
54
+ "6"
55
+ ],
56
+ "require_execution": true,
57
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
58
+ "execution_budget_seconds": 60
59
+ },
60
+ "automatic_evaluation_runtime": {
61
+ "stdlib_only": true,
62
+ "forbid_network": true,
63
+ "forbid_subprocess": false,
64
+ "forbid_native": true,
65
+ "owner_ids": [
66
+ "6"
67
+ ],
68
+ "require_execution": true,
69
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
70
+ "execution_budget_seconds": 60,
71
+ "runtime_owner_ids": [
72
+ "6"
73
+ ],
74
+ "total_evaluation_budget_seconds": 420,
75
+ "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score."
76
+ }
77
+ }
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_contract.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expected_check_ids": [
3
+ "0"
4
+ ],
5
+ "criterion_weights": {
6
+ "0": 1
7
+ }
8
+ }
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_entry.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable result protocol; candidate failures and evaluator errors stay distinct."""
2
+ from pathlib import Path
3
+ import contextlib,io,json,runpy,sys
4
+ from auto_policy import install,finalize
5
+ HERE=Path(__file__).resolve().parent
6
+
7
+ def main():
8
+ captured=io.StringIO()
9
+ try:
10
+ install()
11
+ with contextlib.redirect_stdout(captured):
12
+ try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
13
+ except SystemExit as error:
14
+ if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
15
+ body=None
16
+ for line in reversed(captured.getvalue().splitlines()):
17
+ try:value=json.loads(line)
18
+ except(ValueError,TypeError):continue
19
+ if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
20
+ if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
21
+ if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
22
+ cfgfile=HERE/'auto_policy.json'
23
+ if cfgfile.is_file():
24
+ cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
25
+ if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
26
+ checks=body['checks']
27
+ if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
28
+ ids=[str(c['id'])for c in checks]
29
+ if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
30
+ contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
31
+ if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
32
+ weights=contract['criterion_weights']
33
+ body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
34
+ print(json.dumps(body,ensure_ascii=True));return 0
35
+ except Exception as error:
36
+ print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
37
+
38
+ if __name__=='__main__':raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_policy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted bounded-invocation policy; never infer whole-program properties."""
2
+ from pathlib import Path
3
+ import hashlib,json,os,subprocess,sys,tempfile,time,uuid
4
+
5
+ HERE=Path(__file__).resolve().parent
6
+ ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
7
+ DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
8
+ class PolicyInfrastructureError(RuntimeError): pass
9
+ _installed=False
10
+ _original_popen=subprocess.Popen
11
+ _original_run=subprocess.run
12
+
13
+ def _config():
14
+ p=HERE/'auto_policy.json'
15
+ if not p.is_file():return None
16
+ value=json.loads(p.read_text())
17
+ if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
18
+ return value
19
+
20
+ def _folder():
21
+ if ENV not in os.environ:
22
+ os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
23
+ p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
24
+
25
+ def _python_target(command,cwd):
26
+ if not isinstance(command,(list,tuple))or not command:return None
27
+ argv=[os.fspath(x)for x in command]
28
+ if 'python'not in Path(argv[0]).name.lower():return None
29
+ i=1;flags=[]
30
+ while i<len(argv)and argv[i].startswith('-'):
31
+ flag=argv[i]
32
+ if flag=='-m':
33
+ if i+1>=len(argv):return None
34
+ name=argv[i+1];p=Path(cwd)/name.replace('.','/')
35
+ if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
36
+ return argv[0],flags,'module',name,argv[i+2:]
37
+ if flag in ['-c','-']:return None
38
+ flags.append(flag);i+=1
39
+ if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
40
+ if i>=len(argv)or not argv[i].endswith('.py'):return None
41
+ path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
42
+ path=path.resolve()
43
+ if path==HERE or HERE in path.parents:
44
+ if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
45
+ for value in argv[i+1:]:
46
+ if not value.endswith('.py')or value.startswith('-'):continue
47
+ subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
48
+ subject=subject.resolve()
49
+ if HERE not in subject.parents:
50
+ return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
51
+ return None
52
+ return argv[0],flags,'script',str(path),argv[i+1:]
53
+
54
+ def install():
55
+ global _installed
56
+ if _installed:return
57
+ _installed=True
58
+ cfg=_config()
59
+ if cfg is None:return
60
+ _folder()
61
+ os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
62
+ class GuardedPopen(_original_popen):
63
+ def __init__(self,args,*pos,**kwargs):
64
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
65
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
66
+ receipt=None
67
+ if target:
68
+ executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
69
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
70
+ if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
71
+ args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
72
+ env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
73
+ if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
74
+ try:super().__init__(args,*pos,**kwargs)
75
+ except OSError as error:
76
+ if receipt:
77
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
78
+ raise
79
+ subprocess.Popen=GuardedPopen
80
+ def bounded_run(*pos,**kwargs):
81
+ command=pos[0]if pos else kwargs.get('args')
82
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
83
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
84
+ if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
85
+ if target is not None and cfg.get('execution_budget_seconds')is not None:
86
+ budget=cfg['execution_budget_seconds']
87
+ if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
88
+ kwargs['timeout']=budget
89
+ remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
90
+ if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
91
+ try:
92
+ if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
93
+ result=_original_run(*pos,**kwargs)
94
+ if target is not None and result.returncode<0:
95
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
96
+ return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
97
+ return result
98
+ except subprocess.TimeoutExpired as error:
99
+ if target is None:raise
100
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
101
+ textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
102
+ empty=''if textual else b''
103
+ def output(value):
104
+ if value is None:return empty
105
+ return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
106
+ return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
107
+ subprocess.run=bounded_run
108
+
109
+ def status(require_execution=True):
110
+ install();p=_folder();rows=[]
111
+ for receipt in sorted(p.glob('*.json')):
112
+ try:row=json.loads(receipt.read_text())
113
+ except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
114
+ if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
115
+ raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
116
+ rows.append(row)
117
+ if require_execution and not any(r.get('target_present')for r in rows):return False
118
+ return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
119
+
120
+ def finalize(body,owner_ids,require_execution=True):
121
+ observed=status(require_execution=require_execution)
122
+ wanted=set(map(str,owner_ids))
123
+ for row in body.get('checks',[]):
124
+ if str(row['id'])in wanted:
125
+ if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
126
+ row['passed']=row['passed']and observed
127
+ row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
128
+ body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
129
+ body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
130
+ return body
131
+
132
+ def run(*args,**kwargs):
133
+ install();return subprocess.run(*args,**kwargs)
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/auto_policy_guard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child-side observer for the exact public bounded-invocation policy."""
2
+ from pathlib import Path
3
+ import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
4
+
5
+ receipt,config_file,kind,target,*arguments=sys.argv[1:]
6
+ subject=arguments.pop(0)if kind=='probe'else target
7
+ subject_filename=os.path.abspath(subject)
8
+ receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
9
+ local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
10
+ if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
11
+ if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
12
+ candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
13
+ observer_filename=__file__
14
+ stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
15
+ stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
16
+ if not getattr(sys,'stdlib_module_names',None):
17
+ for p in stdlib_root.iterdir():
18
+ if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
19
+ state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
20
+ busy=False
21
+ def save():
22
+ global busy
23
+ was=busy;busy=True
24
+ try:
25
+ temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
26
+ finally:busy=was
27
+ def violation(code,detail):
28
+ state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
29
+ def local_module(name):
30
+ first=name.partition('.')[0]
31
+ roots=list(local_roots)
32
+ for value in sys.path:
33
+ try:p=Path(value or cwd).resolve()
34
+ except (OSError,TypeError,ValueError):continue
35
+ if any(p==r or r in p.parents for r in local_roots):roots.append(p)
36
+ return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
37
+ def subject_active():
38
+ if kind!='probe':return True
39
+ frame=sys._getframe(1)
40
+ while frame:
41
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
42
+ if isinstance(filename,str):
43
+ absolute=os.path.abspath(filename)
44
+ if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
45
+ frame=frame.f_back
46
+ return False
47
+ def audit(event,args):
48
+ relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
49
+ if busy or not relevant or not subject_active():return
50
+ if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
51
+ check_import(str(args[0]))
52
+ if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
53
+ if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
54
+ if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
55
+ def check_import(name):
56
+ if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
57
+ base=name.partition('.')[0]
58
+ if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
59
+ def import_requested_by_candidate():
60
+ frame=sys._getframe(1)
61
+ while frame:
62
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
63
+ if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
64
+ absolute=os.path.abspath(filename)
65
+ return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
66
+ return False
67
+ original_import=builtins.__import__;original_import_module=importlib.import_module
68
+ def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
69
+ if not busy and subject_active()and import_requested_by_candidate():
70
+ absolute=name
71
+ if level:
72
+ package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
73
+ try:absolute=importlib.util.resolve_name('.'*level+name,package)
74
+ except(ImportError,ValueError):absolute=name
75
+ check_import(absolute)
76
+ return original_import(name,globals,locals,fromlist,level)
77
+ def bounded_import_module(name,package=None):
78
+ if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
79
+ return original_import_module(name,package)
80
+ save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
81
+ @atexit.register
82
+ def finish():state['state']='finished';save()
83
+ for p in reversed(local_roots):sys.path.insert(0,str(p))
84
+ sys.argv=[target,*arguments]
85
+ if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
86
+ else:runpy.run_path(target,run_name='__main__')
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ import sys,json
3
+ from pathlib import Path
4
+ root=Path(__file__).resolve().parent
5
+ sys.path.insert(0,str(root/'legacy_tests'))
6
+ from evaluate import evaluate
7
+ t=json.loads((root/'legacy-task.json').read_text())
8
+ from repair_equivalences import install
9
+ install(t)
10
+ mode=t['workspace']['candidate_mode']
11
+ r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
12
+ if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
13
+ if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
14
+ print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy-task.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "mybench-portable-task-v2",
3
+ "task_id": "719eda04e56bf901",
4
+ "query_id": "719eda04e56bf901_q1",
5
+ "prompt": {
6
+ "path": "instruction.md",
7
+ "sha256": "e996f97ead752faf518b772336a403e7f4374c4ee9be8dd2eddfe93b70561d7f"
8
+ },
9
+ "workspace": {
10
+ "input_mappings": [],
11
+ "skill_packages": [
12
+ {
13
+ "content_hash": "3fea8b2f5df5eeb86d0c3bcc3e7615926dd528a3d4a55fda1f80e8ec857fb259",
14
+ "name": "add-command",
15
+ "package_path": "environment/skills/add-command-3fea8b2f",
16
+ "install_name": "add-command-3fea8b2f",
17
+ "archive_provenance": {
18
+ "archive_id": "logical-skill-05d2555b79374680a33d11ca",
19
+ "archive_schema": "skill-release-v1",
20
+ "release_skill_id": "logical-skill-05d2555b79374680a33d11ca",
21
+ "site": "skills-sh",
22
+ "local_path": "skills/05/logical-skill-05d2555b79374680a33d11ca",
23
+ "skill_md_sha256": "03522f37b6520e695936a99ae17e3d545528edd7281dc3e3a426778531613786",
24
+ "release_payload_sha256": "3fea8b2f5df5eeb86d0c3bcc3e7615926dd528a3d4a55fda1f80e8ec857fb259",
25
+ "license": "Apache-2.0",
26
+ "license_status": "detected",
27
+ "canonical_source_id": "skills-sh:coralogix/cx-cli/add-command"
28
+ },
29
+ "omitted_entries": []
30
+ }
31
+ ],
32
+ "default_skill_target": ".claude/skills",
33
+ "candidate_mode": "response"
34
+ },
35
+ "ground_truth_skills": [
36
+ "3fea8b2f5df5eeb86d0c3bcc3e7615926dd528a3d4a55fda1f80e8ec857fb259"
37
+ ],
38
+ "evaluation": {
39
+ "type": "verified",
40
+ "ground_truth_answer": {
41
+ "answers": {
42
+ "q1": "cx schema",
43
+ "q2": "src/commands/logs/mod.rs",
44
+ "q3": "#[serde(rename_all = \"camelCase\")]",
45
+ "q4": "src/main.rs"
46
+ }
47
+ },
48
+ "verifier": {
49
+ "type": "atomic_json",
50
+ "version": 2,
51
+ "list_order": "ordered",
52
+ "float_tolerance": 0.01,
53
+ "completeness": {
54
+ "forbid_extra": true,
55
+ "shape": {
56
+ "type": "object",
57
+ "keys": {
58
+ "answers": {
59
+ "type": "object",
60
+ "keys": {
61
+ "q1": {
62
+ "type": "string"
63
+ },
64
+ "q2": {
65
+ "type": "string"
66
+ },
67
+ "q3": {
68
+ "type": "string"
69
+ },
70
+ "q4": {
71
+ "type": "string"
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ },
78
+ "assertions": [
79
+ {
80
+ "id": "leaf_001",
81
+ "path": "$.answers.q1",
82
+ "tokens": [
83
+ "answers",
84
+ "q1"
85
+ ],
86
+ "operator": "eq",
87
+ "expected": "cx schema"
88
+ },
89
+ {
90
+ "id": "leaf_002",
91
+ "path": "$.answers.q2",
92
+ "tokens": [
93
+ "answers",
94
+ "q2"
95
+ ],
96
+ "operator": "path_eq",
97
+ "expected": "src/commands/logs/mod.rs"
98
+ },
99
+ {
100
+ "id": "leaf_003",
101
+ "path": "$.answers.q3",
102
+ "tokens": [
103
+ "answers",
104
+ "q3"
105
+ ],
106
+ "operator": "eq",
107
+ "expected": "#[serde(rename_all = \"camelCase\")]"
108
+ },
109
+ {
110
+ "id": "leaf_004",
111
+ "path": "$.answers.q4",
112
+ "tokens": [
113
+ "answers",
114
+ "q4"
115
+ ],
116
+ "operator": "path_eq",
117
+ "expected": "src/main.rs"
118
+ }
119
+ ],
120
+ "path_equivalence_tokens": [
121
+ [
122
+ "answers",
123
+ "q2"
124
+ ],
125
+ [
126
+ "answers",
127
+ "q4"
128
+ ]
129
+ ],
130
+ "self_test_passed": true
131
+ },
132
+ "dependency_contract": {
133
+ "version": 2,
134
+ "mode": "core_answer",
135
+ "dependency_type": "package_knowledge",
136
+ "requirement_ids": [
137
+ "skill_a023",
138
+ "skill_a026",
139
+ "skill_a054",
140
+ "skill_a036"
141
+ ],
142
+ "forbid_meta_reference": true,
143
+ "forbid_answer_leakage": true
144
+ }
145
+ }
146
+ }
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/evaluate.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a candidate response for one portable MyBench task."""
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+
14
+ def _load_verify():
15
+ try:
16
+ from verifiers import verify
17
+ return verify
18
+ except ImportError:
19
+ project_src = Path(__file__).resolve().parents[1] / "src"
20
+ if project_src.is_dir():
21
+ sys.path.insert(0, str(project_src))
22
+ from verifiers import verify
23
+ return verify
24
+ raise
25
+
26
+
27
+ def _emit(result, output=None):
28
+ text = json.dumps(result, ensure_ascii=False)
29
+ print(text)
30
+ if output:
31
+ Path(output).write_text(text + "\n", encoding="utf-8")
32
+
33
+
34
+ def _judge_contract(judge):
35
+ if not isinstance(judge, dict):
36
+ return "Judge output must be a JSON object"
37
+ if type(judge.get("passed")) is not bool:
38
+ return "Judge field passed must be a JSON boolean"
39
+ for key in ("score", "max_score"):
40
+ value = judge.get(key, 100 if key == "max_score" else None)
41
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
42
+ return f"Judge field {key} must be a finite number"
43
+ if not math.isfinite(float(value)):
44
+ return f"Judge field {key} must be a finite number"
45
+ score = float(judge["score"])
46
+ max_score = float(judge.get("max_score", 100))
47
+ if max_score <= 0:
48
+ return "Judge field max_score must be greater than zero"
49
+ if score < 0 or score > max_score:
50
+ return "Judge score must be between zero and max_score"
51
+ return None
52
+
53
+
54
+ def evaluate(task_json, candidate_path, open_judge_command=None,
55
+ open_judge_timeout=None):
56
+ task_json = Path(task_json).resolve()
57
+ candidate_path = Path(candidate_path).resolve()
58
+ task = json.loads(task_json.read_text(encoding="utf-8"))
59
+ evaluation = task.get("evaluation") or {}
60
+ track = evaluation.get("type")
61
+ base = {
62
+ "schema_version": task.get("schema_version"),
63
+ "task_id": task.get("task_id"),
64
+ "query_id": task.get("query_id"),
65
+ "track": track,
66
+ }
67
+ if track == "verified":
68
+ workspace_mode = ((evaluation.get("verifier") or {}).get("type") ==
69
+ "workspace_objective")
70
+ if workspace_mode and not candidate_path.is_dir():
71
+ return {**base, "status": "candidate_contract_error", "passed": False,
72
+ "score": 0, "max_score": 1,
73
+ "details": "workspace evaluator requires a candidate directory"}, 2
74
+ if not workspace_mode and not candidate_path.is_file():
75
+ return {**base, "status": "candidate_contract_error", "passed": False,
76
+ "score": 0, "max_score": 1,
77
+ "details": "response evaluator requires a candidate file"}, 2
78
+ if workspace_mode:
79
+ candidate = str(candidate_path)
80
+ else:
81
+ try:
82
+ candidate = candidate_path.read_text(encoding="utf-8")
83
+ except UnicodeError:
84
+ return {**base, "status": "candidate_contract_error", "passed": False,
85
+ "score": 0, "max_score": 1,
86
+ "details": "candidate response must use valid UTF-8"}, 2
87
+ passed, detail = _load_verify()(
88
+ evaluation.get("verifier") or {},
89
+ evaluation.get("ground_truth_answer"),
90
+ candidate,
91
+ None,
92
+ )
93
+ return {**base, "status": "scored", "passed": bool(passed),
94
+ "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1
95
+ if track != "open":
96
+ return {**base, "status": "unsupported_track", "passed": False,
97
+ "score": None, "details": f"unsupported track: {track}"}, 2
98
+ if not candidate_path.is_file():
99
+ return {**base, "status": "candidate_contract_error", "passed": False,
100
+ "score": None, "details": "open judge requires a candidate response file"}, 2
101
+ candidate_file = candidate_path
102
+ command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND")
103
+ if not command:
104
+ return {**base, "status": "requires_external_judge", "passed": None,
105
+ "score": None, "details": (
106
+ "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads "
107
+ "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2
108
+ environment = os.environ.copy()
109
+ environment["MYBENCH_TASK_JSON"] = str(task_json)
110
+ environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file)
111
+ timeout = float(open_judge_timeout or os.environ.get(
112
+ "MYBENCH_OPEN_JUDGE_TIMEOUT", 600))
113
+ if not math.isfinite(timeout) or timeout <= 0:
114
+ return {**base, "status": "judge_contract_error", "passed": False,
115
+ "score": None, "details": "Judge timeout must be a positive number"}, 2
116
+ try:
117
+ completed = subprocess.run(
118
+ shlex.split(command), cwd=str(task_json.parent), env=environment,
119
+ text=True, capture_output=True, timeout=timeout)
120
+ except (OSError, subprocess.TimeoutExpired) as exc:
121
+ return {**base, "status": "judge_error", "passed": False,
122
+ "score": None, "details": str(exc)}, 2
123
+ if completed.returncode:
124
+ return {**base, "status": "judge_error", "passed": False, "score": None,
125
+ "details": completed.stderr.strip() or completed.stdout.strip()}, 2
126
+ try:
127
+ judge = json.loads(completed.stdout)
128
+ except json.JSONDecodeError as exc:
129
+ return {**base, "status": "judge_contract_error", "passed": False,
130
+ "score": None, "details": str(exc)}, 2
131
+ contract_error = _judge_contract(judge)
132
+ if contract_error:
133
+ return {**base, "status": "judge_contract_error", "passed": False,
134
+ "score": None, "details": contract_error}, 2
135
+ result = {**base, "status": "scored", "passed": judge.get("passed"),
136
+ "score": judge.get("score"), "max_score": judge.get("max_score", 100),
137
+ "details": judge.get("details", judge)}
138
+ return result, 0 if result["passed"] else 1
139
+
140
+
141
+ def main():
142
+ parser = argparse.ArgumentParser()
143
+ parser.add_argument("--task-json", required=True)
144
+ candidates = parser.add_mutually_exclusive_group(required=True)
145
+ candidates.add_argument("--candidate-path")
146
+ candidates.add_argument("--candidate-file") # v1 compatibility
147
+ parser.add_argument("--result-output")
148
+ parser.add_argument("--open-judge-command")
149
+ parser.add_argument("--open-judge-timeout", type=float)
150
+ args = parser.parse_args()
151
+ result, code = evaluate(args.task_json,
152
+ args.candidate_path or args.candidate_file,
153
+ args.open_judge_command, args.open_judge_timeout)
154
+ _emit(result, args.result_output)
155
+ raise SystemExit(code)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/objective_evaluators.py ADDED
@@ -0,0 +1,1329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composable objective evaluators for response and workspace tasks.
2
+
3
+ Task semantics are deliberately *not* enumerated here. A task may describe any
4
+ real user goal; verified membership depends on whether its deliverables compile
5
+ to one of these small, trusted evaluator primitives and pass counterfactual
6
+ execution. This keeps the objective surface closed and auditable without
7
+ turning the benchmark's task ontology into a closed template list.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import copy
13
+ import builtins
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ import shlex
19
+ import subprocess
20
+ import tempfile
21
+ import tomllib
22
+ from pathlib import Path, PurePosixPath
23
+ try:
24
+ from .shell_invocations import shell_invocations
25
+ except ImportError:
26
+ from shell_invocations import shell_invocations
27
+
28
+
29
+ WORKSPACE_EVALUATOR = "workspace_objective"
30
+ WORKSPACE_EVALUATOR_VERSION = 15
31
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
32
+ ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
33
+ _DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
34
+
35
+
36
+ class ObjectiveEvaluatorError(ValueError):
37
+ pass
38
+
39
+
40
+ def safe_relative_path(value):
41
+ """Return a normalized portable relative path or fail closed."""
42
+ text = str(value or "").strip().replace("\\", "/")
43
+ path = PurePosixPath(text)
44
+ if (not text or text.startswith("/") or path.is_absolute() or
45
+ any(part in {"", ".", ".."} for part in path.parts)):
46
+ raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
47
+ if len(path.parts) > 8 or len(text) > 180:
48
+ raise ObjectiveEvaluatorError("workspace path is too deep or long")
49
+ return path.as_posix()
50
+
51
+
52
+ def _json_value(value):
53
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
54
+ return value
55
+ return json.loads(str(value))
56
+
57
+
58
+ def _canonical(value):
59
+ if isinstance(value, dict):
60
+ return {key: _canonical(value[key]) for key in sorted(value)}
61
+ if isinstance(value, list):
62
+ return [_canonical(item) for item in value]
63
+ return value
64
+
65
+
66
+
67
+ def _same_native_json_types(actual, expected):
68
+ if type(expected)is float:
69
+ return type(actual)in(int,float)and math.isfinite(actual)
70
+ if type(actual)is not type(expected):return False
71
+ if isinstance(expected,dict):
72
+ return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected)
73
+ if isinstance(expected,list):
74
+ return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected))
75
+ if isinstance(actual,float):return math.isfinite(actual)
76
+ return True
77
+
78
+ def _file_content(item):
79
+ fmt = str(item.get("format") or "").casefold()
80
+ content = item.get("content")
81
+ if fmt == "json":
82
+ parsed = _json_value(content)
83
+ return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
84
+ if not isinstance(content, str):
85
+ raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
86
+ return content.rstrip() + "\n"
87
+
88
+
89
+ def _ast_name(node):
90
+ if isinstance(node, ast.Name):
91
+ return node.id
92
+ if isinstance(node, ast.Attribute):
93
+ parent = _ast_name(node.value)
94
+ return f"{parent}.{node.attr}" if parent else node.attr
95
+ return ""
96
+
97
+
98
+ def _python_inventory(text):
99
+ tree = ast.parse(text)
100
+ imports, calls = set(), set()
101
+ for node in ast.walk(tree):
102
+ if isinstance(node, ast.Import):
103
+ imports.update(alias.name for alias in node.names)
104
+ elif isinstance(node, ast.ImportFrom):
105
+ module = node.module or ""
106
+ for alias in node.names:
107
+ imports.add(f"{module}.{alias.name}".strip("."))
108
+ elif isinstance(node, ast.Call):
109
+ name = _ast_name(node.func)
110
+ if name:
111
+ calls.add(name)
112
+ return imports, calls
113
+
114
+
115
+ def _literal_value(node, constants=None):
116
+ constants = constants or {}
117
+ if isinstance(node, ast.Constant) and isinstance(
118
+ node.value, (str, int, float, bool, type(None))):
119
+ return node.value
120
+ if isinstance(node, ast.Name) and node.id in constants:
121
+ return constants[node.id]
122
+ if isinstance(node, (ast.Tuple, ast.List)):
123
+ values = [_literal_value(item, constants) for item in node.elts]
124
+ if all(value is not _UNRESOLVED for value in values):
125
+ return tuple(values) if isinstance(node, ast.Tuple) else values
126
+ return _UNRESOLVED
127
+
128
+
129
+ _UNRESOLVED = object()
130
+
131
+
132
+ def _python_semantics(text):
133
+ tree = ast.parse(text)
134
+ _annotate_assignment_contexts(tree)
135
+ imports, calls = _python_inventory(text)
136
+ constants = {}
137
+ for node in tree.body:
138
+ name = None
139
+ value_node = None
140
+ if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
141
+ isinstance(node.targets[0], ast.Name)):
142
+ name, value_node = node.targets[0].id, node.value
143
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
144
+ name, value_node = node.target.id, node.value
145
+ if name and value_node is not None:
146
+ value = _literal_value(value_node, constants)
147
+ if value is not _UNRESOLVED:
148
+ constants[name] = value
149
+ elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
150
+ isinstance(node.targets[0], (ast.Tuple, ast.List)) and
151
+ isinstance(node.value, (ast.Tuple, ast.List)) and
152
+ len(node.targets[0].elts) == len(node.value.elts)):
153
+ # Treat ordinary constant unpacking as semantically equivalent to
154
+ # separate assignments. Generated implementation files commonly
155
+ # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
156
+ # test formatting rather than the required repository values.
157
+ for target, value_node in zip(node.targets[0].elts, node.value.elts):
158
+ if not isinstance(target, ast.Name):
159
+ continue
160
+ value = _literal_value(value_node, constants)
161
+ if value is not _UNRESOLVED:
162
+ constants[target.id] = value
163
+ call_nodes = []
164
+ for node in ast.walk(tree):
165
+ if isinstance(node, ast.Call):
166
+ call_nodes.append((_ast_name(node.func), node))
167
+ return imports, calls, constants, call_nodes
168
+
169
+
170
+ def _python_resolved_call_nodes(text):
171
+ """Resolve call targets through imports and simple constructor bindings.
172
+
173
+ The evaluator intentionally supports a small static subset: imports,
174
+ local definitions, direct aliases, and names assigned from calls. That is
175
+ enough to recognize semantic equivalents such as ``import datetime`` vs
176
+ ``from datetime import timedelta as td`` and instance-variable renames,
177
+ without pretending to perform general Python type inference.
178
+ """
179
+ tree = ast.parse(text)
180
+ _annotate_assignment_contexts(tree)
181
+ bindings = {}
182
+ nodes = sorted(ast.walk(tree), key=lambda node: (
183
+ int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
184
+
185
+ def resolve(node):
186
+ if isinstance(node, ast.Name):
187
+ return bindings.get(node.id, node.id)
188
+ if isinstance(node, ast.Attribute):
189
+ parent = resolve(node.value)
190
+ return f"{parent}.{node.attr}" if parent else node.attr
191
+ return ""
192
+
193
+ # A few fixed-point passes cover aliases declared after an imported name
194
+ # and ordinary ``client = Client()`` instance construction.
195
+ for _ in range(4):
196
+ changed = False
197
+ for node in nodes:
198
+ updates = {}
199
+ if isinstance(node, ast.Import):
200
+ for alias in node.names:
201
+ local = alias.asname or alias.name.split(".")[0]
202
+ updates[local] = alias.name if alias.asname else local
203
+ elif isinstance(node, ast.ImportFrom):
204
+ module = node.module or ""
205
+ for alias in node.names:
206
+ if alias.name == "*":
207
+ continue
208
+ updates[alias.asname or alias.name] = \
209
+ f"{module}.{alias.name}".strip(".")
210
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
211
+ ast.ClassDef)):
212
+ updates[node.name] = "__local__." + node.name
213
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
214
+ targets = (node.targets if isinstance(node, ast.Assign)
215
+ else [node.target])
216
+ value = node.value
217
+ if isinstance(value, ast.Call):
218
+ provenance = resolve(value.func)
219
+ elif isinstance(value, (ast.Name, ast.Attribute)):
220
+ provenance = resolve(value)
221
+ else:
222
+ provenance = ""
223
+ if provenance:
224
+ for target in targets:
225
+ if isinstance(target, ast.Name):
226
+ updates[target.id] = provenance
227
+ for name, value in updates.items():
228
+ if bindings.get(name) != value:
229
+ bindings[name] = value
230
+ changed = True
231
+ if not changed:
232
+ break
233
+ return [(_ast_name(node.func), resolve(node.func), node)
234
+ for node in ast.walk(tree) if isinstance(node, ast.Call)]
235
+
236
+
237
+ def _call_name_matches(observed, expected):
238
+ return observed == expected or observed.endswith("." + expected)
239
+
240
+
241
+ def _objective_call_targets(kind, check, resolved_calls, constants):
242
+ """Return canonical targets satisfying one already-validated call check."""
243
+ function = str(check.get("function") or check.get("value") or "")
244
+ targets = set()
245
+ for name, target, node in resolved_calls:
246
+ if not _call_name_matches(name, function):
247
+ continue
248
+ if kind == "python_call_literal" and not _node_contains_literal(
249
+ node, check.get("value"), constants):
250
+ continue
251
+ if kind == "python_call_keyword_literal" and not _call_keyword_matches(
252
+ node, str(check.get("keyword") or ""), check.get("value"),
253
+ constants):
254
+ continue
255
+ if kind == "python_call_signature" and not _call_signature_matches(
256
+ node, check.get("arguments") or [],
257
+ check.get("keywords") or {}, constants,
258
+ check.get("argument_expressions") or [],
259
+ check.get("keyword_expressions") or {},
260
+ check.get("assignment")):
261
+ continue
262
+ if target:
263
+ targets.add(target)
264
+ return targets
265
+
266
+
267
+ def python_unbound_call_roots(text):
268
+ """Return call-root names that have no static binding in the module.
269
+
270
+ Objective call checks must not accept a syntactically valid file that will
271
+ immediately raise ``NameError``. This deliberately proves only the
272
+ conservative prerequisite that a root is imported, assigned, declared,
273
+ passed as an argument, or provided by Python builtins; it does not claim to
274
+ execute or type-check the program.
275
+ """
276
+ tree = ast.parse(text)
277
+ bound = set(dir(builtins))
278
+ for node in ast.walk(tree):
279
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
280
+ bound.add(node.id)
281
+ elif isinstance(node, ast.arg):
282
+ bound.add(node.arg)
283
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
284
+ ast.ClassDef)):
285
+ bound.add(node.name)
286
+ elif isinstance(node, ast.Import):
287
+ for alias in node.names:
288
+ bound.add(alias.asname or alias.name.split(".")[0])
289
+ elif isinstance(node, ast.ImportFrom):
290
+ for alias in node.names:
291
+ bound.add(alias.asname or alias.name)
292
+ elif isinstance(node, ast.ExceptHandler) and node.name:
293
+ bound.add(node.name)
294
+ unbound = set()
295
+ for node in ast.walk(tree):
296
+ if not isinstance(node, ast.Call):
297
+ continue
298
+ root = node.func
299
+ while isinstance(root, ast.Attribute):
300
+ root = root.value
301
+ if isinstance(root, ast.Name) and root.id not in bound:
302
+ unbound.add(root.id)
303
+ return sorted(unbound)
304
+
305
+
306
+ def _node_contains_literal(node, expected, constants):
307
+ for child in ast.walk(node):
308
+ value = _literal_value(child, constants)
309
+ if value is _UNRESOLVED:
310
+ continue
311
+ if value == expected:
312
+ return True
313
+ if isinstance(value, (list, tuple)) and expected in value:
314
+ return True
315
+ return False
316
+
317
+
318
+ def _call_keyword_matches(node, keyword, expected, constants):
319
+ """Return whether a direct call keyword resolves to the expected scalar."""
320
+ return any(
321
+ item.arg == keyword and _literal_value(item.value, constants) == expected
322
+ for item in getattr(node, "keywords", [])
323
+ if item.arg is not None)
324
+
325
+
326
+ def _portable_literal(value):
327
+ if isinstance(value, tuple):
328
+ return [_portable_literal(item) for item in value]
329
+ if isinstance(value, list):
330
+ return [_portable_literal(item) for item in value]
331
+ return value
332
+
333
+
334
+ def _expression_text(node):
335
+ """Return a formatting-independent, non-executed Python expression."""
336
+ return ast.unparse(node).strip()
337
+
338
+
339
+ def _expression_fingerprint(value):
340
+ if not isinstance(value, str) or not value.strip() or len(value) > 500:
341
+ return None
342
+ try:
343
+ tree = ast.parse(value, mode="eval")
344
+ except SyntaxError:
345
+ return None
346
+ return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
347
+
348
+
349
+ def _expression_matches(node, expected):
350
+ fingerprint = _expression_fingerprint(expected)
351
+ return bool(fingerprint and ast.dump(
352
+ node, annotate_fields=True, include_attributes=False) == fingerprint)
353
+
354
+
355
+ def _annotate_assignment_contexts(tree):
356
+ """Attach one conservative simple-assignment context to nested calls."""
357
+ for statement in ast.walk(tree):
358
+ target, value = None, None
359
+ if (isinstance(statement, ast.Assign) and
360
+ len(statement.targets) == 1 and
361
+ isinstance(statement.targets[0], ast.Name)):
362
+ target, value = statement.targets[0].id, statement.value
363
+ elif (isinstance(statement, ast.AnnAssign) and
364
+ isinstance(statement.target, ast.Name) and
365
+ statement.value is not None):
366
+ target, value = statement.target.id, statement.value
367
+ if not target or value is None:
368
+ continue
369
+ context = {"target": target, "expression": _expression_text(value)}
370
+ for child in ast.walk(value):
371
+ if isinstance(child, ast.Call):
372
+ setattr(child, "_mybench_assignment", context)
373
+
374
+
375
+ def _call_signature(node, constants):
376
+ arguments = []
377
+ argument_expressions = []
378
+ for index, argument in enumerate(getattr(node, "args", [])):
379
+ value = _literal_value(argument, constants)
380
+ if value is not _UNRESOLVED:
381
+ arguments.append({"index": index,
382
+ "value": _portable_literal(value)})
383
+ else:
384
+ argument_expressions.append({
385
+ "index": index, "expression": _expression_text(argument)})
386
+ keywords = {}
387
+ keyword_expressions = {}
388
+ for keyword in getattr(node, "keywords", []):
389
+ if keyword.arg is None:
390
+ continue
391
+ value = _literal_value(keyword.value, constants)
392
+ if value is not _UNRESOLVED:
393
+ keywords[keyword.arg] = _portable_literal(value)
394
+ else:
395
+ keyword_expressions[keyword.arg] = _expression_text(keyword.value)
396
+ signature = {"arguments": arguments, "keywords": keywords,
397
+ "argument_expressions": argument_expressions,
398
+ "keyword_expressions": keyword_expressions}
399
+ assignment = getattr(node, "_mybench_assignment", None)
400
+ if isinstance(assignment, dict):
401
+ signature["assignment"] = dict(assignment)
402
+ return signature
403
+
404
+
405
+ def _call_signature_matches(node, arguments, keywords, constants,
406
+ argument_expressions=None,
407
+ keyword_expressions=None, assignment=None):
408
+ for expected in arguments or []:
409
+ index = expected.get("index")
410
+ if (not isinstance(index, int) or index < 0 or
411
+ index >= len(getattr(node, "args", []))):
412
+ return False
413
+ actual = _literal_value(node.args[index], constants)
414
+ if (actual is _UNRESOLVED or
415
+ _canonical(_portable_literal(actual)) !=
416
+ _canonical(expected.get("value"))):
417
+ return False
418
+ for keyword, expected in (keywords or {}).items():
419
+ if not _call_keyword_matches(node, keyword, expected, constants):
420
+ return False
421
+ for expected in argument_expressions or []:
422
+ index = expected.get("index")
423
+ if (not isinstance(index, int) or index < 0 or
424
+ index >= len(getattr(node, "args", [])) or
425
+ not _expression_matches(
426
+ node.args[index], expected.get("expression"))):
427
+ return False
428
+ node_keywords = {item.arg: item.value for item in
429
+ getattr(node, "keywords", []) if item.arg is not None}
430
+ for keyword, expected in (keyword_expressions or {}).items():
431
+ if (keyword not in node_keywords or
432
+ not _expression_matches(node_keywords[keyword], expected)):
433
+ return False
434
+ if assignment:
435
+ actual = getattr(node, "_mybench_assignment", None)
436
+ if (not isinstance(actual, dict) or
437
+ actual.get("target") != assignment.get("target") or
438
+ _expression_fingerprint(actual.get("expression")) !=
439
+ _expression_fingerprint(assignment.get("expression"))):
440
+ return False
441
+ return bool(arguments or keywords or argument_expressions or
442
+ keyword_expressions or assignment)
443
+
444
+
445
+ def python_call_literal_signatures(text, function, expected, keyword=None):
446
+ """Return full literal signatures for matching reference call sites."""
447
+ _, _, constants, call_nodes = _python_semantics(text)
448
+ out = []
449
+ for name, node in call_nodes:
450
+ if not (name == function or name.endswith("." + function)):
451
+ continue
452
+ matches = (_call_keyword_matches(node, keyword, expected, constants)
453
+ if keyword else
454
+ _node_contains_literal(node, expected, constants))
455
+ if matches:
456
+ out.append(_call_signature(node, constants))
457
+ return out
458
+
459
+
460
+ def python_signature_expression_coverage_issues(evaluator, requirements=None):
461
+ """Detect anchored call expressions omitted by a static verifier.
462
+
463
+ Literal-only call checks used to silently discard non-literal positional
464
+ and keyword expressions from the same package-owned call. That allowed a
465
+ candidate to retain one easy literal while replacing the actual callback,
466
+ input binding, or argument tuple. Only expressions present in the
467
+ selected requirement text are required here; unrelated reference-file
468
+ context remains outside the objective contract.
469
+ """
470
+ if not isinstance(evaluator, dict) or evaluator.get("type") != \
471
+ WORKSPACE_EVALUATOR:
472
+ return []
473
+ reference_files = {
474
+ str(item.get("path") or ""): str(item.get("content") or "")
475
+ for item in evaluator.get("reference_files") or []
476
+ if isinstance(item, dict)}
477
+ requirement_texts = [
478
+ re.sub(r"\s+", "", str(item.get("requirement") or ""))
479
+ for item in requirements or [] if isinstance(item, dict)]
480
+ issues = []
481
+ for check in evaluator.get("checks") or []:
482
+ if (not isinstance(check, dict) or
483
+ check.get("type") != "python_call_signature"):
484
+ continue
485
+ function = str(check.get("function") or "")
486
+ source = reference_files.get(str(check.get("path") or ""), "")
487
+ if not function or not source:
488
+ continue
489
+ try:
490
+ _, _, constants, call_nodes = _python_semantics(source)
491
+ except SyntaxError:
492
+ issues.append("Python signature reference content is invalid")
493
+ continue
494
+ matches = [node for name, node in call_nodes
495
+ if _call_name_matches(name, function) and
496
+ _call_signature_matches(
497
+ node, check.get("arguments") or [],
498
+ check.get("keywords") or {}, constants,
499
+ check.get("argument_expressions") or [],
500
+ check.get("keyword_expressions") or {},
501
+ check.get("assignment"))]
502
+ if len(matches) != 1:
503
+ issues.append(
504
+ "Python call signature does not identify one reference call")
505
+ continue
506
+ reference_signature = _call_signature(matches[0], constants)
507
+ function_tokens = {re.sub(r"\s+", "", function),
508
+ re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
509
+
510
+ def positional_is_anchored(expression):
511
+ compact = re.sub(r"\s+", "", str(expression or ""))
512
+ return any(compact and compact in text and any(
513
+ token and token in text for token in function_tokens)
514
+ for text in requirement_texts)
515
+
516
+ def keyword_is_anchored(name, expression):
517
+ compact = re.sub(r"\s+", "", str(expression or ""))
518
+ needle = f"{name}={compact}"
519
+ return any(compact and needle in text and any(
520
+ token and token in text for token in function_tokens)
521
+ for text in requirement_texts)
522
+
523
+ expected_arguments = {
524
+ item["index"]: item.get("expression")
525
+ for item in reference_signature.get("argument_expressions") or []
526
+ if positional_is_anchored(item.get("expression"))}
527
+ expected_keywords = {
528
+ name: expression for name, expression in
529
+ (reference_signature.get("keyword_expressions") or {}).items()
530
+ if keyword_is_anchored(name, expression)}
531
+ actual_arguments = {
532
+ item.get("index"): item.get("expression")
533
+ for item in check.get("argument_expressions") or []
534
+ if isinstance(item, dict)}
535
+ actual_keywords = check.get("keyword_expressions") or {}
536
+ expected_assignment = reference_signature.get("assignment")
537
+ if expected_assignment:
538
+ compact_assignment = re.sub(
539
+ r"\s+", "", f"{expected_assignment.get('target')}="
540
+ f"{expected_assignment.get('expression')}")
541
+ assignment_is_anchored = any(
542
+ compact_assignment and compact_assignment in text and any(
543
+ token and token in text for token in function_tokens)
544
+ for text in requirement_texts)
545
+ else:
546
+ assignment_is_anchored = False
547
+ actual_assignment = check.get("assignment")
548
+ missing_argument = any(
549
+ index not in actual_arguments or
550
+ _expression_fingerprint(actual_arguments[index]) !=
551
+ _expression_fingerprint(expression)
552
+ for index, expression in expected_arguments.items())
553
+ missing_keyword = any(
554
+ name not in actual_keywords or
555
+ _expression_fingerprint(actual_keywords[name]) !=
556
+ _expression_fingerprint(expression)
557
+ for name, expression in expected_keywords.items())
558
+ missing_assignment = bool(
559
+ assignment_is_anchored and (
560
+ not isinstance(actual_assignment, dict) or
561
+ actual_assignment.get("target") !=
562
+ expected_assignment.get("target") or
563
+ _expression_fingerprint(actual_assignment.get("expression")) !=
564
+ _expression_fingerprint(
565
+ expected_assignment.get("expression"))))
566
+ if missing_argument or missing_keyword or missing_assignment:
567
+ issues.append(
568
+ "Python call signature omits an anchored expression or assignment")
569
+ return issues
570
+
571
+
572
+ def _shell_lines(text):
573
+ """Return executable lines with conservative local scalar substitution.
574
+
575
+ Shell authors routinely name a fixed argument before using it (for example
576
+ ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
577
+ assignments; never evaluate shell expressions, commands, or defaults.
578
+ """
579
+ logical, pending = [], ""
580
+ for raw in str(text or "").splitlines():
581
+ line = " ".join(raw.strip().split())
582
+ if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
583
+ continue
584
+ pending = (pending + " " + line).strip() if pending else line
585
+ if pending.endswith("\\"):
586
+ pending = pending[:-1].rstrip()
587
+ continue
588
+ logical.append(pending)
589
+ pending = ""
590
+ if pending:
591
+ logical.append(pending)
592
+
593
+ constants, out = {}, []
594
+ assignment = re.compile(
595
+ r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
596
+ r"([A-Za-z0-9_./:+-]+))$")
597
+ variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
598
+ for line in logical:
599
+ match = assignment.fullmatch(line)
600
+ if match:
601
+ constants[match.group(1)] = next(
602
+ value for value in match.groups()[1:] if value is not None)
603
+ out.append(line)
604
+ continue
605
+
606
+ def replace(match):
607
+ name = match.group(1) or match.group(2)
608
+ return constants.get(name, match.group(0))
609
+
610
+ out.append(variable.sub(replace, line))
611
+ return out
612
+
613
+
614
+ def _shell_command_matches(expected, actual):
615
+ """Accept the frozen invocation plus documented optional arguments/path prefixes."""
616
+ try:
617
+ wanted = shlex.split(str(expected))
618
+ found = shlex.split(str(actual))
619
+ except ValueError:
620
+ return False
621
+ def normalize_git_log_limit(tokens):
622
+ if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
623
+ return tokens
624
+ normalized, index = [], 0
625
+ while index < len(tokens):
626
+ token = tokens[index]
627
+ short = re.fullmatch(r"-(\d+)", token)
628
+ long = re.fullmatch(r"--max-count=(\d+)", token)
629
+ if short or long:
630
+ normalized.append("--max-count=" + (short or long).group(1))
631
+ elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
632
+ re.fullmatch(r"\d+", tokens[index + 1])):
633
+ normalized.append("--max-count=" + tokens[index + 1])
634
+ index += 1
635
+ else:
636
+ normalized.append(token)
637
+ index += 1
638
+ return normalized
639
+
640
+ wanted = normalize_git_log_limit(wanted)
641
+ found = normalize_git_log_limit(found)
642
+ if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
643
+ return False
644
+ for index, token in enumerate(wanted[1:], 1):
645
+ observed = found[index]
646
+ if observed == token:
647
+ continue
648
+ # A solver may anchor a package-relative script at $REPO_ROOT while
649
+ # preserving the exact package path selected by the Skill.
650
+ if (index == 1 and "/" in token and
651
+ observed.rstrip("/").endswith(token.lstrip("./"))):
652
+ continue
653
+ return False
654
+ return True
655
+
656
+
657
+ def _shell_command_sequence_matches(expected, actual_lines):
658
+ """Require every frozen command in order while allowing extra lines."""
659
+ cursor = 0
660
+ for command in expected:
661
+ for index in range(cursor, len(actual_lines)):
662
+ if _shell_command_matches(command, actual_lines[index]):
663
+ cursor = index + 1
664
+ break
665
+ else:
666
+ return False
667
+ return True
668
+
669
+
670
+ def _shell_unconditional_lines(text):
671
+ """Return conservative top-level command lines from a shell artifact.
672
+
673
+ Checked commands hidden in a conditional branch or an uncalled function do
674
+ not establish that the requested script performs them. This is not a full
675
+ shell parser: unsupported control flow simply makes nested lines
676
+ ineligible, which is appropriate for the small straight-line command
677
+ artifacts compiled by this evaluator.
678
+ """
679
+ lines = _shell_lines(text)
680
+ depth = 0
681
+ out = []
682
+ opener = re.compile(
683
+ r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
684
+ r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
685
+ closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
686
+ for line in lines:
687
+ if closer.match(line):
688
+ depth = max(0, depth - 1)
689
+ continue
690
+ if depth == 0 and not opener.match(line):
691
+ out.append(line)
692
+ if opener.match(line):
693
+ depth += 1
694
+ return out
695
+
696
+
697
+ def _shell_is_straight_line(text):
698
+ """Return whether every executable logical line is top-level.
699
+
700
+ This deliberately reuses the conservative control-flow recognizer used by
701
+ unconditional command checks. Any recognized conditional, loop, case, or
702
+ function makes the whole-script straight-line contract fail closed.
703
+ """
704
+ lines = _shell_lines(text)
705
+ return lines == _shell_unconditional_lines(text)
706
+
707
+
708
+ def compile_workspace_evaluator(deliverables):
709
+ """Compile trusted checks from validated deliverable specifications."""
710
+ if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
711
+ raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
712
+ reference_files, checks, paths = [], [], set()
713
+ for index, raw in enumerate(deliverables, 1):
714
+ if not isinstance(raw, dict):
715
+ raise ObjectiveEvaluatorError("deliverable is not an object")
716
+ path = safe_relative_path(raw.get("path"))
717
+ if path in paths:
718
+ raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
719
+ paths.add(path)
720
+ fmt = str(raw.get("format") or "").strip().casefold()
721
+ if fmt not in ARTIFACT_FORMATS:
722
+ raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
723
+ content = _file_content({**raw, "format": fmt})
724
+ if len(content.encode("utf-8")) > 200_000:
725
+ raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
726
+ reference_files.append({"path": path, "format": fmt, "content": content})
727
+ checks.append({"id": f"file_{index:03d}", "type": "file_exists",
728
+ "path": path})
729
+ if fmt == "json":
730
+ checks.append({"id": f"json_{index:03d}", "type": "json_exact",
731
+ "path": path, "expected": _json_value(raw.get("content"))})
732
+ elif fmt == "toml":
733
+ try:
734
+ expected = tomllib.loads(content)
735
+ except (tomllib.TOMLDecodeError, ValueError) as exc:
736
+ raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
737
+ checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
738
+ "path": path, "expected": expected})
739
+ elif fmt == "python":
740
+ try:
741
+ _, _, constants, call_nodes = _python_semantics(content)
742
+ resolved_calls = _python_resolved_call_nodes(content)
743
+ except SyntaxError as exc:
744
+ raise ObjectiveEvaluatorError("reference Python is invalid") from exc
745
+ checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
746
+ "path": path})
747
+ checks.append({"id": f"python_{index:03d}_bindings",
748
+ "type": "python_bound_calls", "path": path})
749
+ raw_checks = raw.get("checks") or []
750
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
751
+ raise ObjectiveEvaluatorError(
752
+ "Python deliverable requires 1-12 objective import/call checks")
753
+ for check_index, check in enumerate(raw_checks, 1):
754
+ if not isinstance(check, dict):
755
+ raise ObjectiveEvaluatorError("Python check is not an object")
756
+ kind = str(check.get("type") or "").strip().casefold()
757
+ if kind in {"python_import", "python_call"}:
758
+ value = str(check.get("value") or "").strip()
759
+ if not _DOTTED.fullmatch(value):
760
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
761
+ compiled = {"type": kind, "path": path, "value": value}
762
+ elif kind == "python_constant":
763
+ name = str(check.get("name") or "").strip()
764
+ value = check.get("value")
765
+ if (not _DOTTED.fullmatch(name) or "." in name or
766
+ isinstance(value, (dict, list)) or value is None or
767
+ constants.get(name, _UNRESOLVED) != value):
768
+ raise ObjectiveEvaluatorError(
769
+ "Python constant check is invalid or fails reference content")
770
+ compiled = {"type": kind, "path": path, "name": name,
771
+ "value": value}
772
+ elif kind == "python_call_literal":
773
+ function = str(check.get("function") or "").strip()
774
+ value = check.get("value")
775
+ if (not _DOTTED.fullmatch(function) or
776
+ isinstance(value, (dict, list)) or value is None or
777
+ not any(
778
+ (name == function or name.endswith("." + function)) and
779
+ _node_contains_literal(node, value, constants)
780
+ for name, node in call_nodes)):
781
+ raise ObjectiveEvaluatorError(
782
+ "Python call-literal check is invalid or fails reference content")
783
+ compiled = {"type": kind, "path": path,
784
+ "function": function, "value": value}
785
+ elif kind == "python_call_keyword_literal":
786
+ function = str(check.get("function") or "").strip()
787
+ keyword = str(check.get("keyword") or "").strip()
788
+ value = check.get("value")
789
+ if (not _DOTTED.fullmatch(function) or
790
+ not _DOTTED.fullmatch(keyword) or "." in keyword or
791
+ isinstance(value, (dict, list)) or value is None or
792
+ not any(
793
+ (name == function or name.endswith("." + function)) and
794
+ _call_keyword_matches(node, keyword, value, constants)
795
+ for name, node in call_nodes)):
796
+ raise ObjectiveEvaluatorError(
797
+ "Python call-keyword check is invalid or fails reference content")
798
+ compiled = {"type": kind, "path": path,
799
+ "function": function, "keyword": keyword,
800
+ "value": value}
801
+ elif kind == "python_call_signature":
802
+ function = str(check.get("function") or "").strip()
803
+ arguments = check.get("arguments") or []
804
+ keywords = check.get("keywords") or {}
805
+ argument_expressions = check.get(
806
+ "argument_expressions") or []
807
+ keyword_expressions = check.get(
808
+ "keyword_expressions") or {}
809
+ assignment = check.get("assignment")
810
+ if (not _DOTTED.fullmatch(function) or
811
+ not isinstance(arguments, list) or
812
+ not isinstance(keywords, dict) or
813
+ not isinstance(argument_expressions, list) or
814
+ not isinstance(keyword_expressions, dict) or
815
+ not (arguments or keywords or
816
+ argument_expressions or keyword_expressions or
817
+ assignment) or
818
+ any(not isinstance(item, dict) or
819
+ not isinstance(item.get("index"), int) or
820
+ item.get("index") < 0 or
821
+ isinstance(item.get("value"), dict)
822
+ for item in arguments) or
823
+ len({item["index"] for item in arguments}) !=
824
+ len(arguments) or
825
+ any(not _DOTTED.fullmatch(str(name)) or
826
+ "." in str(name) or isinstance(value, dict)
827
+ for name, value in keywords.items()) or
828
+ any(not isinstance(item, dict) or
829
+ not isinstance(item.get("index"), int) or
830
+ item.get("index") < 0 or
831
+ not _expression_fingerprint(
832
+ item.get("expression"))
833
+ for item in argument_expressions) or
834
+ len({item["index"] for item in
835
+ argument_expressions}) !=
836
+ len(argument_expressions) or
837
+ ({item["index"] for item in arguments} &
838
+ {item["index"] for item in
839
+ argument_expressions}) or
840
+ any(not _DOTTED.fullmatch(str(name)) or
841
+ "." in str(name) or
842
+ not _expression_fingerprint(value)
843
+ for name, value in
844
+ keyword_expressions.items()) or
845
+ (set(keywords) & set(keyword_expressions)) or
846
+ (assignment is not None and (
847
+ not isinstance(assignment, dict) or
848
+ not _DOTTED.fullmatch(str(
849
+ assignment.get("target") or "")) or
850
+ "." in str(assignment.get("target") or "") or
851
+ not _expression_fingerprint(
852
+ assignment.get("expression")))) or
853
+ not any(
854
+ (name == function or
855
+ name.endswith("." + function)) and
856
+ _call_signature_matches(
857
+ node, arguments, keywords, constants,
858
+ argument_expressions,
859
+ keyword_expressions, assignment)
860
+ for name, node in call_nodes)):
861
+ raise ObjectiveEvaluatorError(
862
+ "Python call-signature check is invalid or fails reference content")
863
+ compiled = {"type": kind, "path": path,
864
+ "function": function,
865
+ "arguments": arguments,
866
+ "keywords": keywords,
867
+ "argument_expressions": argument_expressions,
868
+ "keyword_expressions": keyword_expressions,
869
+ "assignment": assignment}
870
+ else:
871
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
872
+ if kind in {"python_call", "python_call_literal",
873
+ "python_call_keyword_literal",
874
+ "python_call_signature"}:
875
+ targets = _objective_call_targets(
876
+ kind, compiled, resolved_calls, constants)
877
+ if len(targets) != 1:
878
+ raise ObjectiveEvaluatorError(
879
+ "Python call check has no unique canonical target")
880
+ compiled["target"] = next(iter(targets))
881
+ checks.append({"id": f"python_{index:03d}_{check_index:03d}",
882
+ **compiled})
883
+ else:
884
+ raw_checks = raw.get("checks") or []
885
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
886
+ raise ObjectiveEvaluatorError(
887
+ "shell deliverable requires 1-12 objective command checks")
888
+ checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
889
+ "path": path})
890
+ reference_sequence = _shell_lines(content)
891
+ reference_lines = set(reference_sequence)
892
+ unconditional_lines = _shell_unconditional_lines(content)
893
+ command_checks = []
894
+ for check in raw_checks:
895
+ value = " ".join(str(check.get("value") or "").strip().split())
896
+ if (not isinstance(check, dict) or
897
+ str(check.get("type") or "").strip().casefold() != "shell_command" or
898
+ not value or value not in reference_lines):
899
+ raise ObjectiveEvaluatorError("unsupported shell objective check")
900
+ command_checks.append({"type": "shell_command", "path": path,
901
+ "value": value})
902
+ if len({item["value"] for item in command_checks}) != len(command_checks):
903
+ raise ObjectiveEvaluatorError("shell objective checks must be unique")
904
+ command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
905
+ if not all(any(_shell_command_matches(
906
+ item["value"], line) for line in unconditional_lines)
907
+ for item in command_checks):
908
+ raise ObjectiveEvaluatorError(
909
+ "checked shell commands must be top-level and unconditional")
910
+ for check_index, check in enumerate(command_checks, 1):
911
+ checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
912
+ **check})
913
+ if len(command_checks) >= 2:
914
+ checks.append({
915
+ "id": f"shell_{index:03d}_sequence",
916
+ "type": "shell_command_sequence", "path": path,
917
+ "values": [item["value"] for item in command_checks],
918
+ })
919
+ checks.append({
920
+ "id": f"shell_{index:03d}_unconditional",
921
+ "type": "shell_unconditional_commands", "path": path,
922
+ "values": [item["value"] for item in command_checks],
923
+ })
924
+ # Preserve the reference's fail-fast behavior when accepting normal
925
+ # command-substitution/guard wrappers. Never turn `|| true` into a
926
+ # passing preflight simply because it contains the correct argv.
927
+ reference_calls = shell_invocations(content)
928
+ protected = [item["value"] for item in command_checks if any(
929
+ call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
930
+ for call in reference_calls)]
931
+ if protected:
932
+ checks.append({"id": f"shell_{index:03d}_failure_propagation",
933
+ "type": "shell_failure_propagation", "path": path,
934
+ "values": protected})
935
+ # Candidate workspaces may also contain root-level public inputs and
936
+ # installed Skill packages. Deliverables use dedicated top-level output
937
+ # directories, so enforce an exact file set inside those namespaces while
938
+ # leaving the read-only environment outside them untouched.
939
+ output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
940
+ if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
941
+ checks.insert(0, {
942
+ "id": "workspace_file_set", "type": "workspace_file_set",
943
+ "paths": sorted(paths), "roots": output_roots,
944
+ })
945
+ return {
946
+ "type": WORKSPACE_EVALUATOR,
947
+ "version": WORKSPACE_EVALUATOR_VERSION,
948
+ "output_mode": "workspace",
949
+ "reference_files": reference_files,
950
+ "checks": checks,
951
+ }
952
+
953
+
954
+ def reference_bundle(evaluator):
955
+ if evaluator.get("type") != WORKSPACE_EVALUATOR:
956
+ raise ObjectiveEvaluatorError("not a workspace evaluator")
957
+ return {"files": [
958
+ {"path": item["path"], "content": item["content"]}
959
+ for item in evaluator.get("reference_files") or []
960
+ ]}
961
+
962
+
963
+ def hidden_workspace_values(evaluator):
964
+ """Return decisive package-owned values that public queries must not leak."""
965
+ values = []
966
+ for check in (evaluator or {}).get("checks") or []:
967
+ kind = check.get("type")
968
+ if kind in {"json_exact", "toml_exact"}:
969
+ values.extend(value for _, value in _flatten(check.get("expected")))
970
+ elif kind in {"python_import", "python_call", "shell_command",
971
+ "python_constant", "python_call_literal",
972
+ "python_call_keyword_literal"}:
973
+ values.append(check.get("value"))
974
+ elif kind == "python_call_signature":
975
+ values.extend(value for _, value in _flatten({
976
+ "arguments": [item.get("value") for item in
977
+ check.get("arguments") or []],
978
+ "keywords": check.get("keywords") or {},
979
+ "argument_expressions": [item.get("expression") for item in
980
+ check.get("argument_expressions") or []],
981
+ "keyword_expressions": check.get("keyword_expressions") or {},
982
+ "assignment": check.get("assignment"),
983
+ }))
984
+ return [value for value in values if value is not None]
985
+
986
+
987
+ def _flatten(value, path=()):
988
+ if isinstance(value, dict):
989
+ out = []
990
+ for key, item in value.items():
991
+ out.extend(_flatten(item, path + (str(key),)))
992
+ return out
993
+ if isinstance(value, list):
994
+ out = []
995
+ for index, item in enumerate(value):
996
+ out.extend(_flatten(item, path + (index,)))
997
+ return out
998
+ return [(path, value)]
999
+
1000
+
1001
+ def _bundle_rows(candidate):
1002
+ if isinstance(candidate, str):
1003
+ text = candidate.strip()
1004
+ # Chat solvers often wrap the requested file bundle in a Markdown fence
1005
+ # or append a duplicate FINAL_ANSWER object. Decode one complete JSON
1006
+ # value at a time instead of requiring the entire response to be JSON;
1007
+ # only an object carrying the explicit ``files`` transport field is
1008
+ # eligible, so unrelated prose/objects are not silently accepted.
1009
+ decoder = json.JSONDecoder()
1010
+ candidate = None
1011
+ for match in re.finditer(r"\{", text):
1012
+ try:
1013
+ parsed, _ = decoder.raw_decode(text, match.start())
1014
+ except json.JSONDecodeError:
1015
+ continue
1016
+ if isinstance(parsed, dict) and "files" in parsed:
1017
+ candidate = parsed
1018
+ break
1019
+ if candidate is None:
1020
+ raise ObjectiveEvaluatorError(
1021
+ "workspace response contains no complete JSON file bundle")
1022
+ if not isinstance(candidate, dict):
1023
+ raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
1024
+ files = candidate.get("files")
1025
+ if isinstance(files, dict):
1026
+ files = [{"path": path, "content": content}
1027
+ for path, content in files.items()]
1028
+ if not isinstance(files, list) or len(files) > 30:
1029
+ raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
1030
+ return files
1031
+
1032
+
1033
+ def materialize_bundle(candidate, workspace):
1034
+ root = Path(workspace).resolve()
1035
+ root.mkdir(parents=True, exist_ok=True)
1036
+ seen = set()
1037
+ for item in _bundle_rows(candidate):
1038
+ if not isinstance(item, dict):
1039
+ raise ObjectiveEvaluatorError("candidate file entry is not an object")
1040
+ relative = safe_relative_path(item.get("path"))
1041
+ if relative in seen:
1042
+ raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
1043
+ seen.add(relative)
1044
+ content = item.get("content")
1045
+ if isinstance(content, (dict, list)):
1046
+ content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
1047
+ if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
1048
+ raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
1049
+ target = (root / relative).resolve()
1050
+ if root not in target.parents:
1051
+ raise ObjectiveEvaluatorError("candidate file escapes workspace")
1052
+ target.parent.mkdir(parents=True, exist_ok=True)
1053
+ target.write_text(content, encoding="utf-8")
1054
+ return root
1055
+
1056
+
1057
+ def evaluate_workspace(evaluator, workspace):
1058
+ if (not isinstance(evaluator, dict) or
1059
+ evaluator.get("type") != WORKSPACE_EVALUATOR or
1060
+ int(evaluator.get("version") or 0) not in
1061
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
1062
+ return False, {"error": "invalid workspace evaluator contract"}
1063
+ root = Path(workspace).resolve()
1064
+ results = []
1065
+ for check in evaluator.get("checks") or []:
1066
+ kind = check.get("type")
1067
+ relative, path = "", None
1068
+ if kind != "workspace_file_set":
1069
+ relative = safe_relative_path(check.get("path"))
1070
+ path = (root / relative).resolve()
1071
+ if root not in path.parents:
1072
+ return False, {"error": "evaluator path escapes workspace"}
1073
+ passed, detail = False, ""
1074
+ try:
1075
+ if kind == "workspace_file_set":
1076
+ expected = {safe_relative_path(value)
1077
+ for value in check.get("paths") or []}
1078
+ roots = [safe_relative_path(value)
1079
+ for value in check.get("roots") or []]
1080
+ actual = set()
1081
+ for relative_root in roots:
1082
+ scan_root = (root / relative_root).resolve()
1083
+ if root not in scan_root.parents:
1084
+ raise ObjectiveEvaluatorError(
1085
+ "workspace file-set root escapes workspace")
1086
+ if not scan_root.exists():
1087
+ continue
1088
+ for candidate in scan_root.rglob("*"):
1089
+ if candidate.is_file() or candidate.is_symlink():
1090
+ actual.add(candidate.relative_to(root).as_posix())
1091
+ passed = bool(expected) and actual == expected
1092
+ detail = ("exact deliverable file set" if passed else
1093
+ f"expected_files={sorted(expected)}; "
1094
+ f"actual_files={sorted(actual)}")
1095
+ elif kind == "file_exists":
1096
+ passed = path.is_file()
1097
+ detail = "present" if passed else "missing"
1098
+ elif kind == "json_exact":
1099
+ actual = json.loads(path.read_text(encoding="utf-8"))
1100
+ passed = (_same_native_json_types(actual, check.get("expected")) and
1101
+ _canonical(actual) == _canonical(check.get("expected")))
1102
+ detail = "semantic JSON match" if passed else "JSON value mismatch"
1103
+ elif kind == "toml_exact":
1104
+ actual = tomllib.loads(path.read_text(encoding="utf-8"))
1105
+ passed = _canonical(actual) == _canonical(check.get("expected"))
1106
+ detail = "semantic TOML match" if passed else "TOML value mismatch"
1107
+ elif kind in {"python_syntax", "python_bound_calls",
1108
+ "python_import", "python_call",
1109
+ "python_constant", "python_call_literal",
1110
+ "python_call_keyword_literal",
1111
+ "python_call_signature"}:
1112
+ source = path.read_text(encoding="utf-8")
1113
+ imports, calls, constants, call_nodes = _python_semantics(source)
1114
+ resolved_calls = _python_resolved_call_nodes(source)
1115
+ if kind == "python_syntax":
1116
+ passed, detail = True, "valid Python syntax"
1117
+ elif kind == "python_bound_calls":
1118
+ unbound = python_unbound_call_roots(
1119
+ path.read_text(encoding="utf-8"))
1120
+ passed = not unbound
1121
+ detail = ("all call roots are statically bound" if passed else
1122
+ "unbound call roots=" + repr(unbound))
1123
+ elif kind == "python_import":
1124
+ expected = str(check.get("value") or "")
1125
+ passed = expected in imports or any(
1126
+ value == expected or value.startswith(expected + ".")
1127
+ for value in imports)
1128
+ detail = f"imports={sorted(imports)}"
1129
+ elif kind == "python_call":
1130
+ expected = str(check.get("value") or "")
1131
+ target = str(check.get("target") or "")
1132
+ passed = (any(
1133
+ canonical == target
1134
+ for _, canonical, _ in resolved_calls)
1135
+ if target else expected in calls or any(
1136
+ value.endswith("." + expected)
1137
+ for value in calls))
1138
+ detail = f"calls={sorted(calls)}"
1139
+ elif kind == "python_constant":
1140
+ name, expected = str(check.get("name") or ""), check.get("value")
1141
+ actual = constants.get(name, _UNRESOLVED)
1142
+ passed = actual is not _UNRESOLVED and actual == expected
1143
+ detail = f"constant {name}={actual!r}"
1144
+ elif kind == "python_call_literal":
1145
+ function, expected = (str(check.get("function") or ""),
1146
+ check.get("value"))
1147
+ target = str(check.get("target") or "")
1148
+ source_calls = (resolved_calls if target else
1149
+ [(name, "", node) for name, node in call_nodes])
1150
+ passed = any(
1151
+ (bool(target) or _call_name_matches(name, function)) and
1152
+ (not target or canonical == target) and
1153
+ _node_contains_literal(node, expected, constants)
1154
+ for name, canonical, node in source_calls)
1155
+ detail = f"call={function} literal={expected!r}"
1156
+ elif kind == "python_call_keyword_literal":
1157
+ function = str(check.get("function") or "")
1158
+ keyword = str(check.get("keyword") or "")
1159
+ expected = check.get("value")
1160
+ target = str(check.get("target") or "")
1161
+ source_calls = (resolved_calls if target else
1162
+ [(name, "", node) for name, node in call_nodes])
1163
+ passed = any(
1164
+ (bool(target) or _call_name_matches(name, function)) and
1165
+ (not target or canonical == target) and
1166
+ _call_keyword_matches(node, keyword, expected, constants)
1167
+ for name, canonical, node in source_calls)
1168
+ detail = (f"call={function} keyword={keyword} "
1169
+ f"literal={expected!r}")
1170
+ else:
1171
+ function = str(check.get("function") or "")
1172
+ arguments = check.get("arguments") or []
1173
+ keywords = check.get("keywords") or {}
1174
+ argument_expressions = check.get(
1175
+ "argument_expressions") or []
1176
+ keyword_expressions = check.get(
1177
+ "keyword_expressions") or {}
1178
+ assignment = check.get("assignment")
1179
+ target = str(check.get("target") or "")
1180
+ source_calls = (resolved_calls if target else
1181
+ [(name, "", node) for name, node in call_nodes])
1182
+ passed = any(
1183
+ (bool(target) or _call_name_matches(name, function)) and
1184
+ (not target or canonical == target) and
1185
+ _call_signature_matches(
1186
+ node, arguments, keywords, constants,
1187
+ argument_expressions, keyword_expressions,
1188
+ assignment)
1189
+ for name, canonical, node in source_calls)
1190
+ detail = (f"call={function} arguments={arguments!r} "
1191
+ f"keywords={keywords!r} "
1192
+ f"argument_expressions={argument_expressions!r} "
1193
+ f"keyword_expressions={keyword_expressions!r} "
1194
+ f"assignment={assignment!r}")
1195
+ elif kind == "shell_syntax":
1196
+ completed = subprocess.run(
1197
+ ["bash", "-n", str(path)], capture_output=True, text=True,
1198
+ timeout=5, check=False)
1199
+ passed = completed.returncode == 0
1200
+ detail = ("valid shell syntax" if passed else
1201
+ (completed.stderr or "invalid shell syntax").strip())
1202
+ elif kind == "shell_command":
1203
+ source = path.read_text(encoding="utf-8")
1204
+ lines = ([call["command"] for call in shell_invocations(source)]
1205
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1206
+ expected = " ".join(str(check.get("value") or "").split())
1207
+ passed = any(_shell_command_matches(expected, line) for line in lines)
1208
+ detail = f"executable_lines={lines[:30]}"
1209
+ elif kind == "shell_command_sequence":
1210
+ source = path.read_text(encoding="utf-8")
1211
+ lines = ([call["command"] for call in shell_invocations(source)]
1212
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1213
+ expected = [" ".join(str(value).split())
1214
+ for value in check.get("values") or []]
1215
+ passed = (len(expected) >= 2 and
1216
+ _shell_command_sequence_matches(expected, lines))
1217
+ detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
1218
+ elif kind == "shell_unconditional_commands":
1219
+ source = path.read_text(encoding="utf-8")
1220
+ lines = ([call["command"] for call in shell_invocations(source)]
1221
+ if int(evaluator.get("version", 0)) >= 15
1222
+ else _shell_unconditional_lines(source))
1223
+ expected = [" ".join(str(value).split())
1224
+ for value in check.get("values") or []]
1225
+ passed = (bool(expected) and all(
1226
+ any(_shell_command_matches(command, line) for line in lines)
1227
+ for command in expected))
1228
+ if check.get("require_straight_line"):
1229
+ passed = passed and _shell_is_straight_line(source)
1230
+ detail = (f"expected_unconditional={expected}; "
1231
+ f"top_level_lines={lines[:30]}")
1232
+ elif kind == "shell_failure_propagation":
1233
+ calls = shell_invocations(path.read_text(encoding="utf-8"))
1234
+ expected = [" ".join(str(value).split())
1235
+ for value in check.get("values") or []]
1236
+ passed = bool(expected) and all(any(
1237
+ call["fail_fast"] and _shell_command_matches(command, call["command"])
1238
+ for call in calls) for command in expected)
1239
+ detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
1240
+ elif kind == "shell_straight_line":
1241
+ source = path.read_text(encoding="utf-8")
1242
+ passed = _shell_is_straight_line(source)
1243
+ if "allowed_commands" in check:
1244
+ calls = shell_invocations(source)
1245
+ allowed = check["allowed_commands"]
1246
+ passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and
1247
+ all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls))
1248
+ detail = ("all executable lines are top-level" if passed else
1249
+ "shell contains conditional, loop, case, or function")
1250
+ else:
1251
+ detail = f"unsupported check: {kind}"
1252
+ except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
1253
+ json.JSONDecodeError,
1254
+ tomllib.TOMLDecodeError) as exc:
1255
+ detail = str(exc)
1256
+ results.append({"id": check.get("id"), "type": kind,
1257
+ "path": relative, "passed": bool(passed),
1258
+ "detail": detail[:1000]})
1259
+ return bool(results) and all(item["passed"] for item in results), {
1260
+ "type": WORKSPACE_EVALUATOR,
1261
+ "assertions_passed": sum(item["passed"] for item in results),
1262
+ "assertions_total": len(results),
1263
+ "assertions": results,
1264
+ }
1265
+
1266
+
1267
+ def evaluate_candidate(evaluator, candidate):
1268
+ if isinstance(candidate, os.PathLike):
1269
+ try:
1270
+ return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
1271
+ False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
1272
+ except (OSError, ValueError) as exc:
1273
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1274
+ if isinstance(candidate, str):
1275
+ # A chat file-bundle can be much longer than a filesystem path. Avoid
1276
+ # passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
1277
+ stripped = candidate.strip()
1278
+ if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
1279
+ and not stripped.startswith(("{", "[", "```"))):
1280
+ try:
1281
+ if Path(stripped).is_dir():
1282
+ return evaluate_workspace(evaluator, stripped)
1283
+ except (OSError, ValueError):
1284
+ # Python/platform versions differ on ENAMETOOLONG and invalid
1285
+ # path errors. It is still candidate text: parse it unchanged.
1286
+ pass
1287
+ try:
1288
+ with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
1289
+ materialize_bundle(candidate, temp)
1290
+ return evaluate_workspace(evaluator, temp)
1291
+ except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
1292
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1293
+
1294
+
1295
+ def self_test_workspace_evaluator(evaluator):
1296
+ correct = reference_bundle(evaluator)
1297
+ ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
1298
+ rows = list(correct.get("files") or [])
1299
+ perturbed = {"files": rows[1:] if len(rows) > 1 else []}
1300
+ ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
1301
+ mutations = []
1302
+ # Exact JSON fields must each matter, not merely the file's existence.
1303
+ for check in evaluator.get("checks") or []:
1304
+ if check.get("type") != "json_exact":
1305
+ continue
1306
+ for path, value in _flatten(check.get("expected")):
1307
+ candidate = copy.deepcopy(correct)
1308
+ file_row = next(row for row in candidate["files"]
1309
+ if row["path"] == check["path"])
1310
+ data = json.loads(file_row["content"])
1311
+ replacement = (not value if isinstance(value, bool) else
1312
+ value + 1 if isinstance(value, (int, float)) else
1313
+ str(value) + "__mutation__")
1314
+ if not path:
1315
+ data = replacement
1316
+ else:
1317
+ container = data
1318
+ for key in path[:-1]:
1319
+ container = container[key]
1320
+ container[path[-1]] = replacement
1321
+ file_row["content"] = json.dumps(data)
1322
+ passed, _ = evaluate_candidate(evaluator, candidate)
1323
+ mutations.append({"path": check["path"], "field": list(path),
1324
+ "rejected": not passed})
1325
+ return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
1326
+ "correct": correct_detail,
1327
+ "perturbed": wrong_detail,
1328
+ "scalar_mutations": mutations,
1329
+ }
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/shell_invocations.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A deliberately bounded, non-executing shell structure recognizer.
2
+
3
+ Supports simple commands, literal scalar assignments, one command substitution
4
+ on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
5
+ It does not interpret shell code or credit commands in branch bodies/functions.
6
+ Pipelines, command lists, substitutions within substitutions, and swallowed
7
+ failures are outside this grammar. bash -n remains a separate required check.
8
+ """
9
+ import re
10
+ import shlex
11
+
12
+
13
+ def _statements(text):
14
+ out, current = [], []
15
+ quote, escaped, comment, depth = None, False, False, 0
16
+ for ch in str(text):
17
+ if comment:
18
+ if ch == '\n':
19
+ comment = False
20
+ else:
21
+ continue
22
+ if escaped:
23
+ if ch != '\n':
24
+ current.extend(('\\', ch))
25
+ escaped = False
26
+ continue
27
+ if ch == '\\' and quote != "'":
28
+ escaped = True
29
+ continue
30
+ if quote:
31
+ current.append(ch)
32
+ if ch == quote:
33
+ quote = None
34
+ continue
35
+ if ch in "'\"":
36
+ quote = ch
37
+ current.append(ch)
38
+ elif ch == '#' and (not current or current[-1].isspace()):
39
+ comment = True
40
+ elif ch == '(':
41
+ depth += 1
42
+ current.append(ch)
43
+ elif ch == ')':
44
+ depth -= 1
45
+ if depth < 0:
46
+ return []
47
+ current.append(ch)
48
+ elif ch in '\n;' and depth == 0:
49
+ value = ''.join(current).strip()
50
+ if value:
51
+ out.append(value)
52
+ current = []
53
+ else:
54
+ current.append(ch)
55
+ if quote or escaped or depth:
56
+ return []
57
+ if ''.join(current).strip():
58
+ out.append(''.join(current).strip())
59
+ expanded = []
60
+ for statement in out:
61
+ inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
62
+ expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
63
+ return expanded
64
+
65
+
66
+ def _simple_argv(text):
67
+ if '$(' in text or '`' in text:
68
+ return None
69
+ try:
70
+ lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
71
+ lexer.whitespace_split = True
72
+ tokens = list(lexer)
73
+ except ValueError:
74
+ return None
75
+ argv, index = [], 0
76
+ redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
77
+ while index < len(tokens):
78
+ token = tokens[index]
79
+ if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
80
+ index += 1
81
+ token = tokens[index]
82
+ if token in redirects:
83
+ if index + 1 >= len(tokens):
84
+ return None
85
+ target = tokens[index + 1]
86
+ if (not target or any(c in target for c in '$`;&|<>()')
87
+ or target in ('{', '}')):
88
+ return None
89
+ index += 2
90
+ continue
91
+ if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
92
+ return None
93
+ argv.append(token)
94
+ index += 1
95
+ return argv or None
96
+
97
+
98
+ def _invocation(text):
99
+ substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
100
+ if substitution:
101
+ inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
102
+ argv = _simple_argv(inner)
103
+ return (argv, 'assignment_substitution') if argv else (None, None)
104
+ return _simple_argv(text), 'simple'
105
+
106
+
107
+ def _guard_end(statements, start):
108
+ depth = 1
109
+ for index in range(start + 1, len(statements)):
110
+ item = statements[index]
111
+ if re.match(r'^if\s', item):
112
+ depth += 1
113
+ elif item == 'fi':
114
+ depth -= 1
115
+ if depth == 0:
116
+ return index
117
+ return None
118
+
119
+
120
+ def _nonzero_exit_body(statements):
121
+ """Only literal logging followed by a final unconditional nonzero exit."""
122
+ if not statements:
123
+ return False
124
+ for index, statement in enumerate(statements):
125
+ argv = _simple_argv(statement)
126
+ if not argv:
127
+ return False
128
+ if argv[0] == 'exit':
129
+ return (index == len(statements) - 1 and len(argv) == 2
130
+ and argv[1].isdigit() and 1 <= int(argv[1]) <= 255)
131
+ if argv[0] not in ('echo', 'printf'):
132
+ return False
133
+ return False
134
+
135
+
136
+
137
+ def _expand_known_variables(text, constants):
138
+ """Preserve quote/escape expansion semantics in the bounded shell grammar.
139
+
140
+ Active unknown variables stay symbolic. A quoted/escaped literal dollar or
141
+ tilde has a separate token, so it cannot satisfy an expanding shell call.
142
+ This is parsing only; no shell command is evaluated.
143
+ """
144
+ out,quote,i=[],None,0
145
+ variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
146
+ while i<len(text):
147
+ ch=text[i]
148
+ if ch=='\\' and quote!="'" and i+1<len(text):
149
+ nxt=text[i+1]
150
+ if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__')
151
+ elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__')
152
+ else:out.extend((ch,nxt))
153
+ i+=2;continue
154
+ if ch in "'\"":
155
+ if quote is None:quote=ch
156
+ elif quote==ch:quote=None
157
+ out.append(ch);i+=1;continue
158
+ if ch=='$':
159
+ if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue
160
+ m=variable.match(text,i)
161
+ if m:
162
+ value=constants.get(m.group(1)or m.group(2))
163
+ if value is None:out.append(m.group(0))
164
+ elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$'))
165
+ else:out.append(value)
166
+ i=m.end();continue
167
+ if ch=='~' and quote is not None:
168
+ out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue
169
+ out.append(ch);i+=1
170
+ return ''.join(out)
171
+
172
+ def shell_invocations(text):
173
+ """Return ordered, actually evaluated invocation nodes in the supported subset.
174
+
175
+ fail_fast is a structural proof: a simple command/assignment runs under
176
+ errexit, or a negated test exits nonzero on failure. This is not a complete
177
+ shell interpreter, and unsupported syntax earns no invocation credit.
178
+ """
179
+ statements = _statements(text)
180
+ # Function definitions or dynamic shell mutation can shadow the command or
181
+ # `exit` itself. They are outside this objective subset, even if uncalled.
182
+ if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s)
183
+ or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
184
+ for s in statements):
185
+ return []
186
+ constants, result, index, errexit = {}, [], 0, False
187
+ assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
188
+ variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
189
+ while index < len(statements):
190
+ statement = statements[index]
191
+ literal = assignment.fullmatch(statement)
192
+ if literal:
193
+ constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
194
+ index += 1
195
+ continue
196
+ statement = _expand_known_variables(statement, constants)
197
+ setting = _simple_argv(statement)
198
+ if setting and setting[0] == 'set':
199
+ flag_index = 1
200
+ while flag_index < len(setting):
201
+ flag = setting[flag_index]
202
+ if flag == '--' or not flag.startswith(('-', '+')):
203
+ break # Remaining words set positional parameters.
204
+ if not re.fullmatch(r'[-+][eufxEo]+', flag):
205
+ return [] # e.g. `set -n` suppresses execution entirely.
206
+ if 'e' in flag[1:]:
207
+ errexit = flag[0] == '-'
208
+ if 'o' in flag[1:]:
209
+ if flag_index + 1 >= len(setting):
210
+ return []
211
+ option = setting[flag_index + 1]
212
+ if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
213
+ return []
214
+ if option == 'errexit':
215
+ errexit = flag[0] == '-'
216
+ flag_index += 1
217
+ flag_index += 1
218
+ index += 1
219
+ continue
220
+ if re.match(r'^if\s', statement):
221
+ end = _guard_end(statements, index)
222
+ if end is None:
223
+ return []
224
+ negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
225
+ if (negated and index + 1 < end
226
+ and statements[index + 1] == 'then'
227
+ and _nonzero_exit_body(statements[index + 2:end])):
228
+ argv, kind = _invocation(negated.group(1).strip())
229
+ if argv:
230
+ if argv[0] == 'false':
231
+ break
232
+ result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
233
+ 'fail_fast': True, 'statement_index': index})
234
+ else:
235
+ return []
236
+ else:
237
+ # Arbitrary conditions may terminate the script or shadow its
238
+ # commands. Do not infer a reachable suffix through them.
239
+ return []
240
+ # Bodies are never credited and may have assigned local variables.
241
+ constants.clear()
242
+ index = end + 1
243
+ continue
244
+ if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
245
+ # Unsupported compounds are not searched for command substrings.
246
+ return []
247
+ argv, kind = _invocation(statement)
248
+ if not argv:
249
+ # An unparsed statement may change control flow or shell state.
250
+ # Skipping it would incorrectly credit an unreachable suffix.
251
+ return []
252
+ if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare',
253
+ 'typeset', 'local', 'read', 'mapfile', 'readarray',
254
+ 'unset', 'readonly', '[', '[[', 'test'):
255
+ return []
256
+ if argv[0] == 'exit' or (argv[0] == 'false' and errexit):
257
+ break
258
+ if kind == 'assignment_substitution':
259
+ assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
260
+ if assigned:
261
+ constants.pop(assigned.group(1), None)
262
+ result.append({'command': shlex.join(argv), 'kind': kind,
263
+ 'fail_fast': errexit, 'statement_index': index})
264
+ index += 1
265
+ return result
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/test.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}}
4
+ if [[ -z "$candidate" ]]; then
5
+ echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2
6
+ exit 64
7
+ fi
8
+ python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate"
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/legacy_tests/verifiers.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier execution engine and fail-closed self-tests.
2
+
3
+ New verified tasks use atomic_json (complete shape plus scalar assertions).
4
+ Legacy verifier types remain readable so historical runs can still be audited.
5
+ 自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
6
+ """
7
+ import json
8
+ import math
9
+ import posixpath
10
+ import logging
11
+ import os
12
+ import re
13
+
14
+ try:
15
+ from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
16
+ reference_bundle,
17
+ self_test_workspace_evaluator)
18
+ except ImportError: # portable task copies these modules beside each other
19
+ from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
20
+ reference_bundle,
21
+ self_test_workspace_evaluator)
22
+
23
+ log = logging.getLogger("pipeline")
24
+
25
+
26
+ def _norm(s):
27
+ return str(s).strip().lower()
28
+
29
+
30
+ def _json_value(value):
31
+ """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
32
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
33
+ return value
34
+ text = str(value).strip()
35
+ match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
36
+ if match:
37
+ text = match.group(1).strip()
38
+ text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
39
+ text = re.sub(r"\s*```$", "", text)
40
+ start_obj, start_arr = text.find("{"), text.find("[")
41
+ starts = [x for x in (start_obj, start_arr) if x >= 0]
42
+ if starts:
43
+ start = min(starts)
44
+ closing = "}" if text[start] == "{" else "]"
45
+ end = text.rfind(closing)
46
+ if end >= start:
47
+ text = text[start:end + 1]
48
+ try:return json.loads(text)
49
+ except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
50
+
51
+
52
+
53
+ def _strict_json_value(value):
54
+ """Atomic answer contract: one complete JSON value, no extra prose/keys."""
55
+ def unique(pairs):
56
+ d={}
57
+ for k,v in pairs:
58
+ if k in d:raise ValueError('duplicate JSON key: '+k)
59
+ d[k]=v
60
+ return d
61
+ def invalid(s):raise ValueError('non-finite JSON number: '+s)
62
+ try:
63
+ result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
64
+ if isinstance(value,str) else value)
65
+ except RecursionError as error:
66
+ raise ValueError('Candidate JSON nesting is too deep') from error
67
+ def finite(v):
68
+ if isinstance(v,dict):return all(finite(x)for x in v.values())
69
+ if isinstance(v,list):return all(finite(x)for x in v)
70
+ return not isinstance(v,float)or math.isfinite(v)
71
+ try:is_finite=finite(result)
72
+ except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
73
+ if not is_finite:raise ValueError('non-finite JSON number')
74
+ return result
75
+
76
+ def _path_equal(actual, expected):
77
+ if not isinstance(actual,str)or not isinstance(expected,str):return False
78
+ # A trailing slash is not a harmless spelling for a named file.
79
+ suffix=posixpath.splitext(expected.rstrip('/'))[1]
80
+ if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
81
+ return _path_value(actual)==_path_value(expected)
82
+
83
+ def _canonical_json(value):
84
+ if isinstance(value, dict):
85
+ return {key: _canonical_json(value[key]) for key in sorted(value)}
86
+ if isinstance(value, list):
87
+ values = [_canonical_json(item) for item in value]
88
+ return sorted(values, key=lambda item: json.dumps(
89
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
90
+ return value
91
+
92
+
93
+ def _atomic_prepare(value, list_order):
94
+ if isinstance(value, dict):
95
+ return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
96
+ if isinstance(value, list):
97
+ values = [_atomic_prepare(item, list_order) for item in value]
98
+ if list_order == "unordered":
99
+ values.sort(key=lambda item: json.dumps(
100
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
101
+ return values
102
+ return value
103
+
104
+
105
+ def _atomic_shape(value):
106
+ if isinstance(value, dict):
107
+ return {"type": "object", "keys": {
108
+ key: _atomic_shape(item) for key, item in value.items()}}
109
+ if isinstance(value, list):
110
+ return {"type": "array", "length": len(value),
111
+ "items": [_atomic_shape(item) for item in value]}
112
+ if isinstance(value, bool):
113
+ return {"type": "boolean"}
114
+ if value is None:
115
+ return {"type": "null"}
116
+ if isinstance(value, (int, float)):
117
+ return {"type": "number"}
118
+ return {"type": "string"}
119
+
120
+
121
+ def _atomic_leaves(value, path="$", tokens=()):
122
+ if isinstance(value, dict):
123
+ out = []
124
+ for key, item in value.items():
125
+ out.extend(_atomic_leaves(
126
+ item, path + "." + key, tokens + (key,)))
127
+ return out
128
+ if isinstance(value, list):
129
+ out = []
130
+ for index, item in enumerate(value):
131
+ out.extend(_atomic_leaves(
132
+ item, f"{path}[{index}]", tokens + (index,)))
133
+ return out
134
+ return [(path, tokens, value)]
135
+
136
+
137
+ def _normalize_path_equivalence_tokens(values):
138
+ """Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
139
+ normalized = []
140
+ for tokens in values or []:
141
+ if (not isinstance(tokens, (list, tuple)) or not tokens or
142
+ any(not isinstance(token, (str, int)) for token in tokens)):
143
+ raise ValueError("path equivalence tokens must be non-empty JSON paths")
144
+ item = list(tokens)
145
+ if item not in normalized:
146
+ normalized.append(item)
147
+ return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
148
+
149
+
150
+ def _path_value(value):
151
+ """Normalize only portable path spelling, not general answer text."""
152
+ if not isinstance(value, str):
153
+ return None
154
+ text = value.strip().replace("\\", "/")
155
+ text = posixpath.normpath(text) if text else text
156
+ if text != "/":
157
+ text = text.rstrip("/")
158
+ return text
159
+
160
+
161
+ def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
162
+ path_equivalence_tokens=None):
163
+ """Freeze a complete JSON shape plus one assertion for every scalar leaf."""
164
+ if list_order not in {"ordered", "unordered"}:
165
+ raise ValueError(f"unsupported atomic list_order: {list_order}")
166
+ tolerance = float(float_tolerance)
167
+ prepared = _atomic_prepare(_json_value(expected), list_order)
168
+ path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
169
+ assertions = []
170
+ for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
171
+ assertion = {"id": f"leaf_{index:03d}", "path": path,
172
+ "tokens": list(tokens), "operator": "eq", "expected": value}
173
+ if isinstance(value, float):
174
+ assertion.update({"operator": "abs_diff", "tolerance": tolerance})
175
+ elif list(tokens) in path_tokens:
176
+ if not isinstance(value, str):
177
+ raise ValueError("path equivalence can only target string leaves")
178
+ assertion["operator"] = "path_eq"
179
+ assertions.append(assertion)
180
+ compiled = {
181
+ "type": "atomic_json", "version": 2 if path_tokens else 1,
182
+ "list_order": list_order,
183
+ "float_tolerance": tolerance,
184
+ "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
185
+ "assertions": assertions,
186
+ }
187
+ if path_tokens:
188
+ compiled["path_equivalence_tokens"] = path_tokens
189
+ return compiled
190
+
191
+
192
+ def _shape_differences(expected, actual, path="$"):
193
+ if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
194
+ return [f"{path}: expected {expected.get('type')}, got "
195
+ f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
196
+ kind = expected.get("type")
197
+ if kind == "object":
198
+ expected_keys = set((expected.get("keys") or {}))
199
+ actual_keys = set((actual.get("keys") or {}))
200
+ differences = [f"{path}: missing key {key}" for key in sorted(
201
+ expected_keys - actual_keys)]
202
+ differences.extend(f"{path}: extra key {key}" for key in sorted(
203
+ actual_keys - expected_keys))
204
+ for key in sorted(expected_keys & actual_keys):
205
+ differences.extend(_shape_differences(
206
+ expected["keys"][key], actual["keys"][key], path + "." + key))
207
+ return differences
208
+ if kind == "array":
209
+ differences = []
210
+ if actual.get("length") != expected.get("length"):
211
+ differences.append(
212
+ f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
213
+ for index, (expected_item, actual_item) in enumerate(zip(
214
+ expected.get("items") or [], actual.get("items") or [])):
215
+ differences.extend(_shape_differences(
216
+ expected_item, actual_item, f"{path}[{index}]"))
217
+ return differences
218
+ return []
219
+
220
+
221
+ def _atomic_get(value, tokens):
222
+ current = value
223
+ for token in tokens:
224
+ current = current[token]
225
+ return current
226
+
227
+
228
+ def _int_values(value):
229
+ if isinstance(value, (list, tuple)):
230
+ out = []
231
+ for item in value:
232
+ out.extend(_int_values(item))
233
+ return out
234
+ if isinstance(value, int) and not isinstance(value, bool):
235
+ return [value]
236
+ return [int(number) for number in re.findall(r"\d+", str(value or ""))]
237
+
238
+
239
+ def _finding_type(value):
240
+ text = str(value or "").lower().replace("-", "_")
241
+ if "duplicate" in text:
242
+ return "duplicate_rows"
243
+ if ("none" in text or "null" in text) and "check" in text:
244
+ return "none_check"
245
+ if "missing" in text or "empty" in text or "null" in text:
246
+ return "missing"
247
+ if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
248
+ return "outlier"
249
+ if "invalid" in text and "config" in text:
250
+ return "invalid_config"
251
+ if "off" in text and "one" in text:
252
+ return "off_by_one"
253
+ return text.strip().replace(" ", "_")
254
+
255
+
256
+ def _normalized_findings(value, family):
257
+ obj = _json_value(value)
258
+ findings = obj.get("findings") if isinstance(obj, dict) else None
259
+ if not isinstance(findings, list):
260
+ raise ValueError("answer must contain a findings array")
261
+ normalized = set()
262
+ for finding in findings:
263
+ if not isinstance(finding, dict):
264
+ raise ValueError("each finding must be an object")
265
+ # The public contract uses type/function. Accept common semantically
266
+ # equivalent aliases as a robustness layer, while still comparing the
267
+ # normalized values and exact locations against generator-owned GT.
268
+ kind = _finding_type(finding.get("type", finding.get(
269
+ "defect_type", finding.get("defect"))))
270
+ if family == "csv":
271
+ if kind == "duplicate_rows":
272
+ rows = _int_values(finding.get("rows", finding.get("row")))
273
+ if len(rows) != 2:
274
+ raise ValueError("duplicate finding requires exactly two row numbers")
275
+ normalized.add((kind, *sorted(rows)))
276
+ elif kind in {"missing", "outlier"}:
277
+ rows = _int_values(finding.get("row"))
278
+ column = str(finding.get("column") or "").strip().lower()
279
+ if len(rows) != 1 or not column:
280
+ raise ValueError(f"{kind} requires one row and column")
281
+ normalized.add((kind, rows[0], column))
282
+ else:
283
+ raise ValueError(f"unsupported CSV finding type: {kind}")
284
+ elif family == "config":
285
+ if kind != "invalid_config":
286
+ raise ValueError(f"unsupported config finding type: {kind}")
287
+ normalized.add((kind, str(finding.get("path") or "").lower(),
288
+ json.dumps(finding.get("value"), sort_keys=True),
289
+ str(finding.get("expected") or "").lower()))
290
+ elif family == "code":
291
+ if kind not in {"off_by_one", "none_check"}:
292
+ raise ValueError(f"unsupported code finding type: {kind}")
293
+ function = finding.get("function", finding.get("function_name"))
294
+ function = str(function or "").strip().lower()
295
+ if not function:
296
+ raise ValueError(f"{kind} requires a function")
297
+ normalized.add((kind, function))
298
+ else:
299
+ raise ValueError(f"unsupported findings family: {family}")
300
+ return normalized
301
+
302
+
303
+ def _normalized_facts(value):
304
+ obj = _json_value(value)
305
+ facts = obj.get("facts") if isinstance(obj, dict) else None
306
+ if not isinstance(facts, list):
307
+ raise ValueError("answer must contain a facts array")
308
+ def textual(item):
309
+ # The document generator serializes scalar values as visible text. JSON
310
+ # has no way to infer whether the source token "30" was authored from an
311
+ # integer or a string, so facts_match compares that surface text. Nested
312
+ # values retain structural JSON comparison.
313
+ if isinstance(item, (dict, list)):
314
+ return json.dumps(item, sort_keys=True, ensure_ascii=False,
315
+ separators=(",", ":"))
316
+ if item is None:
317
+ return "None"
318
+ return str(item)
319
+ return {(str(fact.get("key") or ""), textual(fact.get("value")))
320
+ for fact in facts if isinstance(fact, dict)}
321
+
322
+
323
+ def verify(verifier, gt_answer, solver_output, material_paths=None):
324
+ """执行 verifier。返回 (passed, detail)。"""
325
+ vtype = verifier.get("type")
326
+ try:
327
+ if vtype == WORKSPACE_EVALUATOR:
328
+ return evaluate_candidate(verifier, solver_output)
329
+
330
+ if vtype == "json_exact":
331
+ pred = _canonical_json(_json_value(solver_output))
332
+ gold = _canonical_json(_json_value(gt_answer))
333
+ ok = pred == gold
334
+ return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
335
+
336
+ if vtype == "atomic_json":
337
+ try:
338
+ pred = _atomic_prepare(_strict_json_value(solver_output),
339
+ verifier.get("list_order", "ordered"))
340
+ pred_shape = _atomic_shape(pred)
341
+ except RecursionError:
342
+ return False, "candidate JSON nesting is too deep"
343
+ compiled = compile_atomic_verifier(
344
+ gt_answer, verifier.get("list_order", "ordered"),
345
+ verifier.get("float_tolerance", 0.01),
346
+ verifier.get("path_equivalence_tokens"))
347
+ frozen = {key: verifier.get(key) for key in
348
+ ("type", "version", "list_order", "float_tolerance",
349
+ "completeness", "assertions", "path_equivalence_tokens")}
350
+ expected_frozen = {key: compiled.get(key) for key in frozen}
351
+ if frozen != expected_frozen:
352
+ return False, {"error": "atomic verifier does not match ground truth"}
353
+ shape_failures = _shape_differences(
354
+ verifier["completeness"]["shape"], pred_shape)
355
+ assertion_results = []
356
+ for assertion in verifier.get("assertions") or []:
357
+ try:
358
+ actual = _atomic_get(pred, assertion["tokens"])
359
+ if assertion["operator"] == "abs_diff":
360
+ passed = abs(float(actual) - float(assertion["expected"])) <= float(
361
+ assertion.get("tolerance", 0.0))
362
+ elif assertion["operator"] == "path_eq":
363
+ passed = _path_equal(actual, assertion["expected"])
364
+ else:
365
+ passed = (actual is assertion["expected"] if
366
+ isinstance(assertion["expected"], bool) else
367
+ actual == assertion["expected"])
368
+ message = "" if passed else (
369
+ f"actual={actual!r} expected={assertion['expected']!r}")
370
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
371
+ actual, passed, message = None, False, f"lookup/compare failed: {exc}"
372
+ assertion_results.append({
373
+ "id": assertion["id"], "path": assertion["path"],
374
+ "operator": assertion["operator"], "expected": assertion["expected"],
375
+ "actual": actual, "passed": passed, "message": message})
376
+ passed_count = sum(item["passed"] for item in assertion_results)
377
+ ok = not shape_failures and passed_count == len(assertion_results)
378
+ return ok, {
379
+ "type": "atomic_json", "completeness_passed": not shape_failures,
380
+ "completeness_failures": shape_failures,
381
+ "assertions_passed": passed_count,
382
+ "assertions_total": len(assertion_results),
383
+ "assertion_pass_rate": (passed_count / len(assertion_results)
384
+ if assertion_results else 1.0),
385
+ "assertions": assertion_results,
386
+ }
387
+
388
+ if vtype == "findings_match":
389
+ family = verifier.get("family")
390
+ pred = _normalized_findings(solver_output, family)
391
+ gold = _normalized_findings(gt_answer, family)
392
+ ok = pred == gold
393
+ return ok, ("findings_match: pass" if ok else
394
+ f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
395
+
396
+ if vtype == "facts_match":
397
+ pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
398
+ ok = pred == gold
399
+ return ok, ("facts_match: pass" if ok else
400
+ f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
401
+
402
+ if vtype == "exact_match":
403
+ ok = _norm(solver_output) == _norm(gt_answer)
404
+ return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
405
+
406
+ if vtype == "numeric":
407
+ tol = verifier.get("tolerance") or 1e-6
408
+ pred = float(str(solver_output).strip().split()[0])
409
+ gold = float(gt_answer)
410
+ ok = abs(pred - gold) <= tol
411
+ return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
412
+
413
+ if vtype == "set_match":
414
+ pred = set(_as_list(solver_output))
415
+ gold = set(_as_list(gt_answer))
416
+ ok = pred == gold
417
+ return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
418
+
419
+ if vtype == "structured_match":
420
+ pred = _json_value(solver_output)
421
+ gold = _json_value(gt_answer)
422
+ if not isinstance(pred, dict) or not isinstance(gold, dict):
423
+ return False, "structured_match requires JSON objects"
424
+ missing = [f for f in verifier.get("required_fields", []) if f not in pred]
425
+ wrong = [f for f in verifier.get("required_fields", [])
426
+ if f in pred and f in gold and pred[f] != gold[f]]
427
+ ok = not missing and not wrong
428
+ return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
429
+
430
+ if vtype == "execution":
431
+ return False, "execution verifier is disabled in verified-first v2"
432
+
433
+ if vtype == "constraint":
434
+ fails = _check_constraints(verifier.get("criteria", []), solver_output)
435
+ return not fails, f"constraint: failed={fails[:5]}"
436
+
437
+ if vtype == "file_inspection":
438
+ fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
439
+ return not fails, f"file_inspection: failed={fails[:5]}"
440
+
441
+ return False, f"unknown verifier type: {vtype}"
442
+ except Exception as e:
443
+ return False, f"verifier error: {e}"
444
+
445
+
446
+ def _as_list(x):
447
+ if isinstance(x, list):
448
+ return [_norm(i) for i in x]
449
+ # 逗号/换行分隔的字符串
450
+ return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
451
+
452
+
453
+ def _check_constraints(criteria, solver_output):
454
+ """criteria: ["must contain X", "must be valid json", "length <= 500"]"""
455
+ fails = []
456
+ text = str(solver_output)
457
+ for c in criteria:
458
+ cl = c.lower()
459
+ if cl.startswith("must contain "):
460
+ needle = c[len("must contain "):]
461
+ if needle.lower() not in text.lower():
462
+ fails.append(c)
463
+ elif "valid json" in cl:
464
+ try:
465
+ json.loads(text)
466
+ except Exception:
467
+ fails.append(c)
468
+ elif cl.startswith("length <="):
469
+ limit = int(cl.split("<=")[1].strip())
470
+ if len(text) > limit:
471
+ fails.append(c)
472
+ else:
473
+ # Deterministic verifier DSL is closed-world: unknown checks fail.
474
+ fails.append(f"unsupported criterion: {c}")
475
+ return fails
476
+
477
+
478
+ def _inspect_files(expected, material_paths):
479
+ fails = []
480
+ paths = set(material_paths or [])
481
+ for e in expected:
482
+ fname = e.get("filename") if isinstance(e, dict) else str(e)
483
+ if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
484
+ fails.append(f"missing file: {fname}")
485
+ return fails
486
+
487
+
488
+ # ---------------- 自测 ----------------
489
+
490
+ def build_correct_solution(verifier, gt_answer, planted_info):
491
+ """由埋点/ground truth 直接构造正确解。"""
492
+ vtype = verifier.get("type")
493
+ if vtype == WORKSPACE_EVALUATOR:
494
+ return reference_bundle(verifier)
495
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
496
+ "set_match", "structured_match"):
497
+ return gt_answer
498
+ if vtype == "constraint":
499
+ parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
500
+ if c.lower().startswith("must contain ")]
501
+ return " ".join(parts) if parts else str(gt_answer)
502
+ # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
503
+ return None
504
+
505
+
506
+ def build_perturbed_solution(verifier, gt_answer, planted_info):
507
+ """破坏埋点构造扰动解。"""
508
+ vtype = verifier.get("type")
509
+ if vtype == WORKSPACE_EVALUATOR:
510
+ files = list(reference_bundle(verifier).get("files") or [])
511
+ return {"files": files[1:] if len(files) > 1 else []}
512
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
513
+ gold = _json_value(gt_answer)
514
+ if isinstance(gold, dict):
515
+ perturbed = dict(gold)
516
+ key = next(iter(perturbed), "__missing__")
517
+ if key in perturbed:
518
+ perturbed.pop(key)
519
+ else:
520
+ perturbed["__wrong__"] = True
521
+ return perturbed
522
+ if isinstance(gold, list):
523
+ return gold[:-1] if gold else ["__wrong__"]
524
+ return "__wrong__"
525
+ if vtype in ("exact_match", "numeric"):
526
+ return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
527
+ if vtype == "set_match":
528
+ gold = _as_list(gt_answer)
529
+ return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
530
+ if vtype == "structured_match":
531
+ fields = verifier.get("required_fields", [])
532
+ return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
533
+ if vtype == "constraint":
534
+ return "perturbed output lacking required content"
535
+ return None
536
+
537
+
538
+ def self_test(verifier, gt_answer, planted_info, material_paths):
539
+ """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
540
+
541
+ 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
542
+ 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
543
+ """
544
+ if verifier.get("type") == WORKSPACE_EVALUATOR:
545
+ return self_test_workspace_evaluator(verifier)
546
+ correct = build_correct_solution(verifier, gt_answer, planted_info)
547
+ perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
548
+ if correct is None or perturbed is None:
549
+ return False, (f"cannot self-test verifier type {verifier.get('type')} "
550
+ "(execution/file_inspection need real correct/perturbed solutions)")
551
+ ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
552
+ ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
553
+ passed = ok1 and not ok2
554
+ return passed, {"correct": d1, "perturbed": d2}
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/evaluator/repair_equivalences.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task-scoped semantic equivalences for the 112 legacy verifier repairs.
2
+
3
+ No solver, oracle label, historical score or answer hash influences comparison.
4
+ The original private rubric, completeness checks and binary aggregation remain.
5
+ """
6
+ from __future__ import annotations
7
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
8
+ import copy
9
+ import json
10
+ import re
11
+ import shlex
12
+ import shutil
13
+ import tempfile
14
+ from decimal import Decimal, InvalidOperation
15
+ from pathlib import Path
16
+
17
+
18
+ def argv(value):
19
+ if not isinstance(value, str):
20
+ return None
21
+ try:
22
+ result = shlex.split(value, posix=True)
23
+ except ValueError:
24
+ return None
25
+ # Only the Bash execution wrapper is transparent. command -v/-V are queries.
26
+ while len(result) > 1 and result[0] == 'command':
27
+ if result[1] == '--':
28
+ result = result[2:]
29
+ elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]):
30
+ break
31
+ else:
32
+ result = result[1:]
33
+ return result or None
34
+
35
+
36
+ def git_limit(tokens):
37
+ if not tokens or tokens[:2] != ['git', 'log']:
38
+ return tokens
39
+ out, index = [], 0
40
+ while index < len(tokens):
41
+ token = tokens[index]
42
+ compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token)
43
+ if compact:
44
+ out.append('--max-count=' + next(x for x in compact.groups() if x is not None))
45
+ elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit():
46
+ index += 1
47
+ out.append('--max-count=' + tokens[index])
48
+ else:
49
+ out.append(token)
50
+ index += 1
51
+ return out
52
+
53
+
54
+ def shell_equal(expected, actual, normalize_env=False):
55
+ wanted, found = argv(expected), argv(actual)
56
+ if normalize_env and wanted and found:
57
+ wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted]
58
+ found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found]
59
+ wanted, found = git_limit(wanted), git_limit(found)
60
+ if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]:
61
+ return False
62
+ for index, token in enumerate(wanted[1:], 1):
63
+ observed = found[index]
64
+ if observed == token:
65
+ continue
66
+ if (index == 1 and '/' in token and
67
+ observed.rstrip('/').endswith('/' + token.lstrip('./'))):
68
+ continue # Existing package-path anchoring; no changed basename/arguments.
69
+ return False
70
+ return True
71
+
72
+
73
+ def command_equal(expected, value):
74
+ # Response command questions ask for one invocation, with no extra commands.
75
+ return argv(expected) is not None and argv(expected) == argv(value)
76
+
77
+
78
+ def convex_equal(expected, value):
79
+ a, b = argv(expected), argv(value)
80
+ if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]:
81
+ return False
82
+ def no_duplicates(pairs):
83
+ result = {}
84
+ for k, v in pairs:
85
+ if k in result:
86
+ raise ValueError('duplicate JSON key')
87
+ result[k] = v
88
+ return result
89
+ try:
90
+ return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates)
91
+ except (ValueError, TypeError):
92
+ return False
93
+
94
+
95
+ def docker_network_equal(expected, value):
96
+ tokens = argv(value)
97
+ return tokens in (['--network', 'none'], ['--network=none'])
98
+
99
+
100
+ def zar_amount(value):
101
+ if not isinstance(value, str):
102
+ return None
103
+ m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I)
104
+ if not m:
105
+ return None
106
+ number = m.group(1)
107
+ if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number):
108
+ return None
109
+ try:
110
+ amount = Decimal(number.replace(',', ''))
111
+ except InvalidOperation:
112
+ return None
113
+ return amount * (Decimal(1000000) if m.group(2) else 1)
114
+
115
+
116
+ def zar_equal(expected, value):
117
+ return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value)
118
+
119
+
120
+ def rust_attribute_equal(expected, value):
121
+ return isinstance(value, str) and re.fullmatch(r'\s*#\s*\[\s*serde\s*\(\s*rename_all\s*=\s*"camelCase"\s*,?\s*\)\s*\]\s*', value) is not None
122
+
123
+
124
+ def header_equal(expected, value):
125
+ return isinstance(value, str) and value.casefold() == expected.casefold()
126
+
127
+
128
+ def zero_arg_js_equal(expected, value):
129
+ name = expected[:-2]
130
+ return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None
131
+
132
+
133
+ RESPONSE_RULES = {
134
+ '82e94ae96e04ff71_q1': {'q1': convex_equal},
135
+ 'df978907fa6f0eea_q1': {'q1': docker_network_equal},
136
+ 'dee0c878f5707477_q1': {'q1': command_equal},
137
+ 'c51259d0062454b2_q1': {'q1': command_equal},
138
+ 'd25a8956477141f2_q1': {'q2': zar_equal},
139
+ '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal},
140
+ 'a4926e403c8165e9_q1': {'q2': header_equal},
141
+ '2b3bd5786727f2fb_q1': {'q1': command_equal},
142
+ }
143
+
144
+
145
+ def dashboard_contract(evaluator, candidate, objective):
146
+ root = Path(candidate)
147
+ path = evaluator['reference_files'][0]['path']
148
+ try:
149
+ text = (root / path).read_text()
150
+ except (OSError, UnicodeError):
151
+ return False
152
+ lines = objective._shell_lines(text)
153
+ # Public contract explicitly says no other commands/flags. Single quotes
154
+ # would suppress environment expansion; only the correctly quoted form counts.
155
+ return (len(lines) == 2 and
156
+ re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and
157
+ re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None)
158
+
159
+
160
+ def install(task):
161
+ import objective_evaluators as objective
162
+ import verifiers
163
+ task_id = task['query_id']
164
+ original_verify = verifiers.verify
165
+ original_matcher = objective._shell_command_matches
166
+ objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1')
167
+
168
+ def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None):
169
+ if evaluator.get('type') == 'workspace_objective':
170
+ # A text occurrence after exit/return, in echo output or within a
171
+ # non-executed branch does not prove the requested command runs.
172
+ grouped = {}
173
+ for check in evaluator.get('checks', []):
174
+ if check.get('type') == 'shell_command':
175
+ grouped.setdefault(check['path'], []).append(check['value'])
176
+ for path, expected_commands in grouped.items():
177
+ try:
178
+ text = (Path(solver_output) / path).read_text()
179
+ invocations = objective.shell_invocations(text)
180
+ for expected_command in expected_commands:
181
+ tokens = argv(expected_command)
182
+ if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]):
183
+ continue # Required scalar assignment is checked by original rubric.
184
+ if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations):
185
+ return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command}
186
+ except (OSError, UnicodeError, ValueError):
187
+ return False, {'error': 'cannot inspect required shell artifact', 'path': path}
188
+ if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective):
189
+ return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'}
190
+ normalizations = []
191
+ if task_id in RESPONSE_RULES:
192
+ try:
193
+ predicted = verifiers._strict_json_value(solver_output)
194
+ gold = gt_answer
195
+ if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict):
196
+ for key, comparator in RESPONSE_RULES[task_id].items():
197
+ value = predicted['answers'].get(key)
198
+ expected = gold['answers'][key]
199
+ if value != expected and comparator(expected, value):
200
+ predicted['answers'][key] = expected
201
+ normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected})
202
+ solver_output = json.dumps(predicted)
203
+ except (KeyError, ValueError, TypeError):
204
+ pass # Preserve original malformed-answer rejection.
205
+ if task_id == '59f410a185c510f3_q1':
206
+ path = evaluator['reference_files'][0]['path']
207
+ try:
208
+ file_path = Path(solver_output) / path
209
+ predicted = json.loads(file_path.read_text())
210
+ expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact')
211
+ if isinstance(predicted, dict):
212
+ for widget in ('chart', 'banner'):
213
+ row = predicted.get(widget)
214
+ if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')):
215
+ if row.get('hydrate') != expected[widget]['hydrate']:
216
+ normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']})
217
+ row['hydrate'] = expected[widget]['hydrate']
218
+ if normalizations:
219
+ with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary:
220
+ view = Path(temporary) / 'candidate'
221
+ shutil.copytree(solver_output, view, symlinks=True)
222
+ copied = view / path
223
+ resolved = copied.resolve()
224
+ if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink():
225
+ return False, {'error': 'candidate output parent symlink escapes temporary comparison view'}
226
+ if copied.is_symlink():
227
+ copied.unlink() # Do not write through a frozen source symlink.
228
+ copied.write_text(json.dumps(predicted))
229
+ passed, details = original_verify(evaluator, gt_answer, str(view), material_paths)
230
+ if isinstance(details, dict):
231
+ details['equivalence_normalizations'] = normalizations
232
+ return passed, details
233
+ except (KeyError, ValueError, TypeError, OSError, UnicodeError):
234
+ pass
235
+ passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths)
236
+ if normalizations and isinstance(details, dict):
237
+ details['equivalence_normalizations'] = normalizations
238
+ return passed, details
239
+
240
+ verifiers.verify = repaired_verify
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/grading/verified_config.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "719eda04e56bf901_q1",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "repair_equivalences.py": "423dc6037c8c5011596b34545814987c7d12ee6bc67d83a68a84b8b3fb53a2d2",
8
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
9
+ "legacy-task.json": "2dc8f64a868a39c2b39a317d6488855927fafc8774effe592eb3b4a8fd043031",
10
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
11
+ "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d",
12
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
13
+ "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
14
+ "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
15
+ "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
16
+ "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a",
17
+ "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc",
18
+ "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b"
19
+ },
20
+ "runtime_requirements": {
21
+ "candidate_mode": "response",
22
+ "candidate_snapshot_copy_to_ephemeral_app": true,
23
+ "container_private_entry": "/grader/check.py",
24
+ "environment": {
25
+ "CANDIDATE_DIR": "/candidate",
26
+ "CANDIDATE_ROOT": "/candidate",
27
+ "MYBENCH_ANSWER": "/answer.txt",
28
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
29
+ "MYBENCH_CANDIDATE": "/candidate",
30
+ "MYBENCH_EPHEMERAL_APP": "1",
31
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1",
32
+ "MYBENCH_RUN_METADATA": "/run_metadata.json",
33
+ "MYBENCH_SOURCE_TASK": "/source",
34
+ "SOURCE_TASK_DIR": "/source"
35
+ },
36
+ "expected_check_ids": [
37
+ "0"
38
+ ],
39
+ "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
40
+ "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
41
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
42
+ "image_included": false,
43
+ "legacy_adapter": true,
44
+ "mounts_readonly": [
45
+ "/candidate",
46
+ "/source",
47
+ "/grader",
48
+ "/answer.txt"
49
+ ],
50
+ "network": "none",
51
+ "original_declared_resources": {
52
+ "agent": {
53
+ "basis": "advisory_not_measured",
54
+ "cpus": 2,
55
+ "memory_mib": 4096,
56
+ "timeout_sec": 1200
57
+ },
58
+ "oracle": {
59
+ "timeout_sec": 120
60
+ },
61
+ "source_agent": {
62
+ "command_timeout_sec": null,
63
+ "max_steps": null
64
+ },
65
+ "verifier": {
66
+ "cpus": 1,
67
+ "memory_mib": 1024,
68
+ "pids": 64,
69
+ "timeout_sec": 900,
70
+ "tmpfs_mib": 128
71
+ }
72
+ },
73
+ "private_entry": "evaluator/check.py",
74
+ "private_tree_environment_tokens": [
75
+ "MYBENCH_CANDIDATE_FILE",
76
+ "MYBENCH_OPEN_JUDGE_COMMAND",
77
+ "MYBENCH_OPEN_JUDGE_TIMEOUT",
78
+ "MYBENCH_TASK_JSON"
79
+ ],
80
+ "trusted_trace_environment_aliases": [
81
+ "MYBENCH_TOOL_TRAJECTORY",
82
+ "MYBENCH_TRUSTED_TRACE",
83
+ "TOOL_TRAJECTORY",
84
+ "TOOL_TRAJECTORY_FILE"
85
+ ],
86
+ "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
87
+ "working_directory": "/candidate",
88
+ "writable_ephemeral_roots": [
89
+ "/app",
90
+ "/workspace",
91
+ "/tmp"
92
+ ],
93
+ "criterion_weights": {
94
+ "0": 1
95
+ },
96
+ "grader_timeout_seconds": 600,
97
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair."
98
+ },
99
+ "engine": "portable_verified_v1"
100
+ }
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/instruction.md ADDED
@@ -0,0 +1 @@
 
 
1
+ I'm about to add a new command to our internal `cx` Rust CLI, which wraps Coralogix APIs, and I need to follow the repo's mandated conventions before writing code. Answer these from the project's established rules: q1: which command prints the full `cx` command tree as JSON? q2: which source file is the reference implementation for the DataPrime-based command archetype (give its path)? q3: which serde attribute is mandated on REST response types in the API layer? q4: in which file are the `Commands` enum variants and the dispatch match block a new command must be wired into (give its path)? Return exactly one JSON object replacing the placeholders with bare project values: {"answers":{"q1":"string","q2":"string","q3":"string","q4":"string"}}
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/skill/SKILL.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: add-command
3
+ description: Use this skill when the user asks to "add a command", "implement cx <something>", "new subcommand", "new CLI command", "add a new cx command", "create a command", "add subcommand", "implement a new command", "build a cx command", "wire up a new command", "extend the CLI", "add an API to cx", "new cx feature", "integrate a Coralogix API", or wants to add new functionality to the cx CLI. Use this even when the user describes a feature that implies a new command without saying "command" explicitly.
4
+ version: 0.1.0
5
+ metadata:
6
+ internal: true
7
+ ---
8
+
9
+ # Add a CLI Command
10
+
11
+ End-to-end workflow for adding a new command to `cx`. Every command falls into one of two archetypes - determine which one first, then follow the corresponding steps.
12
+
13
+ `docs/adding-a-command.md` has copy-pasteable code templates for every step below. Read it alongside this workflow.
14
+
15
+ ## Step 0: Understand What You're Building
16
+
17
+ Before writing any code, get clarity on the domain:
18
+
19
+ 1. **What Coralogix API are you wrapping?** Find the API docs or example responses. Understand the data model - what entities exist, what fields they have, what operations are supported.
20
+ 2. **What should the user be able to do?** List the subcommands (e.g., `list`, `get`, `create`) and what flags make sense.
21
+ 3. **Does this belong under a wrapper group?** The CLI organizes related commands into wrapper groups. Check if your command fits under an existing group before creating a top-level command:
22
+ - `cx alerts` - alert definitions + `schedulers`
23
+ - `cx notifications` - `connectors`, `routers`, `presets`, `test`
24
+ - `cx webhooks` - outgoing webhooks + `actions`
25
+ - `cx enrichments` - enrichment rules + `custom` enrichment tables
26
+ - `cx integrations` - integrations + `extensions`, `contextual-data`
27
+ - `cx iam` - `api-keys`, `roles`, `scopes`, `users`, `groups`, `ip-access`
28
+ Run `cx schema` to see the full command tree as JSON.
29
+ 4. **Which archetype fits?**
30
+
31
+ | Archetype | When to use | Reference implementation |
32
+ |-----------|------------|--------------------------|
33
+ | **A: DataPrime-based** | Querying logs, spans, or any DataPrime source | `src/commands/logs/mod.rs` |
34
+ | **B: REST-based** | Wrapping a Coralogix REST API (most new commands) | `src/commands/alerts/api.rs` + `src/commands/alerts/mod.rs` |
35
+
36
+ DataPrime commands delegate to a shared pipeline and require minimal code (~130 lines). REST commands build the full pipeline (API client, fan-out, merge, render) - more code but more control.
37
+
38
+ **Important:** All API integrations must use REST (HTTP). The CLI is HTTP-only by design - do not use gRPC.
39
+
40
+ ## Step 1: Read Reference Implementations
41
+
42
+ Before writing any code, read these files to internalize the existing patterns. This step is critical - agents that read existing code first produce implementations that are consistent with the codebase rather than inventing new patterns.
43
+
44
+ **Always read:**
45
+ - `src/main.rs` - study the `Commands` enum to see how variants are structured, and the `match cli.command` dispatch block to see where your new variant fits. Note which commands early-exit (no credentials needed) vs which go through the full config resolution flow. Pay attention to **wrapper groups** (e.g., `Notifications`, `Iam`, `Webhooks`, `Integrations`) - these are top-level commands with nested subcommand enums that group related domains. If your command belongs under an existing group, add a new variant to that group's subcommand enum rather than creating a top-level command.
46
+ - `src/commands/mod.rs` - see existing module registrations so you add yours in the right place
47
+ - `docs/adding-a-command.md` - full guide with code templates for both archetypes
48
+
49
+ **DataPrime archetype - also read:**
50
+ - `src/commands/logs/mod.rs` - a complete DataPrime command; notice how little code is needed because the shared pipeline does the heavy lifting
51
+ - `src/commands/dataprime/mod.rs` - the shared pipeline your command will delegate to; understand the `run_query()` signature and what it handles (fan-out, merge, spilling, agents output)
52
+
53
+ **REST archetype - also read:**
54
+ - `src/commands/alerts/api.rs` - see how response types are structured, how the API struct borrows `&CxClient`, how deserialization tests are written
55
+ - `src/commands/alerts/mod.rs` - see how the handler declares `pub mod api;` and imports types via `use api::{...};`
56
+ - `src/commands/dashboards/mod.rs` - see the fan-out/merge/render pattern using `render::*` helpers, and how all three output formats are handled
57
+
58
+ ## Step 2: Create API Layer (REST Only)
59
+
60
+ > Skip this step for DataPrime commands - they use the shared DataPrime pipeline.
61
+
62
+ Create `src/commands/<domain>/api.rs`. See `docs/adding-a-command.md` § "Archetype B, Step 1" for the full template.
63
+
64
+ Key conventions and why they matter:
65
+
66
+ - **`#[serde(rename_all = "camelCase")]`** on response types - Coralogix APIs use camelCase JSON keys
67
+ - **`#[serde(default)]` on `Vec` fields** - the API sometimes omits empty arrays entirely rather than sending `[]`, so this prevents deserialization failures
68
+ - **`Option<T>` for fields that may be absent** - be defensive, APIs evolve and fields vary across tiers
69
+ - **API struct borrows `&CxClient`** (don't own it) - the client is shared across the fan-out and must outlive individual API calls
70
+ - **`const BASE_PATH`** for the endpoint prefix - keeps URLs DRY
71
+ - **Deserialization tests are mandatory** - test both happy-path and edge cases (empty lists, missing optional fields) since these are the cases that break in production
72
+
73
+ ## Step 3: Create Command Module
74
+
75
+ Create `src/commands/<domain>/mod.rs`. For REST commands, declare `pub mod api;` at the top so the handler can `use api::{...};` types from its sibling `api.rs`. See `docs/adding-a-command.md` for full templates of both archetypes.
76
+
77
+ ### DataPrime archetype
78
+
79
+ Provide two things:
80
+ 1. A text renderer: `pub fn render_<domain>_text(merged: &MergedResults) -> Result<()>` - called only for `OutputFormat::Text`; JSON and Agents output are handled by the shared pipeline
81
+ 2. A thin `run()` wrapper that calls `super::dataprime::run_query()` with your DataPrime source name
82
+
83
+ ### REST archetype
84
+
85
+ Build the full fan-out/merge/render pipeline. Key patterns to understand:
86
+
87
+ - **`render::render_table`** for text output - pass column headers (without "Profile") and rows where the first element is the profile name. The helper conditionally includes the Profile column based on `include_profile`. No duplicate struct definitions needed.
88
+ - **`render::render_json`** for JSON output - pretty-prints a `&[Value]` array
89
+ - **`let include_profile = targets.len() > 1;`** - this single boolean controls all multi-profile behavior (Profile column in text, `"profile"` key in JSON)
90
+ - **Fan-out errors are non-fatal** - print to stderr and continue, because one misconfigured profile shouldn't block results from others
91
+ - **Status messages go to stderr** (`eprintln!`) - stdout is reserved for data so piped output isn't polluted
92
+ - **Agents output is command-owned** - each command calls `toon_encode` directly after any post-processing, because different commands may transform data differently before encoding
93
+
94
+ Register the module in `src/commands/mod.rs`.
95
+
96
+ ## Step 4: Wire into CLI
97
+
98
+ In `src/main.rs`, add three things. See `docs/adding-a-command.md` § "CLI Wiring" for templates.
99
+
100
+ 1. **`Commands` enum variant** - DataPrime commands use inline args; REST commands reference a subcommand enum
101
+ 2. **Subcommand enum** (REST only) - defines `List`, `Get`, etc.
102
+ 3. **Dispatch match arm** - inside the `match cli.command` block. Most commands go through the full config resolution flow; only commands that don't need credentials (like `profiles`, `cleanup`) early-exit.
103
+
104
+ ## Step 5: Add Tests
105
+
106
+ Every new command must add tests at three layers. See
107
+ `docs/adding-a-command.md` § "Testing" for code templates and examples
108
+ of each.
109
+
110
+ | Layer | Location | What it verifies |
111
+ |-------|----------|------------------|
112
+ | Unit | `src/**/<file>.rs` `#[cfg(test)]` | Pure logic - deserialization (mandatory for REST), helpers, transforms |
113
+ | Integration | `tests/<command>/main.rs` (wiremock) | Command runner end-to-end with mocked HTTP |
114
+ | E2E | `tests/e2e/<command>/mod.rs` (assert_cmd, `#[ignore]`d) | Real `cx` binary against the Coralogix test team |
115
+
116
+ Things specific to *this workflow* that the doc doesn't emphasise:
117
+
118
+ - **Don't add e2e for mutating commands** (create/delete/enable/disable)
119
+ unless there's a paired-undo plan - they touch shared test team state.
120
+ Mark them as deliberately uncovered with a comment, like
121
+ `tests/e2e/alerts/mod.rs`.
122
+ - **If a subcommand needs an ID from the test team** (e.g. `get <id>`),
123
+ add a local `discover_*` fn in your e2e test module, modelled after
124
+ `discover_alert_id` in `tests/e2e/alerts/mod.rs`. Cache via `OnceLock`
125
+ and skip gracefully when the test team has no data - don't panic.
126
+ - **Don't forget to declare the new e2e module** in `tests/e2e.rs` via
127
+ `#[path = "e2e/your_domain/mod.rs"] mod your_domain;`.
128
+
129
+ ## Step 6: Create User-Facing Skill
130
+
131
+ Every command needs a corresponding skill in `skills/` so AI agents know how to use it. Use the **add-skill** workflow to create it - it walks through the full process including reading reference implementations, writing effective trigger descriptions, and verification.
132
+
133
+ ## Step 7: Verify
134
+
135
+ Run `cargo build`, `cargo test` (unit + integration), `cargo clippy`,
136
+ and `cargo fmt --check`. Fix any issues before committing.
137
+
138
+ If you have test team credentials configured, also run the e2e suite:
139
+ ```bash
140
+ cargo test --test e2e -- --ignored --test-threads=1
141
+ ```
142
+
143
+ Smoke test all three output formats (`text`, `json`, `agents`) and
144
+ multi-profile (`-p profile1 -p profile2`).
145
+
146
+ See `docs/adding-a-command.md` § "PR Checklist" for the full checklist to include in your PR description.
benchmarks/skillbench-venus-e/tasks/719eda04e56bf901_q1/task.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "719eda04e56bf901",
4
+ "query_id": "719eda04e56bf901_q1",
5
+ "environment": {
6
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
7
+ "network": "none"
8
+ },
9
+ "outputs": [],
10
+ "success_criteria": [
11
+ "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json."
12
+ ],
13
+ "evaluation": {
14
+ "kind": "python",
15
+ "type": "verified"
16
+ },
17
+ "workspace": {
18
+ "input_mappings": [],
19
+ "skill_packages": [
20
+ {
21
+ "content_hash": "781d32b8af0458874e7ba53526a718b3c87f97f37c124d2277ec5b8a01586c1f",
22
+ "name": "add-command",
23
+ "package_path": "skill",
24
+ "install_name": "add-command-3fea8b2f"
25
+ }
26
+ ],
27
+ "default_skill_target": ".claude/skills",
28
+ "candidate_mode": "response"
29
+ },
30
+ "source_skill": {
31
+ "sha256": "781d32b8af0458874e7ba53526a718b3c87f97f37c124d2277ec5b8a01586c1f",
32
+ "files": {
33
+ "SKILL.md": "03522f37b6520e695936a99ae17e3d545528edd7281dc3e3a426778531613786"
34
+ }
35
+ },
36
+ "migration": {
37
+ "source_schema": "mybench-portable-task-v2",
38
+ "legacy_task_json": "provenance/legacy-package/task.json",
39
+ "historical_gain_protocol": "legacy; not Harbor certified",
40
+ "reference_available": true,
41
+ "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task",
42
+ "original_skill_content_hashes": [
43
+ "3fea8b2f5df5eeb86d0c3bcc3e7615926dd528a3d4a55fda1f80e8ec857fb259"
44
+ ]
45
+ }
46
+ }
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_contract.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expected_check_ids": [
3
+ "0",
4
+ "1",
5
+ "2",
6
+ "3",
7
+ "4",
8
+ "5",
9
+ "6",
10
+ "7",
11
+ "8",
12
+ "9"
13
+ ],
14
+ "criterion_weights": {
15
+ "0": 1,
16
+ "1": 1,
17
+ "2": 1,
18
+ "3": 1,
19
+ "4": 1,
20
+ "5": 1,
21
+ "6": 1,
22
+ "7": 1,
23
+ "8": 1,
24
+ "9": 1
25
+ }
26
+ }
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_entry.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable result protocol; candidate failures and evaluator errors stay distinct."""
2
+ from pathlib import Path
3
+ import contextlib,io,json,runpy,sys
4
+ from auto_policy import install,finalize
5
+ HERE=Path(__file__).resolve().parent
6
+
7
+ def main():
8
+ captured=io.StringIO()
9
+ try:
10
+ install()
11
+ with contextlib.redirect_stdout(captured):
12
+ try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
13
+ except SystemExit as error:
14
+ if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
15
+ body=None
16
+ for line in reversed(captured.getvalue().splitlines()):
17
+ try:value=json.loads(line)
18
+ except(ValueError,TypeError):continue
19
+ if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
20
+ if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
21
+ if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
22
+ cfgfile=HERE/'auto_policy.json'
23
+ if cfgfile.is_file():
24
+ cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
25
+ if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
26
+ checks=body['checks']
27
+ if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
28
+ ids=[str(c['id'])for c in checks]
29
+ if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
30
+ contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
31
+ if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
32
+ weights=contract['criterion_weights']
33
+ body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
34
+ print(json.dumps(body,ensure_ascii=True));return 0
35
+ except Exception as error:
36
+ print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
37
+
38
+ if __name__=='__main__':raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "stdlib_only": true,
3
+ "forbid_network": true,
4
+ "forbid_subprocess": false,
5
+ "forbid_native": true,
6
+ "owner_ids": [
7
+ "0"
8
+ ],
9
+ "require_execution": true,
10
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
11
+ "execution_budget_seconds": 60,
12
+ "runtime_owner_ids": [
13
+ "0"
14
+ ],
15
+ "total_evaluation_budget_seconds": 420
16
+ }
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted bounded-invocation policy; never infer whole-program properties."""
2
+ from pathlib import Path
3
+ import hashlib,json,os,subprocess,sys,tempfile,time,uuid
4
+
5
+ HERE=Path(__file__).resolve().parent
6
+ ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
7
+ DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
8
+ class PolicyInfrastructureError(RuntimeError): pass
9
+ _installed=False
10
+ _original_popen=subprocess.Popen
11
+ _original_run=subprocess.run
12
+
13
+ def _config():
14
+ p=HERE/'auto_policy.json'
15
+ if not p.is_file():return None
16
+ value=json.loads(p.read_text())
17
+ if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
18
+ return value
19
+
20
+ def _folder():
21
+ if ENV not in os.environ:
22
+ os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
23
+ p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
24
+
25
+ def _python_target(command,cwd):
26
+ if not isinstance(command,(list,tuple))or not command:return None
27
+ argv=[os.fspath(x)for x in command]
28
+ if 'python'not in Path(argv[0]).name.lower():return None
29
+ i=1;flags=[]
30
+ while i<len(argv)and argv[i].startswith('-'):
31
+ flag=argv[i]
32
+ if flag=='-m':
33
+ if i+1>=len(argv):return None
34
+ name=argv[i+1];p=Path(cwd)/name.replace('.','/')
35
+ if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
36
+ return argv[0],flags,'module',name,argv[i+2:]
37
+ if flag in ['-c','-']:return None
38
+ flags.append(flag);i+=1
39
+ if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
40
+ if i>=len(argv)or not argv[i].endswith('.py'):return None
41
+ path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
42
+ path=path.resolve()
43
+ if path==HERE or HERE in path.parents:
44
+ if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
45
+ for value in argv[i+1:]:
46
+ if not value.endswith('.py')or value.startswith('-'):continue
47
+ subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
48
+ subject=subject.resolve()
49
+ if HERE not in subject.parents:
50
+ return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
51
+ return None
52
+ return argv[0],flags,'script',str(path),argv[i+1:]
53
+
54
+ def install():
55
+ global _installed
56
+ if _installed:return
57
+ _installed=True
58
+ cfg=_config()
59
+ if cfg is None:return
60
+ _folder()
61
+ os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
62
+ class GuardedPopen(_original_popen):
63
+ def __init__(self,args,*pos,**kwargs):
64
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
65
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
66
+ receipt=None
67
+ if target:
68
+ executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
69
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
70
+ if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
71
+ args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
72
+ env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
73
+ if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
74
+ try:super().__init__(args,*pos,**kwargs)
75
+ except OSError as error:
76
+ if receipt:
77
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
78
+ raise
79
+ subprocess.Popen=GuardedPopen
80
+ def bounded_run(*pos,**kwargs):
81
+ command=pos[0]if pos else kwargs.get('args')
82
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
83
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
84
+ if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
85
+ if target is not None and cfg.get('execution_budget_seconds')is not None:
86
+ budget=cfg['execution_budget_seconds']
87
+ if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
88
+ kwargs['timeout']=budget
89
+ remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
90
+ if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
91
+ try:
92
+ if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
93
+ result=_original_run(*pos,**kwargs)
94
+ if target is not None and result.returncode<0:
95
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
96
+ return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
97
+ return result
98
+ except subprocess.TimeoutExpired as error:
99
+ if target is None:raise
100
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
101
+ textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
102
+ empty=''if textual else b''
103
+ def output(value):
104
+ if value is None:return empty
105
+ return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
106
+ return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
107
+ subprocess.run=bounded_run
108
+
109
+ def status(require_execution=True):
110
+ install();p=_folder();rows=[]
111
+ for receipt in sorted(p.glob('*.json')):
112
+ try:row=json.loads(receipt.read_text())
113
+ except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
114
+ if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
115
+ raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
116
+ rows.append(row)
117
+ if require_execution and not any(r.get('target_present')for r in rows):return False
118
+ return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
119
+
120
+ def finalize(body,owner_ids,require_execution=True):
121
+ observed=status(require_execution=require_execution)
122
+ wanted=set(map(str,owner_ids))
123
+ for row in body.get('checks',[]):
124
+ if str(row['id'])in wanted:
125
+ if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
126
+ row['passed']=row['passed']and observed
127
+ row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
128
+ body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
129
+ body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
130
+ return body
131
+
132
+ def run(*args,**kwargs):
133
+ install();return subprocess.run(*args,**kwargs)
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/auto_policy_guard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child-side observer for the exact public bounded-invocation policy."""
2
+ from pathlib import Path
3
+ import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
4
+
5
+ receipt,config_file,kind,target,*arguments=sys.argv[1:]
6
+ subject=arguments.pop(0)if kind=='probe'else target
7
+ subject_filename=os.path.abspath(subject)
8
+ receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
9
+ local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
10
+ if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
11
+ if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
12
+ candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
13
+ observer_filename=__file__
14
+ stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
15
+ stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
16
+ if not getattr(sys,'stdlib_module_names',None):
17
+ for p in stdlib_root.iterdir():
18
+ if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
19
+ state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
20
+ busy=False
21
+ def save():
22
+ global busy
23
+ was=busy;busy=True
24
+ try:
25
+ temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
26
+ finally:busy=was
27
+ def violation(code,detail):
28
+ state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
29
+ def local_module(name):
30
+ first=name.partition('.')[0]
31
+ roots=list(local_roots)
32
+ for value in sys.path:
33
+ try:p=Path(value or cwd).resolve()
34
+ except (OSError,TypeError,ValueError):continue
35
+ if any(p==r or r in p.parents for r in local_roots):roots.append(p)
36
+ return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
37
+ def subject_active():
38
+ if kind!='probe':return True
39
+ frame=sys._getframe(1)
40
+ while frame:
41
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
42
+ if isinstance(filename,str):
43
+ absolute=os.path.abspath(filename)
44
+ if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
45
+ frame=frame.f_back
46
+ return False
47
+ def audit(event,args):
48
+ relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
49
+ if busy or not relevant or not subject_active():return
50
+ if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
51
+ check_import(str(args[0]))
52
+ if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
53
+ if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
54
+ if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
55
+ def check_import(name):
56
+ if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
57
+ base=name.partition('.')[0]
58
+ if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
59
+ def import_requested_by_candidate():
60
+ frame=sys._getframe(1)
61
+ while frame:
62
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
63
+ if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
64
+ absolute=os.path.abspath(filename)
65
+ return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
66
+ return False
67
+ original_import=builtins.__import__;original_import_module=importlib.import_module
68
+ def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
69
+ if not busy and subject_active()and import_requested_by_candidate():
70
+ absolute=name
71
+ if level:
72
+ package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
73
+ try:absolute=importlib.util.resolve_name('.'*level+name,package)
74
+ except(ImportError,ValueError):absolute=name
75
+ check_import(absolute)
76
+ return original_import(name,globals,locals,fromlist,level)
77
+ def bounded_import_module(name,package=None):
78
+ if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
79
+ return original_import_module(name,package)
80
+ save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
81
+ @atexit.register
82
+ def finish():state['state']='finished';save()
83
+ for p in reversed(local_roots):sys.path.insert(0,str(p))
84
+ sys.argv=[target,*arguments]
85
+ if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
86
+ else:runpy.run_path(target,run_name='__main__')
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """R10 independent, varying recon inputs; one fixed program must solve all."""
2
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
3
+ import copy,json,re,shutil,subprocess,sys,tempfile,math
4
+ from pathlib import Path
5
+ from collections import Counter
6
+ from r10_support import dependency,tri
7
+ CANDIDATE=Path('/candidate')
8
+ PORT_W={23:9.5,27017:9.5,6379:9.0,445:9.0,22:8.0,3389:8.5,3306:9.0,5432:8.5,21:7.5,161:7.0,8080:5.0,8443:5.0,8888:5.0,25:5.5,53:5.0,80:2.5,443:3.0}
9
+ SEV={"critical":10,"high":7,"medium":4,"low":2}
10
+ TECH={"struts":8.0,"phpmyadmin":8.0,"weblogic":7.0,"jenkins":7.0,"tomcat":6.0,"php":5.0,"apache":4.0,"nginx":3.0,"node.js":3.0}
11
+ DBP={3306,5432,1433,6379,27017}
12
+ FP={21,445}
13
+ FROZEN_INPUTS = {'asset_inventory.json': '{"assets": [{"hostname": "app.example.com", "ip": "198.51.100.10", "ports": [443, 80], "technologies": ["nginx"], "http": {"status_code": 200, "title": "Corporate Portal", "cdn": false, "https": true}, "sensitive_indicator": false, "vulnerabilities": [{"cve": "CVE-2023-1234", "severity": "medium"}]}, {"hostname": "admin.example.com", "ip": "198.51.100.11", "ports": [443, 8080], "technologies": ["Tomcat", "PHP"], "http": {"status_code": 200, "title": "Admin Dashboard", "cdn": false, "https": true}, "sensitive_indicator": true, "vulnerabilities": [{"cve": "CVE-2022-22965", "severity": "critical"}]}, {"hostname": "dev.example.com", "ip": "203.0.113.99", "ports": [80], "technologies": ["PHP"], "http": {"status_code": 200, "title": "Dev Sandbox", "cdn": false, "https": false}, "sensitive_indicator": false, "vulnerabilities": []}, {"hostname": "db.example.com", "ip": "198.51.100.20", "ports": [3306, 6379, 22], "technologies": [], "http": null, "sensitive_indicator": true, "vulnerabilities": [{"cve": "CVE-2023-9999", "severity": "high"}, {"cve": "CVE-2024-1111", "severity": "low"}]}, {"hostname": "api.example.com", "ip": "198.51.100.30", "ports": [443], "technologies": ["Node.js"], "http": {"status_code": 403, "title": "API Gateway", "cdn": true, "https": true}, "sensitive_indicator": false, "vulnerabilities": []}, {"hostname": "legacy.example.com", "ip": "198.51.100.40", "ports": [23, 21, 445], "technologies": ["Jenkins"], "http": null, "sensitive_indicator": false, "vulnerabilities": []}]}', 'dns_data.json': '{"domain": "example.com", "wildcard_probe": {"subdomain": "doesnotexist-abcxyz.example.com", "resolved": true, "ip": "203.0.113.99"}, "nameservers": [{"host": "ns1.example.com", "axfr_external_allowed": true}, {"host": "ns2.example.com", "axfr_external_allowed": false}]}', 'subdomains.txt': 'app.example.com\nadmin.example.com\ndev.example.com\ndb.example.com\napi.example.com\nlegacy.example.com\nstaging.example.com\nrandom-abc123.example.com', 'repo_history.txt': 'commit a1b2c3\nAuthor: dev@example.com\nDate: Mon Jan 6 2025\n add deployment config\n+database_password = "Sup3rS3cret!"\n+region = us-east-1\n\ncommit d4e5f6\nAuthor: ops@example.com\nDate: Tue Jan 7 2025\n fix ci\n+api_key = "AKIAIOSFODNN7EXAMPLE"\n+token = "ghp_abc123def456"\n+timeout = 30'}
14
+
15
+ def clamp(x): return max(0,min(100,x))
16
+
17
+ def comps(a):
18
+ ports=a["ports"]
19
+ ws=[PORT_W.get(p,4.0) for p in ports]
20
+ ps=min(100,(sum(ws)/len(ws))*10*math.log2(len(ports)+1)) if ports else 0.0
21
+ vs=min(100,sum(SEV[v["severity"]] for v in a["vulnerabilities"])*math.log2(len(a["vulnerabilities"])+1)) if a["vulnerabilities"] else 0.0
22
+ tv=[TECH[t.lower()] for t in a["technologies"] if t.lower() in TECH]
23
+ ts=max(tv) if tv else 10.0
24
+ h=a["http"]; e=50
25
+ if h:
26
+ if (not h.get("https")) and 443 not in ports: e+=15
27
+ if h.get("cdn"): e-=20
28
+ if h.get("status_code") in (401,403): e-=25
29
+ # Hostname evidence is independent of whether HTTP fingerprinting exists.
30
+ blob=(str((h or {}).get("title",""))+" "+a["hostname"]).lower()
31
+ if any(k in blob for k in ("admin","login","dashboard","manage")): e+=20
32
+ e=clamp(e)
33
+ d=0
34
+ for p in ports:
35
+ if p in DBP: d+=20
36
+ if p in FP: d+=15
37
+ if a["sensitive_indicator"]: d+=15
38
+ d=clamp(d)
39
+ final=round(0.25*ps+0.30*vs+0.15*ts+0.15*e+0.15*d,1)
40
+ return ps,vs,ts,e,d,final
41
+
42
+ def band(s):
43
+ return "CRITICAL" if s>=80 else "HIGH" if s>=60 else "MEDIUM" if s>=40 else "LOW" if s>=20 else "INFORMATIONAL"
44
+
45
+ def prio(r): return "Critical" if r in ("CRITICAL","HIGH") else "Medium" if r=="MEDIUM" else "Low"
46
+
47
+ def expected_inputs(inputs):
48
+ inventory=json.loads(inputs['asset_inventory.json'])['assets'];dns=json.loads(inputs['dns_data.json']);probe=dns['wildcard_probe'];wild=probe.get('ip')if probe.get('resolved')else None
49
+ filtered=[a['hostname']for a in inventory if wild is not None and a['ip']==wild];assets={}
50
+ for a in inventory:
51
+ if a['hostname']in filtered:continue
52
+ score=comps(a)[-1];risk=band(score)
53
+ assets[a['hostname']]={'ip':a['ip'],'ports':sorted(a['ports']),'score':score,'risk':risk,'prio':prio(risk)}
54
+ leaks=[]
55
+ for line in inputs['repo_history.txt'].splitlines():
56
+ match=re.search(r'\b([A-Za-z_]\w*(?:password|api_key|secret|token)\w*|password|api_key|secret|token)\s*=\s*[\"\']?([^\"\'\s]+)',line,re.I)
57
+ if match:leaks.append((match[1],match[2]))
58
+ return inventory,wild,filtered,assets,any(x.get('axfr_external_allowed')is True for x in dns.get('nameservers',[])),leaks
59
+ def assess(rep,inputs):
60
+ inventory,wild,filtered,expected,axfr,leaks=expected_inputs(inputs)
61
+ if not isinstance(rep,dict):return[False]*10
62
+ rows=rep.get('assets');names=[x.get('hostname')for x in rows if isinstance(x,dict)]if isinstance(rows,list)else[]
63
+ fields={'hostname','ip','ports','exposure_score','risk_level','priority'}
64
+ good=isinstance(rows,list)and len(rows)==len(expected)and all(isinstance(x,dict)and fields<=set(x)for x in rows)and all(isinstance(x,str)for x in names)and len(set(names))==len(names)and set(names)==set(expected)
65
+ actual={x['hostname']:x for x in rows}if good else{}
66
+ def strings(value,want):return isinstance(value,list)and all(isinstance(x,str)for x in value)and Counter(value)==Counter(want)
67
+ def record(name):
68
+ if name not in expected:return name not in actual
69
+ a=actual.get(name,{});e=expected[name];score=a.get('exposure_score')
70
+ try:return a.get('ip')==e['ip']and isinstance(a.get('ports'),list)and all(type(port)in(int,float)and(type(port)is int or math.isfinite(port))for port in a['ports'])and Counter(a['ports'])==Counter(e['ports'])and type(score)in(int,float)and abs(score-e['score'])<1e-8
71
+ except OverflowError:return False
72
+ op=rep.get('opsec_findings');op=op if isinstance(op,dict)else{}
73
+ groups=[[inventory[i]['hostname']for i in group if i<len(inventory)]for group in[[3],[5,0],[4,1]]]
74
+ ranked=sorted(expected,key=lambda name:(-expected[name]['score'],name))
75
+ observed_leaks=op.get('leaked_credentials');leak_ok=isinstance(observed_leaks,list)and all(isinstance(x,dict)and isinstance(x.get('key'),str)and isinstance(x.get('value'),str)for x in observed_leaks)
76
+ return[good and {'wildcard_ip','filtered_out','assets','ranked_entry_points','opsec_findings'}<=set(rep),rep.get('wildcard_ip')==wild and strings(rep.get('filtered_out'),filtered),*[all(record(n)for n in group)for group in groups],good and all(actual[n].get('risk_level')==e['risk']and actual[n].get('priority')==e['prio']for n,e in expected.items()),rep.get('ranked_entry_points')==ranked and all(record(n)for n in expected),strings(op.get('exposed_nonprod'),[n for n in expected if any(k in n.lower()for k in['dev','staging','test','uat'])]),type(op.get('dns_axfr_exposed'))is bool and op['dns_axfr_exposed']==axfr,leak_ok and Counter((x['key'],x['value'])for x in observed_leaks)==Counter(leaks)]
77
+ def panels():
78
+ yield FROZEN_INPUTS
79
+ for mode in[1,2]:
80
+ inputs=dict(FROZEN_INPUTS);inventory=json.loads(inputs['asset_inventory.json']);dns=json.loads(inputs['dns_data.json'])
81
+ for i,a in enumerate(inventory['assets']):
82
+ a['hostname']=('ADMIN-db-'if i==3 else'uat-'if i%2 else'node-')+str(i)+'.fresh.invalid';a['ip']='198.18.0.'+str(i+1)
83
+ if mode==1:a['ports']=[53,1433,9999]if i%2 else[];a['vulnerabilities']=[];a['technologies']=[];a['http']=None;a['sensitive_indicator']=False
84
+ else:a['ports']=[23,27017,6379,445,3306,5432,21,22];a['vulnerabilities']=[{'cve':'CVE-X-'+str(k),'severity':'critical'}for k in range(35)];a['technologies']=['STRUTS'];a['sensitive_indicator']=True
85
+ dns['wildcard_probe'].update(resolved=mode==2,ip='198.18.0.2');dns['nameservers']=[{'host':'ns.fresh.invalid','axfr_external_allowed':False}]
86
+ inputs['asset_inventory.json']=json.dumps(inventory);inputs['dns_data.json']=json.dumps(dns);inputs['subdomains.txt']='\n'.join(a['hostname']for a in inventory['assets']);inputs['repo_history.txt']='+service_secret = "fresh-value-219"\n+token = "changed-token"\n'
87
+ yield inputs
88
+ def main():
89
+ try:saved=json.loads((CANDIDATE/'report.json').read_text())
90
+ except(OSError,ValueError):saved=None
91
+ delivered=assess(saved,FROZEN_INPUTS);choices=[]
92
+ entries=sorted(p for p in CANDIDATE.rglob('*.py')if not any(x in p.parts for x in['skill','skills','.git','.venv','__pycache__']))
93
+ for entry in entries:
94
+ dep=dependency(CANDIDATE,str(entry.relative_to(CANDIDATE)));bits=list(delivered)
95
+ for inputs in panels():
96
+ with tempfile.TemporaryDirectory(prefix='triage-r10-')as td:
97
+ root=Path(td)/'work';shutil.copytree(CANDIDATE,root,symlinks=True)
98
+ report=root/'report.json'
99
+ if report.is_symlink()or report.is_file():report.unlink()
100
+ elif report.is_dir():shutil.rmtree(report)
101
+ for name,text in inputs.items():(root/name).write_text(text)
102
+ try:p=subprocess.run([sys.executable,'-B','-S',str(entry.relative_to(CANDIDATE))],cwd=root,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=35);rep=json.loads(report.read_text())if p.returncode==0 else None
103
+ except(OSError,ValueError,subprocess.SubprocessError):rep=None
104
+ current=assess(rep,inputs)
105
+ bits=[tri([a,b])for a,b in zip(bits,current)]
106
+ bits[0]=tri([bits[0],dep]);choices.append(bits)
107
+ bits=max(choices,key=lambda x:(sum(v is True for v in x),-sum(v is False for v in x)))if choices else[False]*10
108
+ print(json.dumps({'scoreable':None not in bits,'checks':[dict(id=str(i),passed=v,reason='R10 original delivery and three independent renamed/risk/false-wildcard/AXFR/nonprod/leak panels, fixed entry point')for i,v in enumerate(bits)]}))
109
+ if __name__=='__main__':main()
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/dependency_scan.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private static dependency validation, including local Python namespace packages.
2
+
3
+ This module only parses source. It never imports or runs candidate modules.
4
+ """
5
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
6
+ import _imp
7
+ import ast
8
+ import sys
9
+ import tokenize
10
+ from pathlib import Path
11
+
12
+
13
+ def scan_stdlib(root, entries, external=()):
14
+ return True, [], 'Deferred to public bounded runtime policy; no whole-source inference'
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/evaluator/r10_support.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluator-only workspace and dependency helpers; candidate execution is external."""
2
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
3
+ from pathlib import Path
4
+ import shutil,json
5
+ from dependency_scan import scan_stdlib
6
+
7
+ def tri(values):
8
+ values=list(values)
9
+ return False if any(v is False for v in values) else None if any(v is None for v in values) else True
10
+
11
+ def dependency(root,entry):
12
+ return True
13
+
14
+ def copy_modules(root,destination):
15
+ """Copy the complete authored module/package tree without frozen outputs."""
16
+ root=Path(root);destination=Path(destination);public=set()
17
+ # Supplied Python project files are data, not authored helper modules. Their
18
+ # old contents must never leak into a changed/clean public-input panel.
19
+ try:
20
+ spec=json.loads(Path('/source/task.json').read_text())
21
+ for mapping in spec.get('workspace',{}).get('input_mappings',[]):
22
+ source=Path('/source')/mapping['source'];target=Path(mapping['workspace_target'])
23
+ if source.is_file():public.add(target.as_posix())
24
+ elif source.is_dir():public.update((target/p.relative_to(source)).as_posix()for p in source.rglob('*')if p.is_file())
25
+ except (OSError,ValueError,KeyError):pass
26
+ for src in root.rglob('*'):
27
+ if any(x in src.relative_to(root).parts for x in ['__pycache__','.git','.venv','skill','skills','inputs']):continue
28
+ if not src.is_file() or src.suffix not in ('.py','.pyi') or src.relative_to(root).as_posix()in public:continue
29
+ target=destination/src.relative_to(root)
30
+ if src.resolve()==target.resolve():continue
31
+ target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,target)
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/grading/verified_config.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "74f2ef23fbf581f82a581256",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
8
+ "auto_policy.json": "f245803a06b801617e2ec10e3bf5d2705663cbbcecbb21fff72555eaa9796161",
9
+ "r10_support.py": "87ed18e23d36f87a4a489f274f98ab474ba09d5e40f6a0521b5507e1ca880b96",
10
+ "dependency_scan.py": "aff23360095bcb8289ad65e861c5fe29ae8b9c355ae7cab23f306d1e20c81f67",
11
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
12
+ "autograde_task_check.py": "71e349f4b2ca6bcc1f444a9234b2fff57ab20fce942129cae52280dc00b63311",
13
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
14
+ "auto_contract.json": "5d4ae92114b3624c943c104e899595f0c91c1ca2d906fc23db00ac88445a5f4b"
15
+ },
16
+ "runtime_requirements": {
17
+ "family": "verified_multi10_public_contract",
18
+ "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
19
+ "network": "none",
20
+ "read_only_mounts": [
21
+ "task:/source",
22
+ "task:/task",
23
+ "evaluator:/grader",
24
+ "candidate:/candidate",
25
+ "answer:/answer.txt"
26
+ ],
27
+ "writable_tmpfs": [
28
+ "/app",
29
+ "/workspace",
30
+ "/tmp"
31
+ ],
32
+ "copy_completed_candidate_children_to_app_before_grader": true,
33
+ "entrypoint": [
34
+ "python3",
35
+ "/grader/check.py"
36
+ ],
37
+ "working_directory": "/candidate",
38
+ "environment": {
39
+ "MYBENCH_CANDIDATE": "/candidate",
40
+ "MYBENCH_CANDIDATE_PATH": "/candidate",
41
+ "CANDIDATE_DIR": "/candidate",
42
+ "CANDIDATE_ROOT": "/candidate",
43
+ "MYBENCH_SOURCE_TASK": "/source",
44
+ "SOURCE_TASK_DIR": "/source",
45
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
46
+ "MYBENCH_EPHEMERAL_APP": "1",
47
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1"
48
+ },
49
+ "environment_names_detected": [
50
+ "MYBENCH_CANDIDATE"
51
+ ],
52
+ "expected_check_ids": [
53
+ "0",
54
+ "1",
55
+ "2",
56
+ "3",
57
+ "4",
58
+ "5",
59
+ "6",
60
+ "7",
61
+ "8",
62
+ "9"
63
+ ],
64
+ "criterion_count": 10,
65
+ "criterion_weights": {
66
+ "0": 1,
67
+ "1": 1,
68
+ "2": 1,
69
+ "3": 1,
70
+ "4": 1,
71
+ "5": 1,
72
+ "6": 1,
73
+ "7": 1,
74
+ "8": 1,
75
+ "9": 1
76
+ },
77
+ "actual_original_success_criteria_count": 10,
78
+ "original_task_metadata_must_not_define_override_criterion_count": false,
79
+ "requires_external_actual_native_trace": false,
80
+ "requires_external_trusted_snapshot_binding": false,
81
+ "fresh_native_binding_must_not_require_historical_run_id": true,
82
+ "checker_can_execute_candidate_subprocesses": true,
83
+ "host_execution_forbidden": true,
84
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.",
85
+ "docker_image_payload_in_source_tree": false,
86
+ "runtime_missing": [],
87
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
88
+ "grader_timeout_seconds": 600
89
+ },
90
+ "engine": "portable_verified_v1"
91
+ }
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/asset_inventory.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"assets": [{"hostname": "app.example.com", "ip": "198.51.100.10", "ports": [443, 80], "technologies": ["nginx"], "http": {"status_code": 200, "title": "Corporate Portal", "cdn": false, "https": true}, "sensitive_indicator": false, "vulnerabilities": [{"cve": "CVE-2023-1234", "severity": "medium"}]}, {"hostname": "admin.example.com", "ip": "198.51.100.11", "ports": [443, 8080], "technologies": ["Tomcat", "PHP"], "http": {"status_code": 200, "title": "Admin Dashboard", "cdn": false, "https": true}, "sensitive_indicator": true, "vulnerabilities": [{"cve": "CVE-2022-22965", "severity": "critical"}]}, {"hostname": "dev.example.com", "ip": "203.0.113.99", "ports": [80], "technologies": ["PHP"], "http": {"status_code": 200, "title": "Dev Sandbox", "cdn": false, "https": false}, "sensitive_indicator": false, "vulnerabilities": []}, {"hostname": "db.example.com", "ip": "198.51.100.20", "ports": [3306, 6379, 22], "technologies": [], "http": null, "sensitive_indicator": true, "vulnerabilities": [{"cve": "CVE-2023-9999", "severity": "high"}, {"cve": "CVE-2024-1111", "severity": "low"}]}, {"hostname": "api.example.com", "ip": "198.51.100.30", "ports": [443], "technologies": ["Node.js"], "http": {"status_code": 403, "title": "API Gateway", "cdn": true, "https": true}, "sensitive_indicator": false, "vulnerabilities": []}, {"hostname": "legacy.example.com", "ip": "198.51.100.40", "ports": [23, 21, 445], "technologies": ["Jenkins"], "http": null, "sensitive_indicator": false, "vulnerabilities": []}]}
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/dns_data.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"domain": "example.com", "wildcard_probe": {"subdomain": "doesnotexist-abcxyz.example.com", "resolved": true, "ip": "203.0.113.99"}, "nameservers": [{"host": "ns1.example.com", "axfr_external_allowed": true}, {"host": "ns2.example.com", "axfr_external_allowed": false}]}
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/repo_history.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ commit a1b2c3
2
+ Author: dev@example.com
3
+ Date: Mon Jan 6 2025
4
+ add deployment config
5
+ +database_password = "Sup3rS3cret!"
6
+ +region = us-east-1
7
+
8
+ commit d4e5f6
9
+ Author: ops@example.com
10
+ Date: Tue Jan 7 2025
11
+ fix ci
12
+ +api_key = "AKIAIOSFODNN7EXAMPLE"
13
+ +token = "ghp_abc123def456"
14
+ +timeout = 30
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/inputs/subdomains.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ app.example.com
2
+ admin.example.com
3
+ dev.example.com
4
+ db.example.com
5
+ api.example.com
6
+ legacy.example.com
7
+ staging.example.com
8
+ random-abc123.example.com
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are given offline reconnaissance data for the scope example.com: a passive subdomain list with DNS resolution results (including a wildcard-DNS probe), a per-host service/HTTP fingerprint inventory, and an excerpt of a repository history scan. Write a Python 3 program (standard library only) that produces a single attack-surface triage report (report.json) doing all of the following:
2
+
3
+ 1. Wildcard filtering: the DNS data contains a probe of a random non-existent subdomain; if it resolved, treat its IP as the wildcard IP and remove from the target list every host whose A record equals that wildcard IP (wildcard noise).
4
+ 2. Exposure scoring: for each remaining asset compute an exposure score 0-100 using the five-component weighting in bundled skill/members/M000/references/asm-reference.md, Exposure Scoring Algorithm. Use that frozen reference for the port/vulnerability logarithmic formulas, severity contributions and risk-level thresholds, with the explicit snapshot adaptations below. The bundled agent.py has different per-port/per-technology tables: the following task tables, not that script, govern those weights:
5
+ - For the reference port formula, count is the number of open ports and avg_weight is the mean of these per-port risk weights: Telnet 23=9.5, MongoDB 27017=9.5, Redis 6379=9.0, SMB 445=9.0, SSH 22=8.0, RDP 3389=8.5, MySQL 3306=9.0, PostgreSQL 5432=8.5, FTP 21=7.5, SNMP 161=7.0, alt-HTTP 8080/8443/8888=5.0, SMTP 25=5.5, DNS 53=5.0, HTTP 80=2.5, HTTPS 443=3.0, any other port=4.0.
6
+ - For the reference vulnerability formula, count is the number of vulnerabilities and total_weight sums their severity contributions as defined in that reference.
7
+ - Tech score: use the highest-risk technology detected on the host from this table: Struts=8.0, phpMyAdmin=8.0, WebLogic=7.0, Jenkins=7.0, Tomcat=6.0, PHP=5.0, Apache=4.0, nginx=3.0, Node.js=3.0; if no listed technology is detected use baseline 10.0.
8
+ - Exposure-level component: start at 50 (internet-facing); +15 if the host serves HTTP only (no HTTPS/443); -20 if CDN-protected; -25 if the observed status code is 401 or 403; +20 if the page title or hostname indicates an admin/login panel (title or hostname contains 'admin', 'login', 'dashboard', or 'manage', case-insensitive). Clamp the component to 0-100.
9
+ - Data-sensitivity component: +20 per open database port (3306, 5432, 1433, 6379, 27017), +15 per open file-sharing port (21, 445), +15 if any sensitive service indicator flag is set in the inventory. Clamp to 0-100.
10
+ - Combine the five components by the reference weighted formula, round to 1 decimal, and assign its documented risk level. Treat the band lower bounds as thresholds, so non-integer rounded scores have no gaps between bands.
11
+ 3. Entry-point ranking: sort surviving assets by final score descending (tie-break by hostname ascending) and assign priority 'Critical' for CRITICAL/HIGH risk levels, 'Medium' for MEDIUM, 'Low' otherwise.
12
+ 4. OPSEC findings: (a) flag every surviving host whose hostname contains 'dev', 'staging', 'test', or 'uat' (case-insensitive) as an exposed non-production environment; (b) if the DNS data shows a nameserver with zone transfer (AXFR) permitted externally, flag it as a DNS exposure; (c) extract any credential-looking assignments from the repository history excerpt (lines matching key names password, api_key, secret, or token followed by an assignment) and list each leaked key name with its value.
13
+
14
+ Write the report to report.json with keys: wildcard_ip (string or null), filtered_out (list of hostnames removed as wildcard noise), assets (list of {hostname, ip, ports, exposure_score, risk_level, priority}), ranked_entry_points (hostnames in ranked order), and opsec_findings ({exposed_nonprod: [hostnames], dns_axfr_exposed: bool, leaked_credentials: [{key, value}]}).
15
+ Bounded automatic resource contract: During the actual grader-launched Python invocations, Python imports must resolve to the standard library or submitted local modules/packages (including namespace packages and computed imports). Unused/dead source code and strings are not rejected by static import inference. Do not perform network operations during graded invocations. Do not load or call foreign native libraries through FFI during graded invocations. Child processes are not forbidden solely because they exist; all original output and interface requirements still apply. A launcher or instrumentation failure is an infrastructure error, not a wrong-answer score.
16
+
17
+ Execution budget: every grader-launched candidate Python invocation must complete within 60 seconds. A timeout after candidate startup fails this bounded-completion requirement; a trusted observer or launcher failure is an infrastructure error.
18
+
19
+
20
+ Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score.
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/skill/SKILL.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Multi-skill source bundle
2
+
3
+ Private source bundle wrapper. The original skills are in members/.
benchmarks/skillbench-venus-e/tasks/74f2ef23fbf581f82a581256/skill/members/M000/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ Copyright 2025 mukul975
8
+
9
+ Licensed under the Apache License, Version 2.0 (the "License");
10
+ you may not use this file except in compliance with the License.
11
+ You may obtain a copy of the License at
12
+
13
+ http://www.apache.org/licenses/LICENSE-2.0
14
+
15
+ Unless required by applicable law or agreed to in writing, software
16
+ distributed under the License is distributed on an "AS IS" BASIS,
17
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ See the License for the specific language governing permissions and
19
+ limitations under the License.