diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..63e8fcc36b93eabae52af50d0dd9bc72fd8e985c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1330 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import math +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + + +def _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + actual = json.loads(path.read_text(encoding="utf-8")) + passed = (_same_native_json_types(actual, check.get("expected")) and + _canonical(actual) == _canonical(check.get("expected"))) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + passed = passed and all(call['fail_fast'] or shlex.split(call['command'])[0] in ('true', ':') for call in calls) + detail = f"expected_failure_propagation={expected}; all_calls_fail_fast=True; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..c03f64348caa714a2797a7d6488d9a515c65d380 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,455 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + + +# R7: unwrap only execution wrappers whose effect is proved in this subset. +# In particular `command -v/-V` queries do not run their operand, and `builtin` +# cannot run an external tool. Keep these distinctions before inspecting state. +_BASH_BUILTINS = frozenset({ + ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', + 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs', + 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', + 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', + 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', + 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', + 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', + 'unset', 'wait', +}) +_UNSUPPORTED_STATE = frozenset({ + '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap', + 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local', + 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift', + '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts', +}) + + +def _bash_dialect(text): + """No shebang uses the evaluator's Bash syntax contract; sh is not Bash.""" + first = str(text).splitlines()[0] if str(text).splitlines() else '' + if not first.startswith('#!'): + return True + try: + words = shlex.split(first[2:]) + except ValueError: + return False + if not words: + return False + executable = words[0].rsplit('/', 1)[-1] + if executable == 'env': + words = words[1:] + if words[:1] == ['-S']: + words = words[1:] + executable = words[0] if words else '' + return executable.rsplit('/', 1)[-1] == 'bash' + + +def _execution_argv(argv, bash=True): + """Normalize a finite chain; unsupported wrappers get no command credit.""" + if not argv: + return None + argv = list(argv) + while argv and argv[0] in ('command', 'builtin'): + wrapper = argv[0] + if wrapper == 'builtin': + if not bash: + return None + argv = argv[1:] + if argv[:1] == ['--']: + argv = argv[1:] + if not argv or argv[0] not in _BASH_BUILTINS: + return None + continue + index, query, default_path = 1, False, False + while index < len(argv) and argv[index].startswith('-'): + option = argv[index] + index += 1 + if option == '--': + break + if not re.fullmatch(r'-[pvV]+', option): + return None + query = query or 'v' in option or 'V' in option + default_path = default_path or 'p' in option + if query: + return argv # Query is an invocation of command, not its target. + if index == len(argv): + return None + argv = argv[index:] + # -p changes external PATH lookup. It is transparent for builtins only. + if default_path and argv[0] not in _BASH_BUILTINS: + return None + return argv or None + + +def _set_errexit(argv, current): + """Return the proven option state, or None for unsupported set options.""" + if not argv or argv[0] != 'set': + return None + index = 1 + while index < len(argv): + flag = argv[index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Positional arguments cannot enable errexit. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return None # Includes noexec (-n), which suppresses later work. + if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1): + return None + if 'e' in flag[1:]: + current = flag[0] == '-' + if 'o' in flag[1:]: + if index + 1 >= len(argv): + return None + option = argv[index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return None + if option == 'errexit': + current = flag[0] == '-' + index += 1 + index += 1 + return current + + +def shell_option_setting(text, bash=True): + """Recognize valid option setup for task-specific operation counters.""" + argv = _execution_argv(_simple_argv(text), bash) + return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None) + + +def _exit_status(argv): + """A literal shell exit status; no-argument exit is handled by its caller.""" + args = argv[1:] + if args[:1] == ['--']: + args = args[1:] + if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0]) + or len(args[0]) > 20): + return None + value = int(args[0]) + if not -(2**63) <= value <= 2**63 - 1: + return 2 # Bash exits for an out-of-range numeric argument. + return value % 256 + + + +def _nonzero_exit_body(statements, bash=True): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _execution_argv(_simple_argv(statement), bash) + if not argv: + return False + if argv[0] == 'exit': + status = _exit_status(argv) + return index == len(statements) - 1 and status is not None and status != 0 + if argv[0] not in ('echo', 'printf'): + return False + return False + + + +def _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import math +import posixpath +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + text = posixpath.normpath(text) if text else text + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], _atomic_shape(pred)) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = _path_equal(actual, assertion["expected"]) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..4df26c2ffaf32ee54a18bcb00381e1aef3ec640d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""Task-scoped semantic equivalences for the 112 legacy verifier repairs. + +No solver, oracle label, historical score or answer hash influences comparison. +The original private rubric, completeness checks and binary aggregation remain. +""" +from __future__ import annotations +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import copy +import json +import re +import shlex +import shutil +import tempfile +from decimal import Decimal, InvalidOperation +from pathlib import Path + + +def argv(value): + if not isinstance(value, str): + return None + try: + result = shlex.split(value, posix=True) + except ValueError: + return None + # Only the Bash execution wrapper is transparent. command -v/-V are queries. + while len(result) > 1 and result[0] == 'command': + if result[1] == '--': + result = result[2:] + elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]): + break + else: + result = result[1:] + return result or None + + +def git_limit(tokens): + if not tokens or tokens[:2] != ['git', 'log']: + return tokens + out, index = [], 0 + while index < len(tokens): + token = tokens[index] + compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token) + if compact: + out.append('--max-count=' + next(x for x in compact.groups() if x is not None)) + elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit(): + index += 1 + out.append('--max-count=' + tokens[index]) + else: + out.append(token) + index += 1 + return out + + +def shell_equal(expected, actual, normalize_env=False): + wanted, found = argv(expected), argv(actual) + if normalize_env and wanted and found: + wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted] + found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found] + wanted, found = git_limit(wanted), git_limit(found) + if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + if (index == 1 and '/' in token and + observed.rstrip('/').endswith('/' + token.lstrip('./'))): + continue # Existing package-path anchoring; no changed basename/arguments. + return False + return True + + +def command_equal(expected, value): + # Response command questions ask for one invocation, with no extra commands. + return argv(expected) is not None and argv(expected) == argv(value) + + +def convex_equal(expected, value): + a, b = argv(expected), argv(value) + if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]: + return False + def no_duplicates(pairs): + result = {} + for k, v in pairs: + if k in result: + raise ValueError('duplicate JSON key') + result[k] = v + return result + try: + return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates) + except (ValueError, TypeError): + return False + + +def docker_network_equal(expected, value): + tokens = argv(value) + return tokens in (['--network', 'none'], ['--network=none']) + + +def zar_amount(value): + if not isinstance(value, str): + return None + m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I) + if not m: + return None + number = m.group(1) + if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number): + return None + try: + amount = Decimal(number.replace(',', '')) + except InvalidOperation: + return None + return amount * (Decimal(1000000) if m.group(2) else 1) + + +def zar_equal(expected, value): + return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value) + + +def rust_attribute_equal(expected, value): + 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 + + +def header_equal(expected, value): + return isinstance(value, str) and value.casefold() == expected.casefold() + + +def zero_arg_js_equal(expected, value): + name = expected[:-2] + return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None + + +RESPONSE_RULES = { + '82e94ae96e04ff71_q1': {'q1': convex_equal}, + 'df978907fa6f0eea_q1': {'q1': docker_network_equal}, + 'dee0c878f5707477_q1': {'q1': command_equal}, + 'c51259d0062454b2_q1': {'q1': command_equal}, + 'd25a8956477141f2_q1': {'q2': zar_equal}, + '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal}, + 'a4926e403c8165e9_q1': {'q2': header_equal}, + '2b3bd5786727f2fb_q1': {'q1': command_equal}, +} + + +def dashboard_contract(evaluator, candidate, objective): + root = Path(candidate) + path = evaluator['reference_files'][0]['path'] + try: + text = (root / path).read_text() + except (OSError, UnicodeError): + return False + lines = objective._shell_lines(text) + # Public contract explicitly says no other commands/flags. Single quotes + # would suppress environment expansion; only the correctly quoted form counts. + return (len(lines) == 2 and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None) + + +def install(task): + import objective_evaluators as objective + import verifiers + task_id = task['query_id'] + original_verify = verifiers.verify + original_matcher = objective._shell_command_matches + objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1') + + def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None): + if evaluator.get('type') == 'workspace_objective': + # A text occurrence after exit/return, in echo output or within a + # non-executed branch does not prove the requested command runs. + grouped = {} + for check in evaluator.get('checks', []): + if check.get('type') == 'shell_command': + grouped.setdefault(check['path'], []).append(check['value']) + for path, expected_commands in grouped.items(): + try: + text = (Path(solver_output) / path).read_text() + invocations = objective.shell_invocations(text) + for expected_command in expected_commands: + tokens = argv(expected_command) + if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]): + continue # Required scalar assignment is checked by original rubric. + if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations): + return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command} + except (OSError, UnicodeError, ValueError): + return False, {'error': 'cannot inspect required shell artifact', 'path': path} + if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective): + return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'} + normalizations = [] + if task_id in RESPONSE_RULES: + try: + predicted = verifiers._json_value(solver_output) + gold = gt_answer + if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict): + for key, comparator in RESPONSE_RULES[task_id].items(): + value = predicted['answers'].get(key) + expected = gold['answers'][key] + if value != expected and comparator(expected, value): + predicted['answers'][key] = expected + normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected}) + solver_output = json.dumps(predicted) + except (KeyError, ValueError, TypeError): + pass # Preserve original malformed-answer rejection. + if task_id == '59f410a185c510f3_q1': + path = evaluator['reference_files'][0]['path'] + try: + file_path = Path(solver_output) / path + predicted = json.loads(file_path.read_text()) + expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact') + if isinstance(predicted, dict): + for widget in ('chart', 'banner'): + row = predicted.get(widget) + if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')): + if row.get('hydrate') != expected[widget]['hydrate']: + normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']}) + row['hydrate'] = expected[widget]['hydrate'] + if normalizations: + with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary: + view = Path(temporary) / 'candidate' + shutil.copytree(solver_output, view, symlinks=True) + copied = view / path + resolved = copied.resolve() + if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink(): + return False, {'error': 'candidate output parent symlink escapes temporary comparison view'} + if copied.is_symlink(): + copied.unlink() # Do not write through a frozen source symlink. + copied.write_text(json.dumps(predicted)) + passed, details = original_verify(evaluator, gt_answer, str(view), material_paths) + if isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + except (KeyError, ValueError, TypeError, OSError, UnicodeError): + pass + passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths) + if normalizations and isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + + verifiers.verify = repaired_verify diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..da21272d9c45621d079fe775cf2e0cdd6512eba5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "engine": "portable_verified_v1", + "grader_file_sha256": { + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "36c75295b194bf1ded3f7768fac4a8aab66d6a7adc2d0b53a08ae424c9f83641", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "760065320d62fbbbebf3f6ab839f864b976c3c675a50db4e12f092ffce843f50", + "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70", + "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af" + }, + "query_id": "d76667df8f9db23f_q1", + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "criterion_weights": { + "0": 1 + }, + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "grader_timeout_seconds": 600, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "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.", + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ] + }, + "schema": "audited-verified-grader-v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..8ebac2100cf683063d67ccee51f54dc28f76cf37 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d76667df8f9db23f_q1/skill/SKILL.md @@ -0,0 +1,23 @@ +--- +name: brandkit +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. +--- + +# Skill: Brand Kit + +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. + +## Steps +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`. +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. +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). +4. **Scales** — Major Third type scale + composite text styles, 4px spacing scale, radius tiers, elevation, and `tokens/motion.json`-style durations/easings. +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. + +## Verification (definition of done) +- `python3 scripts/validate_tokens.py` — valid JSON, all aliases resolve. +- `python3 scripts/validate_contrast.py` — required text/action/border pairs pass WCAG AA in **light AND dark**; `border.strong` ≥ 3:1. +- `python3 scripts/validate_theme_refs.py` — every component `var(--…)` resolves to the theme. +- One theme, no per-page palettes; destructive = danger token (not primary); zero hardcoded values. + +> 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`. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..7ff26c7273a12246892c72f028e605b418530ec7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_contract.json @@ -0,0 +1,26 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..1ac6af490e3bc410bcb3bfd624deafee06c491f4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "8" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith('= {"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) + 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"} + print(json.dumps(_r10.finalize(checks, {'8':'hookify_engine.py'}))) + +main() diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/candidate_artifacts.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/candidate_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..01d155d66962e3f1c41443cad117a48e6ca25bc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/candidate_artifacts.py @@ -0,0 +1,24 @@ +"""Read only ordinary candidate artifacts after a bounded child completes. +No launch/setup/monitor exceptions are caught here. Symlinks to regular files +remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from +blocking the trusted grader. Malformed text/JSON is an absent invalid value. +""" +import json, os, stat + +def read_text(path, encoding=None, errors=None): + fd=None + try: + fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode):return '' + with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream: + fd=None + return stream.read() + except (OSError,UnicodeError):return '' + finally: + if fd is not None:os.close(fd) + +def loads(text, **kwargs): + try:return json.loads(text,**kwargs) + except (ValueError,TypeError,RecursionError):return None + +def load(path, **kwargs):return loads(read_text(path),**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/r10_runtime.py b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/r10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..e59e5ac258f6772a6585aa86470cf6d417748118 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/evaluator/r10_runtime.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +"""R10 grader helper. This file runs only inside an offline verifier container.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,os,pathlib,shutil +from dependency_scan import scan_stdlib +C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +_copies={};_deps={} +def dependency(entry): + key=str(entry) + if key not in _deps:_deps[key]=scan_stdlib(C,[key]) + return _deps[key] +def stdlib_gate(entry): + # Unknown is provisionally neutral; finalize() preserves it as unscored. + return dependency(entry)[0] is not False +def finalize(checks,owners): + for row in checks: + entry=owners.get(str(row['id'])) + if entry is None:continue + ok,_,why=dependency(entry) + if ok is False:row['passed']=False + elif ok is None and row.get('passed')is not False:row['passed']=None + row['reason']=row.get('reason','')+'; reachable dependency closure: '+why + return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks} +def strict_pairs(pairs): + out={} + for key,value in pairs: + if key in out:raise ValueError('duplicate JSON object key: '+key) + out[key]=value + return out +def read_json(path): + return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs, + parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x))) +def install_copy(entry): + """Complete authored dependencies without copying stale deliverables into fixtures.""" + if entry in _copies:return + _copies[entry]=True + try:task=json.loads(pathlib.Path('/source/task.json').read_text()) + except (OSError,ValueError):task={} + excluded=[] + for value in task.get('outputs',[]): + value=value.get('path')if isinstance(value,dict)else value + if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value)) + original_copy=shutil.copy;original_copyfile=shutil.copyfile + def extra(src,dst): + try: + source=pathlib.Path(src) + if source.name!=pathlib.Path(entry).name:return + source.resolve().relative_to(C.resolve()) + except (ValueError,TypeError,OSError):return + destination=pathlib.Path(dst) + if destination.is_dir():destination=destination/source.name + root=destination.parent + # Helpers keep the entry's authored relative directory context. + for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent + for dp,dn,fn in os.walk(str(C),followlinks=False): + dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')] + for name in fn: + p=pathlib.Path(dp)/name;rel=p.relative_to(C) + if any(rel==x or x in rel.parents for x in excluded):continue + if p.resolve()==source.resolve():continue + out=root/rel + if out.exists()or out.is_symlink():continue + out.parent.mkdir(parents=True,exist_ok=True) + if p.is_symlink():out.symlink_to(os.readlink(str(p))) + elif p.is_file():original_copyfile(str(p),str(out)) + def copy(src,dst,*args,**kwargs): + result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result + def copyfile(src,dst,*args,**kwargs): + result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result + shutil.copy=copy;shutil.copyfile=copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..9a394aa7046b8ca3ef493af21fc0f9b5898a53d5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/grading/verified_config.json @@ -0,0 +1,90 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d8ca51d1bf001d570190dfca", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "9dbda2dad4e8b0dda92db60176543b74b5f12bdf8e5aec1d848c8c59f5113771", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "4b670bf118b964cc6e879374ac3bb50e0ca8f0c3b6a2ec6d81f3df71e91930d4", + "r10_runtime.py": "02787c5058002e411017bc4735ad2072988bb35281b1c55b711d003ee0f83bde", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "5d4ae92114b3624c943c104e899595f0c91c1ca2d906fc23db00ac88445a5f4b" + }, + "runtime_requirements": { + "family": "legacy_original_verified2", + "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "read_only_mounts": [ + "task:/source", + "task:/task", + "evaluator:/grader", + "candidate:/candidate", + "answer:/answer.txt" + ], + "writable_tmpfs": [ + "/app", + "/workspace", + "/tmp" + ], + "copy_completed_candidate_children_to_app_before_grader": true, + "entrypoint": [ + "python3", + "/grader/check.py" + ], + "working_directory": "/candidate", + "environment": { + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_CANDIDATE_PATH": "/candidate", + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1" + }, + "environment_names_detected": [], + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ], + "criterion_count": 10, + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1 + }, + "actual_original_success_criteria_count": 10, + "original_task_metadata_must_not_define_override_criterion_count": false, + "requires_external_actual_native_trace": false, + "requires_external_trusted_snapshot_binding": false, + "fresh_native_binding_must_not_require_historical_run_id": true, + "checker_can_execute_candidate_subprocesses": true, + "host_execution_forbidden": true, + "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.", + "docker_image_payload_in_source_tree": false, + "runtime_missing": [], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "grader_timeout_seconds": 600 + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/events.l b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/events.l new file mode 100644 index 0000000000000000000000000000000000000000..0791ec9c9f74ae0fe917c5a8281cbed4e5775223 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/events.l @@ -0,0 +1,10 @@ +{"event": "bash", "command": "pip install requests"} +{"event": "bash", "command": "uv add requests"} +{"event": "bash", "command": "rm -rf /tmp/build && rm -rf cache"} +{"event": "file", "file_path": "src/app.py", "new_text": "import os\nprint('hi')"} +{"event": "file", "file_path": "src/app.js", "new_text": "console.log('debug');\nconsole.log(x);"} +{"event": "file", "file_path": ".env", "new_text": "API_KEY=abc123"} +{"event": "file", "file_path": ".env", "new_text": "DATABASE_URL=postgres://localhost"} +{"event": "file", "file_path": ".ruff.toml", "new_text": "select = []"} +{"event": "stop"} +{"event": "prompt", "user_prompt": "deploy to production now"} diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.block-legacy-pm.local.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.block-legacy-pm.local.md new file mode 100644 index 0000000000000000000000000000000000000000..9228a6db487e2f5392541006d0ff37722d7a4d06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.block-legacy-pm.local.md @@ -0,0 +1,9 @@ +--- +name: block-legacy-package-manager +enabled: true +event: bash +action: block +pattern: ^\s*(pip3?|poetry|pipenv)\s+install +--- + +Legacy Python package manager blocked. Use `uv` instead. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.console-log.local.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.console-log.local.md new file mode 100644 index 0000000000000000000000000000000000000000..0bf185d71e153a68595d42041c4dd1d4c9afcd08 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.console-log.local.md @@ -0,0 +1,8 @@ +--- +name: warn-console-log +enabled: true +event: file +pattern: console\.log\( +--- + +⚠️ **Console.log detected!** Debug logs shouldn't ship to production. Use a proper logging library. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.dangerous-rm.local.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.dangerous-rm.local.md new file mode 100644 index 0000000000000000000000000000000000000000..13d3ed3457483bd37ec54bd05e96faf6d0954d05 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.dangerous-rm.local.md @@ -0,0 +1,8 @@ +--- +name: warn-dangerous-rm +enabled: true +event: bash +pattern: rm\s+-rf +--- + +Dangerous recursive force-remove detected. Double-check the path. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.disabled-rule.local.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.disabled-rule.local.md new file mode 100644 index 0000000000000000000000000000000000000000..119509a84cbeab7989eba9baa1858ffd564e527f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.disabled-rule.local.md @@ -0,0 +1,8 @@ +--- +name: warn-disabled-example +enabled: false +event: all +pattern: .* +--- + +This rule is disabled and must never trigger. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.sensitive-files.local.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.sensitive-files.local.md new file mode 100644 index 0000000000000000000000000000000000000000..8f8f801fae4becfd3563a078a169ac271083bfb4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/inputs/rules/hookify.sensitive-files.local.md @@ -0,0 +1,14 @@ +--- +name: warn-sensitive-file +enabled: true +event: file +conditions: + - field: file_path + operator: regex_match + pattern: \.env$ + - field: new_text + operator: contains + pattern: API_KEY +--- + +You're adding an API key to a .env file. Ensure this file is in .gitignore! diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ba0a0fbae2e3be4c89215ebb267b8c02e139bbdc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/SKILL.md @@ -0,0 +1,3 @@ +# Multi-skill source bundle + +Private source bundle wrapper. The original skills are in members/. diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M000/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M000/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..46b1000ad8dcec3ef8779047397cbf5dfbffa986 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M000/SKILL.md @@ -0,0 +1,236 @@ +--- +name: ecc-plankton-code-quality +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." +origin: community +--- + +# Plankton Code Quality Skill + +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. + +## When to Use + +- You want automatic formatting and linting on every file edit (not just at commit time) +- You need defense against agents modifying linter configs to pass instead of fixing code +- You want tiered model routing for fixes (Haiku for simple style, Sonnet for logic, Opus for types) +- You work with multiple languages (Python, TypeScript, Shell, YAML, JSON, TOML, Markdown, Dockerfile) + +## How It Works + +### Three-Phase Architecture + +Every time Claude Code edits or writes a file, Plankton's `multi_linter.sh` PostToolUse hook runs: + +``` +Phase 1: Auto-Format (Silent) +├─ Runs formatters (ruff format, biome, shfmt, taplo, markdownlint) +├─ Fixes 40-50% of issues silently +└─ No output to main agent + +Phase 2: Collect Violations (JSON) +├─ Runs linters and collects unfixable violations +├─ Returns structured JSON: {line, column, code, message, linter} +└─ Still no output to main agent + +Phase 3: Delegate + Verify +├─ Spawns claude -p subprocess with violations JSON +├─ Routes to model tier based on violation complexity: +│ ├─ Haiku: formatting, imports, style (E/W/F codes) — 120s timeout +│ ├─ Sonnet: complexity, refactoring (C901, PLR codes) — 300s timeout +│ └─ Opus: type system, deep reasoning (unresolved-attribute) — 600s timeout +├─ Re-runs Phase 1+2 to verify fixes +└─ Exit 0 if clean, Exit 2 if violations remain (reported to main agent) +``` + +### What the Main Agent Sees + +| Scenario | Agent sees | Hook exit | +|----------|-----------|-----------| +| No violations | Nothing | 0 | +| All fixed by subprocess | Nothing | 0 | +| Violations remain after subprocess | `[hook] N violation(s) remain` | 2 | +| Advisory (duplicates, old tooling) | `[hook:advisory] ...` | 0 | + +The main agent only sees issues the subprocess couldn't fix. Most quality problems are resolved transparently. + +### Config Protection (Defense Against Rule-Gaming) + +LLMs will modify `.ruff.toml` or `biome.json` to disable rules rather than fix code. Plankton blocks this with three layers: + +1. **PreToolUse hook** — `protect_linter_configs.sh` blocks edits to all linter configs before they happen +2. **Stop hook** — `stop_config_guardian.sh` detects config changes via `git diff` at session end +3. **Protected files list** — `.ruff.toml`, `biome.json`, `.shellcheckrc`, `.yamllint`, `.hadolint.yaml`, and more + +### Package Manager Enforcement + +A PreToolUse hook on Bash blocks legacy package managers: +- `pip`, `pip3`, `poetry`, `pipenv` → Blocked (use `uv`) +- `npm`, `yarn`, `pnpm` → Blocked (use `bun`) +- Allowed exceptions: `npm audit`, `npm view`, `npm publish` + +## Setup + +### Quick Start + +> **Note:** Plankton requires manual installation from its repository. Review the code before installing. + +```bash +# Install core dependencies +brew install jaq ruff uv + +# Install Python linters +uv sync --all-extras + +# Start Claude Code — hooks activate automatically +claude +``` + +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. + +### Per-Project Integration + +To use Plankton hooks in your own project: + +1. Copy `.claude/hooks/` directory to your project +2. Copy `.claude/settings.json` hook configuration +3. Copy linter config files (`.ruff.toml`, `biome.json`, etc.) +4. Install the linters for your languages + +### Language-Specific Dependencies + +| Language | Required | Optional | +|----------|----------|----------| +| Python | `ruff`, `uv` | `ty` (types), `vulture` (dead code), `bandit` (security) | +| TypeScript/JS | `biome` | `oxlint`, `semgrep`, `knip` (dead exports) | +| Shell | `shellcheck`, `shfmt` | — | +| YAML | `yamllint` | — | +| Markdown | `markdownlint-cli2` | — | +| Dockerfile | `hadolint` (>= 2.12.0) | — | +| TOML | `taplo` | — | +| JSON | `jaq` | — | + +## Pairing with ECC + +### Complementary, Not Overlapping + +| Concern | ECC | Plankton | +|---------|-----|----------| +| Code quality enforcement | PostToolUse hooks (Prettier, tsc) | PostToolUse hooks (20+ linters + subprocess fixes) | +| Security scanning | AgentShield, security-reviewer agent | Bandit (Python), Semgrep (TypeScript) | +| Config protection | — | PreToolUse blocks + Stop hook detection | +| Package manager | Detection + setup | Enforcement (blocks legacy PMs) | +| CI integration | — | Pre-commit hooks for git | +| Model routing | Manual (`/model opus`) | Automatic (violation complexity → tier) | + +### Recommended Combination + +1. Install ECC as your plugin (agents, skills, commands, rules) +2. Add Plankton hooks for write-time quality enforcement +3. Use AgentShield for security audits +4. Use ECC's verification-loop as a final gate before PRs + +### Avoiding Hook Conflicts + +If running both ECC and Plankton hooks: +- ECC's Prettier hook and Plankton's biome formatter may conflict on JS/TS files +- Resolution: disable ECC's Prettier PostToolUse hook when using Plankton (Plankton's biome is more comprehensive) +- Both can coexist on different file types (ECC handles what Plankton doesn't cover) + +## Configuration Reference + +Plankton's `.claude/hooks/config.json` controls all behavior: + +```json +{ + "languages": { + "python": true, + "shell": true, + "yaml": true, + "json": true, + "toml": true, + "dockerfile": true, + "markdown": true, + "typescript": { + "enabled": true, + "js_runtime": "auto", + "biome_nursery": "warn", + "semgrep": true + } + }, + "phases": { + "auto_format": true, + "subprocess_delegation": true + }, + "subprocess": { + "tiers": { + "haiku": { "timeout": 120, "max_turns": 10 }, + "sonnet": { "timeout": 300, "max_turns": 10 }, + "opus": { "timeout": 600, "max_turns": 15 } + }, + "volume_threshold": 5 + } +} +``` + +**Key settings:** +- Disable languages you don't use to speed up hooks +- `volume_threshold` — violations > this count auto-escalate to a higher model tier +- `subprocess_delegation: false` — skip Phase 3 entirely (just report violations) + +## Environment Overrides + +| Variable | Purpose | +|----------|---------| +| `HOOK_SKIP_SUBPROCESS=1` | Skip Phase 3, report violations directly | +| `HOOK_SUBPROCESS_TIMEOUT=N` | Override tier timeout | +| `HOOK_DEBUG_MODEL=1` | Log model selection decisions | +| `HOOK_SKIP_PM=1` | Bypass package manager enforcement | + +## References + +- Plankton (credit: @alxfazio) +- Plankton REFERENCE.md — Full architecture documentation (credit: @alxfazio) +- Plankton SETUP.md — Detailed installation guide (credit: @alxfazio) + +## ECC v1.8 Additions + +### Copyable Hook Profile + +Set strict quality behavior: + +```bash +export ECC_HOOK_PROFILE=strict +export ECC_QUALITY_GATE_FIX=true +export ECC_QUALITY_GATE_STRICT=true +``` + +### Language Gate Table + +- TypeScript/JavaScript: Biome preferred, Prettier fallback +- Python: Ruff format/check +- Go: gofmt + +### Config Tamper Guard + +During quality enforcement, flag changes to config files in same iteration: + +- `biome.json`, `.eslintrc*`, `prettier.config*`, `tsconfig.json`, `pyproject.toml` + +If config is changed to suppress violations, require explicit review before merge. + +### CI Integration Pattern + +Use the same commands in CI as local hooks: + +1. run formatter checks +2. run lint/type checks +3. fail fast on strict mode +4. publish remediation summary + +### Health Metrics + +Track: +- edits flagged by gates +- average remediation time +- repeat violations by category +- merge blocks due to gate failures diff --git a/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M001/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M001/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5b9bce148c873287339c2656ffe40bd60bcf54f3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d8ca51d1bf001d570190dfca/skill/members/M001/SKILL.md @@ -0,0 +1,379 @@ +--- +name: writing-hookify-rules +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. +version: 0.1.0 +kind: reference +category: platform/governance +status: active +tags: [governance, hookify, hooks, platform, rules, writing] +related_skills: [few-shot-quality-prompting] +--- + +# Writing Hookify Rules + +## Overview + +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. + +## Rule File Format + +### Basic Structure + +```markdown +--- +name: rule-identifier +enabled: true +event: bash|file|stop|prompt|all +pattern: regex-pattern-here +--- + +Message to show Claude when this rule triggers. +Can include markdown formatting, warnings, suggestions, etc. +``` + +### Frontmatter Fields + +**name** (required): Unique identifier for the rule +- Use kebab-case: `warn-dangerous-rm`, `block-console-log` +- Be descriptive and action-oriented +- Start with verb: warn, prevent, block, require, check + +**enabled** (required): Boolean to activate/deactivate +- `true`: Rule is active +- `false`: Rule is disabled (won't trigger) +- Can toggle without deleting rule + +**event** (required): Which hook event to trigger on +- `bash`: Bash tool commands +- `file`: Edit, Write, MultiEdit tools +- `stop`: When agent wants to stop +- `prompt`: When user submits a prompt +- `all`: All events + +**action** (optional): What to do when rule matches +- `warn`: Show message but allow operation (default) +- `block`: Prevent operation (PreToolUse) or stop session (Stop events) +- If omitted, defaults to `warn` + +**pattern** (simple format): Regex pattern to match +- Used for simple single-condition rules +- Matches against command (bash) or new_text (file) +- Python regex syntax + +**Example:** +```yaml +event: bash +pattern: rm\s+-rf +``` + +### Advanced Format (Multiple Conditions) + +For complex rules with multiple conditions: + +```markdown +--- +name: warn-env-file-edits +enabled: true +event: file +conditions: + - field: file_path + operator: regex_match + pattern: \.env$ + - field: new_text + operator: contains + pattern: API_KEY +--- + +You're adding an API key to a .env file. Ensure this file is in .gitignore! +``` + +**Condition fields:** +- `field`: Which field to check + - For bash: `command` + - For file: `file_path`, `new_text`, `old_text`, `content` +- `operator`: How to match + - `regex_match`: Regex pattern matching + - `contains`: Substring check + - `equals`: Exact match + - `not_contains`: Substring must NOT be present + - `starts_with`: Prefix check + - `ends_with`: Suffix check +- `pattern`: Pattern or string to match + +**All conditions must match for rule to trigger.** + +## Message Body + +The markdown content after frontmatter is shown to Claude when the rule triggers. + +**Good messages:** +- Explain what was detected +- Explain why it's problematic +- Suggest alternatives or best practices +- Use formatting for clarity (bold, lists, etc.) + +**Example:** +```markdown +⚠️ **Console.log detected!** + +You're adding console.log to production code. + +**Why this matters:** +- Debug logs shouldn't ship to production +- Console.log can expose sensitive data +- Impacts browser performance + +**Alternatives:** +- Use a proper logging library +- Remove before committing +- Use conditional debug builds +``` + +## Event Type Guide + +### bash Events + +Match Bash command patterns: + +```markdown +--- +event: bash +pattern: sudo\s+|rm\s+-rf|chmod\s+777 +--- + +Dangerous command detected! +``` + +**Common patterns:** +- Dangerous commands: `rm\s+-rf`, `dd\s+if=`, `mkfs` +- Privilege escalation: `sudo\s+`, `su\s+` +- Permission issues: `chmod\s+777`, `chown\s+root` + +### file Events + +Match Edit/Write/MultiEdit operations: + +```markdown +--- +event: file +pattern: console\.log\(|eval\(|innerHTML\s*= +--- + +Potentially problematic code pattern detected! +``` + +**Match on different fields:** +```markdown +--- +event: file +conditions: + - field: file_path + operator: regex_match + pattern: \.tsx?$ + - field: new_text + operator: regex_match + pattern: console\.log\( +--- + +Console.log in TypeScript file! +``` + +**Common patterns:** +- Debug code: `console\.log\(`, `debugger`, `print\(` +- Security risks: `eval\(`, `innerHTML\s*=`, `dangerouslySetInnerHTML` +- Sensitive files: `\.env$`, `credentials`, `\.pem$` +- Generated files: `node_modules/`, `dist/`, `build/` + +### stop Events + +Match when agent wants to stop (completion checks): + +```markdown +--- +event: stop +pattern: .* +--- + +Before stopping, verify: +- [] Tests were run +- [] Build succeeded +- [] Documentation updated +``` + +**Use for:** +- Reminders about required steps +- Completion checklists +- Process enforcement + +### prompt Events + +Match user prompt content (advanced): + +```markdown +--- +event: prompt +conditions: + - field: user_prompt + operator: contains + pattern: deploy to production +--- + +Production deployment checklist: +- [] Tests passing? +- [] Reviewed by team? +- [] Monitoring ready? +``` + +## Pattern Writing Tips + +### Regex Basics + +**Literal characters:** Most characters match themselves +- `rm` matches "rm" +- `console.log` matches "console.log" + +**Special characters need escaping:** +- `.` (any char) → `\.` (literal dot) +- `(` `)` → `\(` `\)` (literal parens) +- `[` `]` → `\[` `\]` (literal brackets) + +**Common metacharacters:** +- `\s` - whitespace (space, tab, newline) +- `\d` - digit (0-9) +- `\w` - word character (a-z, A-Z, 0-9, _) +- `.` - any character +- `+` - one or more +- `*` - zero or more +- `?` - zero or one +- `|` - OR + +**Examples:** +``` +rm\s+-rf Matches: rm -rf, rm -rf +console\.log\( Matches: console.log( +(eval|exec)\( Matches: eval( or exec( +chmod\s+777 Matches: chmod 777, chmod 777 +API_KEY\s*= Matches: API_KEY=, API_KEY = +``` + +### Testing Patterns + +Test regex patterns before using: + +```bash +python3 -c "import re; print(re.search(r'your_pattern', 'test text'))" +``` + +Or use online regex testers (regex101.com with Python flavor). + +### Common Pitfalls + +**Too broad:** +```yaml +pattern: log # Matches "log", "login", "dialog", "catalog" +``` +Better: `console\.log\(|logger\.` + +**Too specific:** +```yaml +pattern: rm -rf /tmp # Only matches exact path +``` +Better: `rm\s+-rf` + +**Escaping issues:** +- YAML quoted strings: `"pattern"` requires double backslashes `\\s` +- YAML unquoted: `pattern: \s` works as-is +- **Recommendation**: Use unquoted patterns in YAML + +## File Organization + +**Location:** All rules in `.claude/` directory +**Naming:** `.claude/hookify.{descriptive-name}.local.md` +**Gitignore:** Add `.claude/*.local.md` to `.gitignore` + +**Good names:** +- `hookify.dangerous-rm.local.md` +- `hookify.console-log.local.md` +- `hookify.require-tests.local.md` +- `hookify.sensitive-files.local.md` + +**Bad names:** +- `hookify.rule1.local.md` (not descriptive) +- `hookify.md` (missing .local) +- `danger.local.md` (missing hookify prefix) + +## Workflow + +### Creating a Rule + +1. Identify unwanted behavior +2. Determine which tool is involved (Bash, Edit, etc.) +3. Choose event type (bash, file, stop, etc.) +4. Write regex pattern +5. Create `.claude/hookify.{name}.local.md` file in project root +6. Test immediately - rules are read dynamically on next tool use + +### Refining a Rule + +1. Edit the `.local.md` file +2. Adjust pattern or message +3. Test immediately - changes take effect on next tool use + +### Disabling a Rule + +**Temporary:** Set `enabled: false` in frontmatter +**Permanent:** Delete the `.local.md` file + +## Examples + +See `${CLAUDE_PLUGIN_ROOT}/examples/` for complete examples: +- `dangerous-rm.local.md` - Block dangerous rm commands +- `console-log-warning.local.md` - Warn about console.log +- `sensitive-files-warning.local.md` - Warn about editing .env files + +## Quick Reference + +**Minimum viable rule:** +```markdown +--- +name: my-rule +enabled: true +event: bash +pattern: dangerous_command +--- + +Warning message here +``` + +**Rule with conditions:** +```markdown +--- +name: my-rule +enabled: true +event: file +conditions: + - field: file_path + operator: regex_match + pattern: \.ts$ + - field: new_text + operator: contains + pattern: any +--- + +Warning message +``` + +**Event types:** +- `bash` - Bash commands +- `file` - File edits +- `stop` - Completion checks +- `prompt` - User input +- `all` - All events + +**Field options:** +- Bash: `command` +- File: `file_path`, `new_text`, `old_text`, `content` +- Prompt: `user_prompt` + +**Operators:** +- `regex_match`, `contains`, `equals`, `not_contains`, `starts_with`, `ends_with` diff --git a/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..7ff26c7273a12246892c72f028e605b418530ec7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_contract.json @@ -0,0 +1,26 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..338e71e03de21732e27ea42384e7daecf23ca3a3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "1" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/da0ea4af7d02ad888fcae5c0/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' ({ + token: localStorage.getItem('token') || null, + usuario: null, + carregando: false, +}) + +const getters = { + estaLogado: (state) => !!state.token, + nomeUsuario: (state) => state.usuario?.nome ?? 'Visitante', + tokenHeader: (state) => state.token ? `Bearer ${state.token}` : null, +} + +const mutations = { + SET_TOKEN(state, token) { + state.token = token + if (token) localStorage.setItem('token', token) + else localStorage.removeItem('token') + }, + SET_USUARIO(state, usuario) { + state.usuario = usuario + }, + SET_CARREGANDO(state, val) { + state.carregando = val + }, +} + +const actions = { + async login({ commit }, credenciais) { + commit('SET_CARREGANDO', true) + try { + const { data } = await api.post('/auth/login', credenciais) + commit('SET_TOKEN', data.token) + commit('SET_USUARIO', data.usuario) + } finally { + commit('SET_CARREGANDO', false) + } + }, + logout({ commit }) { + commit('SET_TOKEN', null) + commit('SET_USUARIO', null) + }, + async carregarPerfil({ commit, state }) { + if (!state.token) return + const { data } = await api.get('/auth/me') + commit('SET_USUARIO', data) + }, +} + +export default { + namespaced: true, + state, + getters, + mutations, + actions, +} +``` + +```js +// src/store/index.js +import Vue from 'vue' +import Vuex from 'vuex' +import auth from './modules/auth' +import usuarios from './modules/usuarios' + +Vue.use(Vuex) + +export default new Vuex.Store({ + strict: process.env.NODE_ENV !== 'production', + modules: { + auth, + usuarios, + }, +}) +``` + +## Uso do Vuex em componentes + +```vue + +``` + +## Acesso direto à store (fora de componentes) + +```js +// Em um serviço ou helper +import store from '@/store' + +// Ler estado +const token = store.getters['auth/tokenHeader'] + +// Disparar action +await store.dispatch('auth/carregarPerfil') + +// Commit direto (evitar fora de componentes) +store.commit('auth/SET_USUARIO', usuario) +``` + +## Vue Router 3 — Configuração + +```js +// src/router/index.js +import Vue from 'vue' +import VueRouter from 'vue-router' +import store from '@/store' + +Vue.use(VueRouter) + +const routes = [ + { + path: '/', + redirect: '/dashboard', + }, + { + path: '/login', + name: 'Login', + component: () => import('@/views/LoginView.vue'), + meta: { publico: true }, + }, + { + path: '/dashboard', + component: () => import('@/layouts/AppLayout.vue'), + meta: { requerAutenticacao: true }, + children: [ + { + path: '', + name: 'Dashboard', + component: () => import('@/views/DashboardView.vue'), + }, + { + path: 'usuarios', + name: 'Usuarios', + component: () => import('@/views/UsuariosView.vue'), + meta: { permissao: 'usuarios.listar' }, + }, + { + path: 'usuarios/:id', + name: 'UsuarioDetalhe', + component: () => import('@/views/UsuarioDetalheView.vue'), + props: true, + }, + ], + }, + { + path: '*', + name: 'NaoEncontrado', + component: () => import('@/views/NaoEncontradoView.vue'), + }, +] + +const router = new VueRouter({ + mode: 'history', + base: process.env.BASE_URL, + routes, + scrollBehavior(to, from, savedPosition) { + return savedPosition ?? { x: 0, y: 0 } + }, +}) + +// Guard global — autenticação +router.beforeEach((to, from, next) => { + const estaLogado = store.getters['auth/estaLogado'] + const requerAuth = to.matched.some((r) => r.meta.requerAutenticacao) + const ehPublico = to.matched.some((r) => r.meta.publico) + + if (requerAuth && !estaLogado) { + return next({ name: 'Login', query: { redirect: to.fullPath } }) + } + + if (ehPublico && estaLogado) { + return next({ name: 'Dashboard' }) + } + + next() +}) + +export default router +``` + +## Navegação programática + +```js +// Navegar para rota nomeada +this.$router.push({ name: 'UsuarioDetalhe', params: { id: 42 } }) + +// Com query string +this.$router.push({ name: 'Usuarios', query: { page: 2, busca: 'Ana' } }) + +// Voltar +this.$router.go(-1) + +// Substituir (sem histórico) +this.$router.replace({ name: 'Login' }) + +// Acessar parâmetros da rota atual +const id = this.$route.params.id +const page = this.$route.query.page +const nomeDaRota = this.$route.name +``` + +## Route guard por componente + +```js +export default { + // Antes de entrar na rota deste componente + beforeRouteEnter(to, from, next) { + next((vm) => { + // vm = instância do componente (única forma de acessar no beforeRouteEnter) + vm.carregarDados() + }) + }, + // Antes de sair (ex.: formulário não salvo) + beforeRouteLeave(to, from, next) { + if (this.formularioSujo) { + const confirmou = window.confirm('Deseja sair sem salvar?') + return confirmou ? next() : next(false) + } + next() + }, +} +``` + +## Checklist Vuex + Router Vue 2 + +- [ ] Store com `strict: true` em desenvolvimento +- [ ] Módulos com `namespaced: true` +- [ ] Mutations são síncronas; actions assíncronas +- [ ] `state` como função (escopo por instância) +- [ ] Token persistido em `localStorage` via mutation +- [ ] Guard global `beforeEach` protege rotas privadas +- [ ] Rotas lazy-loaded com `() => import(...)` +- [ ] `scrollBehavior` configurado +- [ ] Parâmetros de rota acessados via `this.$route.params` + +## Anti-padrões + +| Anti-padrão | Correção | +|-------------|----------| +| Mutar state diretamente fora de mutation | Sempre usar commit/mutation | +| Lógica assíncrona em mutation | Mover para action | +| `store.state.auth.token` em template | Usar getter ou mapState | +| Rotas sem lazy loading | `() => import(...)` em todas as views | +| `next()` sem `return` em guards | Sempre `return next(...)` para evitar double-navigation | + +## Referências canônicas +- https://v3.vuex.vuejs.org/ +- https://v3.router.vuejs.org/ +- https://v2.vuejs.org/v2/guide/ + +## Changelog (este arquivo) + +- 1.0.0 (24/04/2026): E11 P4 — skill criada. Cobre Vuex 3 (módulos, namespace, getters, actions async), Vue Router 3 (rotas aninhadas, lazy loading, guards globais e por componente, navegação programática). diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..a84f00994e1ed87e6407bae462ceedf6daf382f1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "5" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith('=400 for e in events)/len(events)>.05 else'ok'),'WebflowRateLimitLow '+('firing'if min(e['rate_limit_remaining']for e in events)<10 else'ok')] + a_ok=isinstance(alerts,str)and collections.Counter(l.strip()for l in alerts.splitlines()if l.strip())==collections.Counter(want_alerts) + rows=parse(metrics) + if rows is None:return [False]*4+[a_ok] + counter,durations,minimum=truth(events);known={COUNTER,HIST+'_bucket',HIST+'_sum',HIST+'_count',GAUGE} + if any(name not in known for name,lab,val in rows):return [False]*4+[a_ok] + cr=[(lab,val)for name,lab,val in rows if name==COUNTER];wanted=list(counter.items());c_ok=len(cr)==len(wanted)and all(set(lab)=={'operation','status_code','method'}and(lab['operation'],lab['status_code'],lab['method'])==key and val==n for(lab,val),(key,n)in zip(cr,wanted)) + buckets={};sums={};counts={};b_ok=True;sc_ok=True + for name,lab,val in rows: + if name==HIST+'_bucket': + if set(lab)!={'operation','le'}:b_ok=False;continue + try:bound=float('inf')if lab['le']=='+Inf'else float(lab['le']) + except Exception:b_ok=False;continue + key=(lab['operation'],bound) + if key in buckets:b_ok=False + buckets[key]=val + elif name in[HIST+'_sum',HIST+'_count']: + if set(lab)!={'operation'}:sc_ok=False;continue + (sums if name.endswith('_sum')else counts)[lab['operation']]=val + want_b={(op,b):sum(d<=b for d in values)for op,values in durations.items()for b in BOUNDS+[float('inf')]};b_ok&=buckets==want_b + sc_ok&=set(sums)==set(durations)and set(counts)==set(durations)and all(abs(sums[op]-sum(ds))<=1e-6 and counts[op]==len(ds)for op,ds in durations.items()) + gauges=[(lab,val)for name,lab,val in rows if name==GAUGE];g_ok=gauges==[({},minimum)] + + return [c_ok,b_ok,sc_ok,g_ok,a_ok] +def run(events): + with workspace(remove=('metrics.txt', 'alerts.txt', 'events.l'))as ws: + (ws/'events.l').write_text('\n'.join(json.dumps(e)for e in events)+'\n') + try:p=subprocess.run([sys.executable,'observe.py'],cwd=ws,capture_output=True,text=True,timeout=30);return p.returncode,_co_text(ws/'metrics.txt'),_co_text(ws/'alerts.txt') + except subprocess.TimeoutExpired:return 124,None,None + except Exception as error:raise RuntimeError("Trusted metrics launcher failed") from error +def main(): + varied=[{'operation':'op"quoted\\name'if i%2 else'other','method':'PATCH'if i%3 else'GET','status_code':503 if i==0 else 200,'duration_ms':[0,50,100,250,500,1000,2000,5000,10000,11000][i%10],'rate_limit_remaining':10}for i in range(20)];firing=[dict(e,status_code=404 if i<2 else 200,rate_limit_remaining=9)for i,e in enumerate(varied)];panels=[EVENTS,varied,firing] + runs=[run(p)for p in panels] + try:saved_m=_co_text(Path('/candidate/metrics.txt'));saved_a=_co_text(Path('/candidate/alerts.txt')) + except Exception: + try:saved_a=_co_text(Path('/candidate/alerts.txt')) + except Exception:saved_a=None + try:saved_m=_co_text(Path('/candidate/metrics.txt')) + except Exception:saved_m=None + views=[aspects(saved_m,saved_a,EVENTS)]+[aspects(m,a,p)for(rc,m,a),p in zip(runs,panels)] + dep_ok,dep_modules,dep_reason=scan_stdlib('/candidate',['observe.py']) + stdlib=None if dep_reason.startswith('unknown:')else dep_ok + behavior=all(rc==0 and all(aspects(m,a,p))for(rc,m,a),p in zip(runs,panels)) + flags=[all(v[i]for v in views)for i in range(5)]+[(stdlib if behavior else False)] + print(json.dumps({'scoreable':all(type(v)is bool for v in flags),'checks':[dict(id=str(i),passed=v,reason='Actual and fresh complete unique Prometheus series; exact counter first-seen order/labels, escaped label values, all cumulative inclusive bucket boundaries with numeric label equivalence and +Inf, operation-owned sum/count, minimum gauge, full alert inventory with strict .05/10 thresholds, changed-event computation')for i,v in enumerate(flags)]})) +main() diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/original_check.txt b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/original_check.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d280b657c7f47f2bfef4059317126883f735132 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/original_check.txt @@ -0,0 +1,140 @@ +import json,os,shutil,subprocess,tempfile,re + +EVENTS = '{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 120, "rate_limit_remaining": 55}\n{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 80, "rate_limit_remaining": 54}\n{"operation": "items.listLive", "method": "GET", "status_code": 200, "duration_ms": 340, "rate_limit_remaining": 53}\n{"operation": "items.listLive", "method": "GET", "status_code": 200, "duration_ms": 95, "rate_limit_remaining": 52}\n{"operation": "items.create", "method": "POST", "status_code": 429, "duration_ms": 210, "rate_limit_remaining": 8}\n{"operation": "items.create", "method": "POST", "status_code": 200, "duration_ms": 450, "rate_limit_remaining": 7}\n{"operation": "items.create", "method": "POST", "status_code": 500, "duration_ms": 1500, "rate_limit_remaining": 7}\n{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 60, "rate_limit_remaining": 6}\n{"operation": "items.listLive", "method": "GET", "status_code": 404, "duration_ms": 45, "rate_limit_remaining": 6}\n{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 110, "rate_limit_remaining": 5}\n' + +EXPECTED_COUNTER = { + ('sites.list','200','GET'):4, + ('items.listLive','200','GET'):2, + ('items.listLive','404','GET'):1, + ('items.create','429','POST'):1, + ('items.create','200','POST'):1, + ('items.create','500','POST'):1, +} +BUCKETS=[0.05,0.1,0.25,0.5,1,2,5,10] +DUR = { + 'sites.list':[0.12,0.08,0.06,0.11], + 'items.listLive':[0.34,0.095,0.045], + 'items.create':[0.21,0.45,1.5], +} +def cum(durs,b): + return sum(1 for d in durs if d<=b) +EXPECTED_BUCKETS={op:{str(b):cum(durs,b) for b in BUCKETS} for op,durs in DUR.items()} +for op in DUR: EXPECTED_BUCKETS[op]['+Inf']=len(DUR[op]) +EXPECTED_SUMCOUNT={op:(round(sum(durs),6),len(durs)) for op,durs in DUR.items()} + +LINE=re.compile(r'^(\w+)(?:\{([^}]*)\})?\s+(-?[0-9.eE+]+)\s*$') +LAB=re.compile(r'(\w+)="([^"]*)"') + +def parse(path): + out=[] + if not os.path.exists(path): return None + with open(path) as f: + for ln in f: + ln=ln.strip() + if not ln or ln.startswith('#'): continue + m=LINE.match(ln) + if not m: continue + labels=dict(LAB.findall(m.group(2) or '')) + try: val=float(m.group(3)) + except ValueError: continue + out.append((m.group(1),labels,val)) + return out + +def run_candidate(d): + r=subprocess.run(['python3','observe.py'],cwd=d,capture_output=True,text=True,timeout=60) + return r + +def evaluate(): + checks=[None]*6 + src='/candidate' + obs=os.path.join(src,'observe.py') + if not os.path.exists(obs): + for i in range(6): checks[i]={'id':str(i),'passed':False,'reason':'observe.py missing'} + return checks + tmp=tempfile.mkdtemp(dir='/tmp') + shutil.copy(obs,os.path.join(tmp,'observe.py')) + with open(os.path.join(tmp,'events.l'),'w') as f: f.write(EVENTS) + try: + r=run_candidate(tmp) + except subprocess.TimeoutExpired: + for i in range(6): checks[i]={'id':str(i),'passed':False,'reason':'observe.py timed out'} + return checks + if r.returncode!=0: + for i in range(6): checks[i]={'id':str(i),'passed':False,'reason':'observe.py exited with error: '+ (r.stderr or '')[:200]} + return checks + mpath=os.path.join(tmp,'metrics.txt'); apath=os.path.join(tmp,'alerts.txt') + metrics=parse(mpath) + if metrics is None: + for i in range(6): checks[i]={'id':str(i),'passed':False,'reason':'metrics.txt missing'} + checks[4]={'id':'4','passed':False,'reason':'alerts.txt not evaluated (metrics.txt missing)'} + return checks + # check 0: counter + got={} + for name,lab,val in metrics: + if name=='webflow_api_requests_total': + got[(lab.get('operation',''),lab.get('status_code',''),lab.get('method',''))]=got.get((lab.get('operation',''),lab.get('status_code',''),lab.get('method','')),0)+val + ok = got=={k:float(v) for k,v in EXPECTED_COUNTER.items()} + checks[0]={'id':'0','passed':ok,'reason':'counter combos/counts match' if ok else 'webflow_api_requests_total mismatch: got '+json.dumps({str(k):v for k,v in got.items()})} + # check 1: buckets + gb={} + for name,lab,val in metrics: + if name=='webflow_api_request_duration_seconds_bucket': + gb.setdefault(lab.get('operation',''),{})[lab.get('le','')]=val + ok=True; why=[] + for op,exp in EXPECTED_BUCKETS.items(): + g=gb.get(op,{}) + if set(g.keys())!=set(exp.keys()): ok=False; why.append(op+' le set wrong'); continue + for le,v in exp.items(): + if abs(g.get(le,-1)-v)>1e-9: ok=False; why.append(op+' le='+le+' count '+str(g.get(le))+' expected '+str(v)) + if set(gb.keys())!=set(EXPECTED_BUCKETS.keys()): ok=False; why.append('operations set wrong: '+str(sorted(gb.keys()))) + checks[1]={'id':'1','passed':ok,'reason':'cumulative buckets correct' if ok else '; '.join(why)[:300]} + # check 2: sum/count + gs={}; gc={} + for name,lab,val in metrics: + if name=='webflow_api_request_duration_seconds_sum': gs[lab.get('operation','')]=val + if name=='webflow_api_request_duration_seconds_count': gc[lab.get('operation','')]=val + ok=True; why=[] + for op,(s,c) in EXPECTED_SUMCOUNT.items(): + if op not in gs or op not in gc: ok=False; why.append(op+' sum/count missing'); continue + if abs(gs[op]-s)>1e-6: ok=False; why.append(op+' sum '+str(gs[op])+' expected '+str(s)) + if abs(gc[op]-c)>1e-9: ok=False; why.append(op+' count '+str(gc[op])+' expected '+str(c)) + checks[2]={'id':'2','passed':ok,'reason':'sum/count correct' if ok else '; '.join(why)[:300]} + # check 3: gauge + gv=[val for name,lab,val in metrics if name=='webflow_rate_limit_remaining'] + ok=len(gv)>=1 and all(abs(v-5)<1e-9 for v in gv) and len(gv)==1 + checks[3]={'id':'3','passed':ok,'reason':'gauge min = 5' if ok else 'webflow_rate_limit_remaining expected single value 5, got '+str(gv)} + # check 4: alerts + alerts=None + if os.path.exists(apath): + with open(apath) as f: alerts=[l.strip() for l in f if l.strip()] + need=['WebflowHighErrorRate firing','WebflowRateLimitLow firing'] + ok = alerts is not None and all(n in alerts for n in need) + checks[4]={'id':'4','passed':ok,'reason':'both alerts firing' if ok else 'alerts.txt lines: '+str(alerts)} + # check 5: reads events.l, not hardcoded — perturb input + tmp2=tempfile.mkdtemp(dir='/tmp') + shutil.copy(obs,os.path.join(tmp2,'observe.py')) + lines=EVENTS.strip().split('\n') + e=json.loads(lines[0]); e['status_code']=503; e['duration_ms']=3000 + lines[0]=json.dumps(e) + with open(os.path.join(tmp2,'events.l'),'w') as f: f.write('\n'.join(lines)+'\n') + try: + r2=run_candidate(tmp2) + m2=parse(os.path.join(tmp2,'metrics.txt')) + if r2.returncode!=0 or m2 is None: + checks[5]={'id':'5','passed':False,'reason':'rerun with modified events.l failed'} + else: + g2={} + for name,lab,val in m2: + if name=='webflow_api_requests_total': + g2[(lab.get('operation',''),lab.get('status_code',''),lab.get('method',''))]=val + exp2={k:float(v) for k,v in EXPECTED_COUNTER.items()} + del exp2[('sites.list','200','GET')] + exp2[('sites.list','200','GET')]=3.0 + exp2[('sites.list','503','GET')]=1.0 + ok = g2==exp2 + checks[5]={'id':'5','passed':ok,'reason':'output tracks events.l changes' if ok else 'outputs did not change correctly with modified events.l (possible hardcoding): '+json.dumps({str(k):v for k,v in g2.items()})} + except subprocess.TimeoutExpired: + checks[5]={'id':'5','passed':False,'reason':'rerun timed out'} + return checks + +print(json.dumps({'checks':evaluate()})) diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..4766d47384eba80166d3e8635bbd651a56c706a8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/repair_manifest.json @@ -0,0 +1,51 @@ +{ + "query_id": "dda9b3780119998a13ba951b", + "sample_index": 853, + "status": "implemented_pending_independent_review", + "repair_scope": "grader_only", + "root_cause": "Original parser silently skips malformed lines, merges duplicate counter rows and overwrites duplicate buckets, omits first-seen order, accepts extra alerts and poorly probes changed data.", + "public_semantics": "Strict full Prometheus parse without silently discarded lines, exact unique typed label sets and all series, original saved metrics/alerts plus independently changed operation/method/status/duration/limits at threshold boundaries; namespace helpers supported.", + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "original_count": 6, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "rubric": "original IDs/count/equal weights preserved", + "source_hashes": { + "instruction.md": "7faa54ea6b472f7904df5dfde0816c66890dcfacec5ef3699797abd5f1c17a22", + "task.json": "483ebbc3a0ff9caef48f950a9d65955fc5b3a72469f6e82de76d2c500a1ae179", + "evaluator/check.py": "5379ee8a04f4fb6d643011a0d3e8bf2904331f8d35f198913fca91ee55bf55dd", + "inputs/events.l": "035185fdd5e96820ac404d8a754c29666e25ef3356923f4e00b792a0a1337257" + }, + "checker_sha256": "f54dc7c687a1f1c2f8538cf3a632e54ba6062690f88caea42b3817a0eac3b194", + "logic_file_sha256": { + "dependency_scan.py": "58bccf8ba7635a1de6f729930c6000c81b9087cbe6151c27e118badcf89d6db2", + "check.py": "f54dc7c687a1f1c2f8538cf3a632e54ba6062690f88caea42b3817a0eac3b194", + "workspace_copy.py": "7f8c1a51c47350dc84cf9c129923d81b8c080918db05071dd5d93e067b0fe141" + }, + "solver_or_arm_conditioned": false, + "local_validation": "Own overlay AST parsed/compiled only; source/candidate programs not executed locally", + "historical_rescore": "not_seen_by_author", + "notes": [ + "No fresh solver; historical gain not inspected; candidate and checker execution delegated to root offline Docker.", + "Independent review: fixed exclusive workspace preserves every helper/resource and exact frozen outputs; absolute path, real PEP263 namespace and stdlib shadow controls. Metrics/threshold semantics unchanged.", + "Fixture correction: namespace/true-PEP263 helper uses public root cwd paths for events, metrics and alerts; original source and actual correct fixture unchanged." + ], + "all_logic_sha256": { + "dependency_scan.py": "58bccf8ba7635a1de6f729930c6000c81b9087cbe6151c27e118badcf89d6db2", + "check.py": "f54dc7c687a1f1c2f8538cf3a632e54ba6062690f88caea42b3817a0eac3b194", + "workspace_copy.py": "7f8c1a51c47350dc84cf9c129923d81b8c080918db05071dd5d93e067b0fe141" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..6e54ded79d510641b98bd93787b022aa89473b5c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/evaluator/workspace_copy.py @@ -0,0 +1,21 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + root=Path('/workspace');root.mkdir(exist_ok=True);clean(root) + try: + shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield root + finally:clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..d1f9501901622dc403ba74bdda400fa999466ec4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/grading/verified_config.json @@ -0,0 +1,42 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "dda9b3780119998a13ba951b", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "grader_timeout_seconds": 600, + "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." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "d46cd17575ee6038ea42b106b55dd5f944018284e2de11b2403115fb2f965b44", + "original_check.txt": "5379ee8a04f4fb6d643011a0d3e8bf2904331f8d35f198913fca91ee55bf55dd", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "9ebe9f6e50e4aeebaa50167411c4288dee2e01291120b019137f2c56d198e160", + "repair_manifest.json": "b17ff39cc7711881ab760bf7cc4d5b013df7c51f40737fb4a8cf95015214736c", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "bf577c7511333e717b1ffeec296bb2dcae11b9bf289805a6d60b8cff5eaa9475", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/inputs/events.l b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/inputs/events.l new file mode 100644 index 0000000000000000000000000000000000000000..07291508d6fda14deb1e6c7e7887b2800d61bb69 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/inputs/events.l @@ -0,0 +1,10 @@ +{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 120, "rate_limit_remaining": 55} +{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 80, "rate_limit_remaining": 54} +{"operation": "items.listLive", "method": "GET", "status_code": 200, "duration_ms": 340, "rate_limit_remaining": 53} +{"operation": "items.listLive", "method": "GET", "status_code": 200, "duration_ms": 95, "rate_limit_remaining": 52} +{"operation": "items.create", "method": "POST", "status_code": 429, "duration_ms": 210, "rate_limit_remaining": 8} +{"operation": "items.create", "method": "POST", "status_code": 200, "duration_ms": 450, "rate_limit_remaining": 7} +{"operation": "items.create", "method": "POST", "status_code": 500, "duration_ms": 1500, "rate_limit_remaining": 7} +{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 60, "rate_limit_remaining": 6} +{"operation": "items.listLive", "method": "GET", "status_code": 404, "duration_ms": 45, "rate_limit_remaining": 6} +{"operation": "sites.list", "method": "GET", "status_code": 200, "duration_ms": 110, "rate_limit_remaining": 5} diff --git a/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2a51c18c52f7accbe5331dcafc90e52a4a890d9b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/dda9b3780119998a13ba951b/skill/SKILL.md @@ -0,0 +1,371 @@ +--- +name: webflow-observability +description: "Set up observability for Webflow integrations \u2014 Prometheus metrics\ + \ for API calls,\nOpenTelemetry tracing, structured logging with pino, Grafana dashboards,\n\ + and alerting for rate limits, errors, and latency.\nTrigger with phrases like \"\ + webflow monitoring\", \"webflow metrics\",\n\"webflow observability\", \"monitor\ + \ webflow\", \"webflow alerts\", \"webflow tracing\".\n" +allowed-tools: Read, Write, Edit +version: 1.5.0 +license: MIT +author: Jeremy Longshore +tags: +- saas +- design +- no-code +- webflow +compatibility: Designed for Claude Code +--- +# Webflow Observability + +## Overview + +Full observability stack for Webflow Data API v2 integrations: Prometheus metrics +for API call counting and latency, OpenTelemetry distributed tracing, structured +JSON logging, and alerting rules for error rate and rate limit exhaustion. + +## Prerequisites + +- `prom-client` for Prometheus metrics +- `@opentelemetry/api` for tracing (optional) +- `pino` for structured logging +- Prometheus + Grafana (or compatible backend) + +## Instructions + +### Step 1: Prometheus Metrics + +```typescript +// src/observability/metrics.ts +import { Registry, Counter, Histogram, Gauge } from "prom-client"; + +export const registry = new Registry(); + +// API request counter (by operation and status) +export const apiRequests = new Counter({ + name: "webflow_api_requests_total", + help: "Total Webflow API requests", + labelNames: ["operation", "status_code", "method"] as const, + registers: [registry], +}); + +// Request duration histogram +export const apiDuration = new Histogram({ + name: "webflow_api_request_duration_seconds", + help: "Webflow API request duration in seconds", + labelNames: ["operation"] as const, + buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10], + registers: [registry], +}); + +// Error counter by type +export const apiErrors = new Counter({ + name: "webflow_api_errors_total", + help: "Webflow API errors by status code", + labelNames: ["operation", "status_code", "error_type"] as const, + registers: [registry], +}); + +// Rate limit remaining gauge +export const rateLimitRemaining = new Gauge({ + name: "webflow_rate_limit_remaining", + help: "Remaining API calls before rate limit", + registers: [registry], +}); + +// CMS items gauge (track total items across collections) +export const cmsItemCount = new Gauge({ + name: "webflow_cms_items_total", + help: "Total CMS items by collection", + labelNames: ["collection", "site"] as const, + registers: [registry], +}); + +// Webhook event counter +export const webhookEvents = new Counter({ + name: "webflow_webhook_events_total", + help: "Received webhook events by trigger type", + labelNames: ["trigger_type", "status"] as const, + registers: [registry], +}); +``` + +### Step 2: Instrumented Client Wrapper + +```typescript +// src/observability/instrumented-client.ts +import { WebflowClient } from "webflow-api"; +import { apiRequests, apiDuration, apiErrors, rateLimitRemaining } from "./metrics.js"; + +export async function instrumentedCall( + operation: string, + method: string, + fn: () => Promise +): Promise { + const timer = apiDuration.startTimer({ operation }); + + try { + const result = await fn(); + + apiRequests.inc({ operation, status_code: "200", method }); + timer(); + return result; + } catch (error: any) { + const statusCode = String(error.statusCode || error.status || "unknown"); + + apiRequests.inc({ operation, status_code: statusCode, method }); + apiErrors.inc({ + operation, + status_code: statusCode, + error_type: statusCode === "429" ? "rate_limit" : statusCode >= "500" ? "server" : "client", + }); + + timer(); + throw error; + } +} + +// Usage +const { sites } = await instrumentedCall("sites.list", "GET", () => + webflow.sites.list() +); + +const { items } = await instrumentedCall("items.listLive", "GET", () => + webflow.collections.items.listItemsLive(collectionId) +); + +const item = await instrumentedCall("items.create", "POST", () => + webflow.collections.items.createItem(collectionId, { + fieldData: { name: "Test", slug: "test" }, + }) +); +``` + +### Step 3: Metrics Endpoint + +```typescript +// api/metrics.ts +import express from "express"; +import { registry } from "../observability/metrics.js"; + +const app = express(); + +app.get("/metrics", async (req, res) => { + res.set("Content-Type", registry.contentType); + res.send(await registry.metrics()); +}); +``` + +### Step 4: OpenTelemetry Distributed Tracing + +```typescript +// src/observability/tracing.ts +import { trace, SpanStatusCode, context } from "@opentelemetry/api"; + +const tracer = trace.getTracer("webflow-integration", "1.0.0"); + +export async function tracedCall( + operationName: string, + attributes: Record, + fn: () => Promise +): Promise { + return tracer.startActiveSpan(`webflow.${operationName}`, async (span) => { + span.setAttributes({ + "webflow.operation": operationName, + ...attributes, + }); + + try { + const result = await fn(); + span.setStatus({ code: SpanStatusCode.OK }); + return result; + } catch (error: any) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message, + }); + span.recordException(error); + span.setAttributes({ + "webflow.error.status_code": String(error.statusCode || "unknown"), + }); + throw error; + } finally { + span.end(); + } + }); +} + +// Usage +const { collections } = await tracedCall( + "collections.list", + { "webflow.site_id": siteId }, + () => webflow.collections.list(siteId) +); +``` + +### Step 5: Structured Logging + +```typescript +// src/observability/logger.ts +import pino from "pino"; + +export const logger = pino({ + name: "webflow-integration", + level: process.env.LOG_LEVEL || "info", + serializers: { + err: pino.stdSerializers.err, + }, + // Redact sensitive fields + redact: { + paths: ["accessToken", "apiToken", "*.authorization", "req.headers.authorization"], + censor: "[REDACTED]", + }, +}); + +// Log API calls with consistent structure +export function logApiCall( + operation: string, + durationMs: number, + status: "success" | "error", + metadata?: Record +) { + const logFn = status === "error" ? logger.error.bind(logger) : logger.info.bind(logger); + + logFn({ + service: "webflow", + operation, + durationMs, + status, + ...metadata, + }, `webflow.${operation} ${status} (${durationMs}ms)`); +} + +// Log webhook events +export function logWebhook(triggerType: string, status: "processed" | "failed" | "skipped") { + logger.info({ + service: "webflow", + event: "webhook", + triggerType, + status, + }, `webhook.${triggerType} ${status}`); +} +``` + +### Step 6: AlertManager Rules + +```yaml +# prometheus/webflow-alerts.yml +groups: + - name: webflow + rules: + - alert: WebflowHighErrorRate + expr: | + ( + rate(webflow_api_errors_total[5m]) / + rate(webflow_api_requests_total[5m]) + ) > 0.05 + for: 5m + labels: + severity: warning + annotations: + summary: "Webflow API error rate > 5%" + description: "{{ $value | humanizePercentage }} errors in last 5m" + + - alert: WebflowRateLimited + expr: | + rate(webflow_api_errors_total{status_code="429"}[5m]) > 0 + for: 2m + labels: + severity: warning + annotations: + summary: "Webflow API rate limited" + + - alert: WebflowHighLatency + expr: | + histogram_quantile(0.95, + rate(webflow_api_request_duration_seconds_bucket[5m]) + ) > 3 + for: 5m + labels: + severity: warning + annotations: + summary: "Webflow P95 latency > 3s" + + - alert: WebflowDown + expr: | + sum(rate(webflow_api_requests_total{status_code=~"5.."}[5m])) / + sum(rate(webflow_api_requests_total[5m])) > 0.5 + for: 2m + labels: + severity: critical + annotations: + summary: "Webflow API > 50% server errors" + + - alert: WebflowRateLimitLow + expr: webflow_rate_limit_remaining < 10 + for: 1m + labels: + severity: warning + annotations: + summary: "Webflow rate limit nearly exhausted" +``` + +### Step 7: Grafana Dashboard Queries + +```json +{ + "panels": [ + { + "title": "Request Rate by Operation", + "targets": [{ "expr": "sum by (operation) (rate(webflow_api_requests_total[5m]))" }] + }, + { + "title": "Error Rate", + "targets": [{ "expr": "sum(rate(webflow_api_errors_total[5m])) / sum(rate(webflow_api_requests_total[5m]))" }] + }, + { + "title": "Latency P50 / P95 / P99", + "targets": [ + { "expr": "histogram_quantile(0.5, rate(webflow_api_request_duration_seconds_bucket[5m]))", "legendFormat": "p50" }, + { "expr": "histogram_quantile(0.95, rate(webflow_api_request_duration_seconds_bucket[5m]))", "legendFormat": "p95" }, + { "expr": "histogram_quantile(0.99, rate(webflow_api_request_duration_seconds_bucket[5m]))", "legendFormat": "p99" } + ] + }, + { + "title": "Rate Limit Remaining", + "targets": [{ "expr": "webflow_rate_limit_remaining" }] + }, + { + "title": "Webhook Events by Type", + "targets": [{ "expr": "sum by (trigger_type) (rate(webflow_webhook_events_total[5m]))" }] + } + ] +} +``` + +## Output + +- Prometheus metrics: request count, latency histogram, error rate, rate limit gauge +- OpenTelemetry tracing for end-to-end request visibility +- Structured JSON logging with PII redaction +- AlertManager rules for error rate, latency, and rate limits +- Grafana dashboard panels + +## Error Handling + +| Issue | Cause | Solution | +|-------|-------|----------| +| Missing metrics | Calls not instrumented | Wrap with `instrumentedCall()` | +| High cardinality | Too many label values | Limit `operation` to known set | +| Trace gaps | Missing context propagation | Pass OTel context in async calls | +| Alert storms | Thresholds too sensitive | Increase `for` duration | + +## Resources + +- [Prometheus Best Practices](https://prometheus.io/docs/practices/naming/) +- [OpenTelemetry JS](https://opentelemetry.io/docs/languages/js/) +- [pino Documentation](https://github.com/pinojs/pino) + +## Next Steps + +For incident response, see `webflow-incident-runbook`. diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..d649869e1a7a0da3db2cca7c176d23402e9a3def --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1400 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import math +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + + +def _r10_stdout_discarded(statement): + # Parse descriptor redirects in order. A stderr-only sink does not hide stdout. + if '$(' in statement: + begin=statement.find('$(')+2;end=statement.rfind(')') + if end>=begin:statement=statement[begin:end] + lexer=shlex.shlex(statement,posix=True,punctuation_chars=';&|<>()') + lexer.whitespace_split=True + try:tokens=list(lexer) + except ValueError:return False + sinks={1:'stdout',2:'stderr'};i=0 + while i','>>','>&'): + fd=int(op);i+=1;op=tokens[i] + if op in ('>','>>','>&','&>','&>>') and i+1&' and target.isdigit() else 'discard' if target in ('/dev/null','-') else 'file' + sinks[fd]=sink + if op.startswith('&'):sinks[1]=sink;sinks[2]=sink + i+=2 + else:i+=1 + return sinks.get(1)=='discard' + + +def _r10_stdout_target(statement): + # None means inherited output, otherwise the final explicit fd1 destination. + lexer=shlex.shlex(statement,posix=True,punctuation_chars=';&|<>()');lexer.whitespace_split=True + try:tokens=list(lexer) + except ValueError:return 'unknown' + target=None;i=0 + while i','>>','>&'): + fd=int(op);i+=1;op=tokens[i] + if op in('>','>>','>&','&>','&>>')and i+1 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + + +def _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + actual = json.loads(path.read_text(encoding="utf-8")) + passed = (_same_native_json_types(actual, check.get("expected")) and + _canonical(actual) == _canonical(check.get("expected"))) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + if check.get("stdout_must_not_discard"): + try: + from shell_invocations import _statements + statements=_statements(source) + relevant=[call for call in shell_invocations(source) if _shell_command_matches(expected,call['command'])] + passed=passed and any(_r10_stdout_displayed(call,shell_invocations(source),source) for call in relevant) + except (ValueError,IndexError):passed=False + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + passed = passed and all(call['fail_fast'] or shlex.split(call['command'])[0] in ('true', ':') for call in calls) + detail = f"expected_failure_propagation={expected}; all_calls_fail_fast=True; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..c03f64348caa714a2797a7d6488d9a515c65d380 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,455 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + + +# R7: unwrap only execution wrappers whose effect is proved in this subset. +# In particular `command -v/-V` queries do not run their operand, and `builtin` +# cannot run an external tool. Keep these distinctions before inspecting state. +_BASH_BUILTINS = frozenset({ + ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', + 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs', + 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', + 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', + 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', + 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', + 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', + 'unset', 'wait', +}) +_UNSUPPORTED_STATE = frozenset({ + '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap', + 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local', + 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift', + '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts', +}) + + +def _bash_dialect(text): + """No shebang uses the evaluator's Bash syntax contract; sh is not Bash.""" + first = str(text).splitlines()[0] if str(text).splitlines() else '' + if not first.startswith('#!'): + return True + try: + words = shlex.split(first[2:]) + except ValueError: + return False + if not words: + return False + executable = words[0].rsplit('/', 1)[-1] + if executable == 'env': + words = words[1:] + if words[:1] == ['-S']: + words = words[1:] + executable = words[0] if words else '' + return executable.rsplit('/', 1)[-1] == 'bash' + + +def _execution_argv(argv, bash=True): + """Normalize a finite chain; unsupported wrappers get no command credit.""" + if not argv: + return None + argv = list(argv) + while argv and argv[0] in ('command', 'builtin'): + wrapper = argv[0] + if wrapper == 'builtin': + if not bash: + return None + argv = argv[1:] + if argv[:1] == ['--']: + argv = argv[1:] + if not argv or argv[0] not in _BASH_BUILTINS: + return None + continue + index, query, default_path = 1, False, False + while index < len(argv) and argv[index].startswith('-'): + option = argv[index] + index += 1 + if option == '--': + break + if not re.fullmatch(r'-[pvV]+', option): + return None + query = query or 'v' in option or 'V' in option + default_path = default_path or 'p' in option + if query: + return argv # Query is an invocation of command, not its target. + if index == len(argv): + return None + argv = argv[index:] + # -p changes external PATH lookup. It is transparent for builtins only. + if default_path and argv[0] not in _BASH_BUILTINS: + return None + return argv or None + + +def _set_errexit(argv, current): + """Return the proven option state, or None for unsupported set options.""" + if not argv or argv[0] != 'set': + return None + index = 1 + while index < len(argv): + flag = argv[index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Positional arguments cannot enable errexit. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return None # Includes noexec (-n), which suppresses later work. + if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1): + return None + if 'e' in flag[1:]: + current = flag[0] == '-' + if 'o' in flag[1:]: + if index + 1 >= len(argv): + return None + option = argv[index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return None + if option == 'errexit': + current = flag[0] == '-' + index += 1 + index += 1 + return current + + +def shell_option_setting(text, bash=True): + """Recognize valid option setup for task-specific operation counters.""" + argv = _execution_argv(_simple_argv(text), bash) + return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None) + + +def _exit_status(argv): + """A literal shell exit status; no-argument exit is handled by its caller.""" + args = argv[1:] + if args[:1] == ['--']: + args = args[1:] + if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0]) + or len(args[0]) > 20): + return None + value = int(args[0]) + if not -(2**63) <= value <= 2**63 - 1: + return 2 # Bash exits for an out-of-range numeric argument. + return value % 256 + + + +def _nonzero_exit_body(statements, bash=True): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _execution_argv(_simple_argv(statement), bash) + if not argv: + return False + if argv[0] == 'exit': + status = _exit_status(argv) + return index == len(statements) - 1 and status is not None and status != 0 + if argv[0] not in ('echo', 'printf'): + return False + return False + + + +def _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import math +import posixpath +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + text = posixpath.normpath(text) if text else text + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], _atomic_shape(pred)) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = _path_equal(actual, assertion["expected"]) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..4df26c2ffaf32ee54a18bcb00381e1aef3ec640d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""Task-scoped semantic equivalences for the 112 legacy verifier repairs. + +No solver, oracle label, historical score or answer hash influences comparison. +The original private rubric, completeness checks and binary aggregation remain. +""" +from __future__ import annotations +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import copy +import json +import re +import shlex +import shutil +import tempfile +from decimal import Decimal, InvalidOperation +from pathlib import Path + + +def argv(value): + if not isinstance(value, str): + return None + try: + result = shlex.split(value, posix=True) + except ValueError: + return None + # Only the Bash execution wrapper is transparent. command -v/-V are queries. + while len(result) > 1 and result[0] == 'command': + if result[1] == '--': + result = result[2:] + elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]): + break + else: + result = result[1:] + return result or None + + +def git_limit(tokens): + if not tokens or tokens[:2] != ['git', 'log']: + return tokens + out, index = [], 0 + while index < len(tokens): + token = tokens[index] + compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token) + if compact: + out.append('--max-count=' + next(x for x in compact.groups() if x is not None)) + elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit(): + index += 1 + out.append('--max-count=' + tokens[index]) + else: + out.append(token) + index += 1 + return out + + +def shell_equal(expected, actual, normalize_env=False): + wanted, found = argv(expected), argv(actual) + if normalize_env and wanted and found: + wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted] + found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found] + wanted, found = git_limit(wanted), git_limit(found) + if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + if (index == 1 and '/' in token and + observed.rstrip('/').endswith('/' + token.lstrip('./'))): + continue # Existing package-path anchoring; no changed basename/arguments. + return False + return True + + +def command_equal(expected, value): + # Response command questions ask for one invocation, with no extra commands. + return argv(expected) is not None and argv(expected) == argv(value) + + +def convex_equal(expected, value): + a, b = argv(expected), argv(value) + if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]: + return False + def no_duplicates(pairs): + result = {} + for k, v in pairs: + if k in result: + raise ValueError('duplicate JSON key') + result[k] = v + return result + try: + return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates) + except (ValueError, TypeError): + return False + + +def docker_network_equal(expected, value): + tokens = argv(value) + return tokens in (['--network', 'none'], ['--network=none']) + + +def zar_amount(value): + if not isinstance(value, str): + return None + m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I) + if not m: + return None + number = m.group(1) + if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number): + return None + try: + amount = Decimal(number.replace(',', '')) + except InvalidOperation: + return None + return amount * (Decimal(1000000) if m.group(2) else 1) + + +def zar_equal(expected, value): + return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value) + + +def rust_attribute_equal(expected, value): + 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 + + +def header_equal(expected, value): + return isinstance(value, str) and value.casefold() == expected.casefold() + + +def zero_arg_js_equal(expected, value): + name = expected[:-2] + return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None + + +RESPONSE_RULES = { + '82e94ae96e04ff71_q1': {'q1': convex_equal}, + 'df978907fa6f0eea_q1': {'q1': docker_network_equal}, + 'dee0c878f5707477_q1': {'q1': command_equal}, + 'c51259d0062454b2_q1': {'q1': command_equal}, + 'd25a8956477141f2_q1': {'q2': zar_equal}, + '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal}, + 'a4926e403c8165e9_q1': {'q2': header_equal}, + '2b3bd5786727f2fb_q1': {'q1': command_equal}, +} + + +def dashboard_contract(evaluator, candidate, objective): + root = Path(candidate) + path = evaluator['reference_files'][0]['path'] + try: + text = (root / path).read_text() + except (OSError, UnicodeError): + return False + lines = objective._shell_lines(text) + # Public contract explicitly says no other commands/flags. Single quotes + # would suppress environment expansion; only the correctly quoted form counts. + return (len(lines) == 2 and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None) + + +def install(task): + import objective_evaluators as objective + import verifiers + task_id = task['query_id'] + original_verify = verifiers.verify + original_matcher = objective._shell_command_matches + objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1') + + def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None): + if evaluator.get('type') == 'workspace_objective': + # A text occurrence after exit/return, in echo output or within a + # non-executed branch does not prove the requested command runs. + grouped = {} + for check in evaluator.get('checks', []): + if check.get('type') == 'shell_command': + grouped.setdefault(check['path'], []).append(check['value']) + for path, expected_commands in grouped.items(): + try: + text = (Path(solver_output) / path).read_text() + invocations = objective.shell_invocations(text) + for expected_command in expected_commands: + tokens = argv(expected_command) + if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]): + continue # Required scalar assignment is checked by original rubric. + if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations): + return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command} + except (OSError, UnicodeError, ValueError): + return False, {'error': 'cannot inspect required shell artifact', 'path': path} + if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective): + return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'} + normalizations = [] + if task_id in RESPONSE_RULES: + try: + predicted = verifiers._json_value(solver_output) + gold = gt_answer + if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict): + for key, comparator in RESPONSE_RULES[task_id].items(): + value = predicted['answers'].get(key) + expected = gold['answers'][key] + if value != expected and comparator(expected, value): + predicted['answers'][key] = expected + normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected}) + solver_output = json.dumps(predicted) + except (KeyError, ValueError, TypeError): + pass # Preserve original malformed-answer rejection. + if task_id == '59f410a185c510f3_q1': + path = evaluator['reference_files'][0]['path'] + try: + file_path = Path(solver_output) / path + predicted = json.loads(file_path.read_text()) + expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact') + if isinstance(predicted, dict): + for widget in ('chart', 'banner'): + row = predicted.get(widget) + if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')): + if row.get('hydrate') != expected[widget]['hydrate']: + normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']}) + row['hydrate'] = expected[widget]['hydrate'] + if normalizations: + with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary: + view = Path(temporary) / 'candidate' + shutil.copytree(solver_output, view, symlinks=True) + copied = view / path + resolved = copied.resolve() + if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink(): + return False, {'error': 'candidate output parent symlink escapes temporary comparison view'} + if copied.is_symlink(): + copied.unlink() # Do not write through a frozen source symlink. + copied.write_text(json.dumps(predicted)) + passed, details = original_verify(evaluator, gt_answer, str(view), material_paths) + if isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + except (KeyError, ValueError, TypeError, OSError, UnicodeError): + pass + passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths) + if normalizations and isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + + verifiers.verify = repaired_verify diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..05c6983af6feeab08f7419df7e9f3f0f67202489 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "engine": "portable_verified_v1", + "grader_file_sha256": { + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "733613584e40a216857513264eae6bef7ce29c46312ca6f3a1927d1467f23fcb", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "6d80df1617c9f2cfd6d53826a0c8eaf5ef23d24f0012e5b0f11a7ac8ec9f3611", + "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70", + "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af" + }, + "query_id": "ded8d72bd8703126_q1", + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "criterion_weights": { + "0": 1 + }, + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "grader_timeout_seconds": 600, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "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.", + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ] + }, + "schema": "audited-verified-grader-v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703" +} diff --git a/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..00cdcd7011f51708b94087918fb1efa248bbfc28 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ded8d72bd8703126_q1/skill/SKILL.md @@ -0,0 +1,111 @@ +--- +name: revx-auth +description: > + Revolut X CLI setup and authentication. Use when the user asks to "install revx", + "set up Revolut X", "configure API keys", "generate keypair", "set passkey", + "revx configure", or needs help with authentication errors. +--- + +# Auth & Account Setup (`revx configure`) + +> Install the CLI, generate API keys, and configure write-operation security. + +> **Auto-resolve target.** When invoked from another `revx-*` skill due to an auth error, do not bounce the user back to manual setup. Diagnose the failure against the [Error Reference](#error-reference) below, run the fix yourself (e.g. `chmod 600 ~/.config/revolut-x/private.pem`, `revx configure generate-keypair`, `revx configure set --api-key `), then return to the calling skill and retry the original command. Only ask the user for inputs that only they can provide: the 64-character API key string, confirmation that they have registered the public key in their Revolut X profile, the keypair passphrase, or approval to overwrite an existing keypair. + +## Prerequisites + +- **Node.js >= 20** (check with `node -v`) +- **npm** (comes with Node.js) + +## Install + +```bash +npm install -g @revolut/revolut-x-cli && npm link @revolut/revolut-x-cli +``` + +After install, `revx` is available as a global command: + +```bash +revx --version # Should print the version +``` + +--- + +## Getting Started + +### Step 1: Configure Authentication + +```bash +revx configure # Interactive setup wizard +``` + +This will: +1. Generate an Ed25519 keypair (private + public key) +2. Display your public key — copy it +3. Prompt you to register the public key at **exchange.revolut.com -> Profile -> API Keys** +4. Create a new API key — tick the **"Allow usage via Revolut X MCP and CLI"** checkbox +5. Prompt for the 64-character API key you receive after registration + +Or do it step-by-step: + +```bash +revx configure generate-keypair # Creates Ed25519 keypair +# Register public key at exchange.revolut.com -> Profile -> API Keys +# Create API key — tick "Allow usage via Revolut X MCP and CLI" +revx configure set --api-key <64-char-key> +``` + +### Step 2: Verify Configuration + +```bash +revx configure get # Show config status (keys redacted) +revx configure path # Print config directory path +``` + +## Config Commands + +```bash +revx configure # Interactive setup wizard +revx configure get # Show config status (keys redacted) +revx configure set --api-key # Set API key +revx configure generate-keypair # Generate Ed25519 keypair +revx configure path # Print config directory path +``` + +## Config Location + +| Platform | Path | +|---|---| +| macOS/Linux | `~/.config/revolut-x/` | +| Windows | `%APPDATA%\revolut-x\` | +| Override | `REVOLUTX_CONFIG_DIR` env var | + +--- + +## Error Reference + +| Error | Cause | Fix | +|---|---|---| +| Auth not configured | Missing API key or private key | Run `revx configure` | +| Authentication failed (401) | Invalid key or signature | Re-register public key at exchange.revolut.com | +| Network error | Connection/timeout failure | Check connectivity, retry | + +--- + +## Next Steps + +Once configured, explore: +- Check your balances, transactions, and order history — see `revx-account` skill +- View market prices and candles — see `revx-market` skill +- Place your first order — see `revx-trading` skill + +## Related Skills + +| Skill | Purpose | +|---|---| +| `revx-market` | Currencies, pairs, tickers, candles, order book | +| `revx-account` | Balances, transaction history, order queries, trade history | +| `revx-trading` | Place and cancel orders | +| `revx-monitor` | Live price/indicator alerts | +| `revx-telegram` | Telegram notification setup | +| `revx-strategy` | Grid bot backtest, optimize, run | diff --git a/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + 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') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + 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)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + 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 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c0bc6c9e58fe2215ade10ade2f5f25d31b8dbc2d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy.py @@ -0,0 +1,147 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_selected_receipts=None +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def receipt_snapshot(): + install();return frozenset(p.name for p in _folder().glob('*.json')) + +def select_receipts(names): + global _selected_receipts + names=frozenset(names) + if not all(isinstance(name,str)and name.endswith('.json')and '/'not in name for name in names): + raise PolicyInfrastructureError('Invalid selected-entry policy scope') + _selected_receipts=names + +def status(require_execution=True,receipt_names=None): + install();p=_folder();rows=[];available=set() + selected=_selected_receipts if receipt_names is None else frozenset(receipt_names) + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + available.add(receipt.name) + if selected is None or receipt.name in selected:rows.append(row) + if selected is not None and not selected<=available:raise PolicyInfrastructureError('Selected-entry policy receipts missing') + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e08c83cb5492b61ed542740f/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith('=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + 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' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_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=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_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=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def receipt_snapshot(): + install();return frozenset(p.name for p in _folder().glob('*.json')) + +def select_receipts(names): + global _selected_receipts + names=frozenset(names) + if not all(isinstance(name,str)and name.endswith('.json')and '/'not in name for name in names): + raise PolicyInfrastructureError('Invalid selected-entry policy scope') + _selected_receipts=names + +def status(require_execution=True,receipt_names=None): + install();p=_folder();rows=[];available=set() + selected=_selected_receipts if receipt_names is None else frozenset(receipt_names) + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + available.add(receipt.name) + if selected is None or receipt.name in selected:rows.append(row) + if selected is not None and not selected<=available:raise PolicyInfrastructureError('Selected-entry policy receipts missing') + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + 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.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + 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) + 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) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(']*>(.*?)',html,re.I|re.S): + for r in re.finditer(r'([^{}]+)\{([^{}]*)\}',m.group(1)): + selector=r.group(1).strip();start=m.start(1)+r.start(2) + decls=[] + for d in re.finditer(r'([\w-]+)\s*:\s*([^;{}]+)',r.group(2)): + line=html[:start+d.start()].count('\n')+1;decls.append((d.group(1).lower(),d.group(2).strip(),line)) + css.append((selector,decls)) + hits={};add=lambda name,line:hits.setdefault(name,[]).append(line) + focuses=any(':focus-visible' in s for s,ds in css);pads=[];fonts=[];gray=False;white=False + for idx,(sel,ds) in enumerate(css): + padded=False + for prop,val,line in ds: + lower=val.lower();classes=set(re.findall(r'\.([\w-]+)',sel)) + if prop in ['border-left','border-right'] and 'card' in classes: + m=re.match(r'([\d.]+)px\b',lower) + if m and float(m.group(1))>=4 and not re.search(r'\btransparent\b|\bnone\b',lower):add('side-tab',line) + if prop in ['background-clip','-webkit-background-clip'] and lower=='text':add('gradient-text',line) + if prop=='outline' and re.match(r'^(none|0(?:px)?)(?:\s*!important)?$',lower) and not focuses:add('missing-focus-ring',line) + for bez in re.finditer(r'cubic-bezier\s*\(([^)]+)\)',lower): + vals=[float(x.strip()) for x in bez.group(1).split(',')] + if len(vals)==4 and any(not 0<=x<=1 for x in [vals[1],vals[3]]):add('bounce-easing',line) + if prop in ['transition','animation','transition-property','animation-name'] and re.search(r'(?:^|,)\s*(width|height|padding|margin|top|left)\b',lower):add('layout-transition',line) + if prop in ['background','background-color'] and lower in ['#000','#000000','#fff','#ffffff']:add('pure-black-white',line) + if prop=='padding' and lower=='16px' and not padded:pads.append(line);padded=True + if prop=='font-size': + m=re.match(r'^([\d.]+)px$',lower) + if m:fonts.append((float(m.group(1)),line)) + gray=gray or (prop=='color' and lower in ['#777','#777777']);white=white or (prop in ['background','background-color'] and lower in ['#fff','#ffffff']) + if len(pads)>=3:hits['monotonous-spacing']=pads + vals=sorted(set(x for x,l in fonts)) + if len(vals)<2 or any(b/a<1.25 for a,b in zip(vals,vals[1:])): + if fonts:hits['flat-type-hierarchy']=[l for x,l in fonts] + class Dom(HTMLParser): + def __init__(self):super().__init__();self.stack=[] + def handle_starttag(self,tag,attrs): + card='card' in (dict(attrs).get('class') or '').split() + if card and any(c for t,c in self.stack):add('nested-cards',self.getpos()[0]) + if tag not in {'area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr'}:self.stack.append((tag,card)) + def handle_endtag(self,tag): + for i in range(len(self.stack)-1,-1,-1): + if self.stack[i][0]==tag:del self.stack[i:];break + p=Dom();p.feed(html);ids=set(hits);anti=max(0,4-len(ids));theme=0 if 'pure-black-white' in ids else 2 if 'monotonous-spacing' in ids else 3;access=0 if 'missing-focus-ring' in ids else 3 if gray and white else 4;motion=0 if ids&{'bounce-easing','layout-transition'} else 4;total=anti+theme+access+motion;verdict='FAIL' if ids&{'gradient-text','missing-focus-ring','bounce-easing','layout-transition'} or total<12 else 'PASS WITH NOTES' if ids else 'PASS' + return {'signals':[{'id':i,'count':len(hits[i]),'first_line':min(hits[i])} for i in sorted(hits)],'scores':{'Anti-Patterns':anti,'Theming & Consistency':theme,'Accessibility':access,'Motion':motion,'Total':total},'verdict':verdict} + +def grade_css(): + cs=checks(7);w=fresh(['report.','report','report.json']);p=execute(w,'audit.py',['index.html','design_rules.md','report.']);r=load(w/'report.');gold=css_gold(read(w/'index.html') or '');sigs=r.get('signals') if isinstance(r,dict) else None + shape=isinstance(sigs,list) and all(isinstance(s,dict) and set(s)=={'id','count','first_line'} for s in sigs) and len({s.get('id') for s in sigs})==len(sigs);setc(cs,0,p is not None and p.returncode==0 and isinstance(r,dict) and set(r)=={'signals','scores','verdict'} and shape,'fresh exact report. schema, unique actual signal records') + setc(cs,1,shape and [s['id'] for s in sigs]==[s['id'] for s in gold['signals']],'all and only source-derived signal IDs, sorted, no invented or duplicate records') + setc(cs,2,shape and sigs==gold['signals'],'each count and first occurrence line independently computed from source CSS/DOM') + setc(cs,3,isinstance(r,dict) and r.get('scores')==gold['scores'],'all four actual dimensions and total follow public mapping') + setc(cs,4,isinstance(r,dict) and r.get('verdict')==gold['verdict'],'verdict derived from actual source signals and scores') + setc(cs,5,p is not None and p.returncode==0 and p.stdout.strip()==gold['verdict'] and stdlib(CAND/'audit.py'),'stdlib program prints exact computed verdict') + def probe(w): + f=w/'index.html';s=f.read_text().replace(' padding: 16px;',' padding: 12px;',1);s=s.replace('',':focus-visible { outline: 2px solid #555; }\n');f.write_text('\n\n'+s) + w2=fresh(['report.','report','report.json'],probe);p2=execute(w2,'audit.py',['index.html','design_rules.md','report.']);r2=load(w2/'report.');setc(cs,6,p2 is not None and p2.returncode==0 and r2==css_gold(read(w2/'index.html') or ''),'class-aware DOM/CSS and shifted line numbers, focus replacement and sub-threshold spacing adapt to real rules') + return cs + +def layout_role(path,content): + name=Path(path).stem + if re.match(r'use[A-Z_]',name):return 'hooks' + jsx=bool(re.search(r'<[A-Za-z][\w.:-]*(?:\s|/?>)',content)) + if path.endswith(('.tsx','.jsx')) and jsx:return 'components' + if re.search(r'\b(?:interface\s+\w+|type\s+\w+\s*=)',content):return 'types' + if (not path.endswith(('.tsx','.jsx')) and re.search(r'\bfetch\s*\(|\baxios\b|\bHTTP\b',content,re.I)) or re.search(r'(?:Api|Service)$',name):return 'services' + if re.search(r'complex.*(?:feature|screen).*(?:state)|(?:feature|screen).*shared.*state',content,re.I) or re.search(r'Store$',name):return 'store' + if path.endswith(('.tsx','.jsx')) and re.search(r'\b(?:UI|component|render(?:s|ing)?)\b',content,re.I):return 'components' + return None + +def layout_gold(manifest): + files=manifest['files'];known={m.group(1) for f in files for m in [re.search(r'(?:^|/)features/([^/]+)/',f['path'])] if m};result={} + for e in files: + path=norm(e['path']);imports=e.get('imports',[]);content=e.get('content','');v=set();m=re.match(r'^(?:src/)?features/([^/]+)/(.*)$',path);feature=m.group(1) if m else None;reuse=bool(re.search(r'purely reusable|generic utilit|no [^\n]*domain logic',content,re.I));basename=Path(path).stem.lower();hint=any(re.search(r'\b'+re.escape(f)+r'\b',content,re.I) or f.lower() in basename for f in known) + if m and (reuse or m.group(2).split('/')[0] not in {'components','hooks','services','types','store','index.ts'}):v.add('FEATURE_LOCAL') + role=layout_role(path,content) + if m and role and m.group(2).split('/')[0]!=role:v.add('FEATURE_LOCAL') + if not m and re.match(r'^(?:src/)?(?:components|hooks|utils|lib)/',path) and hint and not reuse:v.add('FEATURE_LOCAL') + if not m and re.match(r'^(?:src/)?(?:store|state)/',path) and (hint or any('/features/'+f+'/' in i or '/'+f+'/' in i for f in known for i in imports)):v.add('GLOBAL_STORE_MISUSE') + for i in imports: + target=os.path.normpath(os.path.join(os.path.dirname(path),i)) if i.startswith('.') else i.replace('@/', 'src/').replace('~/', 'src/') + t=re.match(r'^(?:src/)?features/([^/]+)(?:/(.*))?$',target) + if t and t.group(1) in known and t.group(1)!=feature and (t.group(2) or '') not in {'','index','index.ts'}:v.add('CROSS_FEATURE_IMPORT') + if path.endswith(('.tsx','.jsx')) and (any('api' in i.lower() or 'http' in i.lower() for i in imports) or 'fetch(' in content):v.add('HTTP_IN_COMPONENT') + result[e['path']]=v + return result + +def layout_validate(rep,expected): + if not isinstance(rep,dict) or not isinstance(rep.get('files'),list) or not isinstance(rep.get('summary'),dict):return None,False + entries=rep['files'];vm={} + for e in entries: + if not isinstance(e,dict) or set(e)!={'path','violations'} or not isinstance(e.get('path'),str) or not isinstance(e.get('violations'),list) or not all(isinstance(x,str) for x in e['violations']) or e['path'] in vm:return None,False + vm[e['path']]=set(e['violations']) + n=sum(bool(x) for x in vm.values());good=set(vm)==set(expected) and rep['summary']=={'ok':len(vm)-n,'violating':n};return vm,good + +def final_layout_answer(expected): + answer_path=Path(os.environ.get('MYBENCH_ANSWER_PATH','/answer.txt')) + answer=(read(answer_path) or '') if answer_path.is_file() else (read(CAND/'answer.txt') or '') + def unique_object(pairs): + obj={} + for key,value in pairs: + if key in obj:raise ValueError('duplicate final-answer key: '+key) + obj[key]=value + return obj + try: + value=json.loads(answer,object_pairs_hook=unique_object) + except (ValueError,TypeError):return False + if not isinstance(value,dict) or ('explanation' in value and not isinstance(value['explanation'],str)):return False + rules=value.get('applied_rules');files=value.get('violating_files') + if not all(isinstance(items,list) and all(isinstance(item,str) for item in items) and len(items)==len(set(items)) for items in (rules,files)):return False + return set(rules)=={'FEATURE_LOCAL','CROSS_FEATURE_IMPORT','HTTP_IN_COMPONENT','GLOBAL_STORE_MISUSE'} and set(files)=={path for path,violations in expected.items() if violations} + + +def grade_layout(): + cs=checks(9);entry_receipts={};original_reports={};primary_entry=None;manifest=load(PUBLIC/'manifest.');expected=layout_gold(manifest);submitted=load(CAND/'report.');svm,sshape=layout_validate(submitted,expected);rep=None;primary_ok=False + for script in CAND.glob('*.py'): + if not stdlib(script):continue + before=_auto_policy_observer.receipt_snapshot() + w=fresh(['report.','report','report.json']);p=execute(w,script.name);r=load(w/'report.') + entry_receipts[script.name]=set(_auto_policy_observer.receipt_snapshot()-before) + if p is not None and p.returncode in {0,1} and "Traceback" not in (p.stderr or "") and isinstance(r,dict) and isinstance(r.get('files'),list) and isinstance(r.get('summary'),dict):rep=r;primary_ok=True;primary_entry=script.name;break + vm,shape=layout_validate(rep,expected);vm=vm or {};setc(cs,0,primary_ok and shape,'independently fresh public report covers every real manifest path once; script contract does not require pre-generated output') + for i,rule in [(1,'CROSS_FEATURE_IMPORT'),(2,'HTTP_IN_COMPONENT'),(3,'FEATURE_LOCAL'),(4,'GLOBAL_STORE_MISUSE')]: + paths=[p for p in expected if i!=3 or '/features/' in p];setc(cs,i,all(p in vm and (rule in vm[p])==(rule in expected[p]) for p in paths),'every '+rule+' fact matches actual source paths/imports/content') + setc(cs,5,all(p in vm and ('FEATURE_LOCAL' in vm[p])==('FEATURE_LOCAL' in expected[p]) for p in expected if '/features/' not in p),'global drawer feature-local violations source-bound') + setc(cs,6,all(p in vm and not vm[p] for p,v in expected.items() if not v),'all actually clean files including global session remain unflagged') + setc(cs,7,shape and final_layout_answer(expected),'summary counts match entries and formal JSON lists exact unique applied rule IDs and violating paths') + outputs=['report.','report','report.json'];freshcorrect=False;selected_entry=None + def mutate(w): + p=w/'manifest.';m=json.loads(p.read_text()) + for e in m['files']: + if e['path'].endswith('CartList.tsx'):e['imports']=['../services/cartApi'] + if e['path'].endswith('CheckoutForm.tsx'):e['imports']=['react','../../cart/index.ts'] + if e['path'].endswith('PriceTag.tsx'):e['path']='src/components/PriceTag.tsx' + p.write_text(json.dumps(m)) + def wrong_roles(w): + p=w/'manifest.';m=json.loads(p.read_text()) + examples=[ + ('src/features/cart/services/RolePanel.tsx','export function RolePanel(){ return
cart panel
; }'), + ('src/features/cart/types/useRoleProbe.ts','export function useRoleProbe(){ return 1; }'), + ('src/features/cart/hooks/RoleEntity.ts','export interface RoleEntity { id: string }'), + ('src/features/cart/components/RoleApi.ts',"export function load(){ return fetch('/api/cart'); }"), + ('src/features/cart/services/roleStore.ts','// complex feature-shared state for cart screen'), + ('src/features/cart/hooks/useRoleEquivalent.tsx','export function useRoleEquivalent(){ return 1; }')] + m['files'].extend({'path':path,'imports':[],'content':text} for path,text in examples);p.write_text(json.dumps(m)) + for script in CAND.glob('*.py'): + if not stdlib(script):continue + correct=True;before=_auto_policy_observer.receipt_snapshot() + for mutation in [None,mutate,wrong_roles]: + w=fresh(outputs,mutation);p=execute(w,script.name);m=load(w/'manifest.');gold=layout_gold(m);r=load(w/'report.');mapping,shape=layout_validate(r,gold);correct=correct and p is not None and p.returncode in {0,1} and "Traceback" not in (p.stderr or "") and shape and mapping==gold + if mutation is None:original_reports[script.name]=r + entry_receipts.setdefault(script.name,set()).update(_auto_policy_observer.receipt_snapshot()-before) + correct=correct and _auto_policy_observer.status(receipt_names=entry_receipts[script.name]) + if correct:freshcorrect=True;selected_entry=script.name;break + _auto_policy_observer.select_receipts(entry_receipts.get(selected_entry or primary_entry,set())) + if selected_entry: + # Every public report owner uses the finally selected complete entry, + # rather than a merely parseable report from a discarded discovery trial. + rep=original_reports[selected_entry];vm,shape=layout_validate(rep,expected);vm=vm or {} + setc(cs,0,shape,'selected fresh entry covers every real manifest path once') + for i,rule in [(1,'CROSS_FEATURE_IMPORT'),(2,'HTTP_IN_COMPONENT'),(3,'FEATURE_LOCAL'),(4,'GLOBAL_STORE_MISUSE')]: + paths=[p for p in expected if i!=3 or '/features/' in p] + setc(cs,i,all(p in vm and (rule in vm[p])==(rule in expected[p]) for p in paths),'selected-entry source-bound '+rule) + setc(cs,5,all(p in vm and ('FEATURE_LOCAL' in vm[p])==('FEATURE_LOCAL' in expected[p]) for p in expected if '/features/' not in p),'selected-entry global drawer placement') + setc(cs,6,all(p in vm and not vm[p] for p,v in expected.items() if not v),'selected-entry clean files have no fabricated violations') + setc(cs,7,shape and final_layout_answer(expected),'selected-entry summary and exact formal answer') + setc(cs,8,freshcorrect,'fresh stdlib script computes every original and public-rule probe classification, no stale report/empty-file program') + if freshcorrect and selected_entry and __import__('r10_runtime').dependency(selected_entry)[0]is None: + cs[8]['passed']=None;cs[8]['reason']+='; selected executable dependency closure is indeterminate' + return cs + +def yaml_subset(text): + root={};stack=[(-1,root)] + for line in text.splitlines(): + if not line.strip() or line.lstrip().startswith('#'):continue + indent=len(line)-len(line.lstrip());key,sep,value=line.strip().partition(':') + if not sep:continue + while indent<=stack[-1][0]:stack.pop() + d=stack[-1][1];value=value.strip() + if value:d[key]=value.strip('\'"') + else:d[key]={};stack.append((indent,d[key])) + return root + +def yaml_dump(d,indent=0): + return ''.join(' '*indent+str(k)+(':\n'+yaml_dump(v,indent+2) if isinstance(v,dict) else ': '+str(v)+'\n') for k,v in d.items()) + +def azure_gold(w): + y=yaml_subset(read(w/'azure.yaml') or '');services=y.get('services',{});missing={} + for name,s in services.items(): + bad=[k for k in ['project','host'] if not isinstance(s,dict) or not s.get(k)] + if not isinstance(s,dict) or not isinstance(s.get('docker'),dict) or not s['docker'].get('path'):bad.append('docker.path') + if bad:missing[name]=set(bad) + params=load(w/'infra/main.parameters.')['parameters'];bad={k for k,x in params.items() if not isinstance(x.get('value'),str) or re.fullmatch(r'\$\{[A-Za-z_][A-Za-z0-9_]*(?:=[^}]*)?\}',x['value']) is None};src=re.sub(r'//[^\n]*|/\*.*?\*/','',read(w/'src/AppHost.cs') or '',flags=re.S);func='skipped' if 'AddAzureFunctionsProject' not in src else 'ok' if re.search(r'WithEnvironment\s*\(\s*"AzureWebJobsSecretStorageType"\s*,\s*"Files"\s*\)',src) else 'fix_required';docker='\n'.join(x for x in (read(w/'src/backend/Dockerfile') or '').splitlines() if not x.lstrip().startswith('#'));dockerok=not re.search(r'\bnpm\s+ci\b',docker) or (w/'src/backend/package-lock.').is_file();thr=load(w/'runtime-config.')['anchor']['limit_minutes']*60;return services,missing,bad,func,dockerok,thr + +def azure_verify(rep,gold): + if not isinstance(rep,dict):return [False]*7 + services,missing,bad,func,dockerok,thr=gold;shape=set(rep)=={'services','parameters_ok','bad_parameters','functions_secret_storage','docker_build_context','escalation_threshold_seconds'} and isinstance(rep.get('services'),list);ok=[shape,rep.get('functions_secret_storage')==func,False,False,False,type(rep.get('escalation_threshold_seconds')) is int and rep.get('escalation_threshold_seconds')==thr,True] + status=rep.get('docker_build_context');ok[2]=status=='ok' if dockerok else isinstance(status,str) and status.startswith('fail:') and bool(status[5:].strip()) + actual=rep.get('bad_parameters');names=[];valuescorrect=True + if isinstance(actual,list): + for x in actual: + name=x if isinstance(x,str) else x.get('parameter') or x.get('name') if isinstance(x,dict) else None;names.append(name) + ok[3]=len(names)==len(set(names)) and set(names)==bad and rep.get('parameters_ok') is (not bool(bad)) + sv=rep.get('services');seen=set();errors=set();valid=isinstance(sv,list) + if valid: + for x in sv: + if isinstance(x,str): + name=x + if name in missing:errors.add(name) + elif missing:valid=False + elif isinstance(x,dict): + name=x.get('service') or x.get('name');fields=x.get('missing',x.get('missing_fields'));isbad=bool(fields) or x.get('valid') is False or x.get('ok') is False or str(x.get('status','')).lower() in {'fail','invalid','error'} + if isbad:errors.add(name) + if fields is not None and (not isinstance(fields,list) or set(fields)!=missing.get(name,set())):valid=False + if name in missing and not isbad:valid=False + else:name=None;valid=False + if name not in services or name in seen:valid=False + seen.add(name) + valid=valid and errors==set(missing) + ok[4]=valid;return ok + +def grade_azure(): + cs=checks(7);results=[] + def probe(w): + p=w/'azure.yaml';y=yaml_subset(p.read_text());y['services']['backend'].pop('host');y['services']['frontend']['docker'].pop('path');p.write_text(yaml_dump(y));p=w/'infra/main.parameters.';m=json.loads(p.read_text());m['parameters']['azureOpenAiEndpoint']['value']='${ENDPOINT=http://localhost}';m['parameters']['environmentName']['value']='literal';p.write_text(json.dumps(m));p=w/'src/AppHost.cs';p.write_text(p.read_text().replace('.WithHostStorage(storage)','.WithEnvironment("AzureWebJobsSecretStorageType", "Files")\n .WithHostStorage(storage)'));(w/'src/backend/package-lock.').write_text('{}');p=w/'runtime-config.';m=json.loads(p.read_text());m['anchor']['limit_minutes']=37;p.write_text(json.dumps(m)) + def skip(w): + (w/'src/AppHost.cs').write_text('var builder = CreateBuilder();\n');p=w/'runtime-config.';m=json.loads(p.read_text());m['anchor']['limit_minutes']=75;p.write_text(json.dumps(m)) + for mutate in [None,probe,skip]: + w=fresh(['validation-report.','validation-report.json'],mutate);gold=azure_gold(w);p=execute(w,'preflight.py');rep=load(w/'validation-report.');ok=azure_verify(rep,gold);ok[0]=ok[0] and p is not None and p.returncode==0;results.append(ok) + for i in range(6):setc(cs,i,all(x[i] for x in results),['fresh exact public filenames and report shape','true function environment fix/skip decisions','actual npm-ci lockfile check','all and only non-substitution parameter names','real per-service missing fields (problems-only or explicit full-status list)','runtime anchor minute value scales into integer seconds, no literal ban'][i]) + setc(cs,6,stdlib(CAND/'preflight.py') and all(x[0] for x in results),'stdlib offline program succeeds with original exact public input paths and independent variants') + return cs + +def quant_expected(closes): + tree=ast.parse((HERE/'legacy.py').read_text());ns={'math':math,'CLOSES':closes,'TOL':2e-6};names={'run_pipeline','metrics','wf','analysis','close_num','match_metrics'};code=ast.Module(body=[x for x in tree.body if isinstance(x,ast.FunctionDef) and x.name in names],type_ignores=[]);exec(compile(code,'independent_formula_functions','exec'),ns);m=ns['metrics'](ns['run_pipeline'](closes,10));v,recs=ns['analysis'](m);return ns,m,ns['wf'](),v,recs + +def quant_check(rep,closes): + ok=[False]*7 + if not isinstance(rep,dict):return ok + ns,m,wf,v,recs=quant_expected(closes);ok[0]=all(k in rep for k in ['metrics','walk_forward','verdict','recommendations']);metrics=rep.get('metrics');ok[1]=ns['match_metrics'](metrics,m) + unshift=ns['metrics'](ns['run_pipeline'](closes,10,shifted=False));ok[2]=ok[1] and (ns['match_metrics'](unshift,m) or not ns['match_metrics'](metrics,unshift)) + ok[3]=isinstance(metrics,dict) and all(ns['close_num'](metrics.get(k),m[k]) for k in ['total_return','max_drawdown','win_rate']) + values=rep.get('walk_forward');ok[4]=isinstance(values,list) and len(values)==2 and all(isinstance(x,dict) and set(x)==set(y) and all(ns['close_num'](x[k],y[k]) for k in y) for x,y in zip(values,wf));ok[5]=rep.get('verdict')==v and rep.get('recommendations')==recs + def rounded(x): + if isinstance(x,float):return math.isfinite(x) and x==round(x,6) + if isinstance(x,dict):return all(rounded(y) for y in x.values()) + if isinstance(x,list):return all(rounded(y) for y in x) + return True + ok[0]=ok[0] and rounded(rep);return ok + +def grade_quant(): + cs=checks(7);allresults=[] + def probe(w): + p=w/'prices.py';s=p.read_text().replace('100 + 0.3 * i + 8 * math.sin(i / 9)','75 + 0.05 * i + 6 * math.sin(i / 5)');p.write_text(s) + for mutation in [None,probe]: + w=fresh(['results.json'],mutation);source=(w/'prices.py').read_text();ns={'__name__':'prices','__file__':str(w/'prices.py')};exec(compile(source,str(w/'prices.py'),'exec'),ns);closes=[x[1] for x in ns['generate_prices']()];p=execute(w,'backtest.py');rep=load(w/'results.json');ok=quant_check(rep,closes);ok[0]=ok[0] and p is not None and p.returncode==0;allresults.append(ok) + for i in range(6):setc(cs,i,allresults[0][i],['fresh successful backtest and required results with floats rounded6','nine full-period formula metrics','previous-day signal shift (no look-ahead)','turnover costs and compounded equity metrics','both train-Sharpe argmax/OOS window results','full-period threshold verdict and exact ordered recommendations'][i]) + setc(cs,6,stdlib(CAND/'backtest.py') and all(all(x[:6]) for x in allresults),'actual stdlib program consumes prices.py generator; independent changed-price workflow correct, no stale fallback/comment-token source check') + return cs diff --git a/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/common.py b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/common.py new file mode 100644 index 0000000000000000000000000000000000000000..1aca9b79374e991f57fc321f624fee064d32c28c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/common.py @@ -0,0 +1,70 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import r10_runtime as _r10 +import ast, contextlib, csv, hashlib, io, json, math, os, re, shutil, subprocess, sys, tempfile +from pathlib import Path +HERE=Path(__file__).resolve().parent +CAND=Path(os.environ.get('MYBENCH_CANDIDATE_PATH','/candidate')) +PUBLIC=Path('/source/inputs') if Path('/source/inputs').is_dir() else HERE/'public_inputs' + +def read(p): + try:return Path(p).read_text(encoding='utf-8') + except Exception:return None + +def load(p): + try:return json.loads(Path(p).read_text()) + except Exception:return None + +_dependency_entries=set() +def stdlib(p): + entry=str(Path(p).relative_to(CAND));_dependency_entries.add(entry) + return _r10.stdlib_gate(entry) + +def fresh(outputs=(), mutate=None, restore_public=True): + if os.environ.get('MYBENCH_EPHEMERAL_APP')=='1' and Path('/app').is_dir() and not Path('/app').is_symlink(): + w=Path('/app') + for p in w.iterdir(): + if p.is_dir() and not p.is_symlink():shutil.rmtree(p) + else:p.unlink() + else:w=Path(tempfile.mkdtemp(prefix='repair_grade_')) + shutil.copytree(CAND,w,dirs_exist_ok=True,symlinks=True) + if restore_public and PUBLIC.is_dir():shutil.copytree(PUBLIC,w,dirs_exist_ok=True,symlinks=True) + for name in outputs: + p=w/name + if p.is_dir() and not p.is_symlink():shutil.rmtree(p) + elif p.exists() or p.is_symlink():p.unlink() + if mutate:mutate(w) + return w + +def execute(w,name,args=(),timeout=60): + try:return subprocess.run([sys.executable,str(w/name)]+list(args),cwd=w,text=True,capture_output=True,timeout=timeout) + except Exception:return None + +def legacy(): + out=io.StringIO() + try: + code=(HERE/'legacy.py').read_text().replace('/candidate',str(CAND)) + with contextlib.redirect_stdout(out):exec(compile(code,str(HERE/'legacy.py'),'exec'),{'__name__':'__main__','__file__':str(HERE/'legacy.py')}) + except SystemExit:pass + except Exception:pass + for s in reversed(out.getvalue().splitlines()): + try: + r=json.loads(s) + if isinstance(r,dict) and isinstance(r.get('checks'),list):return r['checks'] + except Exception:pass + return [] + +def checks(n):return [{'id':str(i),'passed':False,'reason':'required outputs/program missing or invalid'} for i in range(n)] +def setc(cs,i,value,reason):cs[i]={'id':str(i),'passed':bool(value),'reason':reason} +def norm(s):return str(s).replace('\\','/').removeprefix('./') +def jsonish(s): + try:return json.loads(s) + except Exception: + tree=ast.parse(s,mode='eval') + class B(ast.NodeTransformer): + def visit_Name(self,n): + if n.id not in {'true','false','null'}:raise ValueError(n.id) + return ast.copy_location(ast.Constant({'true':True,'false':False,'null':None}[n.id]),n) + return ast.literal_eval(B().visit(tree)) + +def same_partition(a,b): + return len(a)==len(b) and all((x==-1)==(y==-1) for x,y in zip(a,b)) and all((a[i]==a[j])==(b[i]==b[j]) for i in range(len(a)) for j in range(len(a)) if a[i]!=-1 and a[j]!=-1) diff --git a/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/legacy.py b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc6e3b5db8de9322cbf8dc937849c6543133864 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/e12a4ebd784d954897872ad2/evaluator/legacy.py @@ -0,0 +1,110 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json, os, sys, ast, shutil, subprocess, tempfile + +MANIFEST = json.loads(open('/candidate/manifest.', encoding='utf-8').read()) if os.path.exists('/candidate/manifest.') else None +EMBED_MANIFEST = {"files": [ + {"path":"src/features/cart/components/CartList.tsx","imports":["react","../hooks/useCart"],"content":"export const CartList = () =>
    {/* renders items */}
;"}, + {"path":"src/features/cart/hooks/useCart.ts","imports":["../services/cartApi"],"content":"export const useCart = () => ({ items: [] });"}, + {"path":"src/features/cart/services/cartApi.ts","imports":[],"content":"export const fetchCart = () => fetch('/api/cart');"}, + {"path":"src/features/cart/types/cart.ts","imports":[],"content":"export interface CartItem { id: string; qty: number }"}, + {"path":"src/features/cart/index.ts","imports":["./components/CartList","./hooks/useCart"],"content":"export { CartList } from './components/CartList';"}, + {"path":"src/features/checkout/components/CheckoutForm.tsx","imports":["react","../../cart/hooks/useCart","../../cart/services/cartApi"],"content":"export const CheckoutForm = () => null;"}, + {"path":"src/features/checkout/components/PaymentPanel.tsx","imports":["react","../../shared/api/http"],"content":"export const PaymentPanel = () => { fetch('/api/pay'); return null; };"}, + {"path":"src/components/Button.tsx","imports":["react"],"content":"export const Button = (p) =>