StudentTang commited on
Commit
09cc135
·
verified ·
1 Parent(s): 1fb9374

Add files using upload-large-folder tool

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/d76667df8f9db23f_q1/evaluator/auto_contract.json +8 -0
  2. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_entry.py +38 -0
  3. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy.py +133 -0
  4. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy_guard.py +86 -0
  5. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/autograde_task_check.py +14 -0
  6. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/check.py +2 -0
  7. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy-task.json +159 -0
  8. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/evaluate.py +159 -0
  9. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/objective_evaluators.py +1330 -0
  10. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/shell_invocations.py +455 -0
  11. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/test.sh +8 -0
  12. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/verifiers.py +544 -0
  13. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/repair_equivalences.py +240 -0
  14. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/grading/verified_config.json +100 -0
  15. benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/skill/SKILL.md +23 -0
  16. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_contract.json +26 -0
  17. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_entry.py +38 -0
  18. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.json +13 -0
  19. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.py +133 -0
  20. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy_guard.py +86 -0
  21. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/autograde_task_check.py +217 -0
  22. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/candidate_artifacts.py +24 -0
  23. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/check.py +2 -0
  24. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/dependency_scan.py +16 -0
  25. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/r10_runtime.py +70 -0
  26. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/grading/verified_config.json +90 -0
  27. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/events.l +10 -0
  28. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.block-legacy-pm.local.md +9 -0
  29. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.console-log.local.md +8 -0
  30. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.dangerous-rm.local.md +8 -0
  31. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.disabled-rule.local.md +8 -0
  32. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.sensitive-files.local.md +14 -0
  33. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/SKILL.md +3 -0
  34. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M000/SKILL.md +236 -0
  35. benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M001/SKILL.md +379 -0
  36. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_contract.json +26 -0
  37. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_entry.py +38 -0
  38. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.json +13 -0
  39. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.py +133 -0
  40. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy_guard.py +86 -0
  41. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/autograde_task_check.py +44 -0
  42. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/candidate_artifacts.py +24 -0
  43. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/check.py +2 -0
  44. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/dependency_scan.py +16 -0
  45. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/input_snapshots/routes.json +751 -0
  46. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/repair_manifest.json +318 -0
  47. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/workspace_copy.py +24 -0
  48. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/grading/verified_config.json +49 -0
  49. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/inputs/attempts. +10 -0
  50. benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/inputs/routes. +16 -0
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_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/d76667df8f9db23f_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/d76667df8f9db23f_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/d76667df8f9db23f_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/d76667df8f9db23f_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/d76667df8f9db23f_q1/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy-task.json ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "mybench-portable-task-v2",
3
+ "task_id": "d76667df8f9db23f",
4
+ "query_id": "d76667df8f9db23f_q1",
5
+ "prompt": {
6
+ "path": "instruction.md",
7
+ "sha256": "1f444c349fbf20fa6ce303d4d597398e5bb5a6225cef070b40e08a7fdfcae184"
8
+ },
9
+ "workspace": {
10
+ "input_mappings": [],
11
+ "skill_packages": [
12
+ {
13
+ "content_hash": "5d03c9143cb81caa0b275f66181ea1caa7ffd9e08f5fdafb571ab2128a244e60",
14
+ "name": "brandkit",
15
+ "package_path": "environment/skills/brandkit-5d03c914",
16
+ "install_name": "brandkit-5d03c914",
17
+ "archive_provenance": {
18
+ "archive_id": "logical-skill-e1bbf18f13f193c01a17d1ef",
19
+ "archive_schema": "skill-release-v1",
20
+ "release_skill_id": "logical-skill-e1bbf18f13f193c01a17d1ef",
21
+ "site": "skills-sh",
22
+ "local_path": "skills/e1/logical-skill-e1bbf18f13f193c01a17d1ef",
23
+ "skill_md_sha256": "47f27dd280db557827b8c0fed7463034d61cde29b0ade892bc34f8e55a183ab8",
24
+ "release_payload_sha256": "5d03c9143cb81caa0b275f66181ea1caa7ffd9e08f5fdafb571ab2128a244e60",
25
+ "license": "MIT",
26
+ "license_status": "detected",
27
+ "canonical_source_id": "skills-sh:plugin87/ux-ui-agent-skills/brandkit"
28
+ },
29
+ "omitted_entries": []
30
+ }
31
+ ],
32
+ "default_skill_target": ".claude/skills",
33
+ "candidate_mode": "workspace"
34
+ },
35
+ "ground_truth_skills": [
36
+ "5d03c9143cb81caa0b275f66181ea1caa7ffd9e08f5fdafb571ab2128a244e60"
37
+ ],
38
+ "evaluation": {
39
+ "type": "verified",
40
+ "ground_truth_answer": {
41
+ "files": [
42
+ {
43
+ "path": "output/verify_brand_tokens.sh",
44
+ "content": "#!/usr/bin/env bash\nset -euo pipefail\npython3 scripts/validate_tokens.py\npython3 scripts/validate_contrast.py\npython3 scripts/validate_theme_refs.py\nnpm run verify\n"
45
+ }
46
+ ]
47
+ },
48
+ "verifier": {
49
+ "type": "workspace_objective",
50
+ "version": 15,
51
+ "output_mode": "workspace",
52
+ "reference_files": [
53
+ {
54
+ "path": "output/verify_brand_tokens.sh",
55
+ "format": "shell",
56
+ "content": "#!/usr/bin/env bash\nset -euo pipefail\npython3 scripts/validate_tokens.py\npython3 scripts/validate_contrast.py\npython3 scripts/validate_theme_refs.py\nnpm run verify\n"
57
+ }
58
+ ],
59
+ "checks": [
60
+ {
61
+ "id": "workspace_file_set",
62
+ "type": "workspace_file_set",
63
+ "paths": [
64
+ "output/verify_brand_tokens.sh"
65
+ ],
66
+ "roots": [
67
+ "output"
68
+ ]
69
+ },
70
+ {
71
+ "id": "file_001",
72
+ "type": "file_exists",
73
+ "path": "output/verify_brand_tokens.sh"
74
+ },
75
+ {
76
+ "id": "shell_001",
77
+ "type": "shell_syntax",
78
+ "path": "output/verify_brand_tokens.sh"
79
+ },
80
+ {
81
+ "id": "shell_001_001",
82
+ "type": "shell_command",
83
+ "path": "output/verify_brand_tokens.sh",
84
+ "value": "python3 scripts/validate_tokens.py"
85
+ },
86
+ {
87
+ "id": "shell_001_002",
88
+ "type": "shell_command",
89
+ "path": "output/verify_brand_tokens.sh",
90
+ "value": "python3 scripts/validate_contrast.py"
91
+ },
92
+ {
93
+ "id": "shell_001_003",
94
+ "type": "shell_command",
95
+ "path": "output/verify_brand_tokens.sh",
96
+ "value": "python3 scripts/validate_theme_refs.py"
97
+ },
98
+ {
99
+ "id": "shell_001_004",
100
+ "type": "shell_command",
101
+ "path": "output/verify_brand_tokens.sh",
102
+ "value": "npm run verify"
103
+ },
104
+ {
105
+ "id": "shell_001_sequence",
106
+ "type": "shell_command_sequence",
107
+ "path": "output/verify_brand_tokens.sh",
108
+ "values": [
109
+ "python3 scripts/validate_tokens.py",
110
+ "python3 scripts/validate_contrast.py",
111
+ "python3 scripts/validate_theme_refs.py",
112
+ "npm run verify"
113
+ ]
114
+ },
115
+ {
116
+ "id": "shell_001_unconditional",
117
+ "type": "shell_unconditional_commands",
118
+ "path": "output/verify_brand_tokens.sh",
119
+ "values": [
120
+ "python3 scripts/validate_tokens.py",
121
+ "python3 scripts/validate_contrast.py",
122
+ "python3 scripts/validate_theme_refs.py",
123
+ "npm run verify"
124
+ ]
125
+ },
126
+ {
127
+ "id": "shell_001_failure_propagation",
128
+ "type": "shell_failure_propagation",
129
+ "path": "output/verify_brand_tokens.sh",
130
+ "values": [
131
+ "python3 scripts/validate_tokens.py",
132
+ "python3 scripts/validate_contrast.py",
133
+ "python3 scripts/validate_theme_refs.py",
134
+ "npm run verify"
135
+ ]
136
+ },
137
+ {
138
+ "id": "shell_straight_line_001",
139
+ "type": "shell_straight_line",
140
+ "path": "output/verify_brand_tokens.sh"
141
+ }
142
+ ],
143
+ "self_test_passed": true
144
+ },
145
+ "dependency_contract": {
146
+ "version": 2,
147
+ "mode": "core_answer",
148
+ "dependency_type": "project_command_convention",
149
+ "requirement_ids": [
150
+ "skill_a016",
151
+ "skill_a017",
152
+ "skill_a018",
153
+ "skill_a020"
154
+ ],
155
+ "forbid_meta_reference": true,
156
+ "forbid_answer_leakage": true
157
+ }
158
+ }
159
+ }
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_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/d76667df8f9db23f_q1/evaluator/legacy_tests/objective_evaluators.py ADDED
@@ -0,0 +1,1330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ passed = passed and all(call['fail_fast'] or shlex.split(call['command'])[0] in ('true', ':') for call in calls)
1240
+ detail = f"expected_failure_propagation={expected}; all_calls_fail_fast=True; invocations={calls[:30]}"
1241
+ elif kind == "shell_straight_line":
1242
+ source = path.read_text(encoding="utf-8")
1243
+ passed = _shell_is_straight_line(source)
1244
+ if "allowed_commands" in check:
1245
+ calls = shell_invocations(source)
1246
+ allowed = check["allowed_commands"]
1247
+ passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and
1248
+ all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls))
1249
+ detail = ("all executable lines are top-level" if passed else
1250
+ "shell contains conditional, loop, case, or function")
1251
+ else:
1252
+ detail = f"unsupported check: {kind}"
1253
+ except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
1254
+ json.JSONDecodeError,
1255
+ tomllib.TOMLDecodeError) as exc:
1256
+ detail = str(exc)
1257
+ results.append({"id": check.get("id"), "type": kind,
1258
+ "path": relative, "passed": bool(passed),
1259
+ "detail": detail[:1000]})
1260
+ return bool(results) and all(item["passed"] for item in results), {
1261
+ "type": WORKSPACE_EVALUATOR,
1262
+ "assertions_passed": sum(item["passed"] for item in results),
1263
+ "assertions_total": len(results),
1264
+ "assertions": results,
1265
+ }
1266
+
1267
+
1268
+ def evaluate_candidate(evaluator, candidate):
1269
+ if isinstance(candidate, os.PathLike):
1270
+ try:
1271
+ return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
1272
+ False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
1273
+ except (OSError, ValueError) as exc:
1274
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1275
+ if isinstance(candidate, str):
1276
+ # A chat file-bundle can be much longer than a filesystem path. Avoid
1277
+ # passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
1278
+ stripped = candidate.strip()
1279
+ if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
1280
+ and not stripped.startswith(("{", "[", "```"))):
1281
+ try:
1282
+ if Path(stripped).is_dir():
1283
+ return evaluate_workspace(evaluator, stripped)
1284
+ except (OSError, ValueError):
1285
+ # Python/platform versions differ on ENAMETOOLONG and invalid
1286
+ # path errors. It is still candidate text: parse it unchanged.
1287
+ pass
1288
+ try:
1289
+ with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
1290
+ materialize_bundle(candidate, temp)
1291
+ return evaluate_workspace(evaluator, temp)
1292
+ except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
1293
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1294
+
1295
+
1296
+ def self_test_workspace_evaluator(evaluator):
1297
+ correct = reference_bundle(evaluator)
1298
+ ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
1299
+ rows = list(correct.get("files") or [])
1300
+ perturbed = {"files": rows[1:] if len(rows) > 1 else []}
1301
+ ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
1302
+ mutations = []
1303
+ # Exact JSON fields must each matter, not merely the file's existence.
1304
+ for check in evaluator.get("checks") or []:
1305
+ if check.get("type") != "json_exact":
1306
+ continue
1307
+ for path, value in _flatten(check.get("expected")):
1308
+ candidate = copy.deepcopy(correct)
1309
+ file_row = next(row for row in candidate["files"]
1310
+ if row["path"] == check["path"])
1311
+ data = json.loads(file_row["content"])
1312
+ replacement = (not value if isinstance(value, bool) else
1313
+ value + 1 if isinstance(value, (int, float)) else
1314
+ str(value) + "__mutation__")
1315
+ if not path:
1316
+ data = replacement
1317
+ else:
1318
+ container = data
1319
+ for key in path[:-1]:
1320
+ container = container[key]
1321
+ container[path[-1]] = replacement
1322
+ file_row["content"] = json.dumps(data)
1323
+ passed, _ = evaluate_candidate(evaluator, candidate)
1324
+ mutations.append({"path": check["path"], "field": list(path),
1325
+ "rejected": not passed})
1326
+ return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
1327
+ "correct": correct_detail,
1328
+ "perturbed": wrong_detail,
1329
+ "scalar_mutations": mutations,
1330
+ }
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/shell_invocations.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
121
+ # R7: unwrap only execution wrappers whose effect is proved in this subset.
122
+ # In particular `command -v/-V` queries do not run their operand, and `builtin`
123
+ # cannot run an external tool. Keep these distinctions before inspecting state.
124
+ _BASH_BUILTINS = frozenset({
125
+ ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd',
126
+ 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',
127
+ 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
128
+ 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local',
129
+ 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray',
130
+ 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test',
131
+ 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias',
132
+ 'unset', 'wait',
133
+ })
134
+ _UNSUPPORTED_STATE = frozenset({
135
+ '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap',
136
+ 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local',
137
+ 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift',
138
+ '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts',
139
+ })
140
+
141
+
142
+ def _bash_dialect(text):
143
+ """No shebang uses the evaluator's Bash syntax contract; sh is not Bash."""
144
+ first = str(text).splitlines()[0] if str(text).splitlines() else ''
145
+ if not first.startswith('#!'):
146
+ return True
147
+ try:
148
+ words = shlex.split(first[2:])
149
+ except ValueError:
150
+ return False
151
+ if not words:
152
+ return False
153
+ executable = words[0].rsplit('/', 1)[-1]
154
+ if executable == 'env':
155
+ words = words[1:]
156
+ if words[:1] == ['-S']:
157
+ words = words[1:]
158
+ executable = words[0] if words else ''
159
+ return executable.rsplit('/', 1)[-1] == 'bash'
160
+
161
+
162
+ def _execution_argv(argv, bash=True):
163
+ """Normalize a finite chain; unsupported wrappers get no command credit."""
164
+ if not argv:
165
+ return None
166
+ argv = list(argv)
167
+ while argv and argv[0] in ('command', 'builtin'):
168
+ wrapper = argv[0]
169
+ if wrapper == 'builtin':
170
+ if not bash:
171
+ return None
172
+ argv = argv[1:]
173
+ if argv[:1] == ['--']:
174
+ argv = argv[1:]
175
+ if not argv or argv[0] not in _BASH_BUILTINS:
176
+ return None
177
+ continue
178
+ index, query, default_path = 1, False, False
179
+ while index < len(argv) and argv[index].startswith('-'):
180
+ option = argv[index]
181
+ index += 1
182
+ if option == '--':
183
+ break
184
+ if not re.fullmatch(r'-[pvV]+', option):
185
+ return None
186
+ query = query or 'v' in option or 'V' in option
187
+ default_path = default_path or 'p' in option
188
+ if query:
189
+ return argv # Query is an invocation of command, not its target.
190
+ if index == len(argv):
191
+ return None
192
+ argv = argv[index:]
193
+ # -p changes external PATH lookup. It is transparent for builtins only.
194
+ if default_path and argv[0] not in _BASH_BUILTINS:
195
+ return None
196
+ return argv or None
197
+
198
+
199
+ def _set_errexit(argv, current):
200
+ """Return the proven option state, or None for unsupported set options."""
201
+ if not argv or argv[0] != 'set':
202
+ return None
203
+ index = 1
204
+ while index < len(argv):
205
+ flag = argv[index]
206
+ if flag == '--' or not flag.startswith(('-', '+')):
207
+ break # Positional arguments cannot enable errexit.
208
+ if not re.fullmatch(r'[-+][eufxEo]+', flag):
209
+ return None # Includes noexec (-n), which suppresses later work.
210
+ if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1):
211
+ return None
212
+ if 'e' in flag[1:]:
213
+ current = flag[0] == '-'
214
+ if 'o' in flag[1:]:
215
+ if index + 1 >= len(argv):
216
+ return None
217
+ option = argv[index + 1]
218
+ if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
219
+ return None
220
+ if option == 'errexit':
221
+ current = flag[0] == '-'
222
+ index += 1
223
+ index += 1
224
+ return current
225
+
226
+
227
+ def shell_option_setting(text, bash=True):
228
+ """Recognize valid option setup for task-specific operation counters."""
229
+ argv = _execution_argv(_simple_argv(text), bash)
230
+ return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None)
231
+
232
+
233
+ def _exit_status(argv):
234
+ """A literal shell exit status; no-argument exit is handled by its caller."""
235
+ args = argv[1:]
236
+ if args[:1] == ['--']:
237
+ args = args[1:]
238
+ if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0])
239
+ or len(args[0]) > 20):
240
+ return None
241
+ value = int(args[0])
242
+ if not -(2**63) <= value <= 2**63 - 1:
243
+ return 2 # Bash exits for an out-of-range numeric argument.
244
+ return value % 256
245
+
246
+
247
+
248
+ def _nonzero_exit_body(statements, bash=True):
249
+ """Only literal logging followed by a final unconditional nonzero exit."""
250
+ if not statements:
251
+ return False
252
+ for index, statement in enumerate(statements):
253
+ argv = _execution_argv(_simple_argv(statement), bash)
254
+ if not argv:
255
+ return False
256
+ if argv[0] == 'exit':
257
+ status = _exit_status(argv)
258
+ return index == len(statements) - 1 and status is not None and status != 0
259
+ if argv[0] not in ('echo', 'printf'):
260
+ return False
261
+ return False
262
+
263
+
264
+
265
+ def _expand_known_variables(text, constants):
266
+ """Preserve quote/escape expansion semantics in the bounded shell grammar.
267
+
268
+ Active unknown variables stay symbolic. A quoted/escaped literal dollar or
269
+ tilde has a separate token, so it cannot satisfy an expanding shell call.
270
+ This is parsing only; no shell command is evaluated.
271
+ """
272
+ out,quote,i=[],None,0
273
+ variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
274
+ while i<len(text):
275
+ ch=text[i]
276
+ if ch=='\\' and quote!="'" and i+1<len(text):
277
+ nxt=text[i+1]
278
+ if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__')
279
+ elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__')
280
+ else:out.extend((ch,nxt))
281
+ i+=2;continue
282
+ if ch in "'\"":
283
+ if quote is None:quote=ch
284
+ elif quote==ch:quote=None
285
+ out.append(ch);i+=1;continue
286
+ if ch=='$':
287
+ if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue
288
+ m=variable.match(text,i)
289
+ if m:
290
+ value=constants.get(m.group(1)or m.group(2))
291
+ if value is None:out.append(m.group(0))
292
+ elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$'))
293
+ else:out.append(value)
294
+ i=m.end();continue
295
+ if ch=='~' and quote is not None:
296
+ out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue
297
+ out.append(ch);i+=1
298
+ return ''.join(out)
299
+
300
+
301
+ # Ordinary assignment/parameter defaults are not shell control flow. This
302
+ # recognizer never evaluates their text or assumes the inherited value is empty.
303
+ _DEFAULT_STATE_NAMES = frozenset({
304
+ 'PATH', 'IFS', 'ENV', 'BASH_ENV', 'SHELLOPTS', 'BASHOPTS', 'CDPATH',
305
+ 'GLOBIGNORE', 'FIGNORE', 'POSIXLY_CORRECT', 'BASH_COMPAT',
306
+ 'PROMPT_COMMAND', 'PS0', 'PS1', 'PS2', 'PS4', 'UID', 'EUID', 'PPID',
307
+ 'SHELL', 'RANDOM', 'SRANDOM', 'SECONDS', 'LINENO', 'OPTIND', 'OPTARG',
308
+ '_', 'HOME', 'PWD', 'OLDPWD', 'PIPESTATUS', 'DIRSTACK', 'GROUPS',
309
+ 'FUNCNAME', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME',
310
+ })
311
+
312
+ def _ordinary_parameter_default(statement):
313
+ """Recognize X=${Y:-literal}, ${Y-literal}, ${Y:=literal}, ${Y=literal}.
314
+
315
+ Optional export and double quotes do not change the assignment semantics.
316
+ Both names must be ordinary variables, the nonempty fallback must be literal,
317
+ and no nested expansion/command substitution is allowed. Return every name
318
+ which can be assigned; their effective values remain unknown. Reading Y in
319
+ '-' variants does not erase an earlier known Y value; '=' variants may write
320
+ Y, so both Y and X lose any previously inferred constant.
321
+ """
322
+ match = re.fullmatch(
323
+ r'(?:export\s+(?:--\s+)?)?([A-Za-z_][A-Za-z0-9_]*)='
324
+ r'("?)\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-=])'
325
+ r'[A-Za-z0-9_./:+-]+\}\2', statement)
326
+ if not match:
327
+ return None
328
+ target, _, source, operator = match.groups()
329
+ if any(name in _DEFAULT_STATE_NAMES or
330
+ name.startswith(('BASH_', 'BASH_FUNC_', 'LD_', 'DYLD_'))
331
+ for name in (target, source)):
332
+ return None
333
+ return (target, source) if '=' in operator else (target,)
334
+
335
+ def shell_invocations(text):
336
+ """Return ordered, actually evaluated invocation nodes in the supported subset.
337
+
338
+ fail_fast is a structural proof: a simple command/assignment runs under
339
+ errexit, or a negated test exits nonzero on failure. This is not a complete
340
+ shell interpreter, and unsupported syntax earns no invocation credit.
341
+ """
342
+ statements = _statements(text)
343
+ bash = _bash_dialect(text)
344
+ # Function definitions or dynamic shell mutation can shadow the command or
345
+ # `exit` itself. They are outside this objective subset, even if uncalled.
346
+ 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)
347
+ or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
348
+ for s in statements):
349
+ return []
350
+ constants, result, index, errexit = {}, [], 0, False
351
+ assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
352
+ variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
353
+ while index < len(statements):
354
+ statement = statements[index]
355
+ literal = assignment.fullmatch(statement)
356
+ if literal:
357
+ constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
358
+ index += 1
359
+ continue
360
+ default_names = _ordinary_parameter_default(statement)
361
+ if default_names is not None:
362
+ for default_name in default_names:
363
+ constants.pop(default_name, None)
364
+ index += 1
365
+ continue
366
+ statement = _expand_known_variables(statement, constants)
367
+ if re.match(r'^if\s', statement):
368
+ end = _guard_end(statements, index)
369
+ if end is None:
370
+ return []
371
+ negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
372
+ if (negated and index + 1 < end
373
+ and statements[index + 1] == 'then'
374
+ and _nonzero_exit_body(statements[index + 2:end], bash)):
375
+ argv, kind = _invocation(negated.group(1).strip())
376
+ argv = _execution_argv(argv, bash)
377
+ if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')):
378
+ return []
379
+ if argv:
380
+ if argv[0] == 'false':
381
+ break
382
+ result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
383
+ 'fail_fast': True, 'statement_index': index, 'expanded_statement': statement})
384
+ else:
385
+ return []
386
+ else:
387
+ # Arbitrary conditions may terminate the script or shadow its
388
+ # commands. Do not infer a reachable suffix through them.
389
+ return []
390
+ # Bodies are never credited and may have assigned local variables.
391
+ constants.clear()
392
+ index = end + 1
393
+ continue
394
+ if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
395
+ # Unsupported compounds are not searched for command substrings.
396
+ return []
397
+ argv, kind = _invocation(statement)
398
+ argv = _execution_argv(argv, bash)
399
+ if not argv:
400
+ # An unparsed statement may change control flow or shell state.
401
+ # Skipping it would incorrectly credit an unreachable suffix.
402
+ return []
403
+ if argv[0] in _UNSUPPORTED_STATE:
404
+ return []
405
+ if argv[0] == 'hash':
406
+ # Clearing/querying/cache lookup preserves the command's selected
407
+ # executable. An explicit -p binding can replace a required tool.
408
+ operands, flags = [], ''
409
+ option_mode = True
410
+ for word in argv[1:]:
411
+ if option_mode and word == '--':
412
+ option_mode = False
413
+ elif option_mode and word.startswith('-'):
414
+ if not re.fullmatch(r'-[lrdt]+', word):
415
+ return []
416
+ flags += word[1:]
417
+ else:
418
+ option_mode = False
419
+ if '$' in word:
420
+ return []
421
+ operands.append(word)
422
+ if ('d' in flags or 't' in flags) and not operands:
423
+ return []
424
+ if argv[0] == 'set':
425
+ new_errexit = _set_errexit(argv, errexit)
426
+ if new_errexit is None:
427
+ return []
428
+ if kind == 'simple':
429
+ errexit = new_errexit
430
+ index += 1
431
+ continue
432
+ # An assignment substitution runs in a subshell: set cannot change
433
+ # the parent's flags. Keep it as an ordinary evaluated node.
434
+ if argv[0] == 'exit':
435
+ if kind == 'simple':
436
+ # Only a literal, zero/one-argument exit is proved terminal.
437
+ # An invalid multi-argument exit can return and is unsupported.
438
+ if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None:
439
+ break
440
+ return []
441
+ status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv)
442
+ if status is None:
443
+ return []
444
+ if status and errexit:
445
+ break
446
+ if argv[0] == 'false' and errexit:
447
+ break
448
+ if kind == 'assignment_substitution':
449
+ assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
450
+ if assigned:
451
+ constants.pop(assigned.group(1), None)
452
+ result.append({'command': shlex.join(argv), 'kind': kind,
453
+ 'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement})
454
+ index += 1
455
+ return result
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_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/d76667df8f9db23f_q1/evaluator/legacy_tests/verifiers.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return json.loads(text)
49
+
50
+
51
+
52
+ def _strict_json_value(value):
53
+ """Atomic answer contract: one complete JSON value, no extra prose/keys."""
54
+ def unique(pairs):
55
+ d={}
56
+ for k,v in pairs:
57
+ if k in d:raise ValueError('duplicate JSON key: '+k)
58
+ d[k]=v
59
+ return d
60
+ def invalid(s):raise ValueError('non-finite JSON number: '+s)
61
+ result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
62
+ if isinstance(value,str) else value)
63
+ def finite(v):
64
+ if isinstance(v,dict):return all(finite(x)for x in v.values())
65
+ if isinstance(v,list):return all(finite(x)for x in v)
66
+ return not isinstance(v,float)or math.isfinite(v)
67
+ if not finite(result):raise ValueError('non-finite JSON number')
68
+ return result
69
+
70
+ def _path_equal(actual, expected):
71
+ if not isinstance(actual,str)or not isinstance(expected,str):return False
72
+ # A trailing slash is not a harmless spelling for a named file.
73
+ suffix=posixpath.splitext(expected.rstrip('/'))[1]
74
+ if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
75
+ return _path_value(actual)==_path_value(expected)
76
+
77
+ def _canonical_json(value):
78
+ if isinstance(value, dict):
79
+ return {key: _canonical_json(value[key]) for key in sorted(value)}
80
+ if isinstance(value, list):
81
+ values = [_canonical_json(item) for item in value]
82
+ return sorted(values, key=lambda item: json.dumps(
83
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
84
+ return value
85
+
86
+
87
+ def _atomic_prepare(value, list_order):
88
+ if isinstance(value, dict):
89
+ return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
90
+ if isinstance(value, list):
91
+ values = [_atomic_prepare(item, list_order) for item in value]
92
+ if list_order == "unordered":
93
+ values.sort(key=lambda item: json.dumps(
94
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
95
+ return values
96
+ return value
97
+
98
+
99
+ def _atomic_shape(value):
100
+ if isinstance(value, dict):
101
+ return {"type": "object", "keys": {
102
+ key: _atomic_shape(item) for key, item in value.items()}}
103
+ if isinstance(value, list):
104
+ return {"type": "array", "length": len(value),
105
+ "items": [_atomic_shape(item) for item in value]}
106
+ if isinstance(value, bool):
107
+ return {"type": "boolean"}
108
+ if value is None:
109
+ return {"type": "null"}
110
+ if isinstance(value, (int, float)):
111
+ return {"type": "number"}
112
+ return {"type": "string"}
113
+
114
+
115
+ def _atomic_leaves(value, path="$", tokens=()):
116
+ if isinstance(value, dict):
117
+ out = []
118
+ for key, item in value.items():
119
+ out.extend(_atomic_leaves(
120
+ item, path + "." + key, tokens + (key,)))
121
+ return out
122
+ if isinstance(value, list):
123
+ out = []
124
+ for index, item in enumerate(value):
125
+ out.extend(_atomic_leaves(
126
+ item, f"{path}[{index}]", tokens + (index,)))
127
+ return out
128
+ return [(path, tokens, value)]
129
+
130
+
131
+ def _normalize_path_equivalence_tokens(values):
132
+ """Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
133
+ normalized = []
134
+ for tokens in values or []:
135
+ if (not isinstance(tokens, (list, tuple)) or not tokens or
136
+ any(not isinstance(token, (str, int)) for token in tokens)):
137
+ raise ValueError("path equivalence tokens must be non-empty JSON paths")
138
+ item = list(tokens)
139
+ if item not in normalized:
140
+ normalized.append(item)
141
+ return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
142
+
143
+
144
+ def _path_value(value):
145
+ """Normalize only portable path spelling, not general answer text."""
146
+ if not isinstance(value, str):
147
+ return None
148
+ text = value.strip().replace("\\", "/")
149
+ text = posixpath.normpath(text) if text else text
150
+ if text != "/":
151
+ text = text.rstrip("/")
152
+ return text
153
+
154
+
155
+ def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
156
+ path_equivalence_tokens=None):
157
+ """Freeze a complete JSON shape plus one assertion for every scalar leaf."""
158
+ if list_order not in {"ordered", "unordered"}:
159
+ raise ValueError(f"unsupported atomic list_order: {list_order}")
160
+ tolerance = float(float_tolerance)
161
+ prepared = _atomic_prepare(_json_value(expected), list_order)
162
+ path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
163
+ assertions = []
164
+ for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
165
+ assertion = {"id": f"leaf_{index:03d}", "path": path,
166
+ "tokens": list(tokens), "operator": "eq", "expected": value}
167
+ if isinstance(value, float):
168
+ assertion.update({"operator": "abs_diff", "tolerance": tolerance})
169
+ elif list(tokens) in path_tokens:
170
+ if not isinstance(value, str):
171
+ raise ValueError("path equivalence can only target string leaves")
172
+ assertion["operator"] = "path_eq"
173
+ assertions.append(assertion)
174
+ compiled = {
175
+ "type": "atomic_json", "version": 2 if path_tokens else 1,
176
+ "list_order": list_order,
177
+ "float_tolerance": tolerance,
178
+ "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
179
+ "assertions": assertions,
180
+ }
181
+ if path_tokens:
182
+ compiled["path_equivalence_tokens"] = path_tokens
183
+ return compiled
184
+
185
+
186
+ def _shape_differences(expected, actual, path="$"):
187
+ if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
188
+ return [f"{path}: expected {expected.get('type')}, got "
189
+ f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
190
+ kind = expected.get("type")
191
+ if kind == "object":
192
+ expected_keys = set((expected.get("keys") or {}))
193
+ actual_keys = set((actual.get("keys") or {}))
194
+ differences = [f"{path}: missing key {key}" for key in sorted(
195
+ expected_keys - actual_keys)]
196
+ differences.extend(f"{path}: extra key {key}" for key in sorted(
197
+ actual_keys - expected_keys))
198
+ for key in sorted(expected_keys & actual_keys):
199
+ differences.extend(_shape_differences(
200
+ expected["keys"][key], actual["keys"][key], path + "." + key))
201
+ return differences
202
+ if kind == "array":
203
+ differences = []
204
+ if actual.get("length") != expected.get("length"):
205
+ differences.append(
206
+ f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
207
+ for index, (expected_item, actual_item) in enumerate(zip(
208
+ expected.get("items") or [], actual.get("items") or [])):
209
+ differences.extend(_shape_differences(
210
+ expected_item, actual_item, f"{path}[{index}]"))
211
+ return differences
212
+ return []
213
+
214
+
215
+ def _atomic_get(value, tokens):
216
+ current = value
217
+ for token in tokens:
218
+ current = current[token]
219
+ return current
220
+
221
+
222
+ def _int_values(value):
223
+ if isinstance(value, (list, tuple)):
224
+ out = []
225
+ for item in value:
226
+ out.extend(_int_values(item))
227
+ return out
228
+ if isinstance(value, int) and not isinstance(value, bool):
229
+ return [value]
230
+ return [int(number) for number in re.findall(r"\d+", str(value or ""))]
231
+
232
+
233
+ def _finding_type(value):
234
+ text = str(value or "").lower().replace("-", "_")
235
+ if "duplicate" in text:
236
+ return "duplicate_rows"
237
+ if ("none" in text or "null" in text) and "check" in text:
238
+ return "none_check"
239
+ if "missing" in text or "empty" in text or "null" in text:
240
+ return "missing"
241
+ if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
242
+ return "outlier"
243
+ if "invalid" in text and "config" in text:
244
+ return "invalid_config"
245
+ if "off" in text and "one" in text:
246
+ return "off_by_one"
247
+ return text.strip().replace(" ", "_")
248
+
249
+
250
+ def _normalized_findings(value, family):
251
+ obj = _json_value(value)
252
+ findings = obj.get("findings") if isinstance(obj, dict) else None
253
+ if not isinstance(findings, list):
254
+ raise ValueError("answer must contain a findings array")
255
+ normalized = set()
256
+ for finding in findings:
257
+ if not isinstance(finding, dict):
258
+ raise ValueError("each finding must be an object")
259
+ # The public contract uses type/function. Accept common semantically
260
+ # equivalent aliases as a robustness layer, while still comparing the
261
+ # normalized values and exact locations against generator-owned GT.
262
+ kind = _finding_type(finding.get("type", finding.get(
263
+ "defect_type", finding.get("defect"))))
264
+ if family == "csv":
265
+ if kind == "duplicate_rows":
266
+ rows = _int_values(finding.get("rows", finding.get("row")))
267
+ if len(rows) != 2:
268
+ raise ValueError("duplicate finding requires exactly two row numbers")
269
+ normalized.add((kind, *sorted(rows)))
270
+ elif kind in {"missing", "outlier"}:
271
+ rows = _int_values(finding.get("row"))
272
+ column = str(finding.get("column") or "").strip().lower()
273
+ if len(rows) != 1 or not column:
274
+ raise ValueError(f"{kind} requires one row and column")
275
+ normalized.add((kind, rows[0], column))
276
+ else:
277
+ raise ValueError(f"unsupported CSV finding type: {kind}")
278
+ elif family == "config":
279
+ if kind != "invalid_config":
280
+ raise ValueError(f"unsupported config finding type: {kind}")
281
+ normalized.add((kind, str(finding.get("path") or "").lower(),
282
+ json.dumps(finding.get("value"), sort_keys=True),
283
+ str(finding.get("expected") or "").lower()))
284
+ elif family == "code":
285
+ if kind not in {"off_by_one", "none_check"}:
286
+ raise ValueError(f"unsupported code finding type: {kind}")
287
+ function = finding.get("function", finding.get("function_name"))
288
+ function = str(function or "").strip().lower()
289
+ if not function:
290
+ raise ValueError(f"{kind} requires a function")
291
+ normalized.add((kind, function))
292
+ else:
293
+ raise ValueError(f"unsupported findings family: {family}")
294
+ return normalized
295
+
296
+
297
+ def _normalized_facts(value):
298
+ obj = _json_value(value)
299
+ facts = obj.get("facts") if isinstance(obj, dict) else None
300
+ if not isinstance(facts, list):
301
+ raise ValueError("answer must contain a facts array")
302
+ def textual(item):
303
+ # The document generator serializes scalar values as visible text. JSON
304
+ # has no way to infer whether the source token "30" was authored from an
305
+ # integer or a string, so facts_match compares that surface text. Nested
306
+ # values retain structural JSON comparison.
307
+ if isinstance(item, (dict, list)):
308
+ return json.dumps(item, sort_keys=True, ensure_ascii=False,
309
+ separators=(",", ":"))
310
+ if item is None:
311
+ return "None"
312
+ return str(item)
313
+ return {(str(fact.get("key") or ""), textual(fact.get("value")))
314
+ for fact in facts if isinstance(fact, dict)}
315
+
316
+
317
+ def verify(verifier, gt_answer, solver_output, material_paths=None):
318
+ """执行 verifier。返回 (passed, detail)。"""
319
+ vtype = verifier.get("type")
320
+ try:
321
+ if vtype == WORKSPACE_EVALUATOR:
322
+ return evaluate_candidate(verifier, solver_output)
323
+
324
+ if vtype == "json_exact":
325
+ pred = _canonical_json(_json_value(solver_output))
326
+ gold = _canonical_json(_json_value(gt_answer))
327
+ ok = pred == gold
328
+ return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
329
+
330
+ if vtype == "atomic_json":
331
+ pred = _atomic_prepare(_strict_json_value(solver_output),
332
+ verifier.get("list_order", "ordered"))
333
+ compiled = compile_atomic_verifier(
334
+ gt_answer, verifier.get("list_order", "ordered"),
335
+ verifier.get("float_tolerance", 0.01),
336
+ verifier.get("path_equivalence_tokens"))
337
+ frozen = {key: verifier.get(key) for key in
338
+ ("type", "version", "list_order", "float_tolerance",
339
+ "completeness", "assertions", "path_equivalence_tokens")}
340
+ expected_frozen = {key: compiled.get(key) for key in frozen}
341
+ if frozen != expected_frozen:
342
+ return False, {"error": "atomic verifier does not match ground truth"}
343
+ shape_failures = _shape_differences(
344
+ verifier["completeness"]["shape"], _atomic_shape(pred))
345
+ assertion_results = []
346
+ for assertion in verifier.get("assertions") or []:
347
+ try:
348
+ actual = _atomic_get(pred, assertion["tokens"])
349
+ if assertion["operator"] == "abs_diff":
350
+ passed = abs(float(actual) - float(assertion["expected"])) <= float(
351
+ assertion.get("tolerance", 0.0))
352
+ elif assertion["operator"] == "path_eq":
353
+ passed = _path_equal(actual, assertion["expected"])
354
+ else:
355
+ passed = (actual is assertion["expected"] if
356
+ isinstance(assertion["expected"], bool) else
357
+ actual == assertion["expected"])
358
+ message = "" if passed else (
359
+ f"actual={actual!r} expected={assertion['expected']!r}")
360
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
361
+ actual, passed, message = None, False, f"lookup/compare failed: {exc}"
362
+ assertion_results.append({
363
+ "id": assertion["id"], "path": assertion["path"],
364
+ "operator": assertion["operator"], "expected": assertion["expected"],
365
+ "actual": actual, "passed": passed, "message": message})
366
+ passed_count = sum(item["passed"] for item in assertion_results)
367
+ ok = not shape_failures and passed_count == len(assertion_results)
368
+ return ok, {
369
+ "type": "atomic_json", "completeness_passed": not shape_failures,
370
+ "completeness_failures": shape_failures,
371
+ "assertions_passed": passed_count,
372
+ "assertions_total": len(assertion_results),
373
+ "assertion_pass_rate": (passed_count / len(assertion_results)
374
+ if assertion_results else 1.0),
375
+ "assertions": assertion_results,
376
+ }
377
+
378
+ if vtype == "findings_match":
379
+ family = verifier.get("family")
380
+ pred = _normalized_findings(solver_output, family)
381
+ gold = _normalized_findings(gt_answer, family)
382
+ ok = pred == gold
383
+ return ok, ("findings_match: pass" if ok else
384
+ f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
385
+
386
+ if vtype == "facts_match":
387
+ pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
388
+ ok = pred == gold
389
+ return ok, ("facts_match: pass" if ok else
390
+ f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
391
+
392
+ if vtype == "exact_match":
393
+ ok = _norm(solver_output) == _norm(gt_answer)
394
+ return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
395
+
396
+ if vtype == "numeric":
397
+ tol = verifier.get("tolerance") or 1e-6
398
+ pred = float(str(solver_output).strip().split()[0])
399
+ gold = float(gt_answer)
400
+ ok = abs(pred - gold) <= tol
401
+ return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
402
+
403
+ if vtype == "set_match":
404
+ pred = set(_as_list(solver_output))
405
+ gold = set(_as_list(gt_answer))
406
+ ok = pred == gold
407
+ return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
408
+
409
+ if vtype == "structured_match":
410
+ pred = _json_value(solver_output)
411
+ gold = _json_value(gt_answer)
412
+ if not isinstance(pred, dict) or not isinstance(gold, dict):
413
+ return False, "structured_match requires JSON objects"
414
+ missing = [f for f in verifier.get("required_fields", []) if f not in pred]
415
+ wrong = [f for f in verifier.get("required_fields", [])
416
+ if f in pred and f in gold and pred[f] != gold[f]]
417
+ ok = not missing and not wrong
418
+ return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
419
+
420
+ if vtype == "execution":
421
+ return False, "execution verifier is disabled in verified-first v2"
422
+
423
+ if vtype == "constraint":
424
+ fails = _check_constraints(verifier.get("criteria", []), solver_output)
425
+ return not fails, f"constraint: failed={fails[:5]}"
426
+
427
+ if vtype == "file_inspection":
428
+ fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
429
+ return not fails, f"file_inspection: failed={fails[:5]}"
430
+
431
+ return False, f"unknown verifier type: {vtype}"
432
+ except Exception as e:
433
+ return False, f"verifier error: {e}"
434
+
435
+
436
+ def _as_list(x):
437
+ if isinstance(x, list):
438
+ return [_norm(i) for i in x]
439
+ # 逗号/换行分隔的字符串
440
+ return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
441
+
442
+
443
+ def _check_constraints(criteria, solver_output):
444
+ """criteria: ["must contain X", "must be valid json", "length <= 500"]"""
445
+ fails = []
446
+ text = str(solver_output)
447
+ for c in criteria:
448
+ cl = c.lower()
449
+ if cl.startswith("must contain "):
450
+ needle = c[len("must contain "):]
451
+ if needle.lower() not in text.lower():
452
+ fails.append(c)
453
+ elif "valid json" in cl:
454
+ try:
455
+ json.loads(text)
456
+ except Exception:
457
+ fails.append(c)
458
+ elif cl.startswith("length <="):
459
+ limit = int(cl.split("<=")[1].strip())
460
+ if len(text) > limit:
461
+ fails.append(c)
462
+ else:
463
+ # Deterministic verifier DSL is closed-world: unknown checks fail.
464
+ fails.append(f"unsupported criterion: {c}")
465
+ return fails
466
+
467
+
468
+ def _inspect_files(expected, material_paths):
469
+ fails = []
470
+ paths = set(material_paths or [])
471
+ for e in expected:
472
+ fname = e.get("filename") if isinstance(e, dict) else str(e)
473
+ if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
474
+ fails.append(f"missing file: {fname}")
475
+ return fails
476
+
477
+
478
+ # ---------------- 自测 ----------------
479
+
480
+ def build_correct_solution(verifier, gt_answer, planted_info):
481
+ """由埋点/ground truth 直接构造正确解。"""
482
+ vtype = verifier.get("type")
483
+ if vtype == WORKSPACE_EVALUATOR:
484
+ return reference_bundle(verifier)
485
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
486
+ "set_match", "structured_match"):
487
+ return gt_answer
488
+ if vtype == "constraint":
489
+ parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
490
+ if c.lower().startswith("must contain ")]
491
+ return " ".join(parts) if parts else str(gt_answer)
492
+ # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
493
+ return None
494
+
495
+
496
+ def build_perturbed_solution(verifier, gt_answer, planted_info):
497
+ """破坏埋点构造扰动解。"""
498
+ vtype = verifier.get("type")
499
+ if vtype == WORKSPACE_EVALUATOR:
500
+ files = list(reference_bundle(verifier).get("files") or [])
501
+ return {"files": files[1:] if len(files) > 1 else []}
502
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
503
+ gold = _json_value(gt_answer)
504
+ if isinstance(gold, dict):
505
+ perturbed = dict(gold)
506
+ key = next(iter(perturbed), "__missing__")
507
+ if key in perturbed:
508
+ perturbed.pop(key)
509
+ else:
510
+ perturbed["__wrong__"] = True
511
+ return perturbed
512
+ if isinstance(gold, list):
513
+ return gold[:-1] if gold else ["__wrong__"]
514
+ return "__wrong__"
515
+ if vtype in ("exact_match", "numeric"):
516
+ return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
517
+ if vtype == "set_match":
518
+ gold = _as_list(gt_answer)
519
+ return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
520
+ if vtype == "structured_match":
521
+ fields = verifier.get("required_fields", [])
522
+ return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
523
+ if vtype == "constraint":
524
+ return "perturbed output lacking required content"
525
+ return None
526
+
527
+
528
+ def self_test(verifier, gt_answer, planted_info, material_paths):
529
+ """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
530
+
531
+ 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
532
+ 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
533
+ """
534
+ if verifier.get("type") == WORKSPACE_EVALUATOR:
535
+ return self_test_workspace_evaluator(verifier)
536
+ correct = build_correct_solution(verifier, gt_answer, planted_info)
537
+ perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
538
+ if correct is None or perturbed is None:
539
+ return False, (f"cannot self-test verifier type {verifier.get('type')} "
540
+ "(execution/file_inspection need real correct/perturbed solutions)")
541
+ ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
542
+ ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
543
+ passed = ok1 and not ok2
544
+ return passed, {"correct": d1, "perturbed": d2}
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_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._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/d76667df8f9db23f_q1/grading/verified_config.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "engine": "portable_verified_v1",
3
+ "grader_file_sha256": {
4
+ "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
5
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
6
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
7
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
8
+ "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d",
9
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
10
+ "legacy-task.json": "36c75295b194bf1ded3f7768fac4a8aab66d6a7adc2d0b53a08ae424c9f83641",
11
+ "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
12
+ "legacy_tests/objective_evaluators.py": "760065320d62fbbbebf3f6ab839f864b976c3c675a50db4e12f092ffce843f50",
13
+ "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5",
14
+ "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
15
+ "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70",
16
+ "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af"
17
+ },
18
+ "query_id": "d76667df8f9db23f_q1",
19
+ "runtime_requirements": {
20
+ "candidate_mode": "workspace",
21
+ "candidate_snapshot_copy_to_ephemeral_app": true,
22
+ "container_private_entry": "/grader/check.py",
23
+ "criterion_weights": {
24
+ "0": 1
25
+ },
26
+ "environment": {
27
+ "CANDIDATE_DIR": "/candidate",
28
+ "CANDIDATE_ROOT": "/candidate",
29
+ "MYBENCH_ANSWER": "/answer.txt",
30
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
31
+ "MYBENCH_CANDIDATE": "/candidate",
32
+ "MYBENCH_EPHEMERAL_APP": "1",
33
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1",
34
+ "MYBENCH_RUN_METADATA": "/run_metadata.json",
35
+ "MYBENCH_SOURCE_TASK": "/source",
36
+ "SOURCE_TASK_DIR": "/source"
37
+ },
38
+ "expected_check_ids": [
39
+ "0"
40
+ ],
41
+ "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
42
+ "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
43
+ "grader_timeout_seconds": 600,
44
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
45
+ "image_included": false,
46
+ "legacy_adapter": true,
47
+ "mounts_readonly": [
48
+ "/candidate",
49
+ "/source",
50
+ "/grader",
51
+ "/answer.txt"
52
+ ],
53
+ "network": "none",
54
+ "original_declared_resources": {
55
+ "agent": {
56
+ "basis": "advisory_not_measured",
57
+ "cpus": 2,
58
+ "memory_mib": 4096,
59
+ "timeout_sec": 1200
60
+ },
61
+ "oracle": {
62
+ "timeout_sec": 120
63
+ },
64
+ "source_agent": {
65
+ "command_timeout_sec": null,
66
+ "max_steps": null
67
+ },
68
+ "verifier": {
69
+ "cpus": 1,
70
+ "memory_mib": 1024,
71
+ "pids": 64,
72
+ "timeout_sec": 900,
73
+ "tmpfs_mib": 128
74
+ }
75
+ },
76
+ "private_entry": "evaluator/check.py",
77
+ "private_tree_environment_tokens": [
78
+ "MYBENCH_CANDIDATE_FILE",
79
+ "MYBENCH_OPEN_JUDGE_COMMAND",
80
+ "MYBENCH_OPEN_JUDGE_TIMEOUT",
81
+ "MYBENCH_TASK_JSON"
82
+ ],
83
+ "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.",
84
+ "trusted_trace_environment_aliases": [
85
+ "MYBENCH_TOOL_TRAJECTORY",
86
+ "MYBENCH_TRUSTED_TRACE",
87
+ "TOOL_TRAJECTORY",
88
+ "TOOL_TRAJECTORY_FILE"
89
+ ],
90
+ "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
91
+ "working_directory": "/candidate",
92
+ "writable_ephemeral_roots": [
93
+ "/app",
94
+ "/workspace",
95
+ "/tmp"
96
+ ]
97
+ },
98
+ "schema": "audited-verified-grader-v1",
99
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703"
100
+ }
benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/skill/SKILL.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: brandkit
3
+ description: Generate a complete, accessible brand design system from a brief — primitive → semantic → component DTCG tokens (color, type, spacing, radius, shadow, motion), light + dark, plus a single theme.css — verified for WCAG. Use when the user wants a from-scratch brand/design foundation, a new palette + type system, or a themeable token kit for a product.
4
+ ---
5
+
6
+ # Skill: Brand Kit
7
+
8
+ Stand up the *foundation* (one token system everything renders from) before any screen. Get this right and every page stays consistent and themeable from one place.
9
+
10
+ ## Steps
11
+ 1. **Brief Inference (mandatory)** — name the industry, audience, the one mood adjective, and motion depth (`taste/design-taste.md` → Brief Inference). Pick an anchoring archetype from `taste/aesthetic-systems.md`.
12
+ 2. **Primitives** — generate the brand color ramp in **OKLCH** (11 shades, consistent chroma) + a neutral ramp; verify the 500 shade ≥ 4.5:1 on white (text) and 600 ≥ 3:1 (UI) per CLAUDE.md Color Generation.
13
+ 3. **Semantic layer** — map roles to primitives: `action.primary`/`-hover`/`destructive`, `text.{primary,secondary,on-action,link}`, `surface.{page,card,raised}`, `border.{default,strong}`, `feedback.{success,warning,error,info}` — and the **dark** overrides (designed, not inverted).
14
+ 4. **Scales** — Major Third type scale + composite text styles, 4px spacing scale, radius tiers, elevation, and `tokens/motion.json`-style durations/easings.
15
+ 5. **Emit** the DTCG `tokens/*.json` (3-tier) + a single `theme.css` (the one shared source, `[data-theme="dark"]` overrides). Optionally feed the token-build pipeline (`token-build` skill) for other platforms.
16
+
17
+ ## Verification (definition of done)
18
+ - `python3 scripts/validate_tokens.py` — valid JSON, all aliases resolve.
19
+ - `python3 scripts/validate_contrast.py` — required text/action/border pairs pass WCAG AA in **light AND dark**; `border.strong` ≥ 3:1.
20
+ - `python3 scripts/validate_theme_refs.py` — every component `var(--…)` resolves to the theme.
21
+ - One theme, no per-page palettes; destructive = danger token (not primary); zero hardcoded values.
22
+
23
+ > Output is a verified token foundation — the measurable part is provable (run `npm run verify`). Brand "feel" still benefits from a human review against `taste/design-taste.md`.
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/evaluator/auto_policy.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bounded-policy-v1",
3
+ "stdlib_only": true,
4
+ "forbid_network": false,
5
+ "forbid_subprocess": false,
6
+ "forbid_native": true,
7
+ "runtime_owner_ids": [
8
+ "8"
9
+ ],
10
+ "require_execution": true,
11
+ "execution_budget_seconds": 60,
12
+ "total_evaluation_budget_seconds": 420
13
+ }
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 r10_runtime as _r10
4
+ _r10.install_copy('hookify_engine.py')
5
+ import json, os, re, shutil, subprocess, sys, tempfile, ast
6
+ from collections import Counter
7
+
8
+ RULES = {
9
+ "hookify.block-legacy-pm.local.md": '---\nname: block-legacy-package-manager\nenabled: true\nevent: bash\naction: block\npattern: ^\\s*(pip3?|poetry|pipenv)\\s+install\n---\n\nLegacy Python package manager blocked. Use `uv` instead.\n',
10
+ "hookify.console-log.local.md": '---\nname: warn-console-log\nenabled: true\nevent: file\npattern: console\\.log\\(\n---\n\nConsole.log detected!\n',
11
+ "hookify.sensitive-files.local.md": '---\nname: warn-sensitive-file\nenabled: true\nevent: file\nconditions:\n - field: file_path\n operator: regex_match\n pattern: \\.env$\n - field: new_text\n operator: contains\n pattern: API_KEY\n---\n\nAPI key in .env!\n',
12
+ "hookify.dangerous-rm.local.md": '---\nname: warn-dangerous-rm\nenabled: true\nevent: bash\npattern: rm\\s+-rf\n---\n\nDangerous rm.\n',
13
+ "hookify.disabled-rule.local.md": '---\nname: warn-disabled-example\nenabled: false\nevent: all\npattern: .*\n---\n\nDisabled.\n',
14
+ }
15
+ EVENTS = [
16
+ {"event":"bash","command":"pip install requests"},
17
+ {"event":"bash","command":"uv add requests"},
18
+ {"event":"bash","command":"rm -rf /tmp/build && rm -rf cache"},
19
+ {"event":"file","file_path":"src/app.py","new_text":"import os\\nprint('hi')"},
20
+ {"event":"file","file_path":"src/app.js","new_text":"console.log('debug');\\nconsole.log(x);"},
21
+ {"event":"file","file_path":".env","new_text":"API_KEY=abc123"},
22
+ {"event":"file","file_path":".env","new_text":"DATABASE_URL=postgres://localhost"},
23
+ {"event":"file","file_path":".ruff.toml","new_text":"select = []"},
24
+ {"event":"stop"},
25
+ {"event":"prompt","user_prompt":"deploy to production now"},
26
+ ]
27
+ EXTRA_RULES = {
28
+ "hookify.quoted.local.md": '---\nname: quoted-pattern-test\nenabled: true\nevent: file\naction: block\npattern: "console\\.log\\("\n---\nmsg\n',
29
+ "hookify.condops.local.md": '---\nname: cond-ops-test\nenabled: true\nevent: bash\nconditions:\n - field: command\n operator: starts_with\n pattern: git\n - field: command\n operator: not_contains\n pattern: push\n---\nmsg\n',
30
+ }
31
+ EXTRA_EVENTS = [
32
+ {"event":"file","file_path":"a.js","new_text":"console.log('x')"},
33
+ {"event":"bash","command":"git commit -m x"},
34
+ {"event":"bash","command":"git push origin"},
35
+ {"event":"bash","command":"push git stuff"},
36
+ ]
37
+
38
+ def setup(d, rules, events):
39
+ rd = os.path.join(d, "rules"); os.makedirs(rd,exist_ok=True)
40
+ for n, t in rules.items():
41
+ with open(os.path.join(rd, n), "w") as f: f.write(t)
42
+ with open(os.path.join(d, "events.l"), "w") as f:
43
+ for e in events: f.write(json.dumps(e) + "\n")
44
+
45
+ def run_engine(d, nrules):
46
+ args = ["python3", "hookify_engine.py"] + ["rules/" + n for n in nrules] + ["events.l"]
47
+ p = subprocess.run(args, cwd=d, capture_output=True, text=True, errors='replace', timeout=60)
48
+ rep = os.path.join(d, "report.")
49
+ data = None
50
+ if os.path.exists(rep):
51
+ try:
52
+ data = _co_json(rep)
53
+ except (OSError, UnicodeError, ValueError): data = None
54
+ return p.returncode, data
55
+
56
+ def same_matches(actual,expected):
57
+ if not isinstance(actual,list)or not all(isinstance(m,dict)and set(m)=={'rule','action'}and isinstance(m['rule'],str)and isinstance(m['action'],str)for m in actual):return False
58
+ return Counter((m['rule'],m['action'])for m in actual)==Counter((m['rule'],m['action'])for m in expected)
59
+
60
+ def match_items(matches): return matches if isinstance(matches,list) else []
61
+ def names(matches):
62
+ return {m['rule'] for m in match_items(matches) if isinstance(m,dict) and isinstance(m.get('rule'),str)}
63
+ def index_equal(value,index):return type(value)in(int,float)and value==index
64
+
65
+ def entry(rep, i):
66
+ if not isinstance(rep, list) or len(rep) <= i: return None
67
+ return rep[i]
68
+
69
+ def main():
70
+ checks = [None]*10
71
+ src_path = "/candidate/hookify_engine.py"
72
+ src = None
73
+ if os.path.exists(src_path):
74
+ try: src = open(src_path).read()
75
+ except Exception: src = None
76
+ rep = None; rc = None
77
+ if src is not None:
78
+ d = tempfile.mkdtemp(dir="/tmp")
79
+ shutil.copy(src_path, os.path.join(d, "hookify_engine.py"))
80
+ setup(d, RULES, EVENTS)
81
+ rc, rep = run_engine(d, sorted(RULES))
82
+ def fail(i, r): checks[i] = {"id": str(i), "passed": False, "reason": r}
83
+ if src is None:
84
+ for i in range(10): fail(i, "hookify_engine.py missing or unreadable in /candidate")
85
+ print(json.dumps(_r10.finalize(checks, {'8':'hookify_engine.py'}))); return
86
+ # check 0
87
+ ok = rc == 0 and isinstance(rep, list) and len(rep) == 10 and all(isinstance(e, dict) and index_equal(e.get("event_index"),i) for i, e in enumerate(rep))
88
+ checks[0] = {"id":"0","passed":ok,"reason":"" if ok else f"exit={rc}, report valid 10-entry list with event_index 0..9 required"}
89
+ def get(i):
90
+ e = entry(rep, i)
91
+ return e if isinstance(e, dict) else {}
92
+ # check 1
93
+ e = get(0); ok = e.get("decision")=="block" and any(m.get("rule")=="block-legacy-package-manager" and m.get("action")=="block" for m in match_items(e.get("matches")) if isinstance(m,dict))
94
+ checks[1] = {"id":"1","passed":ok,"reason":"" if ok else "event 0 must be block via block-legacy-package-manager (anchored pip/poetry/pipenv install)"}
95
+ # check 2
96
+ e = get(1); ok = e.get("decision")=="allow" and e.get("matches")==[]
97
+ checks[2] = {"id":"2","passed":ok,"reason":"" if ok else "event 1 (uv add) must be allow with empty matches"}
98
+ # check 3
99
+ e = get(2); ok = e.get("decision")=="warn" and "warn-dangerous-rm" in names(e.get("matches",[]))
100
+ checks[3] = {"id":"3","passed":ok,"reason":"" if ok else "event 2 must be warn matching warn-dangerous-rm (rm\\s+-rf, both occurrences)"}
101
+ # check 4
102
+ e = get(4); ok = e.get("decision")=="warn" and "warn-console-log" in names(e.get("matches",[]))
103
+ checks[4] = {"id":"4","passed":ok,"reason":"" if ok else "event 4 (console.log in app.js) must be warn matching warn-console-log"}
104
+ # check 5
105
+ e5 = get(5); e6 = get(6)
106
+ ok = e5.get("decision")=="warn" and "warn-sensitive-file" in names(e5.get("matches",[])) and e6.get("decision")=="allow" and e6.get("matches")==[]
107
+ checks[5] = {"id":"5","passed":ok,"reason":"" if ok else "event 5 (.env with API_KEY) must be warn via warn-sensitive-file; event 6 (.env without API_KEY) allow with empty matches"}
108
+ # check 6
109
+ e = get(7); ok = e.get("decision")=="block" and any(isinstance(m,dict) and m.get("rule")=="config-tamper-guard" and m.get("action")=="block" for m in match_items(e.get("matches")))
110
+ checks[6] = {"id":"6","passed":ok,"reason":"" if ok else "event 7 (.ruff.toml edit) must be block with config-tamper-guard match appended"}
111
+ # check 7
112
+ bad = any("warn-disabled-example" in names(e.get("matches",[])) for e in (rep if isinstance(rep,list) else []) if isinstance(e,dict))
113
+ checks[7] = {"id":"7","passed":(not bad) and rep is not None,"reason":"" if not bad else "disabled rule warn-disabled-example must never appear in matches"}
114
+ # check 8: quoted patterns, conditions operators, stdlib only
115
+ ok8 = True; why = ""
116
+ try:
117
+ tree = ast.parse(src)
118
+ mods = set()
119
+ for n in ast.walk(tree):
120
+ if isinstance(n, ast.Import):
121
+ for a in n.names: mods.add(a.name.split(".")[0])
122
+ elif isinstance(n, ast.ImportFrom) and n.module and n.level == 0:
123
+ mods.add(n.module.split(".")[0])
124
+ std = getattr(sys, "stdlib_module_names", None)
125
+ if std is None:
126
+ std = {"argparse","json","re","sys","os","pathlib","typing","collections","itertools","functools","dataclasses","shlex","subprocess","math","string","textwrap","io","copy","datetime","enum","glob","tempfile","traceback","ast","abc","contextlib","hashlib","base64","uuid","time","random","csv","statistics"}
127
+ ext = set() if _r10.stdlib_gate('hookify_engine.py') else {'nonstdlib reachable dependency'}
128
+ if ext: ok8, why = False, "non-stdlib imports: " + ",".join(sorted(ext))
129
+ except Exception:
130
+ pass
131
+ if ok8:
132
+ d2 = tempfile.mkdtemp(dir="/tmp")
133
+ shutil.copy(src_path, os.path.join(d2, "hookify_engine.py"))
134
+ setup(d2, EXTRA_RULES, EXTRA_EVENTS)
135
+ rc2, rep2 = run_engine(d2, sorted(EXTRA_RULES))
136
+ def g2(i):
137
+ if not isinstance(rep2, list) or len(rep2) <= i: return {}
138
+ e = rep2[i]; return e if isinstance(e, dict) else {}
139
+ a, b, c, dd = g2(0), g2(1), g2(2), g2(3)
140
+ if rc2 != 0 or not isinstance(rep2, list) or len(rep2) != 4:
141
+ ok8, why = False, "extended run failed (exit=%s)" % rc2
142
+ elif not (a.get("decision")=="block" and "quoted-pattern-test" in names(a.get("matches",[]))):
143
+ ok8, why = False, "quoted pattern not stripped/matched (event 0 of extended run)"
144
+ elif not (b.get("decision")=="warn" and "cond-ops-test" in names(b.get("matches",[]))):
145
+ ok8, why = False, "conditions operators (starts_with+not_contains) not honored (event 1)"
146
+ elif c.get("decision")!="allow" or dd.get("decision")!="allow":
147
+ ok8, why = False, "conditions must all match (events 2/3 should allow)"
148
+ if ok8:
149
+ capability_rules={
150
+ 'equals.md':'---\nname: equals-capability\nenabled: true\nevent: prompt\nconditions:\n - field: user_prompt\n operator: equals\n pattern: exact value\n---\n',
151
+ 'ends.md':'---\nname: ends-capability\nenabled: true\nevent: file\naction: block\nconditions:\n - field: file_path\n operator: ends_with\n pattern: .unit\n---\n'}
152
+ capability_events=[
153
+ {'event':'prompt','user_prompt':'exact value'},
154
+ {'event':'prompt','user_prompt':'pre exact value post'},
155
+ {'event':'prompt','user_prompt':'Exact value'},
156
+ {'event':'prompt'},
157
+ {'event':'file','file_path':'src/check.unit','new_text':''},
158
+ {'event':'file','file_path':'src/check.unit.bak','new_text':''},
159
+ {'event':'file','file_path':'src/check.UNIT','new_text':''},
160
+ {'event':'file','new_text':''}]
161
+ td=tempfile.mkdtemp(dir='/tmp')
162
+ try:
163
+ shutil.copy(src_path,os.path.join(td,'hookify_engine.py'))
164
+ setup(td,capability_rules,capability_events)
165
+ capability_rc,capability=run_engine(td,sorted(capability_rules))
166
+ valid=capability_rc==0 and isinstance(capability,list) and len(capability)==len(capability_events)
167
+ if valid:
168
+ for index,item in enumerate(capability):
169
+ expected=[{'rule':'equals-capability','action':'warn'}] if index==0 else [{'rule':'ends-capability','action':'block'}] if index==4 else []
170
+ decision='warn' if index==0 else 'block' if index==4 else 'allow'
171
+ valid=valid and isinstance(item,dict) and index_equal(item.get('event_index'),index) and item.get('decision')==decision and same_matches(item.get('matches'),expected)
172
+ ok8=ok8 and valid
173
+ if not valid:why='equals/ends_with exact comparison or missing-field failure violated'
174
+ except Exception as error:raise RuntimeError('Trusted operator probe failed') from error
175
+ finally:shutil.rmtree(td,ignore_errors=True)
176
+ try:
177
+ all_rules={'all-warn.md':'---\nname: all-warn\nenabled: true\nevent: all\nconditions:\n - field: probe\n operator: contains\n pattern: needle\n---\n','all-block.md':'---\nname: all-block\nenabled: true\nevent: all\naction: block\nconditions:\n - field: guard\n operator: equals\n pattern: yes\n---\n','all-pattern.md':'---\nname: all-pattern\nenabled: true\nevent: all\npattern: r10signal\n---\n'}
178
+ all_events=[dict(event=e,probe='needle',command='r10signal',new_text='r10signal',file_path='safe.txt',user_prompt='r10signal')for e in['bash','file','stop','prompt']]
179
+ all_events+=[dict(event='prompt',guard='yes'),dict(event='stop',probe='not-a-match')]
180
+ td=tempfile.mkdtemp(dir='/tmp')
181
+ try:
182
+ shutil.copy(src_path,os.path.join(td,'hookify_engine.py'));setup(td,all_rules,all_events);rc_all,r_all=run_engine(td,sorted(all_rules))
183
+ all_ok=rc_all==0 and isinstance(r_all,list)and len(r_all)==len(all_events)
184
+ for j,item in enumerate(r_all if isinstance(r_all,list)else[]):
185
+ expected=[{'rule':'all-pattern','action':'warn'},{'rule':'all-warn','action':'warn'}]if j<2 else[{'rule':'all-warn','action':'warn'}]if j<4 else[{'rule':'all-block','action':'block'}]if j==4 else[]
186
+ all_ok=all_ok and isinstance(item,dict)and index_equal(item.get('event_index'),j) and item.get('decision')==('warn'if j<4 else'block'if j==4 else'allow')and same_matches(item.get('matches'),expected)
187
+ finally:shutil.rmtree(td,ignore_errors=True)
188
+ checks[7]['passed']=checks[7]['passed']and all_ok
189
+ if not all_ok:checks[7]['reason']+='; enabled event=all must match appropriate fields in bash/file/stop/prompt'
190
+ protected=['src/.ruff.toml','nested/biome.','.yamllint','config/.hadolint.yaml','pyproject.toml']
191
+ nearby=['src/.ruff.toml.bak','biome.json','.yamllint.yaml','.hadolint.yml','pyproject.toml.bak','safe.py']
192
+ config_events=[dict(event='file',file_path=f,new_text='setting = true')for f in protected+nearby]
193
+ td=tempfile.mkdtemp(dir='/tmp')
194
+ try:
195
+ shutil.copy(src_path,os.path.join(td,'hookify_engine.py'));setup(td,{'none.md':'---\nname: none\nenabled: false\nevent: all\npattern: .*\n---\n'},config_events);rc_config,r_config=run_engine(td,['none.md'])
196
+ config_ok=rc_config==0 and isinstance(r_config,list)and len(r_config)==len(config_events)
197
+ for j,item in enumerate(r_config if isinstance(r_config,list)else[]):
198
+ expected=[{'rule':'config-tamper-guard','action':'block'}]if j<len(protected)else[]
199
+ config_ok=config_ok and isinstance(item,dict)and index_equal(item.get('event_index'),j) and item.get('decision')==('block'if j<len(protected)else'allow')and same_matches(item.get('matches'),expected)
200
+ finally:shutil.rmtree(td,ignore_errors=True)
201
+ checks[6]['passed']=checks[6]['passed']and config_ok
202
+ if not config_ok:checks[6]['reason']+='; exact five protected suffixes and negative nearby suffixes'
203
+ except Exception as error:
204
+ raise RuntimeError('Trusted all-event or suffix probe failed') from error
205
+ try:
206
+ help_run=subprocess.run([sys.executable,'hookify_engine.py','--help'],cwd=d,capture_output=True,text=True,errors='replace',timeout=20)
207
+ help_ok=help_run.returncode==0 and bool(re.search(r'usage\s*:',help_run.stdout,re.I))
208
+ except (OSError,subprocess.SubprocessError) as error:raise RuntimeError('Trusted help launcher failed') from error
209
+ ok8=ok8 and help_ok
210
+ if not help_ok:why+='; public --help must print argparse usage and exit0'
211
+ checks[8] = {"id":"8","passed":ok8,"reason":why}
212
+ # check 9
213
+ ok = isinstance(rep, list) and all(isinstance(e, dict) and set(e.keys()) >= {"event_index","decision","matches"} and type(e.get('event_index')) is int and e['event_index']>=0 and e.get('decision') in ('allow','warn','block') and isinstance(e['matches'],list) and all(isinstance(m, dict) and set(m.keys()) >= {"rule","action"} and isinstance(m['rule'],str) and m['action'] in ('warn','block') for m in e['matches']) for e in rep)
214
+ checks[9] = {"id":"9","passed":ok,"reason":"" if ok else "report. must be valid JSON; entries need event_index/decision/matches; matches need rule/action"}
215
+ print(json.dumps(_r10.finalize(checks, {'8':'hookify_engine.py'})))
216
+
217
+ main()
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/dependency_scan.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Full-source dependency inference is intentionally absent.
15
+ # The final owner combines functional facts with the trusted invocation receipt.
16
+ return True, [], 'deferred: actual graded invocation policy'
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/r10_runtime.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """R10 grader helper. This file runs only inside an offline verifier container."""
3
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
4
+ import json,os,pathlib,shutil
5
+ from dependency_scan import scan_stdlib
6
+ C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'))
7
+ _copies={};_deps={}
8
+ def dependency(entry):
9
+ key=str(entry)
10
+ if key not in _deps:_deps[key]=scan_stdlib(C,[key])
11
+ return _deps[key]
12
+ def stdlib_gate(entry):
13
+ # Unknown is provisionally neutral; finalize() preserves it as unscored.
14
+ return dependency(entry)[0] is not False
15
+ def finalize(checks,owners):
16
+ for row in checks:
17
+ entry=owners.get(str(row['id']))
18
+ if entry is None:continue
19
+ ok,_,why=dependency(entry)
20
+ if ok is False:row['passed']=False
21
+ elif ok is None and row.get('passed')is not False:row['passed']=None
22
+ row['reason']=row.get('reason','')+'; reachable dependency closure: '+why
23
+ return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks}
24
+ def strict_pairs(pairs):
25
+ out={}
26
+ for key,value in pairs:
27
+ if key in out:raise ValueError('duplicate JSON object key: '+key)
28
+ out[key]=value
29
+ return out
30
+ def read_json(path):
31
+ return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs,
32
+ parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x)))
33
+ def install_copy(entry):
34
+ """Complete authored dependencies without copying stale deliverables into fixtures."""
35
+ if entry in _copies:return
36
+ _copies[entry]=True
37
+ try:task=json.loads(pathlib.Path('/source/task.json').read_text())
38
+ except (OSError,ValueError):task={}
39
+ excluded=[]
40
+ for value in task.get('outputs',[]):
41
+ value=value.get('path')if isinstance(value,dict)else value
42
+ if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value))
43
+ original_copy=shutil.copy;original_copyfile=shutil.copyfile
44
+ def extra(src,dst):
45
+ try:
46
+ source=pathlib.Path(src)
47
+ if source.name!=pathlib.Path(entry).name:return
48
+ source.resolve().relative_to(C.resolve())
49
+ except (ValueError,TypeError,OSError):return
50
+ destination=pathlib.Path(dst)
51
+ if destination.is_dir():destination=destination/source.name
52
+ root=destination.parent
53
+ # Helpers keep the entry's authored relative directory context.
54
+ for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent
55
+ for dp,dn,fn in os.walk(str(C),followlinks=False):
56
+ dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')]
57
+ for name in fn:
58
+ p=pathlib.Path(dp)/name;rel=p.relative_to(C)
59
+ if any(rel==x or x in rel.parents for x in excluded):continue
60
+ if p.resolve()==source.resolve():continue
61
+ out=root/rel
62
+ if out.exists()or out.is_symlink():continue
63
+ out.parent.mkdir(parents=True,exist_ok=True)
64
+ if p.is_symlink():out.symlink_to(os.readlink(str(p)))
65
+ elif p.is_file():original_copyfile(str(p),str(out))
66
+ def copy(src,dst,*args,**kwargs):
67
+ result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result
68
+ def copyfile(src,dst,*args,**kwargs):
69
+ result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result
70
+ shutil.copy=copy;shutil.copyfile=copyfile
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/grading/verified_config.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "d8ca51d1bf001d570190dfca",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185",
8
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
9
+ "auto_policy.json": "9dbda2dad4e8b0dda92db60176543b74b5f12bdf8e5aec1d848c8c59f5113771",
10
+ "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50",
11
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
12
+ "autograde_task_check.py": "4b670bf118b964cc6e879374ac3bb50e0ca8f0c3b6a2ec6d81f3df71e91930d4",
13
+ "r10_runtime.py": "02787c5058002e411017bc4735ad2072988bb35281b1c55b711d003ee0f83bde",
14
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
15
+ "auto_contract.json": "5d4ae92114b3624c943c104e899595f0c91c1ca2d906fc23db00ac88445a5f4b"
16
+ },
17
+ "runtime_requirements": {
18
+ "family": "legacy_original_verified2",
19
+ "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
20
+ "network": "none",
21
+ "read_only_mounts": [
22
+ "task:/source",
23
+ "task:/task",
24
+ "evaluator:/grader",
25
+ "candidate:/candidate",
26
+ "answer:/answer.txt"
27
+ ],
28
+ "writable_tmpfs": [
29
+ "/app",
30
+ "/workspace",
31
+ "/tmp"
32
+ ],
33
+ "copy_completed_candidate_children_to_app_before_grader": true,
34
+ "entrypoint": [
35
+ "python3",
36
+ "/grader/check.py"
37
+ ],
38
+ "working_directory": "/candidate",
39
+ "environment": {
40
+ "MYBENCH_CANDIDATE": "/candidate",
41
+ "MYBENCH_CANDIDATE_PATH": "/candidate",
42
+ "CANDIDATE_DIR": "/candidate",
43
+ "CANDIDATE_ROOT": "/candidate",
44
+ "MYBENCH_SOURCE_TASK": "/source",
45
+ "SOURCE_TASK_DIR": "/source",
46
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
47
+ "MYBENCH_EPHEMERAL_APP": "1",
48
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1"
49
+ },
50
+ "environment_names_detected": [],
51
+ "expected_check_ids": [
52
+ "0",
53
+ "1",
54
+ "2",
55
+ "3",
56
+ "4",
57
+ "5",
58
+ "6",
59
+ "7",
60
+ "8",
61
+ "9"
62
+ ],
63
+ "criterion_count": 10,
64
+ "criterion_weights": {
65
+ "0": 1,
66
+ "1": 1,
67
+ "2": 1,
68
+ "3": 1,
69
+ "4": 1,
70
+ "5": 1,
71
+ "6": 1,
72
+ "7": 1,
73
+ "8": 1,
74
+ "9": 1
75
+ },
76
+ "actual_original_success_criteria_count": 10,
77
+ "original_task_metadata_must_not_define_override_criterion_count": false,
78
+ "requires_external_actual_native_trace": false,
79
+ "requires_external_trusted_snapshot_binding": false,
80
+ "fresh_native_binding_must_not_require_historical_run_id": true,
81
+ "checker_can_execute_candidate_subprocesses": true,
82
+ "host_execution_forbidden": true,
83
+ "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.",
84
+ "docker_image_payload_in_source_tree": false,
85
+ "runtime_missing": [],
86
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
87
+ "grader_timeout_seconds": 600
88
+ },
89
+ "engine": "portable_verified_v1"
90
+ }
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/events.l ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"event": "bash", "command": "pip install requests"}
2
+ {"event": "bash", "command": "uv add requests"}
3
+ {"event": "bash", "command": "rm -rf /tmp/build && rm -rf cache"}
4
+ {"event": "file", "file_path": "src/app.py", "new_text": "import os\nprint('hi')"}
5
+ {"event": "file", "file_path": "src/app.js", "new_text": "console.log('debug');\nconsole.log(x);"}
6
+ {"event": "file", "file_path": ".env", "new_text": "API_KEY=abc123"}
7
+ {"event": "file", "file_path": ".env", "new_text": "DATABASE_URL=postgres://localhost"}
8
+ {"event": "file", "file_path": ".ruff.toml", "new_text": "select = []"}
9
+ {"event": "stop"}
10
+ {"event": "prompt", "user_prompt": "deploy to production now"}
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.block-legacy-pm.local.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: block-legacy-package-manager
3
+ enabled: true
4
+ event: bash
5
+ action: block
6
+ pattern: ^\s*(pip3?|poetry|pipenv)\s+install
7
+ ---
8
+
9
+ Legacy Python package manager blocked. Use `uv` instead.
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.console-log.local.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: warn-console-log
3
+ enabled: true
4
+ event: file
5
+ pattern: console\.log\(
6
+ ---
7
+
8
+ ⚠️ **Console.log detected!** Debug logs shouldn't ship to production. Use a proper logging library.
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.dangerous-rm.local.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: warn-dangerous-rm
3
+ enabled: true
4
+ event: bash
5
+ pattern: rm\s+-rf
6
+ ---
7
+
8
+ Dangerous recursive force-remove detected. Double-check the path.
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.disabled-rule.local.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: warn-disabled-example
3
+ enabled: false
4
+ event: all
5
+ pattern: .*
6
+ ---
7
+
8
+ This rule is disabled and must never trigger.
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.sensitive-files.local.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: warn-sensitive-file
3
+ enabled: true
4
+ event: file
5
+ conditions:
6
+ - field: file_path
7
+ operator: regex_match
8
+ pattern: \.env$
9
+ - field: new_text
10
+ operator: contains
11
+ pattern: API_KEY
12
+ ---
13
+
14
+ You're adding an API key to a .env file. Ensure this file is in .gitignore!
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/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/d8ca51d1bf001d570190dfca/skill/members/M000/SKILL.md ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: ecc-plankton-code-quality
3
+ description: "ECC: Use para qualidade de código em tempo de escrita com Plankton, autoformatação, lint e correções assistidas por Claude via hooks."
4
+ origin: community
5
+ ---
6
+
7
+ # Plankton Code Quality Skill
8
+
9
+ Integration reference for Plankton (credit: @alxfazio), a write-time code quality enforcement system for Claude Code. Plankton runs formatters and linters on every file edit via PostToolUse hooks, then spawns Claude subprocesses to fix violations the agent didn't catch.
10
+
11
+ ## When to Use
12
+
13
+ - You want automatic formatting and linting on every file edit (not just at commit time)
14
+ - You need defense against agents modifying linter configs to pass instead of fixing code
15
+ - You want tiered model routing for fixes (Haiku for simple style, Sonnet for logic, Opus for types)
16
+ - You work with multiple languages (Python, TypeScript, Shell, YAML, JSON, TOML, Markdown, Dockerfile)
17
+
18
+ ## How It Works
19
+
20
+ ### Three-Phase Architecture
21
+
22
+ Every time Claude Code edits or writes a file, Plankton's `multi_linter.sh` PostToolUse hook runs:
23
+
24
+ ```
25
+ Phase 1: Auto-Format (Silent)
26
+ ├─ Runs formatters (ruff format, biome, shfmt, taplo, markdownlint)
27
+ ├─ Fixes 40-50% of issues silently
28
+ └─ No output to main agent
29
+
30
+ Phase 2: Collect Violations (JSON)
31
+ ├─ Runs linters and collects unfixable violations
32
+ ├─ Returns structured JSON: {line, column, code, message, linter}
33
+ └─ Still no output to main agent
34
+
35
+ Phase 3: Delegate + Verify
36
+ ├─ Spawns claude -p subprocess with violations JSON
37
+ ├─ Routes to model tier based on violation complexity:
38
+ │ ├─ Haiku: formatting, imports, style (E/W/F codes) — 120s timeout
39
+ │ ├─ Sonnet: complexity, refactoring (C901, PLR codes) — 300s timeout
40
+ │ └─ Opus: type system, deep reasoning (unresolved-attribute) — 600s timeout
41
+ ├─ Re-runs Phase 1+2 to verify fixes
42
+ └─ Exit 0 if clean, Exit 2 if violations remain (reported to main agent)
43
+ ```
44
+
45
+ ### What the Main Agent Sees
46
+
47
+ | Scenario | Agent sees | Hook exit |
48
+ |----------|-----------|-----------|
49
+ | No violations | Nothing | 0 |
50
+ | All fixed by subprocess | Nothing | 0 |
51
+ | Violations remain after subprocess | `[hook] N violation(s) remain` | 2 |
52
+ | Advisory (duplicates, old tooling) | `[hook:advisory] ...` | 0 |
53
+
54
+ The main agent only sees issues the subprocess couldn't fix. Most quality problems are resolved transparently.
55
+
56
+ ### Config Protection (Defense Against Rule-Gaming)
57
+
58
+ LLMs will modify `.ruff.toml` or `biome.json` to disable rules rather than fix code. Plankton blocks this with three layers:
59
+
60
+ 1. **PreToolUse hook** — `protect_linter_configs.sh` blocks edits to all linter configs before they happen
61
+ 2. **Stop hook** — `stop_config_guardian.sh` detects config changes via `git diff` at session end
62
+ 3. **Protected files list** — `.ruff.toml`, `biome.json`, `.shellcheckrc`, `.yamllint`, `.hadolint.yaml`, and more
63
+
64
+ ### Package Manager Enforcement
65
+
66
+ A PreToolUse hook on Bash blocks legacy package managers:
67
+ - `pip`, `pip3`, `poetry`, `pipenv` → Blocked (use `uv`)
68
+ - `npm`, `yarn`, `pnpm` → Blocked (use `bun`)
69
+ - Allowed exceptions: `npm audit`, `npm view`, `npm publish`
70
+
71
+ ## Setup
72
+
73
+ ### Quick Start
74
+
75
+ > **Note:** Plankton requires manual installation from its repository. Review the code before installing.
76
+
77
+ ```bash
78
+ # Install core dependencies
79
+ brew install jaq ruff uv
80
+
81
+ # Install Python linters
82
+ uv sync --all-extras
83
+
84
+ # Start Claude Code — hooks activate automatically
85
+ claude
86
+ ```
87
+
88
+ No install command, no plugin config. The hooks in `.claude/settings.json` are picked up automatically when you run Claude Code in the Plankton directory.
89
+
90
+ ### Per-Project Integration
91
+
92
+ To use Plankton hooks in your own project:
93
+
94
+ 1. Copy `.claude/hooks/` directory to your project
95
+ 2. Copy `.claude/settings.json` hook configuration
96
+ 3. Copy linter config files (`.ruff.toml`, `biome.json`, etc.)
97
+ 4. Install the linters for your languages
98
+
99
+ ### Language-Specific Dependencies
100
+
101
+ | Language | Required | Optional |
102
+ |----------|----------|----------|
103
+ | Python | `ruff`, `uv` | `ty` (types), `vulture` (dead code), `bandit` (security) |
104
+ | TypeScript/JS | `biome` | `oxlint`, `semgrep`, `knip` (dead exports) |
105
+ | Shell | `shellcheck`, `shfmt` | — |
106
+ | YAML | `yamllint` | — |
107
+ | Markdown | `markdownlint-cli2` | — |
108
+ | Dockerfile | `hadolint` (>= 2.12.0) | — |
109
+ | TOML | `taplo` | — |
110
+ | JSON | `jaq` | — |
111
+
112
+ ## Pairing with ECC
113
+
114
+ ### Complementary, Not Overlapping
115
+
116
+ | Concern | ECC | Plankton |
117
+ |---------|-----|----------|
118
+ | Code quality enforcement | PostToolUse hooks (Prettier, tsc) | PostToolUse hooks (20+ linters + subprocess fixes) |
119
+ | Security scanning | AgentShield, security-reviewer agent | Bandit (Python), Semgrep (TypeScript) |
120
+ | Config protection | — | PreToolUse blocks + Stop hook detection |
121
+ | Package manager | Detection + setup | Enforcement (blocks legacy PMs) |
122
+ | CI integration | — | Pre-commit hooks for git |
123
+ | Model routing | Manual (`/model opus`) | Automatic (violation complexity → tier) |
124
+
125
+ ### Recommended Combination
126
+
127
+ 1. Install ECC as your plugin (agents, skills, commands, rules)
128
+ 2. Add Plankton hooks for write-time quality enforcement
129
+ 3. Use AgentShield for security audits
130
+ 4. Use ECC's verification-loop as a final gate before PRs
131
+
132
+ ### Avoiding Hook Conflicts
133
+
134
+ If running both ECC and Plankton hooks:
135
+ - ECC's Prettier hook and Plankton's biome formatter may conflict on JS/TS files
136
+ - Resolution: disable ECC's Prettier PostToolUse hook when using Plankton (Plankton's biome is more comprehensive)
137
+ - Both can coexist on different file types (ECC handles what Plankton doesn't cover)
138
+
139
+ ## Configuration Reference
140
+
141
+ Plankton's `.claude/hooks/config.json` controls all behavior:
142
+
143
+ ```json
144
+ {
145
+ "languages": {
146
+ "python": true,
147
+ "shell": true,
148
+ "yaml": true,
149
+ "json": true,
150
+ "toml": true,
151
+ "dockerfile": true,
152
+ "markdown": true,
153
+ "typescript": {
154
+ "enabled": true,
155
+ "js_runtime": "auto",
156
+ "biome_nursery": "warn",
157
+ "semgrep": true
158
+ }
159
+ },
160
+ "phases": {
161
+ "auto_format": true,
162
+ "subprocess_delegation": true
163
+ },
164
+ "subprocess": {
165
+ "tiers": {
166
+ "haiku": { "timeout": 120, "max_turns": 10 },
167
+ "sonnet": { "timeout": 300, "max_turns": 10 },
168
+ "opus": { "timeout": 600, "max_turns": 15 }
169
+ },
170
+ "volume_threshold": 5
171
+ }
172
+ }
173
+ ```
174
+
175
+ **Key settings:**
176
+ - Disable languages you don't use to speed up hooks
177
+ - `volume_threshold` — violations > this count auto-escalate to a higher model tier
178
+ - `subprocess_delegation: false` — skip Phase 3 entirely (just report violations)
179
+
180
+ ## Environment Overrides
181
+
182
+ | Variable | Purpose |
183
+ |----------|---------|
184
+ | `HOOK_SKIP_SUBPROCESS=1` | Skip Phase 3, report violations directly |
185
+ | `HOOK_SUBPROCESS_TIMEOUT=N` | Override tier timeout |
186
+ | `HOOK_DEBUG_MODEL=1` | Log model selection decisions |
187
+ | `HOOK_SKIP_PM=1` | Bypass package manager enforcement |
188
+
189
+ ## References
190
+
191
+ - Plankton (credit: @alxfazio)
192
+ - Plankton REFERENCE.md — Full architecture documentation (credit: @alxfazio)
193
+ - Plankton SETUP.md — Detailed installation guide (credit: @alxfazio)
194
+
195
+ ## ECC v1.8 Additions
196
+
197
+ ### Copyable Hook Profile
198
+
199
+ Set strict quality behavior:
200
+
201
+ ```bash
202
+ export ECC_HOOK_PROFILE=strict
203
+ export ECC_QUALITY_GATE_FIX=true
204
+ export ECC_QUALITY_GATE_STRICT=true
205
+ ```
206
+
207
+ ### Language Gate Table
208
+
209
+ - TypeScript/JavaScript: Biome preferred, Prettier fallback
210
+ - Python: Ruff format/check
211
+ - Go: gofmt
212
+
213
+ ### Config Tamper Guard
214
+
215
+ During quality enforcement, flag changes to config files in same iteration:
216
+
217
+ - `biome.json`, `.eslintrc*`, `prettier.config*`, `tsconfig.json`, `pyproject.toml`
218
+
219
+ If config is changed to suppress violations, require explicit review before merge.
220
+
221
+ ### CI Integration Pattern
222
+
223
+ Use the same commands in CI as local hooks:
224
+
225
+ 1. run formatter checks
226
+ 2. run lint/type checks
227
+ 3. fail fast on strict mode
228
+ 4. publish remediation summary
229
+
230
+ ### Health Metrics
231
+
232
+ Track:
233
+ - edits flagged by gates
234
+ - average remediation time
235
+ - repeat violations by category
236
+ - merge blocks due to gate failures
benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M001/SKILL.md ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: writing-hookify-rules
3
+ description: This skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
4
+ version: 0.1.0
5
+ kind: reference
6
+ category: platform/governance
7
+ status: active
8
+ tags: [governance, hookify, hooks, platform, rules, writing]
9
+ related_skills: [few-shot-quality-prompting]
10
+ ---
11
+
12
+ # Writing Hookify Rules
13
+
14
+ ## Overview
15
+
16
+ Hookify rules are markdown files with YAML frontmatter that define patterns to watch for and messages to show when those patterns match. Rules are stored in `.claude/hookify.{rule-name}.local.md` files.
17
+
18
+ ## Rule File Format
19
+
20
+ ### Basic Structure
21
+
22
+ ```markdown
23
+ ---
24
+ name: rule-identifier
25
+ enabled: true
26
+ event: bash|file|stop|prompt|all
27
+ pattern: regex-pattern-here
28
+ ---
29
+
30
+ Message to show Claude when this rule triggers.
31
+ Can include markdown formatting, warnings, suggestions, etc.
32
+ ```
33
+
34
+ ### Frontmatter Fields
35
+
36
+ **name** (required): Unique identifier for the rule
37
+ - Use kebab-case: `warn-dangerous-rm`, `block-console-log`
38
+ - Be descriptive and action-oriented
39
+ - Start with verb: warn, prevent, block, require, check
40
+
41
+ **enabled** (required): Boolean to activate/deactivate
42
+ - `true`: Rule is active
43
+ - `false`: Rule is disabled (won't trigger)
44
+ - Can toggle without deleting rule
45
+
46
+ **event** (required): Which hook event to trigger on
47
+ - `bash`: Bash tool commands
48
+ - `file`: Edit, Write, MultiEdit tools
49
+ - `stop`: When agent wants to stop
50
+ - `prompt`: When user submits a prompt
51
+ - `all`: All events
52
+
53
+ **action** (optional): What to do when rule matches
54
+ - `warn`: Show message but allow operation (default)
55
+ - `block`: Prevent operation (PreToolUse) or stop session (Stop events)
56
+ - If omitted, defaults to `warn`
57
+
58
+ **pattern** (simple format): Regex pattern to match
59
+ - Used for simple single-condition rules
60
+ - Matches against command (bash) or new_text (file)
61
+ - Python regex syntax
62
+
63
+ **Example:**
64
+ ```yaml
65
+ event: bash
66
+ pattern: rm\s+-rf
67
+ ```
68
+
69
+ ### Advanced Format (Multiple Conditions)
70
+
71
+ For complex rules with multiple conditions:
72
+
73
+ ```markdown
74
+ ---
75
+ name: warn-env-file-edits
76
+ enabled: true
77
+ event: file
78
+ conditions:
79
+ - field: file_path
80
+ operator: regex_match
81
+ pattern: \.env$
82
+ - field: new_text
83
+ operator: contains
84
+ pattern: API_KEY
85
+ ---
86
+
87
+ You're adding an API key to a .env file. Ensure this file is in .gitignore!
88
+ ```
89
+
90
+ **Condition fields:**
91
+ - `field`: Which field to check
92
+ - For bash: `command`
93
+ - For file: `file_path`, `new_text`, `old_text`, `content`
94
+ - `operator`: How to match
95
+ - `regex_match`: Regex pattern matching
96
+ - `contains`: Substring check
97
+ - `equals`: Exact match
98
+ - `not_contains`: Substring must NOT be present
99
+ - `starts_with`: Prefix check
100
+ - `ends_with`: Suffix check
101
+ - `pattern`: Pattern or string to match
102
+
103
+ **All conditions must match for rule to trigger.**
104
+
105
+ ## Message Body
106
+
107
+ The markdown content after frontmatter is shown to Claude when the rule triggers.
108
+
109
+ **Good messages:**
110
+ - Explain what was detected
111
+ - Explain why it's problematic
112
+ - Suggest alternatives or best practices
113
+ - Use formatting for clarity (bold, lists, etc.)
114
+
115
+ **Example:**
116
+ ```markdown
117
+ ⚠️ **Console.log detected!**
118
+
119
+ You're adding console.log to production code.
120
+
121
+ **Why this matters:**
122
+ - Debug logs shouldn't ship to production
123
+ - Console.log can expose sensitive data
124
+ - Impacts browser performance
125
+
126
+ **Alternatives:**
127
+ - Use a proper logging library
128
+ - Remove before committing
129
+ - Use conditional debug builds
130
+ ```
131
+
132
+ ## Event Type Guide
133
+
134
+ ### bash Events
135
+
136
+ Match Bash command patterns:
137
+
138
+ ```markdown
139
+ ---
140
+ event: bash
141
+ pattern: sudo\s+|rm\s+-rf|chmod\s+777
142
+ ---
143
+
144
+ Dangerous command detected!
145
+ ```
146
+
147
+ **Common patterns:**
148
+ - Dangerous commands: `rm\s+-rf`, `dd\s+if=`, `mkfs`
149
+ - Privilege escalation: `sudo\s+`, `su\s+`
150
+ - Permission issues: `chmod\s+777`, `chown\s+root`
151
+
152
+ ### file Events
153
+
154
+ Match Edit/Write/MultiEdit operations:
155
+
156
+ ```markdown
157
+ ---
158
+ event: file
159
+ pattern: console\.log\(|eval\(|innerHTML\s*=
160
+ ---
161
+
162
+ Potentially problematic code pattern detected!
163
+ ```
164
+
165
+ **Match on different fields:**
166
+ ```markdown
167
+ ---
168
+ event: file
169
+ conditions:
170
+ - field: file_path
171
+ operator: regex_match
172
+ pattern: \.tsx?$
173
+ - field: new_text
174
+ operator: regex_match
175
+ pattern: console\.log\(
176
+ ---
177
+
178
+ Console.log in TypeScript file!
179
+ ```
180
+
181
+ **Common patterns:**
182
+ - Debug code: `console\.log\(`, `debugger`, `print\(`
183
+ - Security risks: `eval\(`, `innerHTML\s*=`, `dangerouslySetInnerHTML`
184
+ - Sensitive files: `\.env$`, `credentials`, `\.pem$`
185
+ - Generated files: `node_modules/`, `dist/`, `build/`
186
+
187
+ ### stop Events
188
+
189
+ Match when agent wants to stop (completion checks):
190
+
191
+ ```markdown
192
+ ---
193
+ event: stop
194
+ pattern: .*
195
+ ---
196
+
197
+ Before stopping, verify:
198
+ - [] Tests were run
199
+ - [] Build succeeded
200
+ - [] Documentation updated
201
+ ```
202
+
203
+ **Use for:**
204
+ - Reminders about required steps
205
+ - Completion checklists
206
+ - Process enforcement
207
+
208
+ ### prompt Events
209
+
210
+ Match user prompt content (advanced):
211
+
212
+ ```markdown
213
+ ---
214
+ event: prompt
215
+ conditions:
216
+ - field: user_prompt
217
+ operator: contains
218
+ pattern: deploy to production
219
+ ---
220
+
221
+ Production deployment checklist:
222
+ - [] Tests passing?
223
+ - [] Reviewed by team?
224
+ - [] Monitoring ready?
225
+ ```
226
+
227
+ ## Pattern Writing Tips
228
+
229
+ ### Regex Basics
230
+
231
+ **Literal characters:** Most characters match themselves
232
+ - `rm` matches "rm"
233
+ - `console.log` matches "console.log"
234
+
235
+ **Special characters need escaping:**
236
+ - `.` (any char) → `\.` (literal dot)
237
+ - `(` `)` → `\(` `\)` (literal parens)
238
+ - `[` `]` → `\[` `\]` (literal brackets)
239
+
240
+ **Common metacharacters:**
241
+ - `\s` - whitespace (space, tab, newline)
242
+ - `\d` - digit (0-9)
243
+ - `\w` - word character (a-z, A-Z, 0-9, _)
244
+ - `.` - any character
245
+ - `+` - one or more
246
+ - `*` - zero or more
247
+ - `?` - zero or one
248
+ - `|` - OR
249
+
250
+ **Examples:**
251
+ ```
252
+ rm\s+-rf Matches: rm -rf, rm -rf
253
+ console\.log\( Matches: console.log(
254
+ (eval|exec)\( Matches: eval( or exec(
255
+ chmod\s+777 Matches: chmod 777, chmod 777
256
+ API_KEY\s*= Matches: API_KEY=, API_KEY =
257
+ ```
258
+
259
+ ### Testing Patterns
260
+
261
+ Test regex patterns before using:
262
+
263
+ ```bash
264
+ python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"
265
+ ```
266
+
267
+ Or use online regex testers (regex101.com with Python flavor).
268
+
269
+ ### Common Pitfalls
270
+
271
+ **Too broad:**
272
+ ```yaml
273
+ pattern: log # Matches "log", "login", "dialog", "catalog"
274
+ ```
275
+ Better: `console\.log\(|logger\.`
276
+
277
+ **Too specific:**
278
+ ```yaml
279
+ pattern: rm -rf /tmp # Only matches exact path
280
+ ```
281
+ Better: `rm\s+-rf`
282
+
283
+ **Escaping issues:**
284
+ - YAML quoted strings: `"pattern"` requires double backslashes `\\s`
285
+ - YAML unquoted: `pattern: \s` works as-is
286
+ - **Recommendation**: Use unquoted patterns in YAML
287
+
288
+ ## File Organization
289
+
290
+ **Location:** All rules in `.claude/` directory
291
+ **Naming:** `.claude/hookify.{descriptive-name}.local.md`
292
+ **Gitignore:** Add `.claude/*.local.md` to `.gitignore`
293
+
294
+ **Good names:**
295
+ - `hookify.dangerous-rm.local.md`
296
+ - `hookify.console-log.local.md`
297
+ - `hookify.require-tests.local.md`
298
+ - `hookify.sensitive-files.local.md`
299
+
300
+ **Bad names:**
301
+ - `hookify.rule1.local.md` (not descriptive)
302
+ - `hookify.md` (missing .local)
303
+ - `danger.local.md` (missing hookify prefix)
304
+
305
+ ## Workflow
306
+
307
+ ### Creating a Rule
308
+
309
+ 1. Identify unwanted behavior
310
+ 2. Determine which tool is involved (Bash, Edit, etc.)
311
+ 3. Choose event type (bash, file, stop, etc.)
312
+ 4. Write regex pattern
313
+ 5. Create `.claude/hookify.{name}.local.md` file in project root
314
+ 6. Test immediately - rules are read dynamically on next tool use
315
+
316
+ ### Refining a Rule
317
+
318
+ 1. Edit the `.local.md` file
319
+ 2. Adjust pattern or message
320
+ 3. Test immediately - changes take effect on next tool use
321
+
322
+ ### Disabling a Rule
323
+
324
+ **Temporary:** Set `enabled: false` in frontmatter
325
+ **Permanent:** Delete the `.local.md` file
326
+
327
+ ## Examples
328
+
329
+ See `${CLAUDE_PLUGIN_ROOT}/examples/` for complete examples:
330
+ - `dangerous-rm.local.md` - Block dangerous rm commands
331
+ - `console-log-warning.local.md` - Warn about console.log
332
+ - `sensitive-files-warning.local.md` - Warn about editing .env files
333
+
334
+ ## Quick Reference
335
+
336
+ **Minimum viable rule:**
337
+ ```markdown
338
+ ---
339
+ name: my-rule
340
+ enabled: true
341
+ event: bash
342
+ pattern: dangerous_command
343
+ ---
344
+
345
+ Warning message here
346
+ ```
347
+
348
+ **Rule with conditions:**
349
+ ```markdown
350
+ ---
351
+ name: my-rule
352
+ enabled: true
353
+ event: file
354
+ conditions:
355
+ - field: file_path
356
+ operator: regex_match
357
+ pattern: \.ts$
358
+ - field: new_text
359
+ operator: contains
360
+ pattern: any
361
+ ---
362
+
363
+ Warning message
364
+ ```
365
+
366
+ **Event types:**
367
+ - `bash` - Bash commands
368
+ - `file` - File edits
369
+ - `stop` - Completion checks
370
+ - `prompt` - User input
371
+ - `all` - All events
372
+
373
+ **Field options:**
374
+ - Bash: `command`
375
+ - File: `file_path`, `new_text`, `old_text`, `content`
376
+ - Prompt: `user_prompt`
377
+
378
+ **Operators:**
379
+ - `regex_match`, `contains`, `equals`, `not_contains`, `starts_with`, `ends_with`
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/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/da0ea4af7d02ad888fcae5c0/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/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "bounded-policy-v1",
3
+ "stdlib_only": true,
4
+ "forbid_network": true,
5
+ "forbid_subprocess": false,
6
+ "forbid_native": true,
7
+ "runtime_owner_ids": [
8
+ "1"
9
+ ],
10
+ "require_execution": true,
11
+ "execution_budget_seconds": 60,
12
+ "total_evaluation_budget_seconds": 420
13
+ }
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/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/da0ea4af7d02ad888fcae5c0/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/da0ea4af7d02ad888fcae5c0/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,os,subprocess,sys
4
+ from pathlib import Path
5
+ from dependency_scan import scan_stdlib
6
+ from workspace_copy import workspace
7
+ CANDIDATE=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'));IDS=list(map(str,range(10)))
8
+ PANELS=json.loads((Path(__file__).parent/'input_snapshots/routes.json').read_text())
9
+ def tri(values):return False if any(value is False for value in values)else None if any(value is None for value in values)else True
10
+ def entry(actual,wanted):return isinstance(actual,dict)and all(key in actual and actual[key]==value for key,value in wanted.items())
11
+ def grade(out,panel):
12
+ expected=panel['expected']
13
+ shape=isinstance(out,list)and len(out)==len(expected)
14
+ if shape:
15
+ shape=all(isinstance(row,dict)and {'name','path','params','query'}<=row.keys()and(row['name']is None or isinstance(row['name'],str))and isinstance(row['path'],str)and isinstance(row['params'],dict)and all(isinstance(value,str)for value in row['params'].values())and isinstance(row['query'],dict)for row in out)
16
+ values={'2':shape}
17
+ for owner in range(3,9):values[str(owner)]=all(isinstance(out,list)and index<len(out)and entry(out[index],wanted)for index,(wanted,domain)in enumerate(zip(expected,panel['owners']))if domain==owner)
18
+ return values
19
+ def once(panel):
20
+ with workspace():
21
+ work=Path('/app');(work/'routes.').write_text(json.dumps(panel['routes']),encoding='utf-8');(work/'attempts.').write_text(json.dumps(panel['attempts']),encoding='utf-8');output=work/'result.'
22
+ if output.is_dir()and not output.is_symlink():
23
+ import shutil
24
+ shutil.rmtree(output)
25
+ elif output.exists()or output.is_symlink():output.unlink()
26
+ try:process=subprocess.run([sys.executable,'guard_sim.py'],cwd=work,capture_output=True,timeout=35)
27
+ except subprocess.TimeoutExpired:return (False,grade(None,panel))
28
+ except OSError as error:raise RuntimeError("Trusted router launcher failed") from error
29
+ if process.returncode<0:return (False,grade(None,panel))
30
+ try:out=_co_json(output,parse_constant=lambda text:(_ for _ in()).throw(ValueError(text)))
31
+ except(OSError,ValueError,UnicodeError):out=None
32
+ return out is not None,grade(out,panel)
33
+ def main():
34
+ if not(CANDIDATE/'guard_sim.py').is_file():return {i:False for i in IDS}
35
+ ok,_,why=scan_stdlib(CANDIDATE,['guard_sim.py']);dependency=None if why.startswith('unknown:')else ok
36
+ rows=[once(panel)for panel in PANELS]
37
+ values={'0':tri([None if row is None else row[0]for row in rows]),'1':dependency}
38
+ for owner in range(2,9):values[str(owner)]=tri([None if row is None else row[1][str(owner)]for row in rows])
39
+ values['9']=tri([None if row is None else all(row[1].values())for row in rows[1:]])
40
+ return values
41
+ if __name__=='__main__':
42
+ try:values=main();reason='Original10 routing/guard owners, exact supplied semantics original/metaflag/wildcard/param and source-finite deepchain/namedLogin/dynamic/priority panels; fullapp/helper/bytes/std, no Vue runtime/model/network/priorRun/normalrc0 gate'
43
+ except Exception as error:values={i:None for i in IDS};reason='Trusted preparation unavailable: '+str(error)
44
+ print(json.dumps({'scoreable':all(type(value)is bool for value in values.values()),'checks':[dict(id=i,passed=values[i],reason=reason)for i in IDS]}))
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/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/da0ea4af7d02ad888fcae5c0/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/dependency_scan.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Full-source dependency inference is intentionally absent.
15
+ # The final owner combines functional facts with the trusted invocation receipt.
16
+ return True, [], 'deferred: actual graded invocation policy'
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/input_snapshots/routes.json ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "routes": {
4
+ "routes": [
5
+ {
6
+ "path": "/",
7
+ "redirect": "/dashboard"
8
+ },
9
+ {
10
+ "path": "/login",
11
+ "name": "Login",
12
+ "meta": {
13
+ "publico": true
14
+ }
15
+ },
16
+ {
17
+ "path": "/dashboard",
18
+ "meta": {
19
+ "requerAutenticacao": true
20
+ },
21
+ "children": [
22
+ {
23
+ "path": "",
24
+ "name": "Dashboard"
25
+ },
26
+ {
27
+ "path": "usuarios",
28
+ "name": "Usuarios"
29
+ },
30
+ {
31
+ "path": "usuarios/:id",
32
+ "name": "UsuarioDetalhe",
33
+ "props": true
34
+ }
35
+ ]
36
+ },
37
+ {
38
+ "path": "*",
39
+ "name": "NaoEncontrado"
40
+ }
41
+ ]
42
+ },
43
+ "attempts": {
44
+ "attempts": [
45
+ {
46
+ "id": 1,
47
+ "path": "/",
48
+ "estaLogado": false
49
+ },
50
+ {
51
+ "id": 2,
52
+ "path": "/login",
53
+ "estaLogado": true
54
+ },
55
+ {
56
+ "id": 3,
57
+ "path": "/dashboard/usuarios/42",
58
+ "estaLogado": false
59
+ },
60
+ {
61
+ "id": 4,
62
+ "path": "/dashboard/usuarios/42",
63
+ "estaLogado": true
64
+ },
65
+ {
66
+ "id": 5,
67
+ "path": "/foo/bar",
68
+ "estaLogado": false
69
+ },
70
+ {
71
+ "id": 6,
72
+ "path": "/dashboard/usuarios",
73
+ "estaLogado": true
74
+ }
75
+ ]
76
+ },
77
+ "expected": [
78
+ {
79
+ "name": "Login",
80
+ "path": "/login",
81
+ "params": {},
82
+ "query": {
83
+ "redirect": "/"
84
+ }
85
+ },
86
+ {
87
+ "name": "Dashboard",
88
+ "path": "/dashboard",
89
+ "params": {},
90
+ "query": {}
91
+ },
92
+ {
93
+ "name": "Login",
94
+ "path": "/login",
95
+ "params": {},
96
+ "query": {
97
+ "redirect": "/dashboard/usuarios/42"
98
+ }
99
+ },
100
+ {
101
+ "name": "UsuarioDetalhe",
102
+ "path": "/dashboard/usuarios/42",
103
+ "params": {
104
+ "id": "42"
105
+ },
106
+ "query": {}
107
+ },
108
+ {
109
+ "name": "NaoEncontrado",
110
+ "path": "/foo/bar",
111
+ "params": {},
112
+ "query": {}
113
+ },
114
+ {
115
+ "name": "Usuarios",
116
+ "path": "/dashboard/usuarios",
117
+ "params": {},
118
+ "query": {}
119
+ }
120
+ ],
121
+ "owners": [
122
+ 3,
123
+ 4,
124
+ 5,
125
+ 6,
126
+ 7,
127
+ 8
128
+ ]
129
+ },
130
+ {
131
+ "routes": {
132
+ "routes": [
133
+ {
134
+ "path": "/",
135
+ "redirect": "/dashboard"
136
+ },
137
+ {
138
+ "path": "/login",
139
+ "name": "Login",
140
+ "meta": {
141
+ "publico": true
142
+ }
143
+ },
144
+ {
145
+ "path": "/dashboard",
146
+ "meta": {
147
+ "requerAutenticacao": false
148
+ },
149
+ "children": [
150
+ {
151
+ "path": "",
152
+ "name": "Dashboard"
153
+ },
154
+ {
155
+ "path": "usuarios",
156
+ "name": "Usuarios"
157
+ },
158
+ {
159
+ "path": "usuarios/:id",
160
+ "name": "UsuarioDetalhe",
161
+ "props": true
162
+ }
163
+ ]
164
+ },
165
+ {
166
+ "path": "*",
167
+ "name": "NaoEncontrado"
168
+ }
169
+ ]
170
+ },
171
+ "attempts": {
172
+ "attempts": [
173
+ {
174
+ "id": 1,
175
+ "path": "/",
176
+ "estaLogado": false
177
+ },
178
+ {
179
+ "id": 2,
180
+ "path": "/login",
181
+ "estaLogado": true
182
+ },
183
+ {
184
+ "id": 3,
185
+ "path": "/dashboard/usuarios/42",
186
+ "estaLogado": false
187
+ },
188
+ {
189
+ "id": 4,
190
+ "path": "/dashboard/usuarios/42",
191
+ "estaLogado": true
192
+ },
193
+ {
194
+ "id": 5,
195
+ "path": "/foo/bar",
196
+ "estaLogado": false
197
+ },
198
+ {
199
+ "id": 6,
200
+ "path": "/dashboard/usuarios",
201
+ "estaLogado": true
202
+ }
203
+ ]
204
+ },
205
+ "expected": [
206
+ {
207
+ "name": "Dashboard",
208
+ "path": "/dashboard",
209
+ "params": {},
210
+ "query": {}
211
+ },
212
+ {
213
+ "name": "Dashboard",
214
+ "path": "/dashboard",
215
+ "params": {},
216
+ "query": {}
217
+ },
218
+ {
219
+ "name": "UsuarioDetalhe",
220
+ "path": "/dashboard/usuarios/42",
221
+ "params": {
222
+ "id": "42"
223
+ },
224
+ "query": {}
225
+ },
226
+ {
227
+ "name": "UsuarioDetalhe",
228
+ "path": "/dashboard/usuarios/42",
229
+ "params": {
230
+ "id": "42"
231
+ },
232
+ "query": {}
233
+ },
234
+ {
235
+ "name": "NaoEncontrado",
236
+ "path": "/foo/bar",
237
+ "params": {},
238
+ "query": {}
239
+ },
240
+ {
241
+ "name": "Usuarios",
242
+ "path": "/dashboard/usuarios",
243
+ "params": {},
244
+ "query": {}
245
+ }
246
+ ],
247
+ "owners": [
248
+ 3,
249
+ 4,
250
+ 5,
251
+ 6,
252
+ 7,
253
+ 8
254
+ ]
255
+ },
256
+ {
257
+ "routes": {
258
+ "routes": [
259
+ {
260
+ "path": "/",
261
+ "redirect": "/dashboard"
262
+ },
263
+ {
264
+ "path": "/login",
265
+ "name": "Login",
266
+ "meta": {
267
+ "publico": true
268
+ }
269
+ },
270
+ {
271
+ "path": "/dashboard",
272
+ "meta": {
273
+ "requerAutenticacao": true
274
+ },
275
+ "children": [
276
+ {
277
+ "path": "",
278
+ "name": "Dashboard"
279
+ },
280
+ {
281
+ "path": "usuarios",
282
+ "name": "Usuarios"
283
+ },
284
+ {
285
+ "path": "usuarios/:id",
286
+ "name": "UsuarioDetalhe",
287
+ "props": true
288
+ }
289
+ ]
290
+ },
291
+ {
292
+ "path": "*",
293
+ "name": "Coringa"
294
+ }
295
+ ]
296
+ },
297
+ "attempts": {
298
+ "attempts": [
299
+ {
300
+ "id": 1,
301
+ "path": "/",
302
+ "estaLogado": false
303
+ },
304
+ {
305
+ "id": 2,
306
+ "path": "/login",
307
+ "estaLogado": true
308
+ },
309
+ {
310
+ "id": 3,
311
+ "path": "/dashboard/usuarios/42",
312
+ "estaLogado": false
313
+ },
314
+ {
315
+ "id": 4,
316
+ "path": "/dashboard/usuarios/42",
317
+ "estaLogado": true
318
+ },
319
+ {
320
+ "id": 5,
321
+ "path": "/foo/bar",
322
+ "estaLogado": false
323
+ },
324
+ {
325
+ "id": 6,
326
+ "path": "/dashboard/usuarios",
327
+ "estaLogado": true
328
+ }
329
+ ]
330
+ },
331
+ "expected": [
332
+ {
333
+ "name": "Login",
334
+ "path": "/login",
335
+ "params": {},
336
+ "query": {
337
+ "redirect": "/"
338
+ }
339
+ },
340
+ {
341
+ "name": "Dashboard",
342
+ "path": "/dashboard",
343
+ "params": {},
344
+ "query": {}
345
+ },
346
+ {
347
+ "name": "Login",
348
+ "path": "/login",
349
+ "params": {},
350
+ "query": {
351
+ "redirect": "/dashboard/usuarios/42"
352
+ }
353
+ },
354
+ {
355
+ "name": "UsuarioDetalhe",
356
+ "path": "/dashboard/usuarios/42",
357
+ "params": {
358
+ "id": "42"
359
+ },
360
+ "query": {}
361
+ },
362
+ {
363
+ "name": "Coringa",
364
+ "path": "/foo/bar",
365
+ "params": {},
366
+ "query": {}
367
+ },
368
+ {
369
+ "name": "Usuarios",
370
+ "path": "/dashboard/usuarios",
371
+ "params": {},
372
+ "query": {}
373
+ }
374
+ ],
375
+ "owners": [
376
+ 3,
377
+ 4,
378
+ 5,
379
+ 6,
380
+ 7,
381
+ 8
382
+ ]
383
+ },
384
+ {
385
+ "routes": {
386
+ "routes": [
387
+ {
388
+ "path": "/",
389
+ "redirect": "/dashboard"
390
+ },
391
+ {
392
+ "path": "/login",
393
+ "name": "Login",
394
+ "meta": {
395
+ "publico": true
396
+ }
397
+ },
398
+ {
399
+ "path": "/dashboard",
400
+ "meta": {
401
+ "requerAutenticacao": true
402
+ },
403
+ "children": [
404
+ {
405
+ "path": "",
406
+ "name": "Dashboard"
407
+ },
408
+ {
409
+ "path": "usuarios",
410
+ "name": "Usuarios"
411
+ },
412
+ {
413
+ "path": "usuarios/:userId",
414
+ "name": "UsuarioDetalhe",
415
+ "props": true
416
+ }
417
+ ]
418
+ },
419
+ {
420
+ "path": "*",
421
+ "name": "NaoEncontrado"
422
+ }
423
+ ]
424
+ },
425
+ "attempts": {
426
+ "attempts": [
427
+ {
428
+ "id": 1,
429
+ "path": "/",
430
+ "estaLogado": false
431
+ },
432
+ {
433
+ "id": 2,
434
+ "path": "/login",
435
+ "estaLogado": true
436
+ },
437
+ {
438
+ "id": 3,
439
+ "path": "/dashboard/usuarios/42",
440
+ "estaLogado": false
441
+ },
442
+ {
443
+ "id": 4,
444
+ "path": "/dashboard/usuarios/42",
445
+ "estaLogado": true
446
+ },
447
+ {
448
+ "id": 5,
449
+ "path": "/foo/bar",
450
+ "estaLogado": false
451
+ },
452
+ {
453
+ "id": 6,
454
+ "path": "/dashboard/usuarios",
455
+ "estaLogado": true
456
+ }
457
+ ]
458
+ },
459
+ "expected": [
460
+ {
461
+ "name": "Login",
462
+ "path": "/login",
463
+ "params": {},
464
+ "query": {
465
+ "redirect": "/"
466
+ }
467
+ },
468
+ {
469
+ "name": "Dashboard",
470
+ "path": "/dashboard",
471
+ "params": {},
472
+ "query": {}
473
+ },
474
+ {
475
+ "name": "Login",
476
+ "path": "/login",
477
+ "params": {},
478
+ "query": {
479
+ "redirect": "/dashboard/usuarios/42"
480
+ }
481
+ },
482
+ {
483
+ "name": "UsuarioDetalhe",
484
+ "path": "/dashboard/usuarios/42",
485
+ "params": {
486
+ "userId": "42"
487
+ },
488
+ "query": {}
489
+ },
490
+ {
491
+ "name": "NaoEncontrado",
492
+ "path": "/foo/bar",
493
+ "params": {},
494
+ "query": {}
495
+ },
496
+ {
497
+ "name": "Usuarios",
498
+ "path": "/dashboard/usuarios",
499
+ "params": {},
500
+ "query": {}
501
+ }
502
+ ],
503
+ "owners": [
504
+ 3,
505
+ 4,
506
+ 5,
507
+ 6,
508
+ 7,
509
+ 8
510
+ ]
511
+ },
512
+ {
513
+ "routes": {
514
+ "routes": [
515
+ {
516
+ "path": "*",
517
+ "name": "FreshFallback"
518
+ },
519
+ {
520
+ "path": "/",
521
+ "redirect": "/vault/team/A-5"
522
+ },
523
+ {
524
+ "path": "/signin",
525
+ "name": "Login",
526
+ "meta": {
527
+ "publico": true
528
+ }
529
+ },
530
+ {
531
+ "path": "/dashboard",
532
+ "name": "Dashboard",
533
+ "meta": {
534
+ "requerAutenticacao": true
535
+ }
536
+ },
537
+ {
538
+ "path": "/vault",
539
+ "meta": {
540
+ "requerAutenticacao": true
541
+ },
542
+ "children": [
543
+ {
544
+ "path": "team",
545
+ "meta": {
546
+ "requerAutenticacao": false
547
+ },
548
+ "children": [
549
+ {
550
+ "path": "",
551
+ "name": "TeamIndex"
552
+ },
553
+ {
554
+ "path": ":member",
555
+ "name": "Member",
556
+ "meta": {
557
+ "requerAutenticacao": false
558
+ }
559
+ }
560
+ ]
561
+ },
562
+ {
563
+ "path": "shared",
564
+ "name": "Shared",
565
+ "meta": {
566
+ "publico": true
567
+ }
568
+ }
569
+ ]
570
+ },
571
+ {
572
+ "path": "/welcome",
573
+ "meta": {
574
+ "publico": true
575
+ },
576
+ "children": [
577
+ {
578
+ "path": "info",
579
+ "name": "WelcomeInfo",
580
+ "meta": {
581
+ "publico": false
582
+ }
583
+ }
584
+ ]
585
+ }
586
+ ]
587
+ },
588
+ "attempts": {
589
+ "attempts": [
590
+ {
591
+ "id": 1,
592
+ "path": "/",
593
+ "estaLogado": false
594
+ },
595
+ {
596
+ "id": 2,
597
+ "path": "/signin",
598
+ "estaLogado": true
599
+ },
600
+ {
601
+ "id": 3,
602
+ "path": "/vault/team/A-5",
603
+ "estaLogado": false
604
+ },
605
+ {
606
+ "id": 4,
607
+ "path": "/vault/team/A-5",
608
+ "estaLogado": true
609
+ },
610
+ {
611
+ "id": 5,
612
+ "path": "/missing/x",
613
+ "estaLogado": false
614
+ },
615
+ {
616
+ "id": 6,
617
+ "path": "/vault/team",
618
+ "estaLogado": true
619
+ },
620
+ {
621
+ "id": 7,
622
+ "path": "/vault/shared",
623
+ "estaLogado": false
624
+ },
625
+ {
626
+ "id": 8,
627
+ "path": "/vault/shared",
628
+ "estaLogado": true
629
+ },
630
+ {
631
+ "id": 9,
632
+ "path": "/welcome/info",
633
+ "estaLogado": true
634
+ },
635
+ {
636
+ "id": 10,
637
+ "path": "/welcome/info",
638
+ "estaLogado": false
639
+ },
640
+ {
641
+ "id": 11,
642
+ "path": "/",
643
+ "estaLogado": true
644
+ },
645
+ {
646
+ "id": 12,
647
+ "path": "/vault/team/two/segments",
648
+ "estaLogado": true
649
+ }
650
+ ]
651
+ },
652
+ "expected": [
653
+ {
654
+ "name": "Login",
655
+ "path": "/signin",
656
+ "params": {},
657
+ "query": {
658
+ "redirect": "/"
659
+ }
660
+ },
661
+ {
662
+ "name": "Dashboard",
663
+ "path": "/dashboard",
664
+ "params": {},
665
+ "query": {}
666
+ },
667
+ {
668
+ "name": "Login",
669
+ "path": "/signin",
670
+ "params": {},
671
+ "query": {
672
+ "redirect": "/vault/team/A-5"
673
+ }
674
+ },
675
+ {
676
+ "name": "Member",
677
+ "path": "/vault/team/A-5",
678
+ "params": {
679
+ "member": "A-5"
680
+ },
681
+ "query": {}
682
+ },
683
+ {
684
+ "name": "FreshFallback",
685
+ "path": "/missing/x",
686
+ "params": {},
687
+ "query": {}
688
+ },
689
+ {
690
+ "name": "TeamIndex",
691
+ "path": "/vault/team",
692
+ "params": {},
693
+ "query": {}
694
+ },
695
+ {
696
+ "name": "Login",
697
+ "path": "/signin",
698
+ "params": {},
699
+ "query": {
700
+ "redirect": "/vault/shared"
701
+ }
702
+ },
703
+ {
704
+ "name": "Dashboard",
705
+ "path": "/dashboard",
706
+ "params": {},
707
+ "query": {}
708
+ },
709
+ {
710
+ "name": "Dashboard",
711
+ "path": "/dashboard",
712
+ "params": {},
713
+ "query": {}
714
+ },
715
+ {
716
+ "name": "WelcomeInfo",
717
+ "path": "/welcome/info",
718
+ "params": {},
719
+ "query": {}
720
+ },
721
+ {
722
+ "name": "Member",
723
+ "path": "/vault/team/A-5",
724
+ "params": {
725
+ "member": "A-5"
726
+ },
727
+ "query": {}
728
+ },
729
+ {
730
+ "name": "FreshFallback",
731
+ "path": "/vault/team/two/segments",
732
+ "params": {},
733
+ "query": {}
734
+ }
735
+ ],
736
+ "owners": [
737
+ 3,
738
+ 4,
739
+ 5,
740
+ 6,
741
+ 7,
742
+ 8,
743
+ 5,
744
+ 4,
745
+ 4,
746
+ 8,
747
+ 6,
748
+ 7
749
+ ]
750
+ }
751
+ ]
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/repair_manifest.json ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "query_id": "da0ea4af7d02ad888fcae5c0",
3
+ "sample_index": 289,
4
+ "canonical_check_ids": [
5
+ "0",
6
+ "1",
7
+ "2",
8
+ "3",
9
+ "4",
10
+ "5",
11
+ "6",
12
+ "7",
13
+ "8",
14
+ "9"
15
+ ],
16
+ "original_count": 10,
17
+ "revision": 2,
18
+ "repair_scope": "grader_only_round4_20261018",
19
+ "status": "implemented_pending_independent_review",
20
+ "root_cause": "grader",
21
+ "public_semantics": "Preserve original10routing/guardroles andoldmetamorphs; one namedLoginreferencepathfix, source-finite deepchain/fallback/dynamic/metaOR/priority input panel. Completeclone/std/app/bytes andtypedrequiredresultfacts, no hiddenentrymetadata/normal0/priorRun.",
22
+ "checker_sha256": "830f3184d5247ad1a12ff3d17f947297c6a9ca0a925e25f316284f614c720ebf",
23
+ "actual_authors": [
24
+ "b"
25
+ ],
26
+ "canonical_sha256": "3859016e006d944b92b9f6f7510b4009199a3c2fc649b4f3f710131f93c6caf6",
27
+ "source_binding": {
28
+ "evaluator/check.py": {
29
+ "source_sha256": "052d60c2dc3bde08b6caee4304df6d870a42f679344258cc5bb66396fbb249ff",
30
+ "view_sha256": "052d60c2dc3bde08b6caee4304df6d870a42f679344258cc5bb66396fbb249ff"
31
+ },
32
+ "inputs/attempts.": {
33
+ "source_sha256": "4cad2ac2f753e4a2144b2d30913add34afa9ca421fc0022dc17b5e1e33b15123",
34
+ "view_sha256": "4cad2ac2f753e4a2144b2d30913add34afa9ca421fc0022dc17b5e1e33b15123"
35
+ },
36
+ "inputs/routes.": {
37
+ "source_sha256": "a8588e0b3c7872e29075fb7e41cd6d4346c93a480591ca4c48ac024272dbb01a",
38
+ "view_sha256": "a8588e0b3c7872e29075fb7e41cd6d4346c93a480591ca4c48ac024272dbb01a"
39
+ },
40
+ "instruction.md": {
41
+ "source_sha256": "e6bd420d73e8662cbc5030b20f046f6210194c30910c858fc8f6b5531c528ec1",
42
+ "view_sha256": "e6bd420d73e8662cbc5030b20f046f6210194c30910c858fc8f6b5531c528ec1"
43
+ },
44
+ "reference/answer.txt": {
45
+ "source_sha256": "4fd4c331c78c540af59c46acd6297ef017ea2aecce2c6859ca7b8e1560bfd9f2",
46
+ "view_sha256": "4fd4c331c78c540af59c46acd6297ef017ea2aecce2c6859ca7b8e1560bfd9f2"
47
+ },
48
+ "reference/workspace/attempts.": {
49
+ "source_sha256": "4cad2ac2f753e4a2144b2d30913add34afa9ca421fc0022dc17b5e1e33b15123",
50
+ "view_sha256": "4cad2ac2f753e4a2144b2d30913add34afa9ca421fc0022dc17b5e1e33b15123"
51
+ },
52
+ "reference/workspace/guard_sim.py": {
53
+ "source_sha256": "988df090609f1bbe70ce5bc03630cb7777c148b6ccc7d086f38981d4314b9d4a",
54
+ "view_sha256": "988df090609f1bbe70ce5bc03630cb7777c148b6ccc7d086f38981d4314b9d4a"
55
+ },
56
+ "reference/workspace/instruction.md": {
57
+ "source_sha256": "e6bd420d73e8662cbc5030b20f046f6210194c30910c858fc8f6b5531c528ec1",
58
+ "view_sha256": "e6bd420d73e8662cbc5030b20f046f6210194c30910c858fc8f6b5531c528ec1"
59
+ },
60
+ "reference/workspace/result.": {
61
+ "source_sha256": "15464140b48a283f2d47a79c0df3bb94cb9f8876f1bf03b529da82f0e3986dc5",
62
+ "view_sha256": "15464140b48a283f2d47a79c0df3bb94cb9f8876f1bf03b529da82f0e3986dc5"
63
+ },
64
+ "reference/workspace/routes.": {
65
+ "source_sha256": "a8588e0b3c7872e29075fb7e41cd6d4346c93a480591ca4c48ac024272dbb01a",
66
+ "view_sha256": "a8588e0b3c7872e29075fb7e41cd6d4346c93a480591ca4c48ac024272dbb01a"
67
+ },
68
+ "skill/SKILL.md": {
69
+ "source_sha256": "775e77dc8ac605b36488e6369dab372caa102cd824dd495aeb3d7a21e147b1f6",
70
+ "view_sha256": "775e77dc8ac605b36488e6369dab372caa102cd824dd495aeb3d7a21e147b1f6"
71
+ },
72
+ "task.json": {
73
+ "source_sha256": "05fa04b99d47eddbaf90ddd7e4c7fe5e40c7eddc396245602347a7f71cd79053",
74
+ "view_sha256": "05fa04b99d47eddbaf90ddd7e4c7fe5e40c7eddc396245602347a7f71cd79053"
75
+ }
76
+ },
77
+ "contract_audit": {
78
+ "cause": "grader",
79
+ "task_verdict": "sound",
80
+ "grader_verdict": "repaired",
81
+ "execution_chain_verdict": "public_wiring_sound",
82
+ "canonical_ids_sound": true,
83
+ "no_extra_contract_requirements": true,
84
+ "reviewed_source_paths": [
85
+ "instruction.md",
86
+ "task.json",
87
+ "evaluator/check.py",
88
+ "skill/SKILL.md",
89
+ "inputs/routes.",
90
+ "inputs/attempts.",
91
+ "reference/workspace/guard_sim.py",
92
+ "reference/workspace/result.",
93
+ "reference/answer.txt"
94
+ ],
95
+ "obligations": [
96
+ {
97
+ "id": "run",
98
+ "source_path": "instruction.md",
99
+ "source_lines": [
100
+ 1
101
+ ],
102
+ "requirement": "NamedPython simulator normallycompletes andwritesvalidcurrentJSON, no privateexit0/priorRun/streamencoding gate.",
103
+ "material": true,
104
+ "check_ids": [
105
+ "0"
106
+ ],
107
+ "positive_controls": [
108
+ "authored_named_login_path",
109
+ "combined_helper_app_binary_streams_exit7_metadata"
110
+ ],
111
+ "negative_controls": [
112
+ "present_json_null_result"
113
+ ]
114
+ },
115
+ {
116
+ "id": "stdlib",
117
+ "source_path": "instruction.md",
118
+ "source_lines": [
119
+ 1
120
+ ],
121
+ "requirement": "Pythonstandardlibrary closure andlocalhelpers includingPEP263/dynamicliteralcases.",
122
+ "material": true,
123
+ "check_ids": [
124
+ "1"
125
+ ],
126
+ "positive_controls": [
127
+ "authored_named_login_path",
128
+ "combined_helper_app_binary_streams_exit7_metadata"
129
+ ],
130
+ "negative_controls": [
131
+ "wrong_route_fields_nonstdlib"
132
+ ]
133
+ },
134
+ {
135
+ "id": "array_schema",
136
+ "source_path": "instruction.md",
137
+ "source_lines": [
138
+ 1
139
+ ],
140
+ "requirement": "One typedresultentryperattempt inorder, all requiredname/path/params/query; extraentrymetadata allowed, paramsvaluesstrings.",
141
+ "material": true,
142
+ "check_ids": [
143
+ "2"
144
+ ],
145
+ "positive_controls": [
146
+ "authored_named_login_path",
147
+ "combined_helper_app_binary_streams_exit7_metadata"
148
+ ],
149
+ "negative_controls": [
150
+ "frozen_original_result",
151
+ "present_json_null_result",
152
+ "first_row_malformed_other_owners_correct"
153
+ ]
154
+ },
155
+ {
156
+ "id": "root_redirect",
157
+ "source_path": "instruction.md",
158
+ "source_lines": [
159
+ 1
160
+ ],
161
+ "requirement": "Rootstringredirect rematchedonce, thenauthguardusesmatchedtargetchain butLoginqueryoriginalrequest.",
162
+ "material": true,
163
+ "check_ids": [
164
+ "3"
165
+ ],
166
+ "positive_controls": [
167
+ "authored_named_login_path",
168
+ "combined_helper_app_binary_streams_exit7_metadata"
169
+ ],
170
+ "negative_controls": [
171
+ "unchanged_public_reference",
172
+ "frozen_original_result",
173
+ "wrong_route_fields_nonstdlib",
174
+ "present_json_null_result",
175
+ "first_row_malformed_other_owners_correct"
176
+ ]
177
+ },
178
+ {
179
+ "id": "public_guard",
180
+ "source_path": "instruction.md",
181
+ "source_lines": [
182
+ 1
183
+ ],
184
+ "requirement": "Anypublicmeta onchain andloggedtrue redirectsDashboard /dashboard withclearedparams/query, afterauthguardpriority.",
185
+ "material": true,
186
+ "check_ids": [
187
+ "4"
188
+ ],
189
+ "positive_controls": [
190
+ "authored_named_login_path",
191
+ "combined_helper_app_binary_streams_exit7_metadata"
192
+ ],
193
+ "negative_controls": [
194
+ "frozen_original_result",
195
+ "wrong_route_fields_nonstdlib",
196
+ "present_json_null_result"
197
+ ]
198
+ },
199
+ {
200
+ "id": "auth_guard",
201
+ "source_path": "instruction.md",
202
+ "source_lines": [
203
+ 1
204
+ ],
205
+ "requirement": "AnyrequiredAuth onchain cannotbe cancelledbychildfalse; unauth→namedLoginactualpath andqueryoriginal, evenifpublicalso true.",
206
+ "material": true,
207
+ "check_ids": [
208
+ "5"
209
+ ],
210
+ "positive_controls": [
211
+ "authored_named_login_path",
212
+ "combined_helper_app_binary_streams_exit7_metadata"
213
+ ],
214
+ "negative_controls": [
215
+ "unchanged_public_reference",
216
+ "frozen_original_result",
217
+ "wrong_route_fields_nonstdlib",
218
+ "present_json_null_result"
219
+ ]
220
+ },
221
+ {
222
+ "id": "dynamic_allowed",
223
+ "source_path": "instruction.md",
224
+ "source_lines": [
225
+ 1
226
+ ],
227
+ "requirement": "Authenticated allowed dynamic result hasactualfullpath andone-segmentstringparams; authenticatedrootredirect dynamicvalue preserved.",
228
+ "material": true,
229
+ "check_ids": [
230
+ "6"
231
+ ],
232
+ "positive_controls": [
233
+ "authored_named_login_path",
234
+ "combined_helper_app_binary_streams_exit7_metadata"
235
+ ],
236
+ "negative_controls": [
237
+ "frozen_original_result",
238
+ "wrong_route_fields_nonstdlib",
239
+ "present_json_null_result"
240
+ ]
241
+ },
242
+ {
243
+ "id": "wildcard",
244
+ "source_path": "instruction.md",
245
+ "source_lines": [
246
+ 1
247
+ ],
248
+ "requirement": "Wildcardonlyotherwiseunmatched, keepsoriginalpath, metadata/name fromcurrenttable; multisegmentmustnotfitoneparam.",
249
+ "material": true,
250
+ "check_ids": [
251
+ "7"
252
+ ],
253
+ "positive_controls": [
254
+ "authored_named_login_path",
255
+ "combined_helper_app_binary_streams_exit7_metadata"
256
+ ],
257
+ "negative_controls": [
258
+ "frozen_original_result",
259
+ "wrong_route_fields_nonstdlib",
260
+ "present_json_null_result"
261
+ ]
262
+ },
263
+ {
264
+ "id": "exact_allowed",
265
+ "source_path": "instruction.md",
266
+ "source_lines": [
267
+ 1
268
+ ],
269
+ "requirement": "Allowed exactnestedleaf/emptychild resolvedchain properly; unauthpubliconly route proceeds, falsechilddoesnotclearparenttrue.",
270
+ "material": true,
271
+ "check_ids": [
272
+ "8"
273
+ ],
274
+ "positive_controls": [
275
+ "authored_named_login_path",
276
+ "combined_helper_app_binary_streams_exit7_metadata"
277
+ ],
278
+ "negative_controls": [
279
+ "frozen_original_result",
280
+ "wrong_route_fields_nonstdlib",
281
+ "present_json_null_result"
282
+ ]
283
+ },
284
+ {
285
+ "id": "input_rules",
286
+ "source_path": "instruction.md",
287
+ "source_lines": [
288
+ 1
289
+ ],
290
+ "requirement": "Allcurrentroute/attempt facts reflected: old3flag/name/param changes andnew12attempt/deepchain/namedLogin/bothflags/schema.",
291
+ "material": true,
292
+ "check_ids": [
293
+ "9"
294
+ ],
295
+ "positive_controls": [
296
+ "authored_named_login_path",
297
+ "combined_helper_app_binary_streams_exit7_metadata"
298
+ ],
299
+ "negative_controls": [
300
+ "unchanged_public_reference",
301
+ "frozen_original_result",
302
+ "wrong_route_fields_nonstdlib",
303
+ "present_json_null_result",
304
+ "first_row_malformed_other_owners_correct"
305
+ ]
306
+ }
307
+ ],
308
+ "focused_revision_analysis": "FIRST F1: preserve global array/schema owner2 but independently compare each available expected position for owners3..8. One bad/missing row no longer couples unrelated domains. All7oldvectors hand-derived unchanged: each old semantic domain already had its own wrong row whenever previously False. New8th only2/3/9False. Same5literalpanels/helpers/old7producers unchanged; no routeframework expansion or subject/privatehistory execution/read."
309
+ },
310
+ "substantive_change": "Sole FIRST F1: decouple per-domain semantic owners3..8 from global typedarray schema2; one focused firstrow-malformed producer witnesses ownerisolation. No other implementation/panel/oldproducer changes.",
311
+ "historical_scores_seen": false,
312
+ "score_exposure_scope": null,
313
+ "solver_or_arm_conditioned": false,
314
+ "new_solver_executions": 0,
315
+ "notes": [
316
+ "Unique2. All8whole10IDvectors hand-derived: old7 unchanged; new firstrow paramsnull only2/3/9False,0/1/4..8True. Alloriginal5panels/currentold7producers/helpers stable. No candidate/checker/reference/control/model execution or privatehistory read."
317
+ ]
318
+ }
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/workspace_copy.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ from contextlib import contextmanager
3
+ from pathlib import Path
4
+ import shutil
5
+
6
+ def clean(root):
7
+ for path in root.iterdir():
8
+ if path.is_dir() and not path.is_symlink():shutil.rmtree(path)
9
+ else:path.unlink()
10
+
11
+ @contextmanager
12
+ def workspace(remove=()):
13
+ roots=[Path('/workspace'),Path('/app')]
14
+ try:
15
+ for root in roots:
16
+ root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True)
17
+ for name in remove:
18
+ path=root/name
19
+ if path.is_dir() and not path.is_symlink():shutil.rmtree(path)
20
+ elif path.exists() or path.is_symlink():path.unlink()
21
+ yield roots[0]
22
+ finally:
23
+ for root in roots:
24
+ if root.exists():clean(root)
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/grading/verified_config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "da0ea4af7d02ad888fcae5c0",
4
+ "runtime_requirements": {
5
+ "expected_check_ids": [
6
+ "0",
7
+ "1",
8
+ "2",
9
+ "3",
10
+ "4",
11
+ "5",
12
+ "6",
13
+ "7",
14
+ "8",
15
+ "9"
16
+ ],
17
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
18
+ "network": "none",
19
+ "criterion_weights": {
20
+ "0": 1,
21
+ "1": 1,
22
+ "2": 1,
23
+ "3": 1,
24
+ "4": 1,
25
+ "5": 1,
26
+ "6": 1,
27
+ "7": 1,
28
+ "8": 1,
29
+ "9": 1
30
+ },
31
+ "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."
32
+ },
33
+ "engine": "verified514_offline_v1",
34
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
35
+ "grader_file_sha256": {
36
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
37
+ "workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3",
38
+ "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185",
39
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
40
+ "auto_policy.json": "3b9264c20632ed264ad5a2e93cacdb64ea859d2f08dbec7825c6b18db27ea91c",
41
+ "repair_manifest.json": "9e41d50802cb6b90263a8530e4af8d1d1032fac63ebfaf2ce8ea8320faf42142",
42
+ "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50",
43
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
44
+ "autograde_task_check.py": "667a1258124f1e14a2c15c555f06e988cafc5df0004d3758e387db3e7ae79777",
45
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
46
+ "auto_contract.json": "5d4ae92114b3624c943c104e899595f0c91c1ca2d906fc23db00ac88445a5f4b",
47
+ "input_snapshots/routes.json": "8ac84093a985d79b5954983c6998b483057bddb0fc6808a404f7eacbd8f00d8d"
48
+ }
49
+ }
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/inputs/attempts. ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attempts": [
3
+ { "id": 1, "path": "/", "estaLogado": false },
4
+ { "id": 2, "path": "/login", "estaLogado": true },
5
+ { "id": 3, "path": "/dashboard/usuarios/42", "estaLogado": false },
6
+ { "id": 4, "path": "/dashboard/usuarios/42", "estaLogado": true },
7
+ { "id": 5, "path": "/foo/bar", "estaLogado": false },
8
+ { "id": 6, "path": "/dashboard/usuarios", "estaLogado": true }
9
+ ]
10
+ }
benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/inputs/routes. ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "routes": [
3
+ { "path": "/", "redirect": "/dashboard" },
4
+ { "path": "/login", "name": "Login", "meta": { "publico": true } },
5
+ {
6
+ "path": "/dashboard",
7
+ "meta": { "requerAutenticacao": true },
8
+ "children": [
9
+ { "path": "", "name": "Dashboard" },
10
+ { "path": "usuarios", "name": "Usuarios" },
11
+ { "path": "usuarios/:id", "name": "UsuarioDetalhe", "props": true }
12
+ ]
13
+ },
14
+ { "path": "*", "name": "NaoEncontrado" }
15
+ ]
16
+ }