Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_contract.json +20 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy.json +13 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/autograde_task_check.py +68 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/candidate_artifacts.py +24 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/dependency_scan.py +16 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/r10_runtime.py +70 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/r9_json.py +74 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/workspace_copy.py +24 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/grading/verified_config.json +109 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/inputs/spec.json +14 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/SKILL.md +388 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/borrow.ts +19 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/check-position.ts +16 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/get-opportunities.ts +20 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/grant-permissions.ts +15 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/repay.ts +19 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/supply.ts +19 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/withdraw.ts +19 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/abis.ts +177 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/addresses.ts +25 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/client.ts +23 -0
- benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/spark.ts +114 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_contract.json +8 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/autograde_task_check.py +12 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy-task.json +101 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/evaluate.py +159 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/objective_evaluators.py +1337 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/shell_invocations.py +265 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/test.sh +8 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/verifiers.py +544 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/grading/verified_config.json +99 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/SKILL.md +238 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/_export_skill_meta.json +20 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/references/error-codes.md +39 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/references/template-and-signature-api.md +244 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/scripts/sms_client.py +287 -0
- benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/skill-card.md +45 -0
- benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_contract.json +16 -0
- benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy.json +13 -0
- benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy_guard.py +86 -0
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0",
|
| 4 |
+
"1",
|
| 5 |
+
"2",
|
| 6 |
+
"3",
|
| 7 |
+
"4",
|
| 8 |
+
"5",
|
| 9 |
+
"6"
|
| 10 |
+
],
|
| 11 |
+
"criterion_weights": {
|
| 12 |
+
"0": 1,
|
| 13 |
+
"1": 1,
|
| 14 |
+
"2": 1,
|
| 15 |
+
"3": 1,
|
| 16 |
+
"4": 1,
|
| 17 |
+
"5": 1,
|
| 18 |
+
"6": 1
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "bounded-policy-v1",
|
| 3 |
+
"stdlib_only": true,
|
| 4 |
+
"forbid_network": false,
|
| 5 |
+
"forbid_subprocess": false,
|
| 6 |
+
"forbid_native": true,
|
| 7 |
+
"runtime_owner_ids": [
|
| 8 |
+
"0"
|
| 9 |
+
],
|
| 10 |
+
"require_execution": true,
|
| 11 |
+
"execution_budget_seconds": 60,
|
| 12 |
+
"total_evaluation_budget_seconds": 420
|
| 13 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json
|
| 2 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 3 |
+
import collections,json,re,subprocess,sys
|
| 4 |
+
from decimal import Decimal
|
| 5 |
+
from workspace_copy import workspace
|
| 6 |
+
from dependency_scan import scan_stdlib
|
| 7 |
+
from r9_json import parse_file
|
| 8 |
+
|
| 9 |
+
SELECTORS={'approve(address,uint256)':'0x095ea7b3','supply(address,uint256,address,uint16)':'0x617ba037'}
|
| 10 |
+
def fixtures():
|
| 11 |
+
yield {'pool':'0xC13e21B648A5Ee794902342038FF3aDAB66BE987','asset':'0x6B175474E89094C44Da98b954EedeAC495271d0F','wallet':'0x8ba1f109551bD432803012645Ac136ddd64DBA72','assetDecimals':18,'humanAmount':'1000','selectors':SELECTORS}
|
| 12 |
+
for n,(decimals,amount)in enumerate([(6,'0.000001'),(0,'123456789012345678901234567890'),(8,'9007199254740993.01234567')]):
|
| 13 |
+
yield {'pool':'0x'+('%040x'%(0x123abc+n)),'asset':'0x'+('%040x'%(0xffaabc+n)),'wallet':'0x'+('%040x'%(0x987def+n)),'assetDecimals':decimals,'humanAmount':amount,'selectors':SELECTORS if n!=2 else {'approve(address,uint256)':'0x11223344','supply(address,uint256,address,uint16)':'0xaabbccdd'}}
|
| 14 |
+
def amounts(spec):
|
| 15 |
+
# Decimal precision is widened for the full 256-bit integer input space.
|
| 16 |
+
from decimal import localcontext
|
| 17 |
+
with localcontext()as ctx:ctx.prec=100;return int(Decimal(spec['humanAmount'])*(Decimal(10)**spec['assetDecimals']))
|
| 18 |
+
def expected(spec):
|
| 19 |
+
amount=amounts(spec)
|
| 20 |
+
word=lambda v:format(v,'064x')
|
| 21 |
+
addr=lambda v:v[2:].lower().rjust(64,'0')
|
| 22 |
+
ap=spec['selectors']['approve(address,uint256)'].lower()+addr(spec['pool'])+word(amount)
|
| 23 |
+
sp=spec['selectors']['supply(address,uint256,address,uint16)'].lower()+addr(spec['asset'])+word(amount)+addr(spec['wallet'])+word(0)
|
| 24 |
+
return amount,ap,sp
|
| 25 |
+
def valid_address(x,want):return isinstance(x,str)and isinstance(want,str)and re.fullmatch(r'0x[0-9a-fA-F]{40}',x)is not None and x.lower()==want.lower()
|
| 26 |
+
def amount_ok(actual,want):return(type(actual)is int and actual==want)or(isinstance(actual,str)and re.fullmatch(r'[0-9]+',actual)is not None and (actual.lstrip('0')or'0')==str(want))
|
| 27 |
+
def data_ok(obj,want):return isinstance(obj,dict)and isinstance(obj.get('data'),str)and re.fullmatch(r'0x[0-9a-f]+',obj['data'])is not None and obj['data']==want
|
| 28 |
+
|
| 29 |
+
def assess(spec,cd):
|
| 30 |
+
amount,apdata,spdata=expected(spec);ap=cd.get('approve')if isinstance(cd,dict)else None;sp=cd.get('supply')if isinstance(cd,dict)else None
|
| 31 |
+
values={0:isinstance(cd,dict),1:isinstance(cd,dict)and amount_ok(cd.get('amountBaseUnits'),amount),2:data_ok(ap,apdata),3:data_ok(sp,spdata),4:isinstance(ap,dict)and isinstance(sp,dict)and valid_address(ap.get('to'),spec['asset'])and valid_address(sp.get('to'),spec['pool'])}
|
| 32 |
+
calls=cd.get('calls')if isinstance(cd,dict)else None
|
| 33 |
+
values[5]=isinstance(calls,list)and len(calls)==2 and all(isinstance(c,dict)for c in calls)and isinstance(ap,dict)and isinstance(sp,dict)and all(valid_address(c.get('to'),o.get('to',''))and c.get('data')==o.get('data')for c,o in zip(calls,[ap,sp]))
|
| 34 |
+
return values
|
| 35 |
+
|
| 36 |
+
def stdout_sizes(text):
|
| 37 |
+
try:value=_co_loads(text)
|
| 38 |
+
except ValueError:return False
|
| 39 |
+
expected={'calls':2,'approve_bytes':68,'supply_bytes':132}
|
| 40 |
+
return isinstance(value,dict)and set(value)==set(expected)and all(type(value[k])in(int,float)and value[k]==v for k,v in expected.items())
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
from pathlib import Path
|
| 44 |
+
import os
|
| 45 |
+
cand=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'))
|
| 46 |
+
checks=[{'id':str(i),'passed':True,'reason':'original delivered ABI semantics and independent changed-input fixtures'}for i in range(7)]
|
| 47 |
+
def gate(i,value,why):
|
| 48 |
+
row=checks[i];row['passed']=False if row['passed']is False or value is False else None if row['passed']is None or value is None else True
|
| 49 |
+
if value is not True:row['reason']+='; '+why
|
| 50 |
+
dep,_,reason=scan_stdlib(cand,['encode_supply.py']);gate(0,dep,'stdlib dependency check: '+reason)
|
| 51 |
+
for n,spec in enumerate(fixtures()):
|
| 52 |
+
try:
|
| 53 |
+
with workspace(remove=('calldata.json',))as root:
|
| 54 |
+
(root/'spec.json').write_text(json.dumps(spec))
|
| 55 |
+
proc=subprocess.run([sys.executable,str(root/'encode_supply.py')],cwd=str(root),capture_output=True,text=True,timeout=45)
|
| 56 |
+
try:cd=parse_file(root/'calldata.json')if proc.returncode==0 else None
|
| 57 |
+
except (OSError,ValueError,RecursionError):cd=None
|
| 58 |
+
if not isinstance(cd,dict):
|
| 59 |
+
for i in range(7):gate(i,False,"invalid/missing candidate output")
|
| 60 |
+
continue
|
| 61 |
+
except subprocess.TimeoutExpired:
|
| 62 |
+
for i in range(7):gate(i,False,"candidate timeout")
|
| 63 |
+
continue
|
| 64 |
+
except Exception as exc:raise RuntimeError("Trusted ABI fixture/launcher failed") from exc
|
| 65 |
+
for i,value in assess(spec,cd).items():gate(i,value,'changed fixture %d ABI owner %d'%(n,i))
|
| 66 |
+
gate(6,stdout_sizes(proc.stdout),'stdout must report truthful call count2, approve68 and supply132 bytes; explicit labels must not contradict these values')
|
| 67 |
+
print(json.dumps({'scoreable':all(c['passed']is not None for c in checks),'checks':checks}))
|
| 68 |
+
if __name__=='__main__':main()
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/candidate_artifacts.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read only ordinary candidate artifacts after a bounded child completes.
|
| 2 |
+
No launch/setup/monitor exceptions are caught here. Symlinks to regular files
|
| 3 |
+
remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from
|
| 4 |
+
blocking the trusted grader. Malformed text/JSON is an absent invalid value.
|
| 5 |
+
"""
|
| 6 |
+
import json, os, stat
|
| 7 |
+
|
| 8 |
+
def read_text(path, encoding=None, errors=None):
|
| 9 |
+
fd=None
|
| 10 |
+
try:
|
| 11 |
+
fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK)
|
| 12 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):return ''
|
| 13 |
+
with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream:
|
| 14 |
+
fd=None
|
| 15 |
+
return stream.read()
|
| 16 |
+
except (OSError,UnicodeError):return ''
|
| 17 |
+
finally:
|
| 18 |
+
if fd is not None:os.close(fd)
|
| 19 |
+
|
| 20 |
+
def loads(text, **kwargs):
|
| 21 |
+
try:return json.loads(text,**kwargs)
|
| 22 |
+
except (ValueError,TypeError,RecursionError):return None
|
| 23 |
+
|
| 24 |
+
def load(path, **kwargs):return loads(read_text(path),**kwargs)
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/dependency_scan.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private static dependency validation, including local Python namespace packages.
|
| 2 |
+
|
| 3 |
+
This module only parses source. It never imports or runs candidate modules.
|
| 4 |
+
"""
|
| 5 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 6 |
+
import _imp
|
| 7 |
+
import ast
|
| 8 |
+
import sys
|
| 9 |
+
import tokenize
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def scan_stdlib(root, entries, external=()):
|
| 14 |
+
# Full-source dependency inference is intentionally absent.
|
| 15 |
+
# The final owner combines functional facts with the trusted invocation receipt.
|
| 16 |
+
return True, [], 'deferred: actual graded invocation policy'
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/r10_runtime.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""R10 grader helper. This file runs only inside an offline verifier container."""
|
| 3 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 4 |
+
import json,os,pathlib,shutil
|
| 5 |
+
from dependency_scan import scan_stdlib
|
| 6 |
+
C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'))
|
| 7 |
+
_copies={};_deps={}
|
| 8 |
+
def dependency(entry):
|
| 9 |
+
key=str(entry)
|
| 10 |
+
if key not in _deps:_deps[key]=scan_stdlib(C,[key])
|
| 11 |
+
return _deps[key]
|
| 12 |
+
def stdlib_gate(entry):
|
| 13 |
+
# Unknown is provisionally neutral; finalize() preserves it as unscored.
|
| 14 |
+
return dependency(entry)[0] is not False
|
| 15 |
+
def finalize(checks,owners):
|
| 16 |
+
for row in checks:
|
| 17 |
+
entry=owners.get(str(row['id']))
|
| 18 |
+
if entry is None:continue
|
| 19 |
+
ok,_,why=dependency(entry)
|
| 20 |
+
if ok is False:row['passed']=False
|
| 21 |
+
elif ok is None and row.get('passed')is not False:row['passed']=None
|
| 22 |
+
row['reason']=row.get('reason','')+'; reachable dependency closure: '+why
|
| 23 |
+
return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks}
|
| 24 |
+
def strict_pairs(pairs):
|
| 25 |
+
out={}
|
| 26 |
+
for key,value in pairs:
|
| 27 |
+
if key in out:raise ValueError('duplicate JSON object key: '+key)
|
| 28 |
+
out[key]=value
|
| 29 |
+
return out
|
| 30 |
+
def read_json(path):
|
| 31 |
+
return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs,
|
| 32 |
+
parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x)))
|
| 33 |
+
def install_copy(entry):
|
| 34 |
+
"""Complete authored dependencies without copying stale deliverables into fixtures."""
|
| 35 |
+
if entry in _copies:return
|
| 36 |
+
_copies[entry]=True
|
| 37 |
+
try:task=json.loads(pathlib.Path('/source/task.json').read_text())
|
| 38 |
+
except (OSError,ValueError):task={}
|
| 39 |
+
excluded=[]
|
| 40 |
+
for value in task.get('outputs',[]):
|
| 41 |
+
value=value.get('path')if isinstance(value,dict)else value
|
| 42 |
+
if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value))
|
| 43 |
+
original_copy=shutil.copy;original_copyfile=shutil.copyfile
|
| 44 |
+
def extra(src,dst):
|
| 45 |
+
try:
|
| 46 |
+
source=pathlib.Path(src)
|
| 47 |
+
if source.name!=pathlib.Path(entry).name:return
|
| 48 |
+
source.resolve().relative_to(C.resolve())
|
| 49 |
+
except (ValueError,TypeError,OSError):return
|
| 50 |
+
destination=pathlib.Path(dst)
|
| 51 |
+
if destination.is_dir():destination=destination/source.name
|
| 52 |
+
root=destination.parent
|
| 53 |
+
# Helpers keep the entry's authored relative directory context.
|
| 54 |
+
for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent
|
| 55 |
+
for dp,dn,fn in os.walk(str(C),followlinks=False):
|
| 56 |
+
dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')]
|
| 57 |
+
for name in fn:
|
| 58 |
+
p=pathlib.Path(dp)/name;rel=p.relative_to(C)
|
| 59 |
+
if any(rel==x or x in rel.parents for x in excluded):continue
|
| 60 |
+
if p.resolve()==source.resolve():continue
|
| 61 |
+
out=root/rel
|
| 62 |
+
if out.exists()or out.is_symlink():continue
|
| 63 |
+
out.parent.mkdir(parents=True,exist_ok=True)
|
| 64 |
+
if p.is_symlink():out.symlink_to(os.readlink(str(p)))
|
| 65 |
+
elif p.is_file():original_copyfile(str(p),str(out))
|
| 66 |
+
def copy(src,dst,*args,**kwargs):
|
| 67 |
+
result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result
|
| 68 |
+
def copyfile(src,dst,*args,**kwargs):
|
| 69 |
+
result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result
|
| 70 |
+
shutil.copy=copy;shutil.copyfile=copyfile
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/r9_json.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json
|
| 2 |
+
"""JSON wire parsing and native-type equality for the R9 task copies.
|
| 3 |
+
|
| 4 |
+
No expected answers are defined here. Single complete JSON fences are accepted
|
| 5 |
+
only as a transport wrapper when requested by the calling task.
|
| 6 |
+
"""
|
| 7 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def no_duplicates(pairs):
|
| 14 |
+
result = {}
|
| 15 |
+
for key, value in pairs:
|
| 16 |
+
if key in result:
|
| 17 |
+
raise ValueError('duplicate JSON key')
|
| 18 |
+
result[key] = value
|
| 19 |
+
return result
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _finite_tree(value):
|
| 23 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 24 |
+
raise ValueError('non-finite JSON number')
|
| 25 |
+
if isinstance(value, dict):
|
| 26 |
+
for item in value.values():
|
| 27 |
+
_finite_tree(item)
|
| 28 |
+
elif isinstance(value, list):
|
| 29 |
+
for item in value:
|
| 30 |
+
_finite_tree(item)
|
| 31 |
+
return value
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def parse_single(value, allow_fence=True):
|
| 35 |
+
"""Parse the entire response; no prefix/suffix or duplicate keys allowed."""
|
| 36 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 37 |
+
return _finite_tree(value)
|
| 38 |
+
if isinstance(value, bytes):
|
| 39 |
+
value = value.decode('utf-8-sig')
|
| 40 |
+
text = str(value).lstrip('\ufeff').strip()
|
| 41 |
+
if allow_fence and text.startswith('```'):
|
| 42 |
+
match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I)
|
| 43 |
+
if match is None:
|
| 44 |
+
raise ValueError('not one complete JSON fence')
|
| 45 |
+
text = match.group(1)
|
| 46 |
+
return _finite_tree(json.loads(
|
| 47 |
+
text, object_pairs_hook=no_duplicates,
|
| 48 |
+
parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number'))))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def parse_file(path):
|
| 52 |
+
"""Files must contain raw JSON; Markdown fences are not JSON file bytes."""
|
| 53 |
+
return parse_single(_co_text(path,encoding='utf-8-sig'), allow_fence=False)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def strict_equal(actual, expected, number_equivalence=False):
|
| 57 |
+
"""Preserve keys, order and every native type; booleans never equal numbers.
|
| 58 |
+
|
| 59 |
+
Set number_equivalence only if the public contract says a generic number
|
| 60 |
+
rather than an integer. It accepts finite integral numeric equivalents.
|
| 61 |
+
"""
|
| 62 |
+
if type(actual) is not type(expected):
|
| 63 |
+
if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float):
|
| 64 |
+
return math.isfinite(actual) and math.isfinite(expected) and actual == expected
|
| 65 |
+
return False
|
| 66 |
+
if isinstance(expected, dict):
|
| 67 |
+
return set(actual) == set(expected) and all(
|
| 68 |
+
strict_equal(actual[key], value, number_equivalence) for key, value in expected.items())
|
| 69 |
+
if isinstance(expected, list):
|
| 70 |
+
return len(actual) == len(expected) and all(
|
| 71 |
+
strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected))
|
| 72 |
+
if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)):
|
| 73 |
+
return False
|
| 74 |
+
return actual == expected
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/evaluator/workspace_copy.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import shutil
|
| 5 |
+
|
| 6 |
+
def clean(root):
|
| 7 |
+
for path in root.iterdir():
|
| 8 |
+
if path.is_dir() and not path.is_symlink():shutil.rmtree(path)
|
| 9 |
+
else:path.unlink()
|
| 10 |
+
|
| 11 |
+
@contextmanager
|
| 12 |
+
def workspace(remove=()):
|
| 13 |
+
roots=[Path('/workspace'),Path('/app')]
|
| 14 |
+
try:
|
| 15 |
+
for root in roots:
|
| 16 |
+
root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True)
|
| 17 |
+
for name in remove:
|
| 18 |
+
path=root/name
|
| 19 |
+
if path.is_dir() and not path.is_symlink():shutil.rmtree(path)
|
| 20 |
+
elif path.exists() or path.is_symlink():path.unlink()
|
| 21 |
+
yield roots[0]
|
| 22 |
+
finally:
|
| 23 |
+
for root in roots:
|
| 24 |
+
if root.exists():clean(root)
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/grading/verified_config.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "d98cafdf547229dfa1597ad8",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3",
|
| 8 |
+
"candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185",
|
| 9 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 10 |
+
"auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc",
|
| 11 |
+
"dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50",
|
| 12 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 13 |
+
"autograde_task_check.py": "16b88f93c8fb6bf9509c2ca82706b397a929ff4a33908b18febd4ff86fb72f98",
|
| 14 |
+
"r10_runtime.py": "02787c5058002e411017bc4735ad2072988bb35281b1c55b711d003ee0f83bde",
|
| 15 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 16 |
+
"r9_json.py": "df4ac6093228f9bffd5ca9c09c2791fc635d1164d0fbf5cf8aee468086c71c41",
|
| 17 |
+
"auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e"
|
| 18 |
+
},
|
| 19 |
+
"runtime_requirements": {
|
| 20 |
+
"candidate_mode": "workspace",
|
| 21 |
+
"candidate_snapshot_copy_to_ephemeral_app": true,
|
| 22 |
+
"container_private_entry": "/grader/check.py",
|
| 23 |
+
"environment": {
|
| 24 |
+
"CANDIDATE_DIR": "/candidate",
|
| 25 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 26 |
+
"MYBENCH_ANSWER": "/answer.txt",
|
| 27 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 28 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 29 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 30 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1",
|
| 31 |
+
"MYBENCH_RUN_METADATA": "/run_metadata.json",
|
| 32 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 33 |
+
"SOURCE_TASK_DIR": "/source"
|
| 34 |
+
},
|
| 35 |
+
"expected_check_ids": [
|
| 36 |
+
"0",
|
| 37 |
+
"1",
|
| 38 |
+
"2",
|
| 39 |
+
"3",
|
| 40 |
+
"4",
|
| 41 |
+
"5",
|
| 42 |
+
"6"
|
| 43 |
+
],
|
| 44 |
+
"external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
|
| 45 |
+
"external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
|
| 46 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 47 |
+
"image_included": false,
|
| 48 |
+
"legacy_adapter": false,
|
| 49 |
+
"mounts_readonly": [
|
| 50 |
+
"/candidate",
|
| 51 |
+
"/source",
|
| 52 |
+
"/grader",
|
| 53 |
+
"/answer.txt"
|
| 54 |
+
],
|
| 55 |
+
"network": "none",
|
| 56 |
+
"original_declared_resources": {
|
| 57 |
+
"agent": {
|
| 58 |
+
"cpu_memory_basis": "source_runtime_container_limits",
|
| 59 |
+
"cpus": 2,
|
| 60 |
+
"disk_mib": 10240,
|
| 61 |
+
"memory_mib": 4096,
|
| 62 |
+
"timeout_disk_basis": "advisory_not_measured_or_enforced",
|
| 63 |
+
"timeout_sec": 1200
|
| 64 |
+
},
|
| 65 |
+
"oracle": {
|
| 66 |
+
"basis": "advisory_reference_copy",
|
| 67 |
+
"timeout_sec": 120
|
| 68 |
+
},
|
| 69 |
+
"source_agent": {
|
| 70 |
+
"command_timeout_sec": 60,
|
| 71 |
+
"max_steps": 16
|
| 72 |
+
},
|
| 73 |
+
"verifier": {
|
| 74 |
+
"basis": "original_python_evaluator_enforced_limits",
|
| 75 |
+
"cpus": 1,
|
| 76 |
+
"memory_mib": 1024,
|
| 77 |
+
"pids": 64,
|
| 78 |
+
"timeout_sec": 60,
|
| 79 |
+
"tmpfs_mib": 128
|
| 80 |
+
}
|
| 81 |
+
},
|
| 82 |
+
"private_entry": "evaluator/check.py",
|
| 83 |
+
"private_tree_environment_tokens": [],
|
| 84 |
+
"trusted_trace_environment_aliases": [
|
| 85 |
+
"MYBENCH_TOOL_TRAJECTORY",
|
| 86 |
+
"MYBENCH_TRUSTED_TRACE",
|
| 87 |
+
"TOOL_TRAJECTORY",
|
| 88 |
+
"TOOL_TRAJECTORY_FILE"
|
| 89 |
+
],
|
| 90 |
+
"trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
|
| 91 |
+
"working_directory": "/candidate",
|
| 92 |
+
"writable_ephemeral_roots": [
|
| 93 |
+
"/app",
|
| 94 |
+
"/workspace",
|
| 95 |
+
"/tmp"
|
| 96 |
+
],
|
| 97 |
+
"criterion_weights": {
|
| 98 |
+
"0": 1,
|
| 99 |
+
"1": 1,
|
| 100 |
+
"2": 1,
|
| 101 |
+
"3": 1,
|
| 102 |
+
"4": 1,
|
| 103 |
+
"5": 1,
|
| 104 |
+
"6": 1
|
| 105 |
+
},
|
| 106 |
+
"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."
|
| 107 |
+
},
|
| 108 |
+
"engine": "portable_verified_v1"
|
| 109 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/inputs/spec.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"network": "ethereum",
|
| 3 |
+
"pool": "0xC13e21B648A5Ee794902342038FF3aDAB66BE987",
|
| 4 |
+
"asset": "0x6B175474E89094C44Da98b954EedeAC495271d0F",
|
| 5 |
+
"assetSymbol": "DAI",
|
| 6 |
+
"assetDecimals": 18,
|
| 7 |
+
"wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72",
|
| 8 |
+
"humanAmount": "1000",
|
| 9 |
+
"interestRateModeNote": "supply takes no rate mode; referralCode must be 0",
|
| 10 |
+
"selectors": {
|
| 11 |
+
"approve(address,uint256)": "0x095ea7b3",
|
| 12 |
+
"supply(address,uint256,address,uint16)": "0x617ba037"
|
| 13 |
+
}
|
| 14 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/SKILL.md
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: spark-agentic-wallet
|
| 3 |
+
description: Use when interacting with SparkLend protocol (supply, borrow, repay, withdraw, check positions, fetch investment opportunities) via the agentic-wallet MCP. Covers reserve APY fetching, calldata encoding, permission setup, approve+action batching, and health factor monitoring.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# SparkLend via Agentic Wallet
|
| 7 |
+
|
| 8 |
+
## Overview
|
| 9 |
+
|
| 10 |
+
SparkLend is a permissionless, non-custodial lending protocol (an Aave V3 fork) focused on DAI/USDS and stablecoin lending. It borrows from Sky's stablecoin reserves to deploy capital across DeFi. Deployed on **Ethereum** and **Gnosis**.
|
| 11 |
+
|
| 12 |
+
Interactions require ABI-encoded calldata passed to the agentic-wallet MCP tools. The wallet handles signing and submission — you encode the call and specify the Pool address as `to`.
|
| 13 |
+
|
| 14 |
+
**Transaction tools:**
|
| 15 |
+
- `execute_tx` / `execute_batch_tx` — Autonomous execution using session permissions (requires `grant_permissions` first)
|
| 16 |
+
- `send_tx` — One-time user-approved transaction (user signs via URL, no session needed)
|
| 17 |
+
|
| 18 |
+
**Key constraint:** ERC-20 operations (supply, repay) require a prior `approve` to the Pool. Always batch these atomically with `execute_batch_tx`.
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
## CLI Scripts
|
| 23 |
+
|
| 24 |
+
All scripts run via:
|
| 25 |
+
|
| 26 |
+
```
|
| 27 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js <subcommand> [options]
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
> **Standalone usage** (not as a plugin): run from the repository root with `node dist/skills/spark-agentic-wallet/spark.js <subcommand> [options]`
|
| 31 |
+
|
| 32 |
+
### opportunities
|
| 33 |
+
|
| 34 |
+
Fetch and rank supply/borrow APYs across one or all SparkLend networks.
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
# All networks
|
| 38 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js opportunities --network all
|
| 39 |
+
|
| 40 |
+
# Single network
|
| 41 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js opportunities --network ethereum
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### position
|
| 45 |
+
|
| 46 |
+
Show health factor, collateral, and debt for a wallet on a given network.
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js position \
|
| 50 |
+
--wallet 0xYourWalletAddress \
|
| 51 |
+
--network ethereum
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### grant-permissions
|
| 55 |
+
|
| 56 |
+
Print the parameters to pass to the `grant_permissions` MCP tool. Covers approve, supply, borrow, repay, and withdraw for a given token.
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js grant-permissions \
|
| 60 |
+
--wallet 0xYourWalletAddress \
|
| 61 |
+
--network ethereum \
|
| 62 |
+
--token 0x6B175474E89094C44Da98b954EedeAC495271d0F \
|
| 63 |
+
--limit 1000000000000000000000 \
|
| 64 |
+
--expiry-hours 24
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
### supply
|
| 68 |
+
|
| 69 |
+
Print the parameters to pass to `execute_batch_tx` (approve + supply).
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js supply \
|
| 73 |
+
--wallet 0xYourWalletAddress \
|
| 74 |
+
--network ethereum \
|
| 75 |
+
--asset 0x6B175474E89094C44Da98b954EedeAC495271d0F \
|
| 76 |
+
--amount 1000
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
### borrow
|
| 80 |
+
|
| 81 |
+
Print the parameters to pass to `execute_tx` (borrow).
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js borrow \
|
| 85 |
+
--wallet 0xYourWalletAddress \
|
| 86 |
+
--network ethereum \
|
| 87 |
+
--asset 0x6B175474E89094C44Da98b954EedeAC495271d0F \
|
| 88 |
+
--amount 500
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
### repay
|
| 92 |
+
|
| 93 |
+
Print the parameters to pass to `execute_batch_tx` (approve + repay). Use `--amount max` to repay full debt.
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js repay \
|
| 97 |
+
--wallet 0xYourWalletAddress \
|
| 98 |
+
--network ethereum \
|
| 99 |
+
--asset 0x6B175474E89094C44Da98b954EedeAC495271d0F \
|
| 100 |
+
--amount max
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
### withdraw
|
| 104 |
+
|
| 105 |
+
Print the parameters to pass to `execute_tx` (withdraw). Use `--amount max` to withdraw full balance.
|
| 106 |
+
|
| 107 |
+
```bash
|
| 108 |
+
node ${CLAUDE_PLUGIN_DATA}/dist/skills/spark-agentic-wallet/spark.js withdraw \
|
| 109 |
+
--wallet 0xYourWalletAddress \
|
| 110 |
+
--network ethereum \
|
| 111 |
+
--asset 0x6B175474E89094C44Da98b954EedeAC495271d0F \
|
| 112 |
+
--amount max
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
---
|
| 116 |
+
|
| 117 |
+
## Pool Contract Addresses
|
| 118 |
+
|
| 119 |
+
| Network | Pool Address |
|
| 120 |
+
|---------|-------------|
|
| 121 |
+
| Ethereum | `0xC13e21B648A5Ee794902342038FF3aDAB66BE987` |
|
| 122 |
+
| Gnosis | `0x2Dae5307c5E3FD1CF5A72Cb6F698f915860607e0` |
|
| 123 |
+
|
| 124 |
+
> Canonical source: [Spark Address Registry](https://github.com/sparkdotfi/spark-address-registry) and [Spark Docs](https://docs.spark.fi/dev/deployments/)
|
| 125 |
+
|
| 126 |
+
**Interest rate mode:** Always `2` (variable). Stable rate (1) is deprecated.
|
| 127 |
+
|
| 128 |
+
---
|
| 129 |
+
|
| 130 |
+
## ABI Encoding (viem)
|
| 131 |
+
|
| 132 |
+
SparkLend is an Aave V3 fork — all function signatures are identical.
|
| 133 |
+
|
| 134 |
+
All calldata uses `encodeFunctionData` from viem:
|
| 135 |
+
|
| 136 |
+
```typescript
|
| 137 |
+
import { encodeFunctionData, parseUnits, maxUint256 } from "viem";
|
| 138 |
+
|
| 139 |
+
const POOL = "0xC13e21B648A5Ee794902342038FF3aDAB66BE987"; // Ethereum
|
| 140 |
+
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
|
| 141 |
+
const userAddress = "0xYourWalletAddress";
|
| 142 |
+
const amount = parseUnits("1000", 18); // 1000 DAI (18 decimals)
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
---
|
| 146 |
+
|
| 147 |
+
## Core Operations
|
| 148 |
+
|
| 149 |
+
### Supply (deposit collateral)
|
| 150 |
+
|
| 151 |
+
Requires: `approve(Pool, amount)` + `supply(asset, amount, onBehalfOf, 0)`
|
| 152 |
+
|
| 153 |
+
```typescript
|
| 154 |
+
// Step 1: approve
|
| 155 |
+
const approveTx = {
|
| 156 |
+
to: DAI,
|
| 157 |
+
data: encodeFunctionData({
|
| 158 |
+
abi: [{ name: "approve", type: "function", inputs: [
|
| 159 |
+
{ name: "spender", type: "address" },
|
| 160 |
+
{ name: "amount", type: "uint256" }
|
| 161 |
+
], outputs: [{ type: "bool" }] }],
|
| 162 |
+
functionName: "approve",
|
| 163 |
+
args: [POOL, amount],
|
| 164 |
+
}),
|
| 165 |
+
value: "0x0",
|
| 166 |
+
};
|
| 167 |
+
|
| 168 |
+
// Step 2: supply
|
| 169 |
+
const supplyTx = {
|
| 170 |
+
to: POOL,
|
| 171 |
+
data: encodeFunctionData({
|
| 172 |
+
abi: [{ name: "supply", type: "function", inputs: [
|
| 173 |
+
{ name: "asset", type: "address" },
|
| 174 |
+
{ name: "amount", type: "uint256" },
|
| 175 |
+
{ name: "onBehalfOf", type: "address" },
|
| 176 |
+
{ name: "referralCode", type: "uint16" }
|
| 177 |
+
], outputs: [] }],
|
| 178 |
+
functionName: "supply",
|
| 179 |
+
args: [DAI, amount, userAddress, 0],
|
| 180 |
+
}),
|
| 181 |
+
value: "0x0",
|
| 182 |
+
};
|
| 183 |
+
|
| 184 |
+
// Send atomically — get sessionId from list_wallets
|
| 185 |
+
await execute_batch_tx({ sessionId: "<from list_wallets>", calls: [approveTx, supplyTx], feeToken: DAI });
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
### Borrow
|
| 189 |
+
|
| 190 |
+
No prior approval needed. Pool pulls nothing — it sends tokens to you.
|
| 191 |
+
|
| 192 |
+
```typescript
|
| 193 |
+
const borrowTx = {
|
| 194 |
+
to: POOL,
|
| 195 |
+
data: encodeFunctionData({
|
| 196 |
+
abi: [{ name: "borrow", type: "function", inputs: [
|
| 197 |
+
{ name: "asset", type: "address" },
|
| 198 |
+
{ name: "amount", type: "uint256" },
|
| 199 |
+
{ name: "interestRateMode", type: "uint256" },
|
| 200 |
+
{ name: "referralCode", type: "uint16" },
|
| 201 |
+
{ name: "onBehalfOf", type: "address" }
|
| 202 |
+
], outputs: [] }],
|
| 203 |
+
functionName: "borrow",
|
| 204 |
+
args: [DAI, amount, 2n, 0, userAddress],
|
| 205 |
+
}),
|
| 206 |
+
value: "0x0",
|
| 207 |
+
};
|
| 208 |
+
|
| 209 |
+
// Get sessionId from list_wallets
|
| 210 |
+
await execute_tx({ sessionId: "<from list_wallets>", to: POOL, data: borrowTx.data, value: "0x0", feeToken: DAI });
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
### Repay
|
| 214 |
+
|
| 215 |
+
Requires: `approve(Pool, amount)` + `repay(asset, amount, 2, onBehalfOf)`
|
| 216 |
+
|
| 217 |
+
Use `maxUint256` as amount to repay the full debt:
|
| 218 |
+
|
| 219 |
+
```typescript
|
| 220 |
+
const repayAmount = maxUint256; // or exact amount in wei
|
| 221 |
+
|
| 222 |
+
const approveTx = {
|
| 223 |
+
to: DAI,
|
| 224 |
+
data: encodeFunctionData({
|
| 225 |
+
abi: [{ name: "approve", type: "function", inputs: [
|
| 226 |
+
{ name: "spender", type: "address" },
|
| 227 |
+
{ name: "amount", type: "uint256" }
|
| 228 |
+
], outputs: [{ type: "bool" }] }],
|
| 229 |
+
functionName: "approve",
|
| 230 |
+
args: [POOL, repayAmount],
|
| 231 |
+
}),
|
| 232 |
+
value: "0x0",
|
| 233 |
+
};
|
| 234 |
+
|
| 235 |
+
const repayTx = {
|
| 236 |
+
to: POOL,
|
| 237 |
+
data: encodeFunctionData({
|
| 238 |
+
abi: [{ name: "repay", type: "function", inputs: [
|
| 239 |
+
{ name: "asset", type: "address" },
|
| 240 |
+
{ name: "amount", type: "uint256" },
|
| 241 |
+
{ name: "interestRateMode", type: "uint256" },
|
| 242 |
+
{ name: "onBehalfOf", type: "address" }
|
| 243 |
+
], outputs: [{ name: "", type: "uint256" }] }],
|
| 244 |
+
functionName: "repay",
|
| 245 |
+
args: [DAI, repayAmount, 2n, userAddress],
|
| 246 |
+
}),
|
| 247 |
+
value: "0x0",
|
| 248 |
+
};
|
| 249 |
+
|
| 250 |
+
// Get sessionId from list_wallets
|
| 251 |
+
await execute_batch_tx({ sessionId: "<from list_wallets>", calls: [approveTx, repayTx], feeToken: DAI });
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
### Withdraw
|
| 255 |
+
|
| 256 |
+
No approval needed. Use `maxUint256` to withdraw entire balance.
|
| 257 |
+
|
| 258 |
+
```typescript
|
| 259 |
+
const withdrawTx = {
|
| 260 |
+
to: POOL,
|
| 261 |
+
data: encodeFunctionData({
|
| 262 |
+
abi: [{ name: "withdraw", type: "function", inputs: [
|
| 263 |
+
{ name: "asset", type: "address" },
|
| 264 |
+
{ name: "amount", type: "uint256" },
|
| 265 |
+
{ name: "to", type: "address" }
|
| 266 |
+
], outputs: [{ name: "", type: "uint256" }] }],
|
| 267 |
+
functionName: "withdraw",
|
| 268 |
+
args: [DAI, maxUint256, userAddress],
|
| 269 |
+
}),
|
| 270 |
+
value: "0x0",
|
| 271 |
+
};
|
| 272 |
+
|
| 273 |
+
// Get sessionId from list_wallets
|
| 274 |
+
await execute_tx({ sessionId: "<from list_wallets>", to: POOL, data: withdrawTx.data, value: "0x0", feeToken: DAI });
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
---
|
| 278 |
+
|
| 279 |
+
## Fetching Investment Opportunities
|
| 280 |
+
|
| 281 |
+
Use `UiPoolDataProvider.getReservesData()` — a single read call returning all reserves with live APYs, liquidity, and collateral parameters. No wallet or transaction needed.
|
| 282 |
+
|
| 283 |
+
### Key Contracts
|
| 284 |
+
|
| 285 |
+
| Network | UiPoolDataProvider | PoolAddressesProvider |
|
| 286 |
+
|---------|-------------------|----------------------|
|
| 287 |
+
| Ethereum | `0xF028c2F4b19898718fD0F77b9b881CbfdAa5e8Bb` | `0x02C3eA4e34C0cBd694D2adFa2c690EECbC1793eE` |
|
| 288 |
+
| Gnosis | `0xF028c2F4b19898718fD0F77b9b881CbfdAa5e8Bb` | `0xA98DaCB3fC964A6A0d2ce3B77294241585EAbA6d` |
|
| 289 |
+
|
| 290 |
+
> Canonical source: [Spark Address Registry](https://github.com/sparkdotfi/spark-address-registry)
|
| 291 |
+
|
| 292 |
+
### APY Note
|
| 293 |
+
|
| 294 |
+
`liquidityRate` is in **ray units (1e27)**. A simple linear approximation (`rate / 1e27 * 100`) is accurate enough for display.
|
| 295 |
+
|
| 296 |
+
---
|
| 297 |
+
|
| 298 |
+
## Checking Position Health
|
| 299 |
+
|
| 300 |
+
Use `getUserAccountData` to read position before/after operations:
|
| 301 |
+
|
| 302 |
+
```typescript
|
| 303 |
+
import { createPublicClient, http } from "viem";
|
| 304 |
+
import { mainnet } from "viem/chains";
|
| 305 |
+
|
| 306 |
+
const client = createPublicClient({ chain: mainnet, transport: http() });
|
| 307 |
+
|
| 308 |
+
const [
|
| 309 |
+
totalCollateralBase,
|
| 310 |
+
totalDebtBase,
|
| 311 |
+
availableBorrowsBase,
|
| 312 |
+
currentLiquidationThreshold,
|
| 313 |
+
ltv,
|
| 314 |
+
healthFactor,
|
| 315 |
+
] = await client.readContract({
|
| 316 |
+
address: POOL,
|
| 317 |
+
abi: [{ name: "getUserAccountData", type: "function", stateMutability: "view",
|
| 318 |
+
inputs: [{ name: "user", type: "address" }],
|
| 319 |
+
outputs: [
|
| 320 |
+
{ name: "totalCollateralBase", type: "uint256" },
|
| 321 |
+
{ name: "totalDebtBase", type: "uint256" },
|
| 322 |
+
{ name: "availableBorrowsBase", type: "uint256" },
|
| 323 |
+
{ name: "currentLiquidationThreshold", type: "uint256" },
|
| 324 |
+
{ name: "ltv", type: "uint256" },
|
| 325 |
+
{ name: "healthFactor", type: "uint256" },
|
| 326 |
+
]
|
| 327 |
+
}],
|
| 328 |
+
functionName: "getUserAccountData",
|
| 329 |
+
args: [userAddress],
|
| 330 |
+
});
|
| 331 |
+
|
| 332 |
+
// healthFactor is in 1e18 units — safe when > 1.5e18, liquidation risk when < 1.1e18
|
| 333 |
+
const hfFormatted = Number(healthFactor) / 1e18;
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
---
|
| 337 |
+
|
| 338 |
+
## Permissions Setup
|
| 339 |
+
|
| 340 |
+
Request permissions that cover the operations you need. Always include the fee token in spend permissions.
|
| 341 |
+
|
| 342 |
+
```typescript
|
| 343 |
+
// Example: grant permissions for supply + borrow on Ethereum
|
| 344 |
+
await grant_permissions({
|
| 345 |
+
chainId: 1,
|
| 346 |
+
description: "SparkLend operations on Ethereum",
|
| 347 |
+
calls: [
|
| 348 |
+
{ to: DAI, signature: "approve(address,uint256)", label: "Approve DAI" },
|
| 349 |
+
{ to: POOL, signature: "supply(address,uint256,address,uint16)", label: "Supply to SparkLend" },
|
| 350 |
+
{ to: POOL, signature: "borrow(address,uint256,uint256,uint16,address)", label: "Borrow from SparkLend" },
|
| 351 |
+
{ to: POOL, signature: "repay(address,uint256,uint256,address)", label: "Repay SparkLend debt" },
|
| 352 |
+
{ to: POOL, signature: "withdraw(address,uint256,address)", label: "Withdraw from SparkLend" },
|
| 353 |
+
],
|
| 354 |
+
spend: [
|
| 355 |
+
{ token: DAI, limit: "1000000000000000000000", period: "day", label: "DAI spend" }, // 1000 DAI/day
|
| 356 |
+
],
|
| 357 |
+
expiry: 86400, // 24 hours (duration in seconds from now)
|
| 358 |
+
});
|
| 359 |
+
```
|
| 360 |
+
|
| 361 |
+
---
|
| 362 |
+
|
| 363 |
+
## Workflow
|
| 364 |
+
|
| 365 |
+
1. **Check wallet** → `list_wallets` (no params) — returns wallet address and all sessions with `sessionId`, `description`, `chainId`, `permissions`
|
| 366 |
+
2. **Create wallet** → `create_wallet()` — `chainId` and `description` are required when granting permissions at creation
|
| 367 |
+
3. **Discover fee tokens** → `supported_gas_tokens({ chainId })` — `chainId` is **required** (get it from `supported_chains`)
|
| 368 |
+
4. **Grant permissions** → `grant_permissions({ chainId, description, calls, spend, expiry })` — creates a new session. Include Pool `calls` + token `spend` limits (include fee token in `spend`). Suggest a `description` and confirm with the user before calling.
|
| 369 |
+
5. **Select session** → use `list_wallets` to find the right `sessionId` based on description/permissions for the operation
|
| 370 |
+
6. **Check permissions** → `check_permissions({ sessionId, to, feeToken })` before sending — `data` and `value` are optional
|
| 371 |
+
7. **Encode calldata** → use viem `encodeFunctionData`
|
| 372 |
+
8. **Send** → `execute_batch_tx({ sessionId, calls, feeToken })` for approve+action, `execute_tx({ sessionId, to, feeToken })` for borrow/withdraw
|
| 373 |
+
9. **Verify position** → call `getUserAccountData` on-chain
|
| 374 |
+
10. **Revoke session** (optional) → `revoke_session({ sessionId })` — revokes a specific session, others remain active
|
| 375 |
+
|
| 376 |
+
---
|
| 377 |
+
|
| 378 |
+
## Common Mistakes
|
| 379 |
+
|
| 380 |
+
| Mistake | Fix |
|
| 381 |
+
|---------|-----|
|
| 382 |
+
| Forgetting `approve` before supply/repay | Always batch approve+action with `execute_batch_tx` |
|
| 383 |
+
| Using interest rate mode `1` (stable) | Always use `2` (variable); stable is deprecated |
|
| 384 |
+
| `healthFactor < 1e18` after borrow | Check `availableBorrowsBase` before borrowing |
|
| 385 |
+
| Wrong token decimals | DAI = 18, USDC/USDT = 6, WETH/WBTC = 18/8 — use `parseUnits` |
|
| 386 |
+
| Insufficient spend permission | Include both the asset AND the fee token in spend permissions |
|
| 387 |
+
| Not scoping Pool address in `calls` | Specify `to: POOL` to keep permissions minimal |
|
| 388 |
+
| Using Aave Pool address instead of SparkLend | SparkLend has its own Pool contracts — do not mix with Aave addresses |
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/borrow.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodeBorrow } from "../../../core/spark/borrow.js";
|
| 2 |
+
import { getClient } from "../shared/client.js";
|
| 3 |
+
import { ERC20_ABI } from "../shared/abis.js";
|
| 4 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 5 |
+
|
| 6 |
+
export async function borrow(
|
| 7 |
+
wallet: `0x${string}`,
|
| 8 |
+
network: NetworkName,
|
| 9 |
+
asset: `0x${string}`,
|
| 10 |
+
humanAmount: string
|
| 11 |
+
) {
|
| 12 |
+
const client = getClient(network);
|
| 13 |
+
const symbol = await client.readContract({ address: asset, abi: ERC20_ABI, functionName: "symbol" });
|
| 14 |
+
const result = await encodeBorrow(wallet, network, asset, humanAmount);
|
| 15 |
+
|
| 16 |
+
console.log(`\nBorrow ${humanAmount} ${symbol} on ${network}`);
|
| 17 |
+
console.log("Call execute_tx with (use sessionId from list_wallets):");
|
| 18 |
+
console.log(JSON.stringify({ sessionId: "<from list_wallets>", to: result.to, data: result.data, value: "0x0", feeToken: asset }, null, 2));
|
| 19 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/check-position.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getPosition } from "../../../core/spark/position.js";
|
| 2 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 3 |
+
|
| 4 |
+
export async function checkPosition(wallet: `0x${string}`, network: NetworkName) {
|
| 5 |
+
const pos = await getPosition(wallet, network);
|
| 6 |
+
|
| 7 |
+
const hfDisplay = pos.healthStatus === "NO_DEBT" ? "∞" : pos.healthFactor.toFixed(4);
|
| 8 |
+
|
| 9 |
+
console.log(`\nPosition on ${network.toUpperCase()} for ${wallet}`);
|
| 10 |
+
console.log(` Health Factor: ${hfDisplay} (${pos.healthStatus})`);
|
| 11 |
+
console.log(` Total Collateral (USD): $${pos.totalCollateralUSD}`);
|
| 12 |
+
console.log(` Total Debt (USD): $${pos.totalDebtUSD}`);
|
| 13 |
+
console.log(` Available Borrows (USD):$${pos.availableBorrowsUSD}`);
|
| 14 |
+
console.log(` LTV: ${pos.ltv}%`);
|
| 15 |
+
console.log(` Liquidation Threshold: ${pos.liquidationThreshold}%`);
|
| 16 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/get-opportunities.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getOpportunities as _getOpportunities } from "../../../core/spark/opportunities.js";
|
| 2 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 3 |
+
|
| 4 |
+
export async function getOpportunities(network: NetworkName | "all") {
|
| 5 |
+
const results = await _getOpportunities(network);
|
| 6 |
+
|
| 7 |
+
for (const { network: net, reserves } of results) {
|
| 8 |
+
console.log(`\n=== ${net.toUpperCase()} ===`);
|
| 9 |
+
for (const o of reserves) {
|
| 10 |
+
const col = o.canBeCollateral ? `LTV ${o.ltv}%` : "no collateral";
|
| 11 |
+
const borrow = o.borrowingEnabled
|
| 12 |
+
? `Borrow: ${o.borrowAPY.toFixed(2)}%`
|
| 13 |
+
: "no borrowing";
|
| 14 |
+
console.log(
|
| 15 |
+
` ${o.symbol.padEnd(12)} Supply: ${o.supplyAPY.toFixed(2).padStart(6)}%` +
|
| 16 |
+
` | ${borrow.padEnd(20)} | ${col}`
|
| 17 |
+
);
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/grant-permissions.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodePermissions } from "../../../core/spark/permissions.js";
|
| 2 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 3 |
+
|
| 4 |
+
export function grantPermissions(
|
| 5 |
+
wallet: `0x${string}`,
|
| 6 |
+
network: NetworkName,
|
| 7 |
+
spendToken: `0x${string}`,
|
| 8 |
+
spendLimit: string,
|
| 9 |
+
expiryHours = 24
|
| 10 |
+
) {
|
| 11 |
+
const params = encodePermissions(wallet, network, spendToken, spendLimit, expiryHours);
|
| 12 |
+
|
| 13 |
+
console.log("\nCall grant_permissions with these parameters:");
|
| 14 |
+
console.log(JSON.stringify(params, null, 2));
|
| 15 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/repay.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodeRepay } from "../../../core/spark/repay.js";
|
| 2 |
+
import { getClient } from "../shared/client.js";
|
| 3 |
+
import { ERC20_ABI } from "../shared/abis.js";
|
| 4 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 5 |
+
|
| 6 |
+
export async function repay(
|
| 7 |
+
wallet: `0x${string}`,
|
| 8 |
+
network: NetworkName,
|
| 9 |
+
asset: `0x${string}`,
|
| 10 |
+
humanAmount: string
|
| 11 |
+
) {
|
| 12 |
+
const client = getClient(network);
|
| 13 |
+
const symbol = await client.readContract({ address: asset, abi: ERC20_ABI, functionName: "symbol" });
|
| 14 |
+
const result = await encodeRepay(wallet, network, asset, humanAmount);
|
| 15 |
+
|
| 16 |
+
console.log(`\nRepay ${humanAmount === "max" ? "full debt" : humanAmount + " " + symbol} on ${network}`);
|
| 17 |
+
console.log("Call execute_batch_tx with (use sessionId from list_wallets):");
|
| 18 |
+
console.log(JSON.stringify({ sessionId: "<from list_wallets>", calls: result.calls, feeToken: asset }, null, 2));
|
| 19 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/supply.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodeSupply } from "../../../core/spark/supply.js";
|
| 2 |
+
import { getClient } from "../shared/client.js";
|
| 3 |
+
import { ERC20_ABI } from "../shared/abis.js";
|
| 4 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 5 |
+
|
| 6 |
+
export async function supply(
|
| 7 |
+
wallet: `0x${string}`,
|
| 8 |
+
network: NetworkName,
|
| 9 |
+
asset: `0x${string}`,
|
| 10 |
+
humanAmount: string
|
| 11 |
+
) {
|
| 12 |
+
const client = getClient(network);
|
| 13 |
+
const symbol = await client.readContract({ address: asset, abi: ERC20_ABI, functionName: "symbol" });
|
| 14 |
+
const result = await encodeSupply(wallet, network, asset, humanAmount);
|
| 15 |
+
|
| 16 |
+
console.log(`\nSupply ${humanAmount} ${symbol} on ${network}`);
|
| 17 |
+
console.log("Call execute_batch_tx with (use sessionId from list_wallets):");
|
| 18 |
+
console.log(JSON.stringify({ sessionId: "<from list_wallets>", calls: result.calls, feeToken: asset }, null, 2));
|
| 19 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/scripts/withdraw.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { encodeWithdraw } from "../../../core/spark/withdraw.js";
|
| 2 |
+
import { getClient } from "../shared/client.js";
|
| 3 |
+
import { ERC20_ABI } from "../shared/abis.js";
|
| 4 |
+
import type { NetworkName } from "../shared/addresses.js";
|
| 5 |
+
|
| 6 |
+
export async function withdraw(
|
| 7 |
+
wallet: `0x${string}`,
|
| 8 |
+
network: NetworkName,
|
| 9 |
+
asset: `0x${string}`,
|
| 10 |
+
humanAmount: string
|
| 11 |
+
) {
|
| 12 |
+
const client = getClient(network);
|
| 13 |
+
const symbol = await client.readContract({ address: asset, abi: ERC20_ABI, functionName: "symbol" });
|
| 14 |
+
const result = await encodeWithdraw(wallet, network, asset, humanAmount);
|
| 15 |
+
|
| 16 |
+
console.log(`\nWithdraw ${humanAmount === "max" ? "full balance" : humanAmount + " " + symbol} on ${network}`);
|
| 17 |
+
console.log("Call execute_tx with (use sessionId from list_wallets):");
|
| 18 |
+
console.log(JSON.stringify({ sessionId: "<from list_wallets>", to: result.to, data: result.data, value: "0x0", feeToken: asset }, null, 2));
|
| 19 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/abis.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// skills/spark-agentic-wallet/shared/abis.ts
|
| 2 |
+
// SparkLend is an Aave V3 fork — ABIs are identical.
|
| 3 |
+
|
| 4 |
+
export const ERC20_ABI = [
|
| 5 |
+
{
|
| 6 |
+
name: "approve",
|
| 7 |
+
type: "function",
|
| 8 |
+
stateMutability: "nonpayable",
|
| 9 |
+
inputs: [
|
| 10 |
+
{ name: "spender", type: "address" },
|
| 11 |
+
{ name: "amount", type: "uint256" },
|
| 12 |
+
],
|
| 13 |
+
outputs: [{ type: "bool" }],
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
name: "decimals",
|
| 17 |
+
type: "function",
|
| 18 |
+
stateMutability: "view",
|
| 19 |
+
inputs: [],
|
| 20 |
+
outputs: [{ type: "uint8" }],
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
name: "symbol",
|
| 24 |
+
type: "function",
|
| 25 |
+
stateMutability: "view",
|
| 26 |
+
inputs: [],
|
| 27 |
+
outputs: [{ type: "string" }],
|
| 28 |
+
},
|
| 29 |
+
] as const;
|
| 30 |
+
|
| 31 |
+
export const POOL_ABI = [
|
| 32 |
+
{
|
| 33 |
+
name: "supply",
|
| 34 |
+
type: "function",
|
| 35 |
+
stateMutability: "nonpayable",
|
| 36 |
+
inputs: [
|
| 37 |
+
{ name: "asset", type: "address" },
|
| 38 |
+
{ name: "amount", type: "uint256" },
|
| 39 |
+
{ name: "onBehalfOf", type: "address" },
|
| 40 |
+
{ name: "referralCode", type: "uint16" },
|
| 41 |
+
],
|
| 42 |
+
outputs: [],
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
name: "borrow",
|
| 46 |
+
type: "function",
|
| 47 |
+
stateMutability: "nonpayable",
|
| 48 |
+
inputs: [
|
| 49 |
+
{ name: "asset", type: "address" },
|
| 50 |
+
{ name: "amount", type: "uint256" },
|
| 51 |
+
{ name: "interestRateMode", type: "uint256" },
|
| 52 |
+
{ name: "referralCode", type: "uint16" },
|
| 53 |
+
{ name: "onBehalfOf", type: "address" },
|
| 54 |
+
],
|
| 55 |
+
outputs: [],
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
name: "repay",
|
| 59 |
+
type: "function",
|
| 60 |
+
stateMutability: "nonpayable",
|
| 61 |
+
inputs: [
|
| 62 |
+
{ name: "asset", type: "address" },
|
| 63 |
+
{ name: "amount", type: "uint256" },
|
| 64 |
+
{ name: "interestRateMode", type: "uint256" },
|
| 65 |
+
{ name: "onBehalfOf", type: "address" },
|
| 66 |
+
],
|
| 67 |
+
outputs: [{ type: "uint256" }],
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
name: "withdraw",
|
| 71 |
+
type: "function",
|
| 72 |
+
stateMutability: "nonpayable",
|
| 73 |
+
inputs: [
|
| 74 |
+
{ name: "asset", type: "address" },
|
| 75 |
+
{ name: "amount", type: "uint256" },
|
| 76 |
+
{ name: "to", type: "address" },
|
| 77 |
+
],
|
| 78 |
+
outputs: [{ type: "uint256" }],
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
name: "getUserAccountData",
|
| 82 |
+
type: "function",
|
| 83 |
+
stateMutability: "view",
|
| 84 |
+
inputs: [{ name: "user", type: "address" }],
|
| 85 |
+
outputs: [
|
| 86 |
+
{ name: "totalCollateralBase", type: "uint256" },
|
| 87 |
+
{ name: "totalDebtBase", type: "uint256" },
|
| 88 |
+
{ name: "availableBorrowsBase", type: "uint256" },
|
| 89 |
+
{ name: "currentLiquidationThreshold", type: "uint256" },
|
| 90 |
+
{ name: "ltv", type: "uint256" },
|
| 91 |
+
{ name: "healthFactor", type: "uint256" },
|
| 92 |
+
],
|
| 93 |
+
},
|
| 94 |
+
] as const;
|
| 95 |
+
|
| 96 |
+
// SparkLend uses the original Aave V3 UiPoolDataProvider (v2.5.2),
|
| 97 |
+
// which includes stable-borrow and eMode fields removed in v3.3.
|
| 98 |
+
export const UI_POOL_DATA_PROVIDER_ABI = [
|
| 99 |
+
{
|
| 100 |
+
name: "getReservesData",
|
| 101 |
+
type: "function",
|
| 102 |
+
stateMutability: "view",
|
| 103 |
+
inputs: [{ name: "provider", type: "address" }],
|
| 104 |
+
outputs: [
|
| 105 |
+
{
|
| 106 |
+
name: "",
|
| 107 |
+
type: "tuple[]",
|
| 108 |
+
components: [
|
| 109 |
+
{ name: "underlyingAsset", type: "address" },
|
| 110 |
+
{ name: "name", type: "string" },
|
| 111 |
+
{ name: "symbol", type: "string" },
|
| 112 |
+
{ name: "decimals", type: "uint256" },
|
| 113 |
+
{ name: "baseLTVasCollateral", type: "uint256" },
|
| 114 |
+
{ name: "reserveLiquidationThreshold", type: "uint256" },
|
| 115 |
+
{ name: "reserveLiquidationBonus", type: "uint256" },
|
| 116 |
+
{ name: "reserveFactor", type: "uint256" },
|
| 117 |
+
{ name: "usageAsCollateralEnabled", type: "bool" },
|
| 118 |
+
{ name: "borrowingEnabled", type: "bool" },
|
| 119 |
+
{ name: "stableBorrowRateEnabled", type: "bool" },
|
| 120 |
+
{ name: "isActive", type: "bool" },
|
| 121 |
+
{ name: "isFrozen", type: "bool" },
|
| 122 |
+
{ name: "liquidityIndex", type: "uint128" },
|
| 123 |
+
{ name: "variableBorrowIndex", type: "uint128" },
|
| 124 |
+
{ name: "liquidityRate", type: "uint128" },
|
| 125 |
+
{ name: "variableBorrowRate", type: "uint128" },
|
| 126 |
+
{ name: "stableBorrowRate", type: "uint128" },
|
| 127 |
+
{ name: "lastUpdateTimestamp", type: "uint40" },
|
| 128 |
+
{ name: "aTokenAddress", type: "address" },
|
| 129 |
+
{ name: "stableDebtTokenAddress", type: "address" },
|
| 130 |
+
{ name: "variableDebtTokenAddress", type: "address" },
|
| 131 |
+
{ name: "interestRateStrategyAddress", type: "address" },
|
| 132 |
+
{ name: "availableLiquidity", type: "uint256" },
|
| 133 |
+
{ name: "totalPrincipalStableDebt", type: "uint256" },
|
| 134 |
+
{ name: "averageStableRate", type: "uint256" },
|
| 135 |
+
{ name: "stableDebtLastUpdateTimestamp", type: "uint256" },
|
| 136 |
+
{ name: "totalScaledVariableDebt", type: "uint256" },
|
| 137 |
+
{ name: "priceInMarketReferenceCurrency", type: "uint256" },
|
| 138 |
+
{ name: "priceOracle", type: "address" },
|
| 139 |
+
{ name: "variableRateSlope1", type: "uint256" },
|
| 140 |
+
{ name: "variableRateSlope2", type: "uint256" },
|
| 141 |
+
{ name: "stableRateSlope1", type: "uint256" },
|
| 142 |
+
{ name: "stableRateSlope2", type: "uint256" },
|
| 143 |
+
{ name: "baseStableBorrowRate", type: "uint256" },
|
| 144 |
+
{ name: "baseVariableBorrowRate", type: "uint256" },
|
| 145 |
+
{ name: "optimalUsageRatio", type: "uint256" },
|
| 146 |
+
{ name: "isPaused", type: "bool" },
|
| 147 |
+
{ name: "isSiloedBorrowing", type: "bool" },
|
| 148 |
+
{ name: "accruedToTreasury", type: "uint128" },
|
| 149 |
+
{ name: "unbacked", type: "uint128" },
|
| 150 |
+
{ name: "isolationModeTotalDebt", type: "uint128" },
|
| 151 |
+
{ name: "flashLoanEnabled", type: "bool" },
|
| 152 |
+
{ name: "debtCeiling", type: "uint256" },
|
| 153 |
+
{ name: "debtCeilingDecimals", type: "uint256" },
|
| 154 |
+
{ name: "eModeCategoryId", type: "uint8" },
|
| 155 |
+
{ name: "borrowCap", type: "uint256" },
|
| 156 |
+
{ name: "supplyCap", type: "uint256" },
|
| 157 |
+
{ name: "eModeLtv", type: "uint16" },
|
| 158 |
+
{ name: "eModeLiquidationThreshold", type: "uint16" },
|
| 159 |
+
{ name: "eModeLiquidationBonus", type: "uint16" },
|
| 160 |
+
{ name: "eModePriceSource", type: "address" },
|
| 161 |
+
{ name: "eModeLabel", type: "string" },
|
| 162 |
+
{ name: "borrowableInIsolation", type: "bool" },
|
| 163 |
+
],
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
name: "",
|
| 167 |
+
type: "tuple",
|
| 168 |
+
components: [
|
| 169 |
+
{ name: "marketReferenceCurrencyUnit", type: "uint256" },
|
| 170 |
+
{ name: "marketReferenceCurrencyPriceInUsd", type: "int256" },
|
| 171 |
+
{ name: "networkBaseTokenPriceInUsd", type: "int256" },
|
| 172 |
+
{ name: "networkBaseTokenPriceDecimals", type: "uint8" },
|
| 173 |
+
],
|
| 174 |
+
},
|
| 175 |
+
],
|
| 176 |
+
},
|
| 177 |
+
] as const;
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/addresses.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// skills/spark-agentic-wallet/shared/addresses.ts
|
| 2 |
+
|
| 3 |
+
export type NetworkName = "ethereum" | "gnosis";
|
| 4 |
+
|
| 5 |
+
export const POOL: Record<NetworkName, `0x${string}`> = {
|
| 6 |
+
ethereum: "0xC13e21B648A5Ee794902342038FF3aDAB66BE987",
|
| 7 |
+
gnosis: "0x2Dae5307c5E3FD1CF5A72Cb6F698f915860607e0",
|
| 8 |
+
};
|
| 9 |
+
|
| 10 |
+
export const UI_POOL_DATA_PROVIDER: Record<NetworkName, `0x${string}`> = {
|
| 11 |
+
ethereum: "0xF028c2F4b19898718fD0F77b9b881CbfdAa5e8Bb",
|
| 12 |
+
gnosis: "0xF028c2F4b19898718fD0F77b9b881CbfdAa5e8Bb",
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
export const POOL_ADDRESSES_PROVIDER: Record<NetworkName, `0x${string}`> = {
|
| 16 |
+
ethereum: "0x02C3eA4e34C0cBd694D2adFa2c690EECbC1793eE",
|
| 17 |
+
gnosis: "0xA98DaCB3fC964A6A0d2ce3B77294241585EAbA6d",
|
| 18 |
+
};
|
| 19 |
+
|
| 20 |
+
export const CHAIN_IDS: Record<NetworkName, number> = {
|
| 21 |
+
ethereum: 1,
|
| 22 |
+
gnosis: 100,
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
export const NETWORKS: NetworkName[] = ["ethereum", "gnosis"];
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/shared/client.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// skills/spark-agentic-wallet/shared/client.ts
|
| 2 |
+
|
| 3 |
+
import { createPublicClient, http } from "viem";
|
| 4 |
+
import { mainnet, gnosis } from "viem/chains";
|
| 5 |
+
import type { NetworkName } from "./addresses.js";
|
| 6 |
+
|
| 7 |
+
const CHAINS = { mainnet, gnosis };
|
| 8 |
+
|
| 9 |
+
const CHAIN_MAP: Record<NetworkName, keyof typeof CHAINS> = {
|
| 10 |
+
ethereum: "mainnet",
|
| 11 |
+
gnosis: "gnosis",
|
| 12 |
+
};
|
| 13 |
+
|
| 14 |
+
const RPC_URLS: Partial<Record<NetworkName, string>> = {
|
| 15 |
+
ethereum: process.env.ETH_RPC_URL ?? "https://ethereum.publicnode.com",
|
| 16 |
+
gnosis: process.env.GNOSIS_RPC_URL ?? "https://gnosis.publicnode.com",
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
export function getClient(network: NetworkName) {
|
| 20 |
+
const chainKey = CHAIN_MAP[network];
|
| 21 |
+
const rpcUrl = RPC_URLS[network];
|
| 22 |
+
return createPublicClient({ chain: CHAINS[chainKey], transport: http(rpcUrl) });
|
| 23 |
+
}
|
benchmarks/skillbench-venus-e/tasks/d98cafdf547229dfa1597ad8/skill/spark.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// skills/spark-agentic-wallet/spark.ts
|
| 2 |
+
// Usage: node ${process.env.CLAUDE_PLUGIN_DATA ?? "."}/dist/skills/spark-agentic-wallet/spark.js <subcommand> [options]
|
| 3 |
+
|
| 4 |
+
import { getOpportunities } from "./scripts/get-opportunities.js";
|
| 5 |
+
import { checkPosition } from "./scripts/check-position.js";
|
| 6 |
+
import { grantPermissions } from "./scripts/grant-permissions.js";
|
| 7 |
+
import { supply } from "./scripts/supply.js";
|
| 8 |
+
import { borrow } from "./scripts/borrow.js";
|
| 9 |
+
import { repay } from "./scripts/repay.js";
|
| 10 |
+
import { withdraw } from "./scripts/withdraw.js";
|
| 11 |
+
import type { NetworkName } from "./shared/addresses.js";
|
| 12 |
+
|
| 13 |
+
function parseArgs(argv: string[]): Record<string, string> {
|
| 14 |
+
const args: Record<string, string> = {};
|
| 15 |
+
for (let i = 0; i < argv.length; i++) {
|
| 16 |
+
if (argv[i].startsWith("--") && i + 1 < argv.length) {
|
| 17 |
+
args[argv[i].slice(2)] = argv[i + 1];
|
| 18 |
+
i++;
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
return args;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
function usage() {
|
| 25 |
+
console.log(`
|
| 26 |
+
SparkLend CLI — node ${process.env.CLAUDE_PLUGIN_DATA ?? "."}/dist/skills/spark-agentic-wallet/spark.js <subcommand> [options]
|
| 27 |
+
|
| 28 |
+
Subcommands:
|
| 29 |
+
opportunities --network <name|all>
|
| 30 |
+
Fetch and rank supply/borrow APYs across SparkLend markets.
|
| 31 |
+
Networks: ethereum, gnosis, all
|
| 32 |
+
|
| 33 |
+
position --wallet <addr> --network <name>
|
| 34 |
+
Show health factor, collateral, debt for a wallet.
|
| 35 |
+
|
| 36 |
+
grant-permissions --wallet <addr> --network <name> --token <addr> --limit <amount> [--expiry-hours <n>]
|
| 37 |
+
Print grant_permissions parameters for SparkLend operations.
|
| 38 |
+
|
| 39 |
+
supply --wallet <addr> --network <name> --asset <addr> --amount <n>
|
| 40 |
+
Print execute_batch_tx parameters for approve + supply.
|
| 41 |
+
|
| 42 |
+
borrow --wallet <addr> --network <name> --asset <addr> --amount <n>
|
| 43 |
+
Print execute_tx parameters for borrow.
|
| 44 |
+
|
| 45 |
+
repay --wallet <addr> --network <name> --asset <addr> --amount <n|max>
|
| 46 |
+
Print execute_batch_tx parameters for approve + repay.
|
| 47 |
+
|
| 48 |
+
withdraw --wallet <addr> --network <name> --asset <addr> --amount <n|max>
|
| 49 |
+
Print execute_tx parameters for withdraw.
|
| 50 |
+
`);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
const [subcommand, ...rest] = process.argv.slice(2);
|
| 54 |
+
const args = parseArgs(rest);
|
| 55 |
+
|
| 56 |
+
switch (subcommand) {
|
| 57 |
+
case "opportunities":
|
| 58 |
+
await getOpportunities((args.network ?? "all") as NetworkName | "all");
|
| 59 |
+
break;
|
| 60 |
+
|
| 61 |
+
case "position":
|
| 62 |
+
if (!args.wallet || !args.network) { console.error("Missing --wallet or --network"); process.exit(1); }
|
| 63 |
+
await checkPosition(args.wallet as `0x${string}`, args.network as NetworkName);
|
| 64 |
+
break;
|
| 65 |
+
|
| 66 |
+
case "grant-permissions":
|
| 67 |
+
if (!args.wallet || !args.network || !args.token || !args.limit) {
|
| 68 |
+
console.error("Missing --wallet, --network, --token, or --limit");
|
| 69 |
+
process.exit(1);
|
| 70 |
+
}
|
| 71 |
+
grantPermissions(
|
| 72 |
+
args.wallet as `0x${string}`,
|
| 73 |
+
args.network as NetworkName,
|
| 74 |
+
args.token as `0x${string}`,
|
| 75 |
+
args.limit,
|
| 76 |
+
args["expiry-hours"] ? Number(args["expiry-hours"]) : 24
|
| 77 |
+
);
|
| 78 |
+
break;
|
| 79 |
+
|
| 80 |
+
case "supply":
|
| 81 |
+
if (!args.wallet || !args.network || !args.asset || !args.amount) {
|
| 82 |
+
console.error("Missing --wallet, --network, --asset, or --amount");
|
| 83 |
+
process.exit(1);
|
| 84 |
+
}
|
| 85 |
+
await supply(args.wallet as `0x${string}`, args.network as NetworkName, args.asset as `0x${string}`, args.amount);
|
| 86 |
+
break;
|
| 87 |
+
|
| 88 |
+
case "borrow":
|
| 89 |
+
if (!args.wallet || !args.network || !args.asset || !args.amount) {
|
| 90 |
+
console.error("Missing --wallet, --network, --asset, or --amount");
|
| 91 |
+
process.exit(1);
|
| 92 |
+
}
|
| 93 |
+
await borrow(args.wallet as `0x${string}`, args.network as NetworkName, args.asset as `0x${string}`, args.amount);
|
| 94 |
+
break;
|
| 95 |
+
|
| 96 |
+
case "repay":
|
| 97 |
+
if (!args.wallet || !args.network || !args.asset || !args.amount) {
|
| 98 |
+
console.error("Missing --wallet, --network, --asset, or --amount");
|
| 99 |
+
process.exit(1);
|
| 100 |
+
}
|
| 101 |
+
await repay(args.wallet as `0x${string}`, args.network as NetworkName, args.asset as `0x${string}`, args.amount);
|
| 102 |
+
break;
|
| 103 |
+
|
| 104 |
+
case "withdraw":
|
| 105 |
+
if (!args.wallet || !args.network || !args.asset || !args.amount) {
|
| 106 |
+
console.error("Missing --wallet, --network, --asset, or --amount");
|
| 107 |
+
process.exit(1);
|
| 108 |
+
}
|
| 109 |
+
await withdraw(args.wallet as `0x${string}`, args.network as NetworkName, args.asset as `0x${string}`, args.amount);
|
| 110 |
+
break;
|
| 111 |
+
|
| 112 |
+
default:
|
| 113 |
+
usage();
|
| 114 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0"
|
| 4 |
+
],
|
| 5 |
+
"criterion_weights": {
|
| 6 |
+
"0": 1
|
| 7 |
+
}
|
| 8 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
root=Path(__file__).resolve().parent
|
| 5 |
+
sys.path.insert(0,str(root/'legacy_tests'))
|
| 6 |
+
from evaluate import evaluate
|
| 7 |
+
t=json.loads((root/'legacy-task.json').read_text())
|
| 8 |
+
mode=t['workspace']['candidate_mode']
|
| 9 |
+
r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
|
| 10 |
+
if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
|
| 11 |
+
if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
|
| 12 |
+
print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy-task.json
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "mybench-portable-task-v2",
|
| 3 |
+
"task_id": "de0d341bc8e13144",
|
| 4 |
+
"query_id": "de0d341bc8e13144_q1",
|
| 5 |
+
"prompt": {
|
| 6 |
+
"path": "instruction.md",
|
| 7 |
+
"sha256": "3f7b0274f30dfdc667e416f0521d45ccd14e2ed660c34813901b5c08cde71774"
|
| 8 |
+
},
|
| 9 |
+
"workspace": {
|
| 10 |
+
"input_mappings": [],
|
| 11 |
+
"skill_packages": [
|
| 12 |
+
{
|
| 13 |
+
"content_hash": "598f52ccf6cd32549010df059a49bb612786ef5d6d4dbeea508a777bcc09b41d",
|
| 14 |
+
"name": "engagelab-sms",
|
| 15 |
+
"package_path": "environment/skills/engagelab-sms-598f52cc",
|
| 16 |
+
"install_name": "engagelab-sms-598f52cc",
|
| 17 |
+
"archive_provenance": {
|
| 18 |
+
"archive_id": "logical-skill-190086e984cc9039d0bc3c53",
|
| 19 |
+
"archive_schema": "skill-release-v1",
|
| 20 |
+
"release_skill_id": "logical-skill-190086e984cc9039d0bc3c53",
|
| 21 |
+
"site": "clawhub",
|
| 22 |
+
"local_path": "skills/19/logical-skill-190086e984cc9039d0bc3c53",
|
| 23 |
+
"skill_md_sha256": "bc5e21b6bf15aa51e748687a279cb1705dca4d943d842ba4eca41f088a3cb9f3",
|
| 24 |
+
"release_payload_sha256": "598f52ccf6cd32549010df059a49bb612786ef5d6d4dbeea508a777bcc09b41d",
|
| 25 |
+
"license": "MIT-0",
|
| 26 |
+
"license_status": "detected",
|
| 27 |
+
"canonical_source_id": "clawhub:devengagelab/engagelab-sms"
|
| 28 |
+
},
|
| 29 |
+
"omitted_entries": []
|
| 30 |
+
}
|
| 31 |
+
],
|
| 32 |
+
"default_skill_target": ".claude/skills",
|
| 33 |
+
"candidate_mode": "workspace"
|
| 34 |
+
},
|
| 35 |
+
"ground_truth_skills": [
|
| 36 |
+
"598f52ccf6cd32549010df059a49bb612786ef5d6d4dbeea508a777bcc09b41d"
|
| 37 |
+
],
|
| 38 |
+
"evaluation": {
|
| 39 |
+
"type": "verified",
|
| 40 |
+
"ground_truth_answer": {
|
| 41 |
+
"files": [
|
| 42 |
+
{
|
| 43 |
+
"path": "output/signature_attachment.json",
|
| 44 |
+
"content": "{\n \"add_signature\": true,\n \"sign_position\": 2,\n \"template_type\": \"utility\"\n}\n"
|
| 45 |
+
}
|
| 46 |
+
]
|
| 47 |
+
},
|
| 48 |
+
"verifier": {
|
| 49 |
+
"type": "workspace_objective",
|
| 50 |
+
"version": 15,
|
| 51 |
+
"output_mode": "workspace",
|
| 52 |
+
"reference_files": [
|
| 53 |
+
{
|
| 54 |
+
"path": "output/signature_attachment.json",
|
| 55 |
+
"format": "json",
|
| 56 |
+
"content": "{\n \"add_signature\": true,\n \"sign_position\": 2,\n \"template_type\": \"utility\"\n}\n"
|
| 57 |
+
}
|
| 58 |
+
],
|
| 59 |
+
"checks": [
|
| 60 |
+
{
|
| 61 |
+
"id": "workspace_file_set",
|
| 62 |
+
"type": "workspace_file_set",
|
| 63 |
+
"paths": [
|
| 64 |
+
"output/signature_attachment.json"
|
| 65 |
+
],
|
| 66 |
+
"roots": [
|
| 67 |
+
"output"
|
| 68 |
+
]
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"id": "file_001",
|
| 72 |
+
"type": "file_exists",
|
| 73 |
+
"path": "output/signature_attachment.json"
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"id": "json_001",
|
| 77 |
+
"type": "json_exact",
|
| 78 |
+
"path": "output/signature_attachment.json",
|
| 79 |
+
"expected": {
|
| 80 |
+
"template_type": "utility",
|
| 81 |
+
"add_signature": true,
|
| 82 |
+
"sign_position": 2
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
],
|
| 86 |
+
"self_test_passed": true
|
| 87 |
+
},
|
| 88 |
+
"dependency_contract": {
|
| 89 |
+
"version": 2,
|
| 90 |
+
"mode": "core_answer",
|
| 91 |
+
"dependency_type": "project_configuration",
|
| 92 |
+
"requirement_ids": [
|
| 93 |
+
"skill_a092",
|
| 94 |
+
"skill_a095",
|
| 95 |
+
"skill_a097"
|
| 96 |
+
],
|
| 97 |
+
"forbid_meta_reference": true,
|
| 98 |
+
"forbid_answer_leakage": true
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/evaluate.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Evaluate a candidate response for one portable MyBench task."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import shlex
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _load_verify():
|
| 15 |
+
try:
|
| 16 |
+
from verifiers import verify
|
| 17 |
+
return verify
|
| 18 |
+
except ImportError:
|
| 19 |
+
project_src = Path(__file__).resolve().parents[1] / "src"
|
| 20 |
+
if project_src.is_dir():
|
| 21 |
+
sys.path.insert(0, str(project_src))
|
| 22 |
+
from verifiers import verify
|
| 23 |
+
return verify
|
| 24 |
+
raise
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _emit(result, output=None):
|
| 28 |
+
text = json.dumps(result, ensure_ascii=False)
|
| 29 |
+
print(text)
|
| 30 |
+
if output:
|
| 31 |
+
Path(output).write_text(text + "\n", encoding="utf-8")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _judge_contract(judge):
|
| 35 |
+
if not isinstance(judge, dict):
|
| 36 |
+
return "Judge output must be a JSON object"
|
| 37 |
+
if type(judge.get("passed")) is not bool:
|
| 38 |
+
return "Judge field passed must be a JSON boolean"
|
| 39 |
+
for key in ("score", "max_score"):
|
| 40 |
+
value = judge.get(key, 100 if key == "max_score" else None)
|
| 41 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
| 42 |
+
return f"Judge field {key} must be a finite number"
|
| 43 |
+
if not math.isfinite(float(value)):
|
| 44 |
+
return f"Judge field {key} must be a finite number"
|
| 45 |
+
score = float(judge["score"])
|
| 46 |
+
max_score = float(judge.get("max_score", 100))
|
| 47 |
+
if max_score <= 0:
|
| 48 |
+
return "Judge field max_score must be greater than zero"
|
| 49 |
+
if score < 0 or score > max_score:
|
| 50 |
+
return "Judge score must be between zero and max_score"
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def evaluate(task_json, candidate_path, open_judge_command=None,
|
| 55 |
+
open_judge_timeout=None):
|
| 56 |
+
task_json = Path(task_json).resolve()
|
| 57 |
+
candidate_path = Path(candidate_path).resolve()
|
| 58 |
+
task = json.loads(task_json.read_text(encoding="utf-8"))
|
| 59 |
+
evaluation = task.get("evaluation") or {}
|
| 60 |
+
track = evaluation.get("type")
|
| 61 |
+
base = {
|
| 62 |
+
"schema_version": task.get("schema_version"),
|
| 63 |
+
"task_id": task.get("task_id"),
|
| 64 |
+
"query_id": task.get("query_id"),
|
| 65 |
+
"track": track,
|
| 66 |
+
}
|
| 67 |
+
if track == "verified":
|
| 68 |
+
workspace_mode = ((evaluation.get("verifier") or {}).get("type") ==
|
| 69 |
+
"workspace_objective")
|
| 70 |
+
if workspace_mode and not candidate_path.is_dir():
|
| 71 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 72 |
+
"score": 0, "max_score": 1,
|
| 73 |
+
"details": "workspace evaluator requires a candidate directory"}, 2
|
| 74 |
+
if not workspace_mode and not candidate_path.is_file():
|
| 75 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 76 |
+
"score": 0, "max_score": 1,
|
| 77 |
+
"details": "response evaluator requires a candidate file"}, 2
|
| 78 |
+
if workspace_mode:
|
| 79 |
+
candidate = str(candidate_path)
|
| 80 |
+
else:
|
| 81 |
+
try:
|
| 82 |
+
candidate = candidate_path.read_text(encoding="utf-8")
|
| 83 |
+
except UnicodeError:
|
| 84 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 85 |
+
"score": 0, "max_score": 1,
|
| 86 |
+
"details": "candidate response must use valid UTF-8"}, 2
|
| 87 |
+
passed, detail = _load_verify()(
|
| 88 |
+
evaluation.get("verifier") or {},
|
| 89 |
+
evaluation.get("ground_truth_answer"),
|
| 90 |
+
candidate,
|
| 91 |
+
None,
|
| 92 |
+
)
|
| 93 |
+
return {**base, "status": "scored", "passed": bool(passed),
|
| 94 |
+
"score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1
|
| 95 |
+
if track != "open":
|
| 96 |
+
return {**base, "status": "unsupported_track", "passed": False,
|
| 97 |
+
"score": None, "details": f"unsupported track: {track}"}, 2
|
| 98 |
+
if not candidate_path.is_file():
|
| 99 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 100 |
+
"score": None, "details": "open judge requires a candidate response file"}, 2
|
| 101 |
+
candidate_file = candidate_path
|
| 102 |
+
command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND")
|
| 103 |
+
if not command:
|
| 104 |
+
return {**base, "status": "requires_external_judge", "passed": None,
|
| 105 |
+
"score": None, "details": (
|
| 106 |
+
"Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads "
|
| 107 |
+
"MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2
|
| 108 |
+
environment = os.environ.copy()
|
| 109 |
+
environment["MYBENCH_TASK_JSON"] = str(task_json)
|
| 110 |
+
environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file)
|
| 111 |
+
timeout = float(open_judge_timeout or os.environ.get(
|
| 112 |
+
"MYBENCH_OPEN_JUDGE_TIMEOUT", 600))
|
| 113 |
+
if not math.isfinite(timeout) or timeout <= 0:
|
| 114 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 115 |
+
"score": None, "details": "Judge timeout must be a positive number"}, 2
|
| 116 |
+
try:
|
| 117 |
+
completed = subprocess.run(
|
| 118 |
+
shlex.split(command), cwd=str(task_json.parent), env=environment,
|
| 119 |
+
text=True, capture_output=True, timeout=timeout)
|
| 120 |
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
| 121 |
+
return {**base, "status": "judge_error", "passed": False,
|
| 122 |
+
"score": None, "details": str(exc)}, 2
|
| 123 |
+
if completed.returncode:
|
| 124 |
+
return {**base, "status": "judge_error", "passed": False, "score": None,
|
| 125 |
+
"details": completed.stderr.strip() or completed.stdout.strip()}, 2
|
| 126 |
+
try:
|
| 127 |
+
judge = json.loads(completed.stdout)
|
| 128 |
+
except json.JSONDecodeError as exc:
|
| 129 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 130 |
+
"score": None, "details": str(exc)}, 2
|
| 131 |
+
contract_error = _judge_contract(judge)
|
| 132 |
+
if contract_error:
|
| 133 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 134 |
+
"score": None, "details": contract_error}, 2
|
| 135 |
+
result = {**base, "status": "scored", "passed": judge.get("passed"),
|
| 136 |
+
"score": judge.get("score"), "max_score": judge.get("max_score", 100),
|
| 137 |
+
"details": judge.get("details", judge)}
|
| 138 |
+
return result, 0 if result["passed"] else 1
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def main():
|
| 142 |
+
parser = argparse.ArgumentParser()
|
| 143 |
+
parser.add_argument("--task-json", required=True)
|
| 144 |
+
candidates = parser.add_mutually_exclusive_group(required=True)
|
| 145 |
+
candidates.add_argument("--candidate-path")
|
| 146 |
+
candidates.add_argument("--candidate-file") # v1 compatibility
|
| 147 |
+
parser.add_argument("--result-output")
|
| 148 |
+
parser.add_argument("--open-judge-command")
|
| 149 |
+
parser.add_argument("--open-judge-timeout", type=float)
|
| 150 |
+
args = parser.parse_args()
|
| 151 |
+
result, code = evaluate(args.task_json,
|
| 152 |
+
args.candidate_path or args.candidate_file,
|
| 153 |
+
args.open_judge_command, args.open_judge_timeout)
|
| 154 |
+
_emit(result, args.result_output)
|
| 155 |
+
raise SystemExit(code)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
main()
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/objective_evaluators.py
ADDED
|
@@ -0,0 +1,1337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Composable objective evaluators for response and workspace tasks.
|
| 2 |
+
|
| 3 |
+
Task semantics are deliberately *not* enumerated here. A task may describe any
|
| 4 |
+
real user goal; verified membership depends on whether its deliverables compile
|
| 5 |
+
to one of these small, trusted evaluator primitives and pass counterfactual
|
| 6 |
+
execution. This keeps the objective surface closed and auditable without
|
| 7 |
+
turning the benchmark's task ontology into a closed template list.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import ast
|
| 12 |
+
import copy
|
| 13 |
+
import builtins
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shlex
|
| 19 |
+
import subprocess
|
| 20 |
+
import tempfile
|
| 21 |
+
import tomllib
|
| 22 |
+
from pathlib import Path, PurePosixPath
|
| 23 |
+
try:
|
| 24 |
+
from .shell_invocations import shell_invocations
|
| 25 |
+
except ImportError:
|
| 26 |
+
from shell_invocations import shell_invocations
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _r10_unique_pairs(pairs):
|
| 31 |
+
result={}
|
| 32 |
+
for key,value in pairs:
|
| 33 |
+
if key in result:raise ValueError('duplicate JSON object key: '+key)
|
| 34 |
+
result[key]=value
|
| 35 |
+
return result
|
| 36 |
+
|
| 37 |
+
WORKSPACE_EVALUATOR = "workspace_objective"
|
| 38 |
+
WORKSPACE_EVALUATOR_VERSION = 15
|
| 39 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
| 40 |
+
ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
|
| 41 |
+
_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ObjectiveEvaluatorError(ValueError):
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def safe_relative_path(value):
|
| 49 |
+
"""Return a normalized portable relative path or fail closed."""
|
| 50 |
+
text = str(value or "").strip().replace("\\", "/")
|
| 51 |
+
path = PurePosixPath(text)
|
| 52 |
+
if (not text or text.startswith("/") or path.is_absolute() or
|
| 53 |
+
any(part in {"", ".", ".."} for part in path.parts)):
|
| 54 |
+
raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
|
| 55 |
+
if len(path.parts) > 8 or len(text) > 180:
|
| 56 |
+
raise ObjectiveEvaluatorError("workspace path is too deep or long")
|
| 57 |
+
return path.as_posix()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _json_value(value):
|
| 61 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 62 |
+
return value
|
| 63 |
+
return json.loads(str(value))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _canonical(value):
|
| 67 |
+
if isinstance(value, dict):
|
| 68 |
+
return {key: _canonical(value[key]) for key in sorted(value)}
|
| 69 |
+
if isinstance(value, list):
|
| 70 |
+
return [_canonical(item) for item in value]
|
| 71 |
+
return value
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _same_native_json_types(actual, expected):
|
| 76 |
+
if type(expected)is float:
|
| 77 |
+
return type(actual)in(int,float)and math.isfinite(actual)
|
| 78 |
+
if type(actual)is not type(expected):return False
|
| 79 |
+
if isinstance(expected,dict):
|
| 80 |
+
return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected)
|
| 81 |
+
if isinstance(expected,list):
|
| 82 |
+
return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected))
|
| 83 |
+
if isinstance(actual,float):return math.isfinite(actual)
|
| 84 |
+
return True
|
| 85 |
+
|
| 86 |
+
def _file_content(item):
|
| 87 |
+
fmt = str(item.get("format") or "").casefold()
|
| 88 |
+
content = item.get("content")
|
| 89 |
+
if fmt == "json":
|
| 90 |
+
parsed = _json_value(content)
|
| 91 |
+
return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 92 |
+
if not isinstance(content, str):
|
| 93 |
+
raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
|
| 94 |
+
return content.rstrip() + "\n"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _ast_name(node):
|
| 98 |
+
if isinstance(node, ast.Name):
|
| 99 |
+
return node.id
|
| 100 |
+
if isinstance(node, ast.Attribute):
|
| 101 |
+
parent = _ast_name(node.value)
|
| 102 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 103 |
+
return ""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _python_inventory(text):
|
| 107 |
+
tree = ast.parse(text)
|
| 108 |
+
imports, calls = set(), set()
|
| 109 |
+
for node in ast.walk(tree):
|
| 110 |
+
if isinstance(node, ast.Import):
|
| 111 |
+
imports.update(alias.name for alias in node.names)
|
| 112 |
+
elif isinstance(node, ast.ImportFrom):
|
| 113 |
+
module = node.module or ""
|
| 114 |
+
for alias in node.names:
|
| 115 |
+
imports.add(f"{module}.{alias.name}".strip("."))
|
| 116 |
+
elif isinstance(node, ast.Call):
|
| 117 |
+
name = _ast_name(node.func)
|
| 118 |
+
if name:
|
| 119 |
+
calls.add(name)
|
| 120 |
+
return imports, calls
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _literal_value(node, constants=None):
|
| 124 |
+
constants = constants or {}
|
| 125 |
+
if isinstance(node, ast.Constant) and isinstance(
|
| 126 |
+
node.value, (str, int, float, bool, type(None))):
|
| 127 |
+
return node.value
|
| 128 |
+
if isinstance(node, ast.Name) and node.id in constants:
|
| 129 |
+
return constants[node.id]
|
| 130 |
+
if isinstance(node, (ast.Tuple, ast.List)):
|
| 131 |
+
values = [_literal_value(item, constants) for item in node.elts]
|
| 132 |
+
if all(value is not _UNRESOLVED for value in values):
|
| 133 |
+
return tuple(values) if isinstance(node, ast.Tuple) else values
|
| 134 |
+
return _UNRESOLVED
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
_UNRESOLVED = object()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _python_semantics(text):
|
| 141 |
+
tree = ast.parse(text)
|
| 142 |
+
_annotate_assignment_contexts(tree)
|
| 143 |
+
imports, calls = _python_inventory(text)
|
| 144 |
+
constants = {}
|
| 145 |
+
for node in tree.body:
|
| 146 |
+
name = None
|
| 147 |
+
value_node = None
|
| 148 |
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 149 |
+
isinstance(node.targets[0], ast.Name)):
|
| 150 |
+
name, value_node = node.targets[0].id, node.value
|
| 151 |
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
| 152 |
+
name, value_node = node.target.id, node.value
|
| 153 |
+
if name and value_node is not None:
|
| 154 |
+
value = _literal_value(value_node, constants)
|
| 155 |
+
if value is not _UNRESOLVED:
|
| 156 |
+
constants[name] = value
|
| 157 |
+
elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 158 |
+
isinstance(node.targets[0], (ast.Tuple, ast.List)) and
|
| 159 |
+
isinstance(node.value, (ast.Tuple, ast.List)) and
|
| 160 |
+
len(node.targets[0].elts) == len(node.value.elts)):
|
| 161 |
+
# Treat ordinary constant unpacking as semantically equivalent to
|
| 162 |
+
# separate assignments. Generated implementation files commonly
|
| 163 |
+
# use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
|
| 164 |
+
# test formatting rather than the required repository values.
|
| 165 |
+
for target, value_node in zip(node.targets[0].elts, node.value.elts):
|
| 166 |
+
if not isinstance(target, ast.Name):
|
| 167 |
+
continue
|
| 168 |
+
value = _literal_value(value_node, constants)
|
| 169 |
+
if value is not _UNRESOLVED:
|
| 170 |
+
constants[target.id] = value
|
| 171 |
+
call_nodes = []
|
| 172 |
+
for node in ast.walk(tree):
|
| 173 |
+
if isinstance(node, ast.Call):
|
| 174 |
+
call_nodes.append((_ast_name(node.func), node))
|
| 175 |
+
return imports, calls, constants, call_nodes
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _python_resolved_call_nodes(text):
|
| 179 |
+
"""Resolve call targets through imports and simple constructor bindings.
|
| 180 |
+
|
| 181 |
+
The evaluator intentionally supports a small static subset: imports,
|
| 182 |
+
local definitions, direct aliases, and names assigned from calls. That is
|
| 183 |
+
enough to recognize semantic equivalents such as ``import datetime`` vs
|
| 184 |
+
``from datetime import timedelta as td`` and instance-variable renames,
|
| 185 |
+
without pretending to perform general Python type inference.
|
| 186 |
+
"""
|
| 187 |
+
tree = ast.parse(text)
|
| 188 |
+
_annotate_assignment_contexts(tree)
|
| 189 |
+
bindings = {}
|
| 190 |
+
nodes = sorted(ast.walk(tree), key=lambda node: (
|
| 191 |
+
int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
|
| 192 |
+
|
| 193 |
+
def resolve(node):
|
| 194 |
+
if isinstance(node, ast.Name):
|
| 195 |
+
return bindings.get(node.id, node.id)
|
| 196 |
+
if isinstance(node, ast.Attribute):
|
| 197 |
+
parent = resolve(node.value)
|
| 198 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 199 |
+
return ""
|
| 200 |
+
|
| 201 |
+
# A few fixed-point passes cover aliases declared after an imported name
|
| 202 |
+
# and ordinary ``client = Client()`` instance construction.
|
| 203 |
+
for _ in range(4):
|
| 204 |
+
changed = False
|
| 205 |
+
for node in nodes:
|
| 206 |
+
updates = {}
|
| 207 |
+
if isinstance(node, ast.Import):
|
| 208 |
+
for alias in node.names:
|
| 209 |
+
local = alias.asname or alias.name.split(".")[0]
|
| 210 |
+
updates[local] = alias.name if alias.asname else local
|
| 211 |
+
elif isinstance(node, ast.ImportFrom):
|
| 212 |
+
module = node.module or ""
|
| 213 |
+
for alias in node.names:
|
| 214 |
+
if alias.name == "*":
|
| 215 |
+
continue
|
| 216 |
+
updates[alias.asname or alias.name] = \
|
| 217 |
+
f"{module}.{alias.name}".strip(".")
|
| 218 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 219 |
+
ast.ClassDef)):
|
| 220 |
+
updates[node.name] = "__local__." + node.name
|
| 221 |
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
| 222 |
+
targets = (node.targets if isinstance(node, ast.Assign)
|
| 223 |
+
else [node.target])
|
| 224 |
+
value = node.value
|
| 225 |
+
if isinstance(value, ast.Call):
|
| 226 |
+
provenance = resolve(value.func)
|
| 227 |
+
elif isinstance(value, (ast.Name, ast.Attribute)):
|
| 228 |
+
provenance = resolve(value)
|
| 229 |
+
else:
|
| 230 |
+
provenance = ""
|
| 231 |
+
if provenance:
|
| 232 |
+
for target in targets:
|
| 233 |
+
if isinstance(target, ast.Name):
|
| 234 |
+
updates[target.id] = provenance
|
| 235 |
+
for name, value in updates.items():
|
| 236 |
+
if bindings.get(name) != value:
|
| 237 |
+
bindings[name] = value
|
| 238 |
+
changed = True
|
| 239 |
+
if not changed:
|
| 240 |
+
break
|
| 241 |
+
return [(_ast_name(node.func), resolve(node.func), node)
|
| 242 |
+
for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _call_name_matches(observed, expected):
|
| 246 |
+
return observed == expected or observed.endswith("." + expected)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _objective_call_targets(kind, check, resolved_calls, constants):
|
| 250 |
+
"""Return canonical targets satisfying one already-validated call check."""
|
| 251 |
+
function = str(check.get("function") or check.get("value") or "")
|
| 252 |
+
targets = set()
|
| 253 |
+
for name, target, node in resolved_calls:
|
| 254 |
+
if not _call_name_matches(name, function):
|
| 255 |
+
continue
|
| 256 |
+
if kind == "python_call_literal" and not _node_contains_literal(
|
| 257 |
+
node, check.get("value"), constants):
|
| 258 |
+
continue
|
| 259 |
+
if kind == "python_call_keyword_literal" and not _call_keyword_matches(
|
| 260 |
+
node, str(check.get("keyword") or ""), check.get("value"),
|
| 261 |
+
constants):
|
| 262 |
+
continue
|
| 263 |
+
if kind == "python_call_signature" and not _call_signature_matches(
|
| 264 |
+
node, check.get("arguments") or [],
|
| 265 |
+
check.get("keywords") or {}, constants,
|
| 266 |
+
check.get("argument_expressions") or [],
|
| 267 |
+
check.get("keyword_expressions") or {},
|
| 268 |
+
check.get("assignment")):
|
| 269 |
+
continue
|
| 270 |
+
if target:
|
| 271 |
+
targets.add(target)
|
| 272 |
+
return targets
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def python_unbound_call_roots(text):
|
| 276 |
+
"""Return call-root names that have no static binding in the module.
|
| 277 |
+
|
| 278 |
+
Objective call checks must not accept a syntactically valid file that will
|
| 279 |
+
immediately raise ``NameError``. This deliberately proves only the
|
| 280 |
+
conservative prerequisite that a root is imported, assigned, declared,
|
| 281 |
+
passed as an argument, or provided by Python builtins; it does not claim to
|
| 282 |
+
execute or type-check the program.
|
| 283 |
+
"""
|
| 284 |
+
tree = ast.parse(text)
|
| 285 |
+
bound = set(dir(builtins))
|
| 286 |
+
for node in ast.walk(tree):
|
| 287 |
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
| 288 |
+
bound.add(node.id)
|
| 289 |
+
elif isinstance(node, ast.arg):
|
| 290 |
+
bound.add(node.arg)
|
| 291 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 292 |
+
ast.ClassDef)):
|
| 293 |
+
bound.add(node.name)
|
| 294 |
+
elif isinstance(node, ast.Import):
|
| 295 |
+
for alias in node.names:
|
| 296 |
+
bound.add(alias.asname or alias.name.split(".")[0])
|
| 297 |
+
elif isinstance(node, ast.ImportFrom):
|
| 298 |
+
for alias in node.names:
|
| 299 |
+
bound.add(alias.asname or alias.name)
|
| 300 |
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
| 301 |
+
bound.add(node.name)
|
| 302 |
+
unbound = set()
|
| 303 |
+
for node in ast.walk(tree):
|
| 304 |
+
if not isinstance(node, ast.Call):
|
| 305 |
+
continue
|
| 306 |
+
root = node.func
|
| 307 |
+
while isinstance(root, ast.Attribute):
|
| 308 |
+
root = root.value
|
| 309 |
+
if isinstance(root, ast.Name) and root.id not in bound:
|
| 310 |
+
unbound.add(root.id)
|
| 311 |
+
return sorted(unbound)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _node_contains_literal(node, expected, constants):
|
| 315 |
+
for child in ast.walk(node):
|
| 316 |
+
value = _literal_value(child, constants)
|
| 317 |
+
if value is _UNRESOLVED:
|
| 318 |
+
continue
|
| 319 |
+
if value == expected:
|
| 320 |
+
return True
|
| 321 |
+
if isinstance(value, (list, tuple)) and expected in value:
|
| 322 |
+
return True
|
| 323 |
+
return False
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _call_keyword_matches(node, keyword, expected, constants):
|
| 327 |
+
"""Return whether a direct call keyword resolves to the expected scalar."""
|
| 328 |
+
return any(
|
| 329 |
+
item.arg == keyword and _literal_value(item.value, constants) == expected
|
| 330 |
+
for item in getattr(node, "keywords", [])
|
| 331 |
+
if item.arg is not None)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _portable_literal(value):
|
| 335 |
+
if isinstance(value, tuple):
|
| 336 |
+
return [_portable_literal(item) for item in value]
|
| 337 |
+
if isinstance(value, list):
|
| 338 |
+
return [_portable_literal(item) for item in value]
|
| 339 |
+
return value
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _expression_text(node):
|
| 343 |
+
"""Return a formatting-independent, non-executed Python expression."""
|
| 344 |
+
return ast.unparse(node).strip()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _expression_fingerprint(value):
|
| 348 |
+
if not isinstance(value, str) or not value.strip() or len(value) > 500:
|
| 349 |
+
return None
|
| 350 |
+
try:
|
| 351 |
+
tree = ast.parse(value, mode="eval")
|
| 352 |
+
except SyntaxError:
|
| 353 |
+
return None
|
| 354 |
+
return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _expression_matches(node, expected):
|
| 358 |
+
fingerprint = _expression_fingerprint(expected)
|
| 359 |
+
return bool(fingerprint and ast.dump(
|
| 360 |
+
node, annotate_fields=True, include_attributes=False) == fingerprint)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _annotate_assignment_contexts(tree):
|
| 364 |
+
"""Attach one conservative simple-assignment context to nested calls."""
|
| 365 |
+
for statement in ast.walk(tree):
|
| 366 |
+
target, value = None, None
|
| 367 |
+
if (isinstance(statement, ast.Assign) and
|
| 368 |
+
len(statement.targets) == 1 and
|
| 369 |
+
isinstance(statement.targets[0], ast.Name)):
|
| 370 |
+
target, value = statement.targets[0].id, statement.value
|
| 371 |
+
elif (isinstance(statement, ast.AnnAssign) and
|
| 372 |
+
isinstance(statement.target, ast.Name) and
|
| 373 |
+
statement.value is not None):
|
| 374 |
+
target, value = statement.target.id, statement.value
|
| 375 |
+
if not target or value is None:
|
| 376 |
+
continue
|
| 377 |
+
context = {"target": target, "expression": _expression_text(value)}
|
| 378 |
+
for child in ast.walk(value):
|
| 379 |
+
if isinstance(child, ast.Call):
|
| 380 |
+
setattr(child, "_mybench_assignment", context)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _call_signature(node, constants):
|
| 384 |
+
arguments = []
|
| 385 |
+
argument_expressions = []
|
| 386 |
+
for index, argument in enumerate(getattr(node, "args", [])):
|
| 387 |
+
value = _literal_value(argument, constants)
|
| 388 |
+
if value is not _UNRESOLVED:
|
| 389 |
+
arguments.append({"index": index,
|
| 390 |
+
"value": _portable_literal(value)})
|
| 391 |
+
else:
|
| 392 |
+
argument_expressions.append({
|
| 393 |
+
"index": index, "expression": _expression_text(argument)})
|
| 394 |
+
keywords = {}
|
| 395 |
+
keyword_expressions = {}
|
| 396 |
+
for keyword in getattr(node, "keywords", []):
|
| 397 |
+
if keyword.arg is None:
|
| 398 |
+
continue
|
| 399 |
+
value = _literal_value(keyword.value, constants)
|
| 400 |
+
if value is not _UNRESOLVED:
|
| 401 |
+
keywords[keyword.arg] = _portable_literal(value)
|
| 402 |
+
else:
|
| 403 |
+
keyword_expressions[keyword.arg] = _expression_text(keyword.value)
|
| 404 |
+
signature = {"arguments": arguments, "keywords": keywords,
|
| 405 |
+
"argument_expressions": argument_expressions,
|
| 406 |
+
"keyword_expressions": keyword_expressions}
|
| 407 |
+
assignment = getattr(node, "_mybench_assignment", None)
|
| 408 |
+
if isinstance(assignment, dict):
|
| 409 |
+
signature["assignment"] = dict(assignment)
|
| 410 |
+
return signature
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _call_signature_matches(node, arguments, keywords, constants,
|
| 414 |
+
argument_expressions=None,
|
| 415 |
+
keyword_expressions=None, assignment=None):
|
| 416 |
+
for expected in arguments or []:
|
| 417 |
+
index = expected.get("index")
|
| 418 |
+
if (not isinstance(index, int) or index < 0 or
|
| 419 |
+
index >= len(getattr(node, "args", []))):
|
| 420 |
+
return False
|
| 421 |
+
actual = _literal_value(node.args[index], constants)
|
| 422 |
+
if (actual is _UNRESOLVED or
|
| 423 |
+
_canonical(_portable_literal(actual)) !=
|
| 424 |
+
_canonical(expected.get("value"))):
|
| 425 |
+
return False
|
| 426 |
+
for keyword, expected in (keywords or {}).items():
|
| 427 |
+
if not _call_keyword_matches(node, keyword, expected, constants):
|
| 428 |
+
return False
|
| 429 |
+
for expected in argument_expressions or []:
|
| 430 |
+
index = expected.get("index")
|
| 431 |
+
if (not isinstance(index, int) or index < 0 or
|
| 432 |
+
index >= len(getattr(node, "args", [])) or
|
| 433 |
+
not _expression_matches(
|
| 434 |
+
node.args[index], expected.get("expression"))):
|
| 435 |
+
return False
|
| 436 |
+
node_keywords = {item.arg: item.value for item in
|
| 437 |
+
getattr(node, "keywords", []) if item.arg is not None}
|
| 438 |
+
for keyword, expected in (keyword_expressions or {}).items():
|
| 439 |
+
if (keyword not in node_keywords or
|
| 440 |
+
not _expression_matches(node_keywords[keyword], expected)):
|
| 441 |
+
return False
|
| 442 |
+
if assignment:
|
| 443 |
+
actual = getattr(node, "_mybench_assignment", None)
|
| 444 |
+
if (not isinstance(actual, dict) or
|
| 445 |
+
actual.get("target") != assignment.get("target") or
|
| 446 |
+
_expression_fingerprint(actual.get("expression")) !=
|
| 447 |
+
_expression_fingerprint(assignment.get("expression"))):
|
| 448 |
+
return False
|
| 449 |
+
return bool(arguments or keywords or argument_expressions or
|
| 450 |
+
keyword_expressions or assignment)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def python_call_literal_signatures(text, function, expected, keyword=None):
|
| 454 |
+
"""Return full literal signatures for matching reference call sites."""
|
| 455 |
+
_, _, constants, call_nodes = _python_semantics(text)
|
| 456 |
+
out = []
|
| 457 |
+
for name, node in call_nodes:
|
| 458 |
+
if not (name == function or name.endswith("." + function)):
|
| 459 |
+
continue
|
| 460 |
+
matches = (_call_keyword_matches(node, keyword, expected, constants)
|
| 461 |
+
if keyword else
|
| 462 |
+
_node_contains_literal(node, expected, constants))
|
| 463 |
+
if matches:
|
| 464 |
+
out.append(_call_signature(node, constants))
|
| 465 |
+
return out
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def python_signature_expression_coverage_issues(evaluator, requirements=None):
|
| 469 |
+
"""Detect anchored call expressions omitted by a static verifier.
|
| 470 |
+
|
| 471 |
+
Literal-only call checks used to silently discard non-literal positional
|
| 472 |
+
and keyword expressions from the same package-owned call. That allowed a
|
| 473 |
+
candidate to retain one easy literal while replacing the actual callback,
|
| 474 |
+
input binding, or argument tuple. Only expressions present in the
|
| 475 |
+
selected requirement text are required here; unrelated reference-file
|
| 476 |
+
context remains outside the objective contract.
|
| 477 |
+
"""
|
| 478 |
+
if not isinstance(evaluator, dict) or evaluator.get("type") != \
|
| 479 |
+
WORKSPACE_EVALUATOR:
|
| 480 |
+
return []
|
| 481 |
+
reference_files = {
|
| 482 |
+
str(item.get("path") or ""): str(item.get("content") or "")
|
| 483 |
+
for item in evaluator.get("reference_files") or []
|
| 484 |
+
if isinstance(item, dict)}
|
| 485 |
+
requirement_texts = [
|
| 486 |
+
re.sub(r"\s+", "", str(item.get("requirement") or ""))
|
| 487 |
+
for item in requirements or [] if isinstance(item, dict)]
|
| 488 |
+
issues = []
|
| 489 |
+
for check in evaluator.get("checks") or []:
|
| 490 |
+
if (not isinstance(check, dict) or
|
| 491 |
+
check.get("type") != "python_call_signature"):
|
| 492 |
+
continue
|
| 493 |
+
function = str(check.get("function") or "")
|
| 494 |
+
source = reference_files.get(str(check.get("path") or ""), "")
|
| 495 |
+
if not function or not source:
|
| 496 |
+
continue
|
| 497 |
+
try:
|
| 498 |
+
_, _, constants, call_nodes = _python_semantics(source)
|
| 499 |
+
except SyntaxError:
|
| 500 |
+
issues.append("Python signature reference content is invalid")
|
| 501 |
+
continue
|
| 502 |
+
matches = [node for name, node in call_nodes
|
| 503 |
+
if _call_name_matches(name, function) and
|
| 504 |
+
_call_signature_matches(
|
| 505 |
+
node, check.get("arguments") or [],
|
| 506 |
+
check.get("keywords") or {}, constants,
|
| 507 |
+
check.get("argument_expressions") or [],
|
| 508 |
+
check.get("keyword_expressions") or {},
|
| 509 |
+
check.get("assignment"))]
|
| 510 |
+
if len(matches) != 1:
|
| 511 |
+
issues.append(
|
| 512 |
+
"Python call signature does not identify one reference call")
|
| 513 |
+
continue
|
| 514 |
+
reference_signature = _call_signature(matches[0], constants)
|
| 515 |
+
function_tokens = {re.sub(r"\s+", "", function),
|
| 516 |
+
re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
|
| 517 |
+
|
| 518 |
+
def positional_is_anchored(expression):
|
| 519 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 520 |
+
return any(compact and compact in text and any(
|
| 521 |
+
token and token in text for token in function_tokens)
|
| 522 |
+
for text in requirement_texts)
|
| 523 |
+
|
| 524 |
+
def keyword_is_anchored(name, expression):
|
| 525 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 526 |
+
needle = f"{name}={compact}"
|
| 527 |
+
return any(compact and needle in text and any(
|
| 528 |
+
token and token in text for token in function_tokens)
|
| 529 |
+
for text in requirement_texts)
|
| 530 |
+
|
| 531 |
+
expected_arguments = {
|
| 532 |
+
item["index"]: item.get("expression")
|
| 533 |
+
for item in reference_signature.get("argument_expressions") or []
|
| 534 |
+
if positional_is_anchored(item.get("expression"))}
|
| 535 |
+
expected_keywords = {
|
| 536 |
+
name: expression for name, expression in
|
| 537 |
+
(reference_signature.get("keyword_expressions") or {}).items()
|
| 538 |
+
if keyword_is_anchored(name, expression)}
|
| 539 |
+
actual_arguments = {
|
| 540 |
+
item.get("index"): item.get("expression")
|
| 541 |
+
for item in check.get("argument_expressions") or []
|
| 542 |
+
if isinstance(item, dict)}
|
| 543 |
+
actual_keywords = check.get("keyword_expressions") or {}
|
| 544 |
+
expected_assignment = reference_signature.get("assignment")
|
| 545 |
+
if expected_assignment:
|
| 546 |
+
compact_assignment = re.sub(
|
| 547 |
+
r"\s+", "", f"{expected_assignment.get('target')}="
|
| 548 |
+
f"{expected_assignment.get('expression')}")
|
| 549 |
+
assignment_is_anchored = any(
|
| 550 |
+
compact_assignment and compact_assignment in text and any(
|
| 551 |
+
token and token in text for token in function_tokens)
|
| 552 |
+
for text in requirement_texts)
|
| 553 |
+
else:
|
| 554 |
+
assignment_is_anchored = False
|
| 555 |
+
actual_assignment = check.get("assignment")
|
| 556 |
+
missing_argument = any(
|
| 557 |
+
index not in actual_arguments or
|
| 558 |
+
_expression_fingerprint(actual_arguments[index]) !=
|
| 559 |
+
_expression_fingerprint(expression)
|
| 560 |
+
for index, expression in expected_arguments.items())
|
| 561 |
+
missing_keyword = any(
|
| 562 |
+
name not in actual_keywords or
|
| 563 |
+
_expression_fingerprint(actual_keywords[name]) !=
|
| 564 |
+
_expression_fingerprint(expression)
|
| 565 |
+
for name, expression in expected_keywords.items())
|
| 566 |
+
missing_assignment = bool(
|
| 567 |
+
assignment_is_anchored and (
|
| 568 |
+
not isinstance(actual_assignment, dict) or
|
| 569 |
+
actual_assignment.get("target") !=
|
| 570 |
+
expected_assignment.get("target") or
|
| 571 |
+
_expression_fingerprint(actual_assignment.get("expression")) !=
|
| 572 |
+
_expression_fingerprint(
|
| 573 |
+
expected_assignment.get("expression"))))
|
| 574 |
+
if missing_argument or missing_keyword or missing_assignment:
|
| 575 |
+
issues.append(
|
| 576 |
+
"Python call signature omits an anchored expression or assignment")
|
| 577 |
+
return issues
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def _shell_lines(text):
|
| 581 |
+
"""Return executable lines with conservative local scalar substitution.
|
| 582 |
+
|
| 583 |
+
Shell authors routinely name a fixed argument before using it (for example
|
| 584 |
+
``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
|
| 585 |
+
assignments; never evaluate shell expressions, commands, or defaults.
|
| 586 |
+
"""
|
| 587 |
+
logical, pending = [], ""
|
| 588 |
+
for raw in str(text or "").splitlines():
|
| 589 |
+
line = " ".join(raw.strip().split())
|
| 590 |
+
if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
|
| 591 |
+
continue
|
| 592 |
+
pending = (pending + " " + line).strip() if pending else line
|
| 593 |
+
if pending.endswith("\\"):
|
| 594 |
+
pending = pending[:-1].rstrip()
|
| 595 |
+
continue
|
| 596 |
+
logical.append(pending)
|
| 597 |
+
pending = ""
|
| 598 |
+
if pending:
|
| 599 |
+
logical.append(pending)
|
| 600 |
+
|
| 601 |
+
constants, out = {}, []
|
| 602 |
+
assignment = re.compile(
|
| 603 |
+
r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
|
| 604 |
+
r"([A-Za-z0-9_./:+-]+))$")
|
| 605 |
+
variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
|
| 606 |
+
for line in logical:
|
| 607 |
+
match = assignment.fullmatch(line)
|
| 608 |
+
if match:
|
| 609 |
+
constants[match.group(1)] = next(
|
| 610 |
+
value for value in match.groups()[1:] if value is not None)
|
| 611 |
+
out.append(line)
|
| 612 |
+
continue
|
| 613 |
+
|
| 614 |
+
def replace(match):
|
| 615 |
+
name = match.group(1) or match.group(2)
|
| 616 |
+
return constants.get(name, match.group(0))
|
| 617 |
+
|
| 618 |
+
out.append(variable.sub(replace, line))
|
| 619 |
+
return out
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def _shell_command_matches(expected, actual):
|
| 623 |
+
"""Accept the frozen invocation plus documented optional arguments/path prefixes."""
|
| 624 |
+
try:
|
| 625 |
+
wanted = shlex.split(str(expected))
|
| 626 |
+
found = shlex.split(str(actual))
|
| 627 |
+
except ValueError:
|
| 628 |
+
return False
|
| 629 |
+
def normalize_git_log_limit(tokens):
|
| 630 |
+
if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
|
| 631 |
+
return tokens
|
| 632 |
+
normalized, index = [], 0
|
| 633 |
+
while index < len(tokens):
|
| 634 |
+
token = tokens[index]
|
| 635 |
+
short = re.fullmatch(r"-(\d+)", token)
|
| 636 |
+
long = re.fullmatch(r"--max-count=(\d+)", token)
|
| 637 |
+
if short or long:
|
| 638 |
+
normalized.append("--max-count=" + (short or long).group(1))
|
| 639 |
+
elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
|
| 640 |
+
re.fullmatch(r"\d+", tokens[index + 1])):
|
| 641 |
+
normalized.append("--max-count=" + tokens[index + 1])
|
| 642 |
+
index += 1
|
| 643 |
+
else:
|
| 644 |
+
normalized.append(token)
|
| 645 |
+
index += 1
|
| 646 |
+
return normalized
|
| 647 |
+
|
| 648 |
+
wanted = normalize_git_log_limit(wanted)
|
| 649 |
+
found = normalize_git_log_limit(found)
|
| 650 |
+
if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
|
| 651 |
+
return False
|
| 652 |
+
for index, token in enumerate(wanted[1:], 1):
|
| 653 |
+
observed = found[index]
|
| 654 |
+
if observed == token:
|
| 655 |
+
continue
|
| 656 |
+
# A solver may anchor a package-relative script at $REPO_ROOT while
|
| 657 |
+
# preserving the exact package path selected by the Skill.
|
| 658 |
+
if (index == 1 and "/" in token and
|
| 659 |
+
observed.rstrip("/").endswith(token.lstrip("./"))):
|
| 660 |
+
continue
|
| 661 |
+
return False
|
| 662 |
+
return True
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _shell_command_sequence_matches(expected, actual_lines):
|
| 666 |
+
"""Require every frozen command in order while allowing extra lines."""
|
| 667 |
+
cursor = 0
|
| 668 |
+
for command in expected:
|
| 669 |
+
for index in range(cursor, len(actual_lines)):
|
| 670 |
+
if _shell_command_matches(command, actual_lines[index]):
|
| 671 |
+
cursor = index + 1
|
| 672 |
+
break
|
| 673 |
+
else:
|
| 674 |
+
return False
|
| 675 |
+
return True
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _shell_unconditional_lines(text):
|
| 679 |
+
"""Return conservative top-level command lines from a shell artifact.
|
| 680 |
+
|
| 681 |
+
Checked commands hidden in a conditional branch or an uncalled function do
|
| 682 |
+
not establish that the requested script performs them. This is not a full
|
| 683 |
+
shell parser: unsupported control flow simply makes nested lines
|
| 684 |
+
ineligible, which is appropriate for the small straight-line command
|
| 685 |
+
artifacts compiled by this evaluator.
|
| 686 |
+
"""
|
| 687 |
+
lines = _shell_lines(text)
|
| 688 |
+
depth = 0
|
| 689 |
+
out = []
|
| 690 |
+
opener = re.compile(
|
| 691 |
+
r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
|
| 692 |
+
r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
|
| 693 |
+
closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
|
| 694 |
+
for line in lines:
|
| 695 |
+
if closer.match(line):
|
| 696 |
+
depth = max(0, depth - 1)
|
| 697 |
+
continue
|
| 698 |
+
if depth == 0 and not opener.match(line):
|
| 699 |
+
out.append(line)
|
| 700 |
+
if opener.match(line):
|
| 701 |
+
depth += 1
|
| 702 |
+
return out
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def _shell_is_straight_line(text):
|
| 706 |
+
"""Return whether every executable logical line is top-level.
|
| 707 |
+
|
| 708 |
+
This deliberately reuses the conservative control-flow recognizer used by
|
| 709 |
+
unconditional command checks. Any recognized conditional, loop, case, or
|
| 710 |
+
function makes the whole-script straight-line contract fail closed.
|
| 711 |
+
"""
|
| 712 |
+
lines = _shell_lines(text)
|
| 713 |
+
return lines == _shell_unconditional_lines(text)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def compile_workspace_evaluator(deliverables):
|
| 717 |
+
"""Compile trusted checks from validated deliverable specifications."""
|
| 718 |
+
if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
|
| 719 |
+
raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
|
| 720 |
+
reference_files, checks, paths = [], [], set()
|
| 721 |
+
for index, raw in enumerate(deliverables, 1):
|
| 722 |
+
if not isinstance(raw, dict):
|
| 723 |
+
raise ObjectiveEvaluatorError("deliverable is not an object")
|
| 724 |
+
path = safe_relative_path(raw.get("path"))
|
| 725 |
+
if path in paths:
|
| 726 |
+
raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
|
| 727 |
+
paths.add(path)
|
| 728 |
+
fmt = str(raw.get("format") or "").strip().casefold()
|
| 729 |
+
if fmt not in ARTIFACT_FORMATS:
|
| 730 |
+
raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
|
| 731 |
+
content = _file_content({**raw, "format": fmt})
|
| 732 |
+
if len(content.encode("utf-8")) > 200_000:
|
| 733 |
+
raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
|
| 734 |
+
reference_files.append({"path": path, "format": fmt, "content": content})
|
| 735 |
+
checks.append({"id": f"file_{index:03d}", "type": "file_exists",
|
| 736 |
+
"path": path})
|
| 737 |
+
if fmt == "json":
|
| 738 |
+
checks.append({"id": f"json_{index:03d}", "type": "json_exact",
|
| 739 |
+
"path": path, "expected": _json_value(raw.get("content"))})
|
| 740 |
+
elif fmt == "toml":
|
| 741 |
+
try:
|
| 742 |
+
expected = tomllib.loads(content)
|
| 743 |
+
except (tomllib.TOMLDecodeError, ValueError) as exc:
|
| 744 |
+
raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
|
| 745 |
+
checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
|
| 746 |
+
"path": path, "expected": expected})
|
| 747 |
+
elif fmt == "python":
|
| 748 |
+
try:
|
| 749 |
+
_, _, constants, call_nodes = _python_semantics(content)
|
| 750 |
+
resolved_calls = _python_resolved_call_nodes(content)
|
| 751 |
+
except SyntaxError as exc:
|
| 752 |
+
raise ObjectiveEvaluatorError("reference Python is invalid") from exc
|
| 753 |
+
checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
|
| 754 |
+
"path": path})
|
| 755 |
+
checks.append({"id": f"python_{index:03d}_bindings",
|
| 756 |
+
"type": "python_bound_calls", "path": path})
|
| 757 |
+
raw_checks = raw.get("checks") or []
|
| 758 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 759 |
+
raise ObjectiveEvaluatorError(
|
| 760 |
+
"Python deliverable requires 1-12 objective import/call checks")
|
| 761 |
+
for check_index, check in enumerate(raw_checks, 1):
|
| 762 |
+
if not isinstance(check, dict):
|
| 763 |
+
raise ObjectiveEvaluatorError("Python check is not an object")
|
| 764 |
+
kind = str(check.get("type") or "").strip().casefold()
|
| 765 |
+
if kind in {"python_import", "python_call"}:
|
| 766 |
+
value = str(check.get("value") or "").strip()
|
| 767 |
+
if not _DOTTED.fullmatch(value):
|
| 768 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 769 |
+
compiled = {"type": kind, "path": path, "value": value}
|
| 770 |
+
elif kind == "python_constant":
|
| 771 |
+
name = str(check.get("name") or "").strip()
|
| 772 |
+
value = check.get("value")
|
| 773 |
+
if (not _DOTTED.fullmatch(name) or "." in name or
|
| 774 |
+
isinstance(value, (dict, list)) or value is None or
|
| 775 |
+
constants.get(name, _UNRESOLVED) != value):
|
| 776 |
+
raise ObjectiveEvaluatorError(
|
| 777 |
+
"Python constant check is invalid or fails reference content")
|
| 778 |
+
compiled = {"type": kind, "path": path, "name": name,
|
| 779 |
+
"value": value}
|
| 780 |
+
elif kind == "python_call_literal":
|
| 781 |
+
function = str(check.get("function") or "").strip()
|
| 782 |
+
value = check.get("value")
|
| 783 |
+
if (not _DOTTED.fullmatch(function) or
|
| 784 |
+
isinstance(value, (dict, list)) or value is None or
|
| 785 |
+
not any(
|
| 786 |
+
(name == function or name.endswith("." + function)) and
|
| 787 |
+
_node_contains_literal(node, value, constants)
|
| 788 |
+
for name, node in call_nodes)):
|
| 789 |
+
raise ObjectiveEvaluatorError(
|
| 790 |
+
"Python call-literal check is invalid or fails reference content")
|
| 791 |
+
compiled = {"type": kind, "path": path,
|
| 792 |
+
"function": function, "value": value}
|
| 793 |
+
elif kind == "python_call_keyword_literal":
|
| 794 |
+
function = str(check.get("function") or "").strip()
|
| 795 |
+
keyword = str(check.get("keyword") or "").strip()
|
| 796 |
+
value = check.get("value")
|
| 797 |
+
if (not _DOTTED.fullmatch(function) or
|
| 798 |
+
not _DOTTED.fullmatch(keyword) or "." in keyword or
|
| 799 |
+
isinstance(value, (dict, list)) or value is None or
|
| 800 |
+
not any(
|
| 801 |
+
(name == function or name.endswith("." + function)) and
|
| 802 |
+
_call_keyword_matches(node, keyword, value, constants)
|
| 803 |
+
for name, node in call_nodes)):
|
| 804 |
+
raise ObjectiveEvaluatorError(
|
| 805 |
+
"Python call-keyword check is invalid or fails reference content")
|
| 806 |
+
compiled = {"type": kind, "path": path,
|
| 807 |
+
"function": function, "keyword": keyword,
|
| 808 |
+
"value": value}
|
| 809 |
+
elif kind == "python_call_signature":
|
| 810 |
+
function = str(check.get("function") or "").strip()
|
| 811 |
+
arguments = check.get("arguments") or []
|
| 812 |
+
keywords = check.get("keywords") or {}
|
| 813 |
+
argument_expressions = check.get(
|
| 814 |
+
"argument_expressions") or []
|
| 815 |
+
keyword_expressions = check.get(
|
| 816 |
+
"keyword_expressions") or {}
|
| 817 |
+
assignment = check.get("assignment")
|
| 818 |
+
if (not _DOTTED.fullmatch(function) or
|
| 819 |
+
not isinstance(arguments, list) or
|
| 820 |
+
not isinstance(keywords, dict) or
|
| 821 |
+
not isinstance(argument_expressions, list) or
|
| 822 |
+
not isinstance(keyword_expressions, dict) or
|
| 823 |
+
not (arguments or keywords or
|
| 824 |
+
argument_expressions or keyword_expressions or
|
| 825 |
+
assignment) or
|
| 826 |
+
any(not isinstance(item, dict) or
|
| 827 |
+
not isinstance(item.get("index"), int) or
|
| 828 |
+
item.get("index") < 0 or
|
| 829 |
+
isinstance(item.get("value"), dict)
|
| 830 |
+
for item in arguments) or
|
| 831 |
+
len({item["index"] for item in arguments}) !=
|
| 832 |
+
len(arguments) or
|
| 833 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 834 |
+
"." in str(name) or isinstance(value, dict)
|
| 835 |
+
for name, value in keywords.items()) or
|
| 836 |
+
any(not isinstance(item, dict) or
|
| 837 |
+
not isinstance(item.get("index"), int) or
|
| 838 |
+
item.get("index") < 0 or
|
| 839 |
+
not _expression_fingerprint(
|
| 840 |
+
item.get("expression"))
|
| 841 |
+
for item in argument_expressions) or
|
| 842 |
+
len({item["index"] for item in
|
| 843 |
+
argument_expressions}) !=
|
| 844 |
+
len(argument_expressions) or
|
| 845 |
+
({item["index"] for item in arguments} &
|
| 846 |
+
{item["index"] for item in
|
| 847 |
+
argument_expressions}) or
|
| 848 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 849 |
+
"." in str(name) or
|
| 850 |
+
not _expression_fingerprint(value)
|
| 851 |
+
for name, value in
|
| 852 |
+
keyword_expressions.items()) or
|
| 853 |
+
(set(keywords) & set(keyword_expressions)) or
|
| 854 |
+
(assignment is not None and (
|
| 855 |
+
not isinstance(assignment, dict) or
|
| 856 |
+
not _DOTTED.fullmatch(str(
|
| 857 |
+
assignment.get("target") or "")) or
|
| 858 |
+
"." in str(assignment.get("target") or "") or
|
| 859 |
+
not _expression_fingerprint(
|
| 860 |
+
assignment.get("expression")))) or
|
| 861 |
+
not any(
|
| 862 |
+
(name == function or
|
| 863 |
+
name.endswith("." + function)) and
|
| 864 |
+
_call_signature_matches(
|
| 865 |
+
node, arguments, keywords, constants,
|
| 866 |
+
argument_expressions,
|
| 867 |
+
keyword_expressions, assignment)
|
| 868 |
+
for name, node in call_nodes)):
|
| 869 |
+
raise ObjectiveEvaluatorError(
|
| 870 |
+
"Python call-signature check is invalid or fails reference content")
|
| 871 |
+
compiled = {"type": kind, "path": path,
|
| 872 |
+
"function": function,
|
| 873 |
+
"arguments": arguments,
|
| 874 |
+
"keywords": keywords,
|
| 875 |
+
"argument_expressions": argument_expressions,
|
| 876 |
+
"keyword_expressions": keyword_expressions,
|
| 877 |
+
"assignment": assignment}
|
| 878 |
+
else:
|
| 879 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 880 |
+
if kind in {"python_call", "python_call_literal",
|
| 881 |
+
"python_call_keyword_literal",
|
| 882 |
+
"python_call_signature"}:
|
| 883 |
+
targets = _objective_call_targets(
|
| 884 |
+
kind, compiled, resolved_calls, constants)
|
| 885 |
+
if len(targets) != 1:
|
| 886 |
+
raise ObjectiveEvaluatorError(
|
| 887 |
+
"Python call check has no unique canonical target")
|
| 888 |
+
compiled["target"] = next(iter(targets))
|
| 889 |
+
checks.append({"id": f"python_{index:03d}_{check_index:03d}",
|
| 890 |
+
**compiled})
|
| 891 |
+
else:
|
| 892 |
+
raw_checks = raw.get("checks") or []
|
| 893 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 894 |
+
raise ObjectiveEvaluatorError(
|
| 895 |
+
"shell deliverable requires 1-12 objective command checks")
|
| 896 |
+
checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
|
| 897 |
+
"path": path})
|
| 898 |
+
reference_sequence = _shell_lines(content)
|
| 899 |
+
reference_lines = set(reference_sequence)
|
| 900 |
+
unconditional_lines = _shell_unconditional_lines(content)
|
| 901 |
+
command_checks = []
|
| 902 |
+
for check in raw_checks:
|
| 903 |
+
value = " ".join(str(check.get("value") or "").strip().split())
|
| 904 |
+
if (not isinstance(check, dict) or
|
| 905 |
+
str(check.get("type") or "").strip().casefold() != "shell_command" or
|
| 906 |
+
not value or value not in reference_lines):
|
| 907 |
+
raise ObjectiveEvaluatorError("unsupported shell objective check")
|
| 908 |
+
command_checks.append({"type": "shell_command", "path": path,
|
| 909 |
+
"value": value})
|
| 910 |
+
if len({item["value"] for item in command_checks}) != len(command_checks):
|
| 911 |
+
raise ObjectiveEvaluatorError("shell objective checks must be unique")
|
| 912 |
+
command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
|
| 913 |
+
if not all(any(_shell_command_matches(
|
| 914 |
+
item["value"], line) for line in unconditional_lines)
|
| 915 |
+
for item in command_checks):
|
| 916 |
+
raise ObjectiveEvaluatorError(
|
| 917 |
+
"checked shell commands must be top-level and unconditional")
|
| 918 |
+
for check_index, check in enumerate(command_checks, 1):
|
| 919 |
+
checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
|
| 920 |
+
**check})
|
| 921 |
+
if len(command_checks) >= 2:
|
| 922 |
+
checks.append({
|
| 923 |
+
"id": f"shell_{index:03d}_sequence",
|
| 924 |
+
"type": "shell_command_sequence", "path": path,
|
| 925 |
+
"values": [item["value"] for item in command_checks],
|
| 926 |
+
})
|
| 927 |
+
checks.append({
|
| 928 |
+
"id": f"shell_{index:03d}_unconditional",
|
| 929 |
+
"type": "shell_unconditional_commands", "path": path,
|
| 930 |
+
"values": [item["value"] for item in command_checks],
|
| 931 |
+
})
|
| 932 |
+
# Preserve the reference's fail-fast behavior when accepting normal
|
| 933 |
+
# command-substitution/guard wrappers. Never turn `|| true` into a
|
| 934 |
+
# passing preflight simply because it contains the correct argv.
|
| 935 |
+
reference_calls = shell_invocations(content)
|
| 936 |
+
protected = [item["value"] for item in command_checks if any(
|
| 937 |
+
call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
|
| 938 |
+
for call in reference_calls)]
|
| 939 |
+
if protected:
|
| 940 |
+
checks.append({"id": f"shell_{index:03d}_failure_propagation",
|
| 941 |
+
"type": "shell_failure_propagation", "path": path,
|
| 942 |
+
"values": protected})
|
| 943 |
+
# Candidate workspaces may also contain root-level public inputs and
|
| 944 |
+
# installed Skill packages. Deliverables use dedicated top-level output
|
| 945 |
+
# directories, so enforce an exact file set inside those namespaces while
|
| 946 |
+
# leaving the read-only environment outside them untouched.
|
| 947 |
+
output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
|
| 948 |
+
if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
|
| 949 |
+
checks.insert(0, {
|
| 950 |
+
"id": "workspace_file_set", "type": "workspace_file_set",
|
| 951 |
+
"paths": sorted(paths), "roots": output_roots,
|
| 952 |
+
})
|
| 953 |
+
return {
|
| 954 |
+
"type": WORKSPACE_EVALUATOR,
|
| 955 |
+
"version": WORKSPACE_EVALUATOR_VERSION,
|
| 956 |
+
"output_mode": "workspace",
|
| 957 |
+
"reference_files": reference_files,
|
| 958 |
+
"checks": checks,
|
| 959 |
+
}
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def reference_bundle(evaluator):
|
| 963 |
+
if evaluator.get("type") != WORKSPACE_EVALUATOR:
|
| 964 |
+
raise ObjectiveEvaluatorError("not a workspace evaluator")
|
| 965 |
+
return {"files": [
|
| 966 |
+
{"path": item["path"], "content": item["content"]}
|
| 967 |
+
for item in evaluator.get("reference_files") or []
|
| 968 |
+
]}
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def hidden_workspace_values(evaluator):
|
| 972 |
+
"""Return decisive package-owned values that public queries must not leak."""
|
| 973 |
+
values = []
|
| 974 |
+
for check in (evaluator or {}).get("checks") or []:
|
| 975 |
+
kind = check.get("type")
|
| 976 |
+
if kind in {"json_exact", "toml_exact"}:
|
| 977 |
+
values.extend(value for _, value in _flatten(check.get("expected")))
|
| 978 |
+
elif kind in {"python_import", "python_call", "shell_command",
|
| 979 |
+
"python_constant", "python_call_literal",
|
| 980 |
+
"python_call_keyword_literal"}:
|
| 981 |
+
values.append(check.get("value"))
|
| 982 |
+
elif kind == "python_call_signature":
|
| 983 |
+
values.extend(value for _, value in _flatten({
|
| 984 |
+
"arguments": [item.get("value") for item in
|
| 985 |
+
check.get("arguments") or []],
|
| 986 |
+
"keywords": check.get("keywords") or {},
|
| 987 |
+
"argument_expressions": [item.get("expression") for item in
|
| 988 |
+
check.get("argument_expressions") or []],
|
| 989 |
+
"keyword_expressions": check.get("keyword_expressions") or {},
|
| 990 |
+
"assignment": check.get("assignment"),
|
| 991 |
+
}))
|
| 992 |
+
return [value for value in values if value is not None]
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def _flatten(value, path=()):
|
| 996 |
+
if isinstance(value, dict):
|
| 997 |
+
out = []
|
| 998 |
+
for key, item in value.items():
|
| 999 |
+
out.extend(_flatten(item, path + (str(key),)))
|
| 1000 |
+
return out
|
| 1001 |
+
if isinstance(value, list):
|
| 1002 |
+
out = []
|
| 1003 |
+
for index, item in enumerate(value):
|
| 1004 |
+
out.extend(_flatten(item, path + (index,)))
|
| 1005 |
+
return out
|
| 1006 |
+
return [(path, value)]
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def _bundle_rows(candidate):
|
| 1010 |
+
if isinstance(candidate, str):
|
| 1011 |
+
text = candidate.strip()
|
| 1012 |
+
# Chat solvers often wrap the requested file bundle in a Markdown fence
|
| 1013 |
+
# or append a duplicate FINAL_ANSWER object. Decode one complete JSON
|
| 1014 |
+
# value at a time instead of requiring the entire response to be JSON;
|
| 1015 |
+
# only an object carrying the explicit ``files`` transport field is
|
| 1016 |
+
# eligible, so unrelated prose/objects are not silently accepted.
|
| 1017 |
+
decoder = json.JSONDecoder()
|
| 1018 |
+
candidate = None
|
| 1019 |
+
for match in re.finditer(r"\{", text):
|
| 1020 |
+
try:
|
| 1021 |
+
parsed, _ = decoder.raw_decode(text, match.start())
|
| 1022 |
+
except json.JSONDecodeError:
|
| 1023 |
+
continue
|
| 1024 |
+
if isinstance(parsed, dict) and "files" in parsed:
|
| 1025 |
+
candidate = parsed
|
| 1026 |
+
break
|
| 1027 |
+
if candidate is None:
|
| 1028 |
+
raise ObjectiveEvaluatorError(
|
| 1029 |
+
"workspace response contains no complete JSON file bundle")
|
| 1030 |
+
if not isinstance(candidate, dict):
|
| 1031 |
+
raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
|
| 1032 |
+
files = candidate.get("files")
|
| 1033 |
+
if isinstance(files, dict):
|
| 1034 |
+
files = [{"path": path, "content": content}
|
| 1035 |
+
for path, content in files.items()]
|
| 1036 |
+
if not isinstance(files, list) or len(files) > 30:
|
| 1037 |
+
raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
|
| 1038 |
+
return files
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
def materialize_bundle(candidate, workspace):
|
| 1042 |
+
root = Path(workspace).resolve()
|
| 1043 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 1044 |
+
seen = set()
|
| 1045 |
+
for item in _bundle_rows(candidate):
|
| 1046 |
+
if not isinstance(item, dict):
|
| 1047 |
+
raise ObjectiveEvaluatorError("candidate file entry is not an object")
|
| 1048 |
+
relative = safe_relative_path(item.get("path"))
|
| 1049 |
+
if relative in seen:
|
| 1050 |
+
raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
|
| 1051 |
+
seen.add(relative)
|
| 1052 |
+
content = item.get("content")
|
| 1053 |
+
if isinstance(content, (dict, list)):
|
| 1054 |
+
content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 1055 |
+
if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
|
| 1056 |
+
raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
|
| 1057 |
+
target = (root / relative).resolve()
|
| 1058 |
+
if root not in target.parents:
|
| 1059 |
+
raise ObjectiveEvaluatorError("candidate file escapes workspace")
|
| 1060 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 1061 |
+
target.write_text(content, encoding="utf-8")
|
| 1062 |
+
return root
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def evaluate_workspace(evaluator, workspace):
|
| 1066 |
+
if (not isinstance(evaluator, dict) or
|
| 1067 |
+
evaluator.get("type") != WORKSPACE_EVALUATOR or
|
| 1068 |
+
int(evaluator.get("version") or 0) not in
|
| 1069 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
|
| 1070 |
+
return False, {"error": "invalid workspace evaluator contract"}
|
| 1071 |
+
root = Path(workspace).resolve()
|
| 1072 |
+
results = []
|
| 1073 |
+
for check in evaluator.get("checks") or []:
|
| 1074 |
+
kind = check.get("type")
|
| 1075 |
+
relative, path = "", None
|
| 1076 |
+
if kind != "workspace_file_set":
|
| 1077 |
+
relative = safe_relative_path(check.get("path"))
|
| 1078 |
+
path = (root / relative).resolve()
|
| 1079 |
+
if root not in path.parents:
|
| 1080 |
+
return False, {"error": "evaluator path escapes workspace"}
|
| 1081 |
+
passed, detail = False, ""
|
| 1082 |
+
try:
|
| 1083 |
+
if kind == "workspace_file_set":
|
| 1084 |
+
expected = {safe_relative_path(value)
|
| 1085 |
+
for value in check.get("paths") or []}
|
| 1086 |
+
roots = [safe_relative_path(value)
|
| 1087 |
+
for value in check.get("roots") or []]
|
| 1088 |
+
actual = set()
|
| 1089 |
+
for relative_root in roots:
|
| 1090 |
+
scan_root = (root / relative_root).resolve()
|
| 1091 |
+
if root not in scan_root.parents:
|
| 1092 |
+
raise ObjectiveEvaluatorError(
|
| 1093 |
+
"workspace file-set root escapes workspace")
|
| 1094 |
+
if not scan_root.exists():
|
| 1095 |
+
continue
|
| 1096 |
+
for candidate in scan_root.rglob("*"):
|
| 1097 |
+
if candidate.is_file() or candidate.is_symlink():
|
| 1098 |
+
actual.add(candidate.relative_to(root).as_posix())
|
| 1099 |
+
passed = bool(expected) and actual == expected
|
| 1100 |
+
detail = ("exact deliverable file set" if passed else
|
| 1101 |
+
f"expected_files={sorted(expected)}; "
|
| 1102 |
+
f"actual_files={sorted(actual)}")
|
| 1103 |
+
elif kind == "file_exists":
|
| 1104 |
+
passed = path.is_file()
|
| 1105 |
+
detail = "present" if passed else "missing"
|
| 1106 |
+
elif kind == "json_exact":
|
| 1107 |
+
actual = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_r10_unique_pairs, parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x)))
|
| 1108 |
+
passed = (_same_native_json_types(actual, check.get("expected")) and
|
| 1109 |
+
_canonical(actual) == _canonical(check.get("expected")))
|
| 1110 |
+
detail = "semantic JSON match" if passed else "JSON value mismatch"
|
| 1111 |
+
elif kind == "toml_exact":
|
| 1112 |
+
actual = tomllib.loads(path.read_text(encoding="utf-8"))
|
| 1113 |
+
passed = _canonical(actual) == _canonical(check.get("expected"))
|
| 1114 |
+
detail = "semantic TOML match" if passed else "TOML value mismatch"
|
| 1115 |
+
elif kind in {"python_syntax", "python_bound_calls",
|
| 1116 |
+
"python_import", "python_call",
|
| 1117 |
+
"python_constant", "python_call_literal",
|
| 1118 |
+
"python_call_keyword_literal",
|
| 1119 |
+
"python_call_signature"}:
|
| 1120 |
+
source = path.read_text(encoding="utf-8")
|
| 1121 |
+
imports, calls, constants, call_nodes = _python_semantics(source)
|
| 1122 |
+
resolved_calls = _python_resolved_call_nodes(source)
|
| 1123 |
+
if kind == "python_syntax":
|
| 1124 |
+
passed, detail = True, "valid Python syntax"
|
| 1125 |
+
elif kind == "python_bound_calls":
|
| 1126 |
+
unbound = python_unbound_call_roots(
|
| 1127 |
+
path.read_text(encoding="utf-8"))
|
| 1128 |
+
passed = not unbound
|
| 1129 |
+
detail = ("all call roots are statically bound" if passed else
|
| 1130 |
+
"unbound call roots=" + repr(unbound))
|
| 1131 |
+
elif kind == "python_import":
|
| 1132 |
+
expected = str(check.get("value") or "")
|
| 1133 |
+
passed = expected in imports or any(
|
| 1134 |
+
value == expected or value.startswith(expected + ".")
|
| 1135 |
+
for value in imports)
|
| 1136 |
+
detail = f"imports={sorted(imports)}"
|
| 1137 |
+
elif kind == "python_call":
|
| 1138 |
+
expected = str(check.get("value") or "")
|
| 1139 |
+
target = str(check.get("target") or "")
|
| 1140 |
+
passed = (any(
|
| 1141 |
+
canonical == target
|
| 1142 |
+
for _, canonical, _ in resolved_calls)
|
| 1143 |
+
if target else expected in calls or any(
|
| 1144 |
+
value.endswith("." + expected)
|
| 1145 |
+
for value in calls))
|
| 1146 |
+
detail = f"calls={sorted(calls)}"
|
| 1147 |
+
elif kind == "python_constant":
|
| 1148 |
+
name, expected = str(check.get("name") or ""), check.get("value")
|
| 1149 |
+
actual = constants.get(name, _UNRESOLVED)
|
| 1150 |
+
passed = actual is not _UNRESOLVED and actual == expected
|
| 1151 |
+
detail = f"constant {name}={actual!r}"
|
| 1152 |
+
elif kind == "python_call_literal":
|
| 1153 |
+
function, expected = (str(check.get("function") or ""),
|
| 1154 |
+
check.get("value"))
|
| 1155 |
+
target = str(check.get("target") or "")
|
| 1156 |
+
source_calls = (resolved_calls if target else
|
| 1157 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1158 |
+
passed = any(
|
| 1159 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1160 |
+
(not target or canonical == target) and
|
| 1161 |
+
_node_contains_literal(node, expected, constants)
|
| 1162 |
+
for name, canonical, node in source_calls)
|
| 1163 |
+
detail = f"call={function} literal={expected!r}"
|
| 1164 |
+
elif kind == "python_call_keyword_literal":
|
| 1165 |
+
function = str(check.get("function") or "")
|
| 1166 |
+
keyword = str(check.get("keyword") or "")
|
| 1167 |
+
expected = check.get("value")
|
| 1168 |
+
target = str(check.get("target") or "")
|
| 1169 |
+
source_calls = (resolved_calls if target else
|
| 1170 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1171 |
+
passed = any(
|
| 1172 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1173 |
+
(not target or canonical == target) and
|
| 1174 |
+
_call_keyword_matches(node, keyword, expected, constants)
|
| 1175 |
+
for name, canonical, node in source_calls)
|
| 1176 |
+
detail = (f"call={function} keyword={keyword} "
|
| 1177 |
+
f"literal={expected!r}")
|
| 1178 |
+
else:
|
| 1179 |
+
function = str(check.get("function") or "")
|
| 1180 |
+
arguments = check.get("arguments") or []
|
| 1181 |
+
keywords = check.get("keywords") or {}
|
| 1182 |
+
argument_expressions = check.get(
|
| 1183 |
+
"argument_expressions") or []
|
| 1184 |
+
keyword_expressions = check.get(
|
| 1185 |
+
"keyword_expressions") or {}
|
| 1186 |
+
assignment = check.get("assignment")
|
| 1187 |
+
target = str(check.get("target") or "")
|
| 1188 |
+
source_calls = (resolved_calls if target else
|
| 1189 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1190 |
+
passed = any(
|
| 1191 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1192 |
+
(not target or canonical == target) and
|
| 1193 |
+
_call_signature_matches(
|
| 1194 |
+
node, arguments, keywords, constants,
|
| 1195 |
+
argument_expressions, keyword_expressions,
|
| 1196 |
+
assignment)
|
| 1197 |
+
for name, canonical, node in source_calls)
|
| 1198 |
+
detail = (f"call={function} arguments={arguments!r} "
|
| 1199 |
+
f"keywords={keywords!r} "
|
| 1200 |
+
f"argument_expressions={argument_expressions!r} "
|
| 1201 |
+
f"keyword_expressions={keyword_expressions!r} "
|
| 1202 |
+
f"assignment={assignment!r}")
|
| 1203 |
+
elif kind == "shell_syntax":
|
| 1204 |
+
completed = subprocess.run(
|
| 1205 |
+
["bash", "-n", str(path)], capture_output=True, text=True,
|
| 1206 |
+
timeout=5, check=False)
|
| 1207 |
+
passed = completed.returncode == 0
|
| 1208 |
+
detail = ("valid shell syntax" if passed else
|
| 1209 |
+
(completed.stderr or "invalid shell syntax").strip())
|
| 1210 |
+
elif kind == "shell_command":
|
| 1211 |
+
source = path.read_text(encoding="utf-8")
|
| 1212 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1213 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1214 |
+
expected = " ".join(str(check.get("value") or "").split())
|
| 1215 |
+
passed = any(_shell_command_matches(expected, line) for line in lines)
|
| 1216 |
+
detail = f"executable_lines={lines[:30]}"
|
| 1217 |
+
elif kind == "shell_command_sequence":
|
| 1218 |
+
source = path.read_text(encoding="utf-8")
|
| 1219 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1220 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1221 |
+
expected = [" ".join(str(value).split())
|
| 1222 |
+
for value in check.get("values") or []]
|
| 1223 |
+
passed = (len(expected) >= 2 and
|
| 1224 |
+
_shell_command_sequence_matches(expected, lines))
|
| 1225 |
+
detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
|
| 1226 |
+
elif kind == "shell_unconditional_commands":
|
| 1227 |
+
source = path.read_text(encoding="utf-8")
|
| 1228 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1229 |
+
if int(evaluator.get("version", 0)) >= 15
|
| 1230 |
+
else _shell_unconditional_lines(source))
|
| 1231 |
+
expected = [" ".join(str(value).split())
|
| 1232 |
+
for value in check.get("values") or []]
|
| 1233 |
+
passed = (bool(expected) and all(
|
| 1234 |
+
any(_shell_command_matches(command, line) for line in lines)
|
| 1235 |
+
for command in expected))
|
| 1236 |
+
if check.get("require_straight_line"):
|
| 1237 |
+
passed = passed and _shell_is_straight_line(source)
|
| 1238 |
+
detail = (f"expected_unconditional={expected}; "
|
| 1239 |
+
f"top_level_lines={lines[:30]}")
|
| 1240 |
+
elif kind == "shell_failure_propagation":
|
| 1241 |
+
calls = shell_invocations(path.read_text(encoding="utf-8"))
|
| 1242 |
+
expected = [" ".join(str(value).split())
|
| 1243 |
+
for value in check.get("values") or []]
|
| 1244 |
+
passed = bool(expected) and all(any(
|
| 1245 |
+
call["fail_fast"] and _shell_command_matches(command, call["command"])
|
| 1246 |
+
for call in calls) for command in expected)
|
| 1247 |
+
detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
|
| 1248 |
+
elif kind == "shell_straight_line":
|
| 1249 |
+
source = path.read_text(encoding="utf-8")
|
| 1250 |
+
passed = _shell_is_straight_line(source)
|
| 1251 |
+
if "allowed_commands" in check:
|
| 1252 |
+
calls = shell_invocations(source)
|
| 1253 |
+
allowed = check["allowed_commands"]
|
| 1254 |
+
passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and
|
| 1255 |
+
all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls))
|
| 1256 |
+
detail = ("all executable lines are top-level" if passed else
|
| 1257 |
+
"shell contains conditional, loop, case, or function")
|
| 1258 |
+
else:
|
| 1259 |
+
detail = f"unsupported check: {kind}"
|
| 1260 |
+
except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
|
| 1261 |
+
json.JSONDecodeError,
|
| 1262 |
+
tomllib.TOMLDecodeError) as exc:
|
| 1263 |
+
detail = str(exc)
|
| 1264 |
+
results.append({"id": check.get("id"), "type": kind,
|
| 1265 |
+
"path": relative, "passed": bool(passed),
|
| 1266 |
+
"detail": detail[:1000]})
|
| 1267 |
+
return bool(results) and all(item["passed"] for item in results), {
|
| 1268 |
+
"type": WORKSPACE_EVALUATOR,
|
| 1269 |
+
"assertions_passed": sum(item["passed"] for item in results),
|
| 1270 |
+
"assertions_total": len(results),
|
| 1271 |
+
"assertions": results,
|
| 1272 |
+
}
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
def evaluate_candidate(evaluator, candidate):
|
| 1276 |
+
if isinstance(candidate, os.PathLike):
|
| 1277 |
+
try:
|
| 1278 |
+
return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
|
| 1279 |
+
False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
|
| 1280 |
+
except (OSError, ValueError) as exc:
|
| 1281 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1282 |
+
if isinstance(candidate, str):
|
| 1283 |
+
# A chat file-bundle can be much longer than a filesystem path. Avoid
|
| 1284 |
+
# passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
|
| 1285 |
+
stripped = candidate.strip()
|
| 1286 |
+
if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
|
| 1287 |
+
and not stripped.startswith(("{", "[", "```"))):
|
| 1288 |
+
try:
|
| 1289 |
+
if Path(stripped).is_dir():
|
| 1290 |
+
return evaluate_workspace(evaluator, stripped)
|
| 1291 |
+
except (OSError, ValueError):
|
| 1292 |
+
# Python/platform versions differ on ENAMETOOLONG and invalid
|
| 1293 |
+
# path errors. It is still candidate text: parse it unchanged.
|
| 1294 |
+
pass
|
| 1295 |
+
try:
|
| 1296 |
+
with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
|
| 1297 |
+
materialize_bundle(candidate, temp)
|
| 1298 |
+
return evaluate_workspace(evaluator, temp)
|
| 1299 |
+
except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
|
| 1300 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def self_test_workspace_evaluator(evaluator):
|
| 1304 |
+
correct = reference_bundle(evaluator)
|
| 1305 |
+
ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
|
| 1306 |
+
rows = list(correct.get("files") or [])
|
| 1307 |
+
perturbed = {"files": rows[1:] if len(rows) > 1 else []}
|
| 1308 |
+
ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
|
| 1309 |
+
mutations = []
|
| 1310 |
+
# Exact JSON fields must each matter, not merely the file's existence.
|
| 1311 |
+
for check in evaluator.get("checks") or []:
|
| 1312 |
+
if check.get("type") != "json_exact":
|
| 1313 |
+
continue
|
| 1314 |
+
for path, value in _flatten(check.get("expected")):
|
| 1315 |
+
candidate = copy.deepcopy(correct)
|
| 1316 |
+
file_row = next(row for row in candidate["files"]
|
| 1317 |
+
if row["path"] == check["path"])
|
| 1318 |
+
data = json.loads(file_row["content"])
|
| 1319 |
+
replacement = (not value if isinstance(value, bool) else
|
| 1320 |
+
value + 1 if isinstance(value, (int, float)) else
|
| 1321 |
+
str(value) + "__mutation__")
|
| 1322 |
+
if not path:
|
| 1323 |
+
data = replacement
|
| 1324 |
+
else:
|
| 1325 |
+
container = data
|
| 1326 |
+
for key in path[:-1]:
|
| 1327 |
+
container = container[key]
|
| 1328 |
+
container[path[-1]] = replacement
|
| 1329 |
+
file_row["content"] = json.dumps(data)
|
| 1330 |
+
passed, _ = evaluate_candidate(evaluator, candidate)
|
| 1331 |
+
mutations.append({"path": check["path"], "field": list(path),
|
| 1332 |
+
"rejected": not passed})
|
| 1333 |
+
return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
|
| 1334 |
+
"correct": correct_detail,
|
| 1335 |
+
"perturbed": wrong_detail,
|
| 1336 |
+
"scalar_mutations": mutations,
|
| 1337 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/shell_invocations.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A deliberately bounded, non-executing shell structure recognizer.
|
| 2 |
+
|
| 3 |
+
Supports simple commands, literal scalar assignments, one command substitution
|
| 4 |
+
on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
|
| 5 |
+
It does not interpret shell code or credit commands in branch bodies/functions.
|
| 6 |
+
Pipelines, command lists, substitutions within substitutions, and swallowed
|
| 7 |
+
failures are outside this grammar. bash -n remains a separate required check.
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
import shlex
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _statements(text):
|
| 14 |
+
out, current = [], []
|
| 15 |
+
quote, escaped, comment, depth = None, False, False, 0
|
| 16 |
+
for ch in str(text):
|
| 17 |
+
if comment:
|
| 18 |
+
if ch == '\n':
|
| 19 |
+
comment = False
|
| 20 |
+
else:
|
| 21 |
+
continue
|
| 22 |
+
if escaped:
|
| 23 |
+
if ch != '\n':
|
| 24 |
+
current.extend(('\\', ch))
|
| 25 |
+
escaped = False
|
| 26 |
+
continue
|
| 27 |
+
if ch == '\\' and quote != "'":
|
| 28 |
+
escaped = True
|
| 29 |
+
continue
|
| 30 |
+
if quote:
|
| 31 |
+
current.append(ch)
|
| 32 |
+
if ch == quote:
|
| 33 |
+
quote = None
|
| 34 |
+
continue
|
| 35 |
+
if ch in "'\"":
|
| 36 |
+
quote = ch
|
| 37 |
+
current.append(ch)
|
| 38 |
+
elif ch == '#' and (not current or current[-1].isspace()):
|
| 39 |
+
comment = True
|
| 40 |
+
elif ch == '(':
|
| 41 |
+
depth += 1
|
| 42 |
+
current.append(ch)
|
| 43 |
+
elif ch == ')':
|
| 44 |
+
depth -= 1
|
| 45 |
+
if depth < 0:
|
| 46 |
+
return []
|
| 47 |
+
current.append(ch)
|
| 48 |
+
elif ch in '\n;' and depth == 0:
|
| 49 |
+
value = ''.join(current).strip()
|
| 50 |
+
if value:
|
| 51 |
+
out.append(value)
|
| 52 |
+
current = []
|
| 53 |
+
else:
|
| 54 |
+
current.append(ch)
|
| 55 |
+
if quote or escaped or depth:
|
| 56 |
+
return []
|
| 57 |
+
if ''.join(current).strip():
|
| 58 |
+
out.append(''.join(current).strip())
|
| 59 |
+
expanded = []
|
| 60 |
+
for statement in out:
|
| 61 |
+
inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
|
| 62 |
+
expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
|
| 63 |
+
return expanded
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _simple_argv(text):
|
| 67 |
+
if '$(' in text or '`' in text:
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
|
| 71 |
+
lexer.whitespace_split = True
|
| 72 |
+
tokens = list(lexer)
|
| 73 |
+
except ValueError:
|
| 74 |
+
return None
|
| 75 |
+
argv, index = [], 0
|
| 76 |
+
redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
|
| 77 |
+
while index < len(tokens):
|
| 78 |
+
token = tokens[index]
|
| 79 |
+
if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
|
| 80 |
+
index += 1
|
| 81 |
+
token = tokens[index]
|
| 82 |
+
if token in redirects:
|
| 83 |
+
if index + 1 >= len(tokens):
|
| 84 |
+
return None
|
| 85 |
+
target = tokens[index + 1]
|
| 86 |
+
if (not target or any(c in target for c in '$`;&|<>()')
|
| 87 |
+
or target in ('{', '}')):
|
| 88 |
+
return None
|
| 89 |
+
index += 2
|
| 90 |
+
continue
|
| 91 |
+
if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
|
| 92 |
+
return None
|
| 93 |
+
argv.append(token)
|
| 94 |
+
index += 1
|
| 95 |
+
return argv or None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _invocation(text):
|
| 99 |
+
substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
|
| 100 |
+
if substitution:
|
| 101 |
+
inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
|
| 102 |
+
argv = _simple_argv(inner)
|
| 103 |
+
return (argv, 'assignment_substitution') if argv else (None, None)
|
| 104 |
+
return _simple_argv(text), 'simple'
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _guard_end(statements, start):
|
| 108 |
+
depth = 1
|
| 109 |
+
for index in range(start + 1, len(statements)):
|
| 110 |
+
item = statements[index]
|
| 111 |
+
if re.match(r'^if\s', item):
|
| 112 |
+
depth += 1
|
| 113 |
+
elif item == 'fi':
|
| 114 |
+
depth -= 1
|
| 115 |
+
if depth == 0:
|
| 116 |
+
return index
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _nonzero_exit_body(statements):
|
| 121 |
+
"""Only literal logging followed by a final unconditional nonzero exit."""
|
| 122 |
+
if not statements:
|
| 123 |
+
return False
|
| 124 |
+
for index, statement in enumerate(statements):
|
| 125 |
+
argv = _simple_argv(statement)
|
| 126 |
+
if not argv:
|
| 127 |
+
return False
|
| 128 |
+
if argv[0] == 'exit':
|
| 129 |
+
return (index == len(statements) - 1 and len(argv) == 2
|
| 130 |
+
and argv[1].isdigit() and 1 <= int(argv[1]) <= 255)
|
| 131 |
+
if argv[0] not in ('echo', 'printf'):
|
| 132 |
+
return False
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _expand_known_variables(text, constants):
|
| 138 |
+
"""Preserve quote/escape expansion semantics in the bounded shell grammar.
|
| 139 |
+
|
| 140 |
+
Active unknown variables stay symbolic. A quoted/escaped literal dollar or
|
| 141 |
+
tilde has a separate token, so it cannot satisfy an expanding shell call.
|
| 142 |
+
This is parsing only; no shell command is evaluated.
|
| 143 |
+
"""
|
| 144 |
+
out,quote,i=[],None,0
|
| 145 |
+
variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 146 |
+
while i<len(text):
|
| 147 |
+
ch=text[i]
|
| 148 |
+
if ch=='\\' and quote!="'" and i+1<len(text):
|
| 149 |
+
nxt=text[i+1]
|
| 150 |
+
if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__')
|
| 151 |
+
elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__')
|
| 152 |
+
else:out.extend((ch,nxt))
|
| 153 |
+
i+=2;continue
|
| 154 |
+
if ch in "'\"":
|
| 155 |
+
if quote is None:quote=ch
|
| 156 |
+
elif quote==ch:quote=None
|
| 157 |
+
out.append(ch);i+=1;continue
|
| 158 |
+
if ch=='$':
|
| 159 |
+
if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue
|
| 160 |
+
m=variable.match(text,i)
|
| 161 |
+
if m:
|
| 162 |
+
value=constants.get(m.group(1)or m.group(2))
|
| 163 |
+
if value is None:out.append(m.group(0))
|
| 164 |
+
elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$'))
|
| 165 |
+
else:out.append(value)
|
| 166 |
+
i=m.end();continue
|
| 167 |
+
if ch=='~' and quote is not None:
|
| 168 |
+
out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue
|
| 169 |
+
out.append(ch);i+=1
|
| 170 |
+
return ''.join(out)
|
| 171 |
+
|
| 172 |
+
def shell_invocations(text):
|
| 173 |
+
"""Return ordered, actually evaluated invocation nodes in the supported subset.
|
| 174 |
+
|
| 175 |
+
fail_fast is a structural proof: a simple command/assignment runs under
|
| 176 |
+
errexit, or a negated test exits nonzero on failure. This is not a complete
|
| 177 |
+
shell interpreter, and unsupported syntax earns no invocation credit.
|
| 178 |
+
"""
|
| 179 |
+
statements = _statements(text)
|
| 180 |
+
# Function definitions or dynamic shell mutation can shadow the command or
|
| 181 |
+
# `exit` itself. They are outside this objective subset, even if uncalled.
|
| 182 |
+
if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s)
|
| 183 |
+
or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
|
| 184 |
+
for s in statements):
|
| 185 |
+
return []
|
| 186 |
+
constants, result, index, errexit = {}, [], 0, False
|
| 187 |
+
assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
|
| 188 |
+
variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 189 |
+
while index < len(statements):
|
| 190 |
+
statement = statements[index]
|
| 191 |
+
literal = assignment.fullmatch(statement)
|
| 192 |
+
if literal:
|
| 193 |
+
constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
|
| 194 |
+
index += 1
|
| 195 |
+
continue
|
| 196 |
+
statement = _expand_known_variables(statement, constants)
|
| 197 |
+
setting = _simple_argv(statement)
|
| 198 |
+
if setting and setting[0] == 'set':
|
| 199 |
+
flag_index = 1
|
| 200 |
+
while flag_index < len(setting):
|
| 201 |
+
flag = setting[flag_index]
|
| 202 |
+
if flag == '--' or not flag.startswith(('-', '+')):
|
| 203 |
+
break # Remaining words set positional parameters.
|
| 204 |
+
if not re.fullmatch(r'[-+][eufxEo]+', flag):
|
| 205 |
+
return [] # e.g. `set -n` suppresses execution entirely.
|
| 206 |
+
if 'e' in flag[1:]:
|
| 207 |
+
errexit = flag[0] == '-'
|
| 208 |
+
if 'o' in flag[1:]:
|
| 209 |
+
if flag_index + 1 >= len(setting):
|
| 210 |
+
return []
|
| 211 |
+
option = setting[flag_index + 1]
|
| 212 |
+
if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
|
| 213 |
+
return []
|
| 214 |
+
if option == 'errexit':
|
| 215 |
+
errexit = flag[0] == '-'
|
| 216 |
+
flag_index += 1
|
| 217 |
+
flag_index += 1
|
| 218 |
+
index += 1
|
| 219 |
+
continue
|
| 220 |
+
if re.match(r'^if\s', statement):
|
| 221 |
+
end = _guard_end(statements, index)
|
| 222 |
+
if end is None:
|
| 223 |
+
return []
|
| 224 |
+
negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
|
| 225 |
+
if (negated and index + 1 < end
|
| 226 |
+
and statements[index + 1] == 'then'
|
| 227 |
+
and _nonzero_exit_body(statements[index + 2:end])):
|
| 228 |
+
argv, kind = _invocation(negated.group(1).strip())
|
| 229 |
+
if argv:
|
| 230 |
+
if argv[0] == 'false':
|
| 231 |
+
break
|
| 232 |
+
result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
|
| 233 |
+
'fail_fast': True, 'statement_index': index})
|
| 234 |
+
else:
|
| 235 |
+
return []
|
| 236 |
+
else:
|
| 237 |
+
# Arbitrary conditions may terminate the script or shadow its
|
| 238 |
+
# commands. Do not infer a reachable suffix through them.
|
| 239 |
+
return []
|
| 240 |
+
# Bodies are never credited and may have assigned local variables.
|
| 241 |
+
constants.clear()
|
| 242 |
+
index = end + 1
|
| 243 |
+
continue
|
| 244 |
+
if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
|
| 245 |
+
# Unsupported compounds are not searched for command substrings.
|
| 246 |
+
return []
|
| 247 |
+
argv, kind = _invocation(statement)
|
| 248 |
+
if not argv:
|
| 249 |
+
# An unparsed statement may change control flow or shell state.
|
| 250 |
+
# Skipping it would incorrectly credit an unreachable suffix.
|
| 251 |
+
return []
|
| 252 |
+
if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare',
|
| 253 |
+
'typeset', 'local', 'read', 'mapfile', 'readarray',
|
| 254 |
+
'unset', 'readonly', '[', '[[', 'test'):
|
| 255 |
+
return []
|
| 256 |
+
if argv[0] == 'exit' or (argv[0] == 'false' and errexit):
|
| 257 |
+
break
|
| 258 |
+
if kind == 'assignment_substitution':
|
| 259 |
+
assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
|
| 260 |
+
if assigned:
|
| 261 |
+
constants.pop(assigned.group(1), None)
|
| 262 |
+
result.append({'command': shlex.join(argv), 'kind': kind,
|
| 263 |
+
'fail_fast': errexit, 'statement_index': index})
|
| 264 |
+
index += 1
|
| 265 |
+
return result
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/test.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}}
|
| 4 |
+
if [[ -z "$candidate" ]]; then
|
| 5 |
+
echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2
|
| 6 |
+
exit 64
|
| 7 |
+
fi
|
| 8 |
+
python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate"
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/evaluator/legacy_tests/verifiers.py
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verifier execution engine and fail-closed self-tests.
|
| 2 |
+
|
| 3 |
+
New verified tasks use atomic_json (complete shape plus scalar assertions).
|
| 4 |
+
Legacy verifier types remain readable so historical runs can still be audited.
|
| 5 |
+
自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import posixpath
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 16 |
+
reference_bundle,
|
| 17 |
+
self_test_workspace_evaluator)
|
| 18 |
+
except ImportError: # portable task copies these modules beside each other
|
| 19 |
+
from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 20 |
+
reference_bundle,
|
| 21 |
+
self_test_workspace_evaluator)
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger("pipeline")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _norm(s):
|
| 27 |
+
return str(s).strip().lower()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _json_value(value):
|
| 31 |
+
"""Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
|
| 32 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 33 |
+
return value
|
| 34 |
+
text = str(value).strip()
|
| 35 |
+
match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
|
| 36 |
+
if match:
|
| 37 |
+
text = match.group(1).strip()
|
| 38 |
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
|
| 39 |
+
text = re.sub(r"\s*```$", "", text)
|
| 40 |
+
start_obj, start_arr = text.find("{"), text.find("[")
|
| 41 |
+
starts = [x for x in (start_obj, start_arr) if x >= 0]
|
| 42 |
+
if starts:
|
| 43 |
+
start = min(starts)
|
| 44 |
+
closing = "}" if text[start] == "{" else "]"
|
| 45 |
+
end = text.rfind(closing)
|
| 46 |
+
if end >= start:
|
| 47 |
+
text = text[start:end + 1]
|
| 48 |
+
return json.loads(text)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _strict_json_value(value):
|
| 53 |
+
"""Atomic answer contract: one complete JSON value, no extra prose/keys."""
|
| 54 |
+
def unique(pairs):
|
| 55 |
+
d={}
|
| 56 |
+
for k,v in pairs:
|
| 57 |
+
if k in d:raise ValueError('duplicate JSON key: '+k)
|
| 58 |
+
d[k]=v
|
| 59 |
+
return d
|
| 60 |
+
def invalid(s):raise ValueError('non-finite JSON number: '+s)
|
| 61 |
+
result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
|
| 62 |
+
if isinstance(value,str) else value)
|
| 63 |
+
def finite(v):
|
| 64 |
+
if isinstance(v,dict):return all(finite(x)for x in v.values())
|
| 65 |
+
if isinstance(v,list):return all(finite(x)for x in v)
|
| 66 |
+
return not isinstance(v,float)or math.isfinite(v)
|
| 67 |
+
if not finite(result):raise ValueError('non-finite JSON number')
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
def _path_equal(actual, expected):
|
| 71 |
+
if not isinstance(actual,str)or not isinstance(expected,str):return False
|
| 72 |
+
# A trailing slash is not a harmless spelling for a named file.
|
| 73 |
+
suffix=posixpath.splitext(expected.rstrip('/'))[1]
|
| 74 |
+
if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
|
| 75 |
+
return _path_value(actual)==_path_value(expected)
|
| 76 |
+
|
| 77 |
+
def _canonical_json(value):
|
| 78 |
+
if isinstance(value, dict):
|
| 79 |
+
return {key: _canonical_json(value[key]) for key in sorted(value)}
|
| 80 |
+
if isinstance(value, list):
|
| 81 |
+
values = [_canonical_json(item) for item in value]
|
| 82 |
+
return sorted(values, key=lambda item: json.dumps(
|
| 83 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 84 |
+
return value
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _atomic_prepare(value, list_order):
|
| 88 |
+
if isinstance(value, dict):
|
| 89 |
+
return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
|
| 90 |
+
if isinstance(value, list):
|
| 91 |
+
values = [_atomic_prepare(item, list_order) for item in value]
|
| 92 |
+
if list_order == "unordered":
|
| 93 |
+
values.sort(key=lambda item: json.dumps(
|
| 94 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 95 |
+
return values
|
| 96 |
+
return value
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _atomic_shape(value):
|
| 100 |
+
if isinstance(value, dict):
|
| 101 |
+
return {"type": "object", "keys": {
|
| 102 |
+
key: _atomic_shape(item) for key, item in value.items()}}
|
| 103 |
+
if isinstance(value, list):
|
| 104 |
+
return {"type": "array", "length": len(value),
|
| 105 |
+
"items": [_atomic_shape(item) for item in value]}
|
| 106 |
+
if isinstance(value, bool):
|
| 107 |
+
return {"type": "boolean"}
|
| 108 |
+
if value is None:
|
| 109 |
+
return {"type": "null"}
|
| 110 |
+
if isinstance(value, (int, float)):
|
| 111 |
+
return {"type": "number"}
|
| 112 |
+
return {"type": "string"}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _atomic_leaves(value, path="$", tokens=()):
|
| 116 |
+
if isinstance(value, dict):
|
| 117 |
+
out = []
|
| 118 |
+
for key, item in value.items():
|
| 119 |
+
out.extend(_atomic_leaves(
|
| 120 |
+
item, path + "." + key, tokens + (key,)))
|
| 121 |
+
return out
|
| 122 |
+
if isinstance(value, list):
|
| 123 |
+
out = []
|
| 124 |
+
for index, item in enumerate(value):
|
| 125 |
+
out.extend(_atomic_leaves(
|
| 126 |
+
item, f"{path}[{index}]", tokens + (index,)))
|
| 127 |
+
return out
|
| 128 |
+
return [(path, tokens, value)]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _normalize_path_equivalence_tokens(values):
|
| 132 |
+
"""Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
|
| 133 |
+
normalized = []
|
| 134 |
+
for tokens in values or []:
|
| 135 |
+
if (not isinstance(tokens, (list, tuple)) or not tokens or
|
| 136 |
+
any(not isinstance(token, (str, int)) for token in tokens)):
|
| 137 |
+
raise ValueError("path equivalence tokens must be non-empty JSON paths")
|
| 138 |
+
item = list(tokens)
|
| 139 |
+
if item not in normalized:
|
| 140 |
+
normalized.append(item)
|
| 141 |
+
return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _path_value(value):
|
| 145 |
+
"""Normalize only portable path spelling, not general answer text."""
|
| 146 |
+
if not isinstance(value, str):
|
| 147 |
+
return None
|
| 148 |
+
text = value.strip().replace("\\", "/")
|
| 149 |
+
text = posixpath.normpath(text) if text else text
|
| 150 |
+
if text != "/":
|
| 151 |
+
text = text.rstrip("/")
|
| 152 |
+
return text
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
|
| 156 |
+
path_equivalence_tokens=None):
|
| 157 |
+
"""Freeze a complete JSON shape plus one assertion for every scalar leaf."""
|
| 158 |
+
if list_order not in {"ordered", "unordered"}:
|
| 159 |
+
raise ValueError(f"unsupported atomic list_order: {list_order}")
|
| 160 |
+
tolerance = float(float_tolerance)
|
| 161 |
+
prepared = _atomic_prepare(_json_value(expected), list_order)
|
| 162 |
+
path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
|
| 163 |
+
assertions = []
|
| 164 |
+
for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
|
| 165 |
+
assertion = {"id": f"leaf_{index:03d}", "path": path,
|
| 166 |
+
"tokens": list(tokens), "operator": "eq", "expected": value}
|
| 167 |
+
if isinstance(value, float):
|
| 168 |
+
assertion.update({"operator": "abs_diff", "tolerance": tolerance})
|
| 169 |
+
elif list(tokens) in path_tokens:
|
| 170 |
+
if not isinstance(value, str):
|
| 171 |
+
raise ValueError("path equivalence can only target string leaves")
|
| 172 |
+
assertion["operator"] = "path_eq"
|
| 173 |
+
assertions.append(assertion)
|
| 174 |
+
compiled = {
|
| 175 |
+
"type": "atomic_json", "version": 2 if path_tokens else 1,
|
| 176 |
+
"list_order": list_order,
|
| 177 |
+
"float_tolerance": tolerance,
|
| 178 |
+
"completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
|
| 179 |
+
"assertions": assertions,
|
| 180 |
+
}
|
| 181 |
+
if path_tokens:
|
| 182 |
+
compiled["path_equivalence_tokens"] = path_tokens
|
| 183 |
+
return compiled
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _shape_differences(expected, actual, path="$"):
|
| 187 |
+
if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
|
| 188 |
+
return [f"{path}: expected {expected.get('type')}, got "
|
| 189 |
+
f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
|
| 190 |
+
kind = expected.get("type")
|
| 191 |
+
if kind == "object":
|
| 192 |
+
expected_keys = set((expected.get("keys") or {}))
|
| 193 |
+
actual_keys = set((actual.get("keys") or {}))
|
| 194 |
+
differences = [f"{path}: missing key {key}" for key in sorted(
|
| 195 |
+
expected_keys - actual_keys)]
|
| 196 |
+
differences.extend(f"{path}: extra key {key}" for key in sorted(
|
| 197 |
+
actual_keys - expected_keys))
|
| 198 |
+
for key in sorted(expected_keys & actual_keys):
|
| 199 |
+
differences.extend(_shape_differences(
|
| 200 |
+
expected["keys"][key], actual["keys"][key], path + "." + key))
|
| 201 |
+
return differences
|
| 202 |
+
if kind == "array":
|
| 203 |
+
differences = []
|
| 204 |
+
if actual.get("length") != expected.get("length"):
|
| 205 |
+
differences.append(
|
| 206 |
+
f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
|
| 207 |
+
for index, (expected_item, actual_item) in enumerate(zip(
|
| 208 |
+
expected.get("items") or [], actual.get("items") or [])):
|
| 209 |
+
differences.extend(_shape_differences(
|
| 210 |
+
expected_item, actual_item, f"{path}[{index}]"))
|
| 211 |
+
return differences
|
| 212 |
+
return []
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _atomic_get(value, tokens):
|
| 216 |
+
current = value
|
| 217 |
+
for token in tokens:
|
| 218 |
+
current = current[token]
|
| 219 |
+
return current
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _int_values(value):
|
| 223 |
+
if isinstance(value, (list, tuple)):
|
| 224 |
+
out = []
|
| 225 |
+
for item in value:
|
| 226 |
+
out.extend(_int_values(item))
|
| 227 |
+
return out
|
| 228 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 229 |
+
return [value]
|
| 230 |
+
return [int(number) for number in re.findall(r"\d+", str(value or ""))]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _finding_type(value):
|
| 234 |
+
text = str(value or "").lower().replace("-", "_")
|
| 235 |
+
if "duplicate" in text:
|
| 236 |
+
return "duplicate_rows"
|
| 237 |
+
if ("none" in text or "null" in text) and "check" in text:
|
| 238 |
+
return "none_check"
|
| 239 |
+
if "missing" in text or "empty" in text or "null" in text:
|
| 240 |
+
return "missing"
|
| 241 |
+
if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
|
| 242 |
+
return "outlier"
|
| 243 |
+
if "invalid" in text and "config" in text:
|
| 244 |
+
return "invalid_config"
|
| 245 |
+
if "off" in text and "one" in text:
|
| 246 |
+
return "off_by_one"
|
| 247 |
+
return text.strip().replace(" ", "_")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _normalized_findings(value, family):
|
| 251 |
+
obj = _json_value(value)
|
| 252 |
+
findings = obj.get("findings") if isinstance(obj, dict) else None
|
| 253 |
+
if not isinstance(findings, list):
|
| 254 |
+
raise ValueError("answer must contain a findings array")
|
| 255 |
+
normalized = set()
|
| 256 |
+
for finding in findings:
|
| 257 |
+
if not isinstance(finding, dict):
|
| 258 |
+
raise ValueError("each finding must be an object")
|
| 259 |
+
# The public contract uses type/function. Accept common semantically
|
| 260 |
+
# equivalent aliases as a robustness layer, while still comparing the
|
| 261 |
+
# normalized values and exact locations against generator-owned GT.
|
| 262 |
+
kind = _finding_type(finding.get("type", finding.get(
|
| 263 |
+
"defect_type", finding.get("defect"))))
|
| 264 |
+
if family == "csv":
|
| 265 |
+
if kind == "duplicate_rows":
|
| 266 |
+
rows = _int_values(finding.get("rows", finding.get("row")))
|
| 267 |
+
if len(rows) != 2:
|
| 268 |
+
raise ValueError("duplicate finding requires exactly two row numbers")
|
| 269 |
+
normalized.add((kind, *sorted(rows)))
|
| 270 |
+
elif kind in {"missing", "outlier"}:
|
| 271 |
+
rows = _int_values(finding.get("row"))
|
| 272 |
+
column = str(finding.get("column") or "").strip().lower()
|
| 273 |
+
if len(rows) != 1 or not column:
|
| 274 |
+
raise ValueError(f"{kind} requires one row and column")
|
| 275 |
+
normalized.add((kind, rows[0], column))
|
| 276 |
+
else:
|
| 277 |
+
raise ValueError(f"unsupported CSV finding type: {kind}")
|
| 278 |
+
elif family == "config":
|
| 279 |
+
if kind != "invalid_config":
|
| 280 |
+
raise ValueError(f"unsupported config finding type: {kind}")
|
| 281 |
+
normalized.add((kind, str(finding.get("path") or "").lower(),
|
| 282 |
+
json.dumps(finding.get("value"), sort_keys=True),
|
| 283 |
+
str(finding.get("expected") or "").lower()))
|
| 284 |
+
elif family == "code":
|
| 285 |
+
if kind not in {"off_by_one", "none_check"}:
|
| 286 |
+
raise ValueError(f"unsupported code finding type: {kind}")
|
| 287 |
+
function = finding.get("function", finding.get("function_name"))
|
| 288 |
+
function = str(function or "").strip().lower()
|
| 289 |
+
if not function:
|
| 290 |
+
raise ValueError(f"{kind} requires a function")
|
| 291 |
+
normalized.add((kind, function))
|
| 292 |
+
else:
|
| 293 |
+
raise ValueError(f"unsupported findings family: {family}")
|
| 294 |
+
return normalized
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _normalized_facts(value):
|
| 298 |
+
obj = _json_value(value)
|
| 299 |
+
facts = obj.get("facts") if isinstance(obj, dict) else None
|
| 300 |
+
if not isinstance(facts, list):
|
| 301 |
+
raise ValueError("answer must contain a facts array")
|
| 302 |
+
def textual(item):
|
| 303 |
+
# The document generator serializes scalar values as visible text. JSON
|
| 304 |
+
# has no way to infer whether the source token "30" was authored from an
|
| 305 |
+
# integer or a string, so facts_match compares that surface text. Nested
|
| 306 |
+
# values retain structural JSON comparison.
|
| 307 |
+
if isinstance(item, (dict, list)):
|
| 308 |
+
return json.dumps(item, sort_keys=True, ensure_ascii=False,
|
| 309 |
+
separators=(",", ":"))
|
| 310 |
+
if item is None:
|
| 311 |
+
return "None"
|
| 312 |
+
return str(item)
|
| 313 |
+
return {(str(fact.get("key") or ""), textual(fact.get("value")))
|
| 314 |
+
for fact in facts if isinstance(fact, dict)}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def verify(verifier, gt_answer, solver_output, material_paths=None):
|
| 318 |
+
"""执行 verifier。返回 (passed, detail)。"""
|
| 319 |
+
vtype = verifier.get("type")
|
| 320 |
+
try:
|
| 321 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 322 |
+
return evaluate_candidate(verifier, solver_output)
|
| 323 |
+
|
| 324 |
+
if vtype == "json_exact":
|
| 325 |
+
pred = _canonical_json(_json_value(solver_output))
|
| 326 |
+
gold = _canonical_json(_json_value(gt_answer))
|
| 327 |
+
ok = pred == gold
|
| 328 |
+
return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
|
| 329 |
+
|
| 330 |
+
if vtype == "atomic_json":
|
| 331 |
+
pred = _atomic_prepare(_strict_json_value(solver_output),
|
| 332 |
+
verifier.get("list_order", "ordered"))
|
| 333 |
+
compiled = compile_atomic_verifier(
|
| 334 |
+
gt_answer, verifier.get("list_order", "ordered"),
|
| 335 |
+
verifier.get("float_tolerance", 0.01),
|
| 336 |
+
verifier.get("path_equivalence_tokens"))
|
| 337 |
+
frozen = {key: verifier.get(key) for key in
|
| 338 |
+
("type", "version", "list_order", "float_tolerance",
|
| 339 |
+
"completeness", "assertions", "path_equivalence_tokens")}
|
| 340 |
+
expected_frozen = {key: compiled.get(key) for key in frozen}
|
| 341 |
+
if frozen != expected_frozen:
|
| 342 |
+
return False, {"error": "atomic verifier does not match ground truth"}
|
| 343 |
+
shape_failures = _shape_differences(
|
| 344 |
+
verifier["completeness"]["shape"], _atomic_shape(pred))
|
| 345 |
+
assertion_results = []
|
| 346 |
+
for assertion in verifier.get("assertions") or []:
|
| 347 |
+
try:
|
| 348 |
+
actual = _atomic_get(pred, assertion["tokens"])
|
| 349 |
+
if assertion["operator"] == "abs_diff":
|
| 350 |
+
passed = abs(float(actual) - float(assertion["expected"])) <= float(
|
| 351 |
+
assertion.get("tolerance", 0.0))
|
| 352 |
+
elif assertion["operator"] == "path_eq":
|
| 353 |
+
passed = _path_equal(actual, assertion["expected"])
|
| 354 |
+
else:
|
| 355 |
+
passed = (actual is assertion["expected"] if
|
| 356 |
+
isinstance(assertion["expected"], bool) else
|
| 357 |
+
actual == assertion["expected"])
|
| 358 |
+
message = "" if passed else (
|
| 359 |
+
f"actual={actual!r} expected={assertion['expected']!r}")
|
| 360 |
+
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
| 361 |
+
actual, passed, message = None, False, f"lookup/compare failed: {exc}"
|
| 362 |
+
assertion_results.append({
|
| 363 |
+
"id": assertion["id"], "path": assertion["path"],
|
| 364 |
+
"operator": assertion["operator"], "expected": assertion["expected"],
|
| 365 |
+
"actual": actual, "passed": passed, "message": message})
|
| 366 |
+
passed_count = sum(item["passed"] for item in assertion_results)
|
| 367 |
+
ok = not shape_failures and passed_count == len(assertion_results)
|
| 368 |
+
return ok, {
|
| 369 |
+
"type": "atomic_json", "completeness_passed": not shape_failures,
|
| 370 |
+
"completeness_failures": shape_failures,
|
| 371 |
+
"assertions_passed": passed_count,
|
| 372 |
+
"assertions_total": len(assertion_results),
|
| 373 |
+
"assertion_pass_rate": (passed_count / len(assertion_results)
|
| 374 |
+
if assertion_results else 1.0),
|
| 375 |
+
"assertions": assertion_results,
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
if vtype == "findings_match":
|
| 379 |
+
family = verifier.get("family")
|
| 380 |
+
pred = _normalized_findings(solver_output, family)
|
| 381 |
+
gold = _normalized_findings(gt_answer, family)
|
| 382 |
+
ok = pred == gold
|
| 383 |
+
return ok, ("findings_match: pass" if ok else
|
| 384 |
+
f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 385 |
+
|
| 386 |
+
if vtype == "facts_match":
|
| 387 |
+
pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
|
| 388 |
+
ok = pred == gold
|
| 389 |
+
return ok, ("facts_match: pass" if ok else
|
| 390 |
+
f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 391 |
+
|
| 392 |
+
if vtype == "exact_match":
|
| 393 |
+
ok = _norm(solver_output) == _norm(gt_answer)
|
| 394 |
+
return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
|
| 395 |
+
|
| 396 |
+
if vtype == "numeric":
|
| 397 |
+
tol = verifier.get("tolerance") or 1e-6
|
| 398 |
+
pred = float(str(solver_output).strip().split()[0])
|
| 399 |
+
gold = float(gt_answer)
|
| 400 |
+
ok = abs(pred - gold) <= tol
|
| 401 |
+
return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
|
| 402 |
+
|
| 403 |
+
if vtype == "set_match":
|
| 404 |
+
pred = set(_as_list(solver_output))
|
| 405 |
+
gold = set(_as_list(gt_answer))
|
| 406 |
+
ok = pred == gold
|
| 407 |
+
return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
|
| 408 |
+
|
| 409 |
+
if vtype == "structured_match":
|
| 410 |
+
pred = _json_value(solver_output)
|
| 411 |
+
gold = _json_value(gt_answer)
|
| 412 |
+
if not isinstance(pred, dict) or not isinstance(gold, dict):
|
| 413 |
+
return False, "structured_match requires JSON objects"
|
| 414 |
+
missing = [f for f in verifier.get("required_fields", []) if f not in pred]
|
| 415 |
+
wrong = [f for f in verifier.get("required_fields", [])
|
| 416 |
+
if f in pred and f in gold and pred[f] != gold[f]]
|
| 417 |
+
ok = not missing and not wrong
|
| 418 |
+
return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
|
| 419 |
+
|
| 420 |
+
if vtype == "execution":
|
| 421 |
+
return False, "execution verifier is disabled in verified-first v2"
|
| 422 |
+
|
| 423 |
+
if vtype == "constraint":
|
| 424 |
+
fails = _check_constraints(verifier.get("criteria", []), solver_output)
|
| 425 |
+
return not fails, f"constraint: failed={fails[:5]}"
|
| 426 |
+
|
| 427 |
+
if vtype == "file_inspection":
|
| 428 |
+
fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
|
| 429 |
+
return not fails, f"file_inspection: failed={fails[:5]}"
|
| 430 |
+
|
| 431 |
+
return False, f"unknown verifier type: {vtype}"
|
| 432 |
+
except Exception as e:
|
| 433 |
+
return False, f"verifier error: {e}"
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def _as_list(x):
|
| 437 |
+
if isinstance(x, list):
|
| 438 |
+
return [_norm(i) for i in x]
|
| 439 |
+
# 逗号/换行分隔的字符串
|
| 440 |
+
return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _check_constraints(criteria, solver_output):
|
| 444 |
+
"""criteria: ["must contain X", "must be valid json", "length <= 500"]"""
|
| 445 |
+
fails = []
|
| 446 |
+
text = str(solver_output)
|
| 447 |
+
for c in criteria:
|
| 448 |
+
cl = c.lower()
|
| 449 |
+
if cl.startswith("must contain "):
|
| 450 |
+
needle = c[len("must contain "):]
|
| 451 |
+
if needle.lower() not in text.lower():
|
| 452 |
+
fails.append(c)
|
| 453 |
+
elif "valid json" in cl:
|
| 454 |
+
try:
|
| 455 |
+
json.loads(text)
|
| 456 |
+
except Exception:
|
| 457 |
+
fails.append(c)
|
| 458 |
+
elif cl.startswith("length <="):
|
| 459 |
+
limit = int(cl.split("<=")[1].strip())
|
| 460 |
+
if len(text) > limit:
|
| 461 |
+
fails.append(c)
|
| 462 |
+
else:
|
| 463 |
+
# Deterministic verifier DSL is closed-world: unknown checks fail.
|
| 464 |
+
fails.append(f"unsupported criterion: {c}")
|
| 465 |
+
return fails
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _inspect_files(expected, material_paths):
|
| 469 |
+
fails = []
|
| 470 |
+
paths = set(material_paths or [])
|
| 471 |
+
for e in expected:
|
| 472 |
+
fname = e.get("filename") if isinstance(e, dict) else str(e)
|
| 473 |
+
if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
|
| 474 |
+
fails.append(f"missing file: {fname}")
|
| 475 |
+
return fails
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# ---------------- 自测 ----------------
|
| 479 |
+
|
| 480 |
+
def build_correct_solution(verifier, gt_answer, planted_info):
|
| 481 |
+
"""由埋点/ground truth 直接构造正确解。"""
|
| 482 |
+
vtype = verifier.get("type")
|
| 483 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 484 |
+
return reference_bundle(verifier)
|
| 485 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
|
| 486 |
+
"set_match", "structured_match"):
|
| 487 |
+
return gt_answer
|
| 488 |
+
if vtype == "constraint":
|
| 489 |
+
parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
|
| 490 |
+
if c.lower().startswith("must contain ")]
|
| 491 |
+
return " ".join(parts) if parts else str(gt_answer)
|
| 492 |
+
# execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
|
| 493 |
+
return None
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def build_perturbed_solution(verifier, gt_answer, planted_info):
|
| 497 |
+
"""破坏埋点构造扰动解。"""
|
| 498 |
+
vtype = verifier.get("type")
|
| 499 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 500 |
+
files = list(reference_bundle(verifier).get("files") or [])
|
| 501 |
+
return {"files": files[1:] if len(files) > 1 else []}
|
| 502 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
|
| 503 |
+
gold = _json_value(gt_answer)
|
| 504 |
+
if isinstance(gold, dict):
|
| 505 |
+
perturbed = dict(gold)
|
| 506 |
+
key = next(iter(perturbed), "__missing__")
|
| 507 |
+
if key in perturbed:
|
| 508 |
+
perturbed.pop(key)
|
| 509 |
+
else:
|
| 510 |
+
perturbed["__wrong__"] = True
|
| 511 |
+
return perturbed
|
| 512 |
+
if isinstance(gold, list):
|
| 513 |
+
return gold[:-1] if gold else ["__wrong__"]
|
| 514 |
+
return "__wrong__"
|
| 515 |
+
if vtype in ("exact_match", "numeric"):
|
| 516 |
+
return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
|
| 517 |
+
if vtype == "set_match":
|
| 518 |
+
gold = _as_list(gt_answer)
|
| 519 |
+
return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
|
| 520 |
+
if vtype == "structured_match":
|
| 521 |
+
fields = verifier.get("required_fields", [])
|
| 522 |
+
return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
|
| 523 |
+
if vtype == "constraint":
|
| 524 |
+
return "perturbed output lacking required content"
|
| 525 |
+
return None
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def self_test(verifier, gt_answer, planted_info, material_paths):
|
| 529 |
+
"""返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
|
| 530 |
+
|
| 531 |
+
之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
|
| 532 |
+
可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
|
| 533 |
+
"""
|
| 534 |
+
if verifier.get("type") == WORKSPACE_EVALUATOR:
|
| 535 |
+
return self_test_workspace_evaluator(verifier)
|
| 536 |
+
correct = build_correct_solution(verifier, gt_answer, planted_info)
|
| 537 |
+
perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
|
| 538 |
+
if correct is None or perturbed is None:
|
| 539 |
+
return False, (f"cannot self-test verifier type {verifier.get('type')} "
|
| 540 |
+
"(execution/file_inspection need real correct/perturbed solutions)")
|
| 541 |
+
ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
|
| 542 |
+
ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
|
| 543 |
+
passed = ok1 and not ok2
|
| 544 |
+
return passed, {"correct": d1, "perturbed": d2}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/grading/verified_config.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "de0d341bc8e13144_q1",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 8 |
+
"legacy-task.json": "9d54c9efda59e9464a0248e03f40555dc08c81ac3c7ff7472abd37785c1c6c06",
|
| 9 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 10 |
+
"autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278",
|
| 11 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 12 |
+
"auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
|
| 13 |
+
"legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
|
| 14 |
+
"legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
|
| 15 |
+
"legacy_tests/objective_evaluators.py": "ca01231938f79d2c66c7a0ba8013bd215d79fe35850d10514fa740c38307b00b",
|
| 16 |
+
"legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc",
|
| 17 |
+
"legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70"
|
| 18 |
+
},
|
| 19 |
+
"runtime_requirements": {
|
| 20 |
+
"candidate_mode": "workspace",
|
| 21 |
+
"candidate_snapshot_copy_to_ephemeral_app": true,
|
| 22 |
+
"container_private_entry": "/grader/check.py",
|
| 23 |
+
"environment": {
|
| 24 |
+
"CANDIDATE_DIR": "/candidate",
|
| 25 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 26 |
+
"MYBENCH_ANSWER": "/answer.txt",
|
| 27 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 28 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 29 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 30 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1",
|
| 31 |
+
"MYBENCH_RUN_METADATA": "/run_metadata.json",
|
| 32 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 33 |
+
"SOURCE_TASK_DIR": "/source"
|
| 34 |
+
},
|
| 35 |
+
"expected_check_ids": [
|
| 36 |
+
"0"
|
| 37 |
+
],
|
| 38 |
+
"external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
|
| 39 |
+
"external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
|
| 40 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 41 |
+
"image_included": false,
|
| 42 |
+
"legacy_adapter": true,
|
| 43 |
+
"mounts_readonly": [
|
| 44 |
+
"/candidate",
|
| 45 |
+
"/source",
|
| 46 |
+
"/grader",
|
| 47 |
+
"/answer.txt"
|
| 48 |
+
],
|
| 49 |
+
"network": "none",
|
| 50 |
+
"original_declared_resources": {
|
| 51 |
+
"agent": {
|
| 52 |
+
"basis": "advisory_not_measured",
|
| 53 |
+
"cpus": 2,
|
| 54 |
+
"memory_mib": 4096,
|
| 55 |
+
"timeout_sec": 1200
|
| 56 |
+
},
|
| 57 |
+
"oracle": {
|
| 58 |
+
"timeout_sec": 120
|
| 59 |
+
},
|
| 60 |
+
"source_agent": {
|
| 61 |
+
"command_timeout_sec": null,
|
| 62 |
+
"max_steps": null
|
| 63 |
+
},
|
| 64 |
+
"verifier": {
|
| 65 |
+
"cpus": 1,
|
| 66 |
+
"memory_mib": 1024,
|
| 67 |
+
"pids": 64,
|
| 68 |
+
"timeout_sec": 900,
|
| 69 |
+
"tmpfs_mib": 128
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
"private_entry": "evaluator/check.py",
|
| 73 |
+
"private_tree_environment_tokens": [
|
| 74 |
+
"MYBENCH_CANDIDATE_FILE",
|
| 75 |
+
"MYBENCH_OPEN_JUDGE_COMMAND",
|
| 76 |
+
"MYBENCH_OPEN_JUDGE_TIMEOUT",
|
| 77 |
+
"MYBENCH_TASK_JSON"
|
| 78 |
+
],
|
| 79 |
+
"trusted_trace_environment_aliases": [
|
| 80 |
+
"MYBENCH_TOOL_TRAJECTORY",
|
| 81 |
+
"MYBENCH_TRUSTED_TRACE",
|
| 82 |
+
"TOOL_TRAJECTORY",
|
| 83 |
+
"TOOL_TRAJECTORY_FILE"
|
| 84 |
+
],
|
| 85 |
+
"trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
|
| 86 |
+
"working_directory": "/candidate",
|
| 87 |
+
"writable_ephemeral_roots": [
|
| 88 |
+
"/app",
|
| 89 |
+
"/workspace",
|
| 90 |
+
"/tmp"
|
| 91 |
+
],
|
| 92 |
+
"criterion_weights": {
|
| 93 |
+
"0": 1
|
| 94 |
+
},
|
| 95 |
+
"grader_timeout_seconds": 600,
|
| 96 |
+
"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."
|
| 97 |
+
},
|
| 98 |
+
"engine": "portable_verified_v1"
|
| 99 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/SKILL.md
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: engagelab-sms
|
| 3 |
+
description: >
|
| 4 |
+
Call EngageLab SMS REST APIs to send SMS messages and manage SMS templates and
|
| 5 |
+
signatures (sender IDs). Use this skill whenever the user wants to send an SMS
|
| 6 |
+
via EngageLab, create or manage SMS templates, configure sender ID signatures,
|
| 7 |
+
or interact with any EngageLab SMS API endpoint. Also trigger when the user
|
| 8 |
+
mentions "engagelab", "engagelab sms", "sms api", "send sms via api",
|
| 9 |
+
"sms template management", "sender id", "sign config", or asks to integrate
|
| 10 |
+
with the EngageLab messaging platform. This skill covers authentication,
|
| 11 |
+
message sending, template CRUD, and signature CRUD — use it even if the user
|
| 12 |
+
only needs one of these capabilities.
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# EngageLab SMS API Skill
|
| 16 |
+
|
| 17 |
+
This skill enables you to interact with the EngageLab SMS REST API. It covers three areas:
|
| 18 |
+
|
| 19 |
+
1. **Send SMS** — Send notification or marketing SMS to one or more recipients
|
| 20 |
+
2. **Template Management** — Create, read, update, and delete SMS templates
|
| 21 |
+
3. **Signature (Sender ID) Management** — Create, read, update, and delete sender ID signatures
|
| 22 |
+
|
| 23 |
+
## Resources
|
| 24 |
+
|
| 25 |
+
### scripts/
|
| 26 |
+
|
| 27 |
+
- **`sms_client.py`** — Python client class (`EngageLabSMS`) wrapping all API endpoints: `send_sms()` (immediate and scheduled), template CRUD (`list_templates()`, `get_template()`, `create_template()`, `update_template()`, `delete_template()`), and signature CRUD (`list_signatures()`, `get_signature()`, `create_signature()`, `update_signature()`, `delete_signature()`). Handles authentication, request construction, and typed error handling. Use as a ready-to-run helper or import into the user's project.
|
| 28 |
+
|
| 29 |
+
### references/
|
| 30 |
+
|
| 31 |
+
- **`template-and-signature-api.md`** — Full request/response field specs for all template and signature endpoints
|
| 32 |
+
- **`error-codes.md`** — Complete error code tables for SMS sending and template/signature operations
|
| 33 |
+
|
| 34 |
+
## Authentication
|
| 35 |
+
|
| 36 |
+
All EngageLab SMS API calls use **HTTP Basic Authentication**.
|
| 37 |
+
|
| 38 |
+
- **Base URL**: `https://smsapi.engagelab.com`
|
| 39 |
+
- **Header**: `Authorization: Basic <base64(dev_key:dev_secret)>`
|
| 40 |
+
- **Content-Type**: `application/json`
|
| 41 |
+
|
| 42 |
+
The user must provide their `dev_key` and `dev_secret` (also called `apikey` and `apisecret`). Encode them as `base64("dev_key:dev_secret")` and set the `Authorization` header.
|
| 43 |
+
|
| 44 |
+
**Example** (using curl):
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
curl -X POST https://smsapi.engagelab.com/v1/messages \
|
| 48 |
+
-H "Content-Type: application/json" \
|
| 49 |
+
-H "Authorization: Basic $(echo -n 'YOUR_DEV_KEY:YOUR_DEV_SECRET' | base64)" \
|
| 50 |
+
-d '{ ... }'
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
If the user hasn't provided credentials, ask them for their `dev_key` and `dev_secret` before generating API calls.
|
| 54 |
+
|
| 55 |
+
## Quick Reference — All Endpoints
|
| 56 |
+
|
| 57 |
+
| Operation | Method | Path |
|
| 58 |
+
|-----------|--------|------|
|
| 59 |
+
| Send SMS | `POST` | `/v1/messages` |
|
| 60 |
+
| List templates | `GET` | `/v1/template-configs` |
|
| 61 |
+
| Get template | `GET` | `/v1/template-configs/:templateId` |
|
| 62 |
+
| Create template | `POST` | `/v1/template-configs` |
|
| 63 |
+
| Update template | `PUT` | `/v1/template-configs/:templateId` |
|
| 64 |
+
| Delete template | `DELETE` | `/v1/template-configs/:templateId` |
|
| 65 |
+
| List signatures | `GET` | `/v1/sign-configs` |
|
| 66 |
+
| Get signature | `GET` | `/v1/sign-configs/:signId` |
|
| 67 |
+
| Create signature | `POST` | `/v1/sign-configs` |
|
| 68 |
+
| Update signature | `PUT` | `/v1/sign-configs/:signId` |
|
| 69 |
+
| Delete signature | `DELETE` | `/v1/sign-configs/:signId` |
|
| 70 |
+
|
| 71 |
+
## Sending SMS
|
| 72 |
+
|
| 73 |
+
**Endpoint**: `POST /v1/messages`
|
| 74 |
+
|
| 75 |
+
### Request Body
|
| 76 |
+
|
| 77 |
+
```json
|
| 78 |
+
{
|
| 79 |
+
"to": ["+6591234567"],
|
| 80 |
+
"template": {
|
| 81 |
+
"id": "TEMPLATE_ID",
|
| 82 |
+
"params": {
|
| 83 |
+
"var_name": "value"
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"plan_name": "Optional plan name",
|
| 87 |
+
"schedule_time": 1700000000,
|
| 88 |
+
"custom_args": {}
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
### Parameters
|
| 93 |
+
|
| 94 |
+
| Field | Type | Required | Description |
|
| 95 |
+
|-------|------|----------|-------------|
|
| 96 |
+
| `to` | `string[]` | Yes | Target phone numbers (include country code) |
|
| 97 |
+
| `template.id` | `string` | Yes | ID of an approved SMS template |
|
| 98 |
+
| `template.params` | `object` | Yes | Key-value pairs matching template variables (e.g., `{{name}}` → `{"name": "Bob"}`) |
|
| 99 |
+
| `plan_name` | `string` | No | Plan name, defaults to `"-"` |
|
| 100 |
+
| `schedule_time` | `integer` | No | Unix timestamp for scheduled sends; omit for immediate |
|
| 101 |
+
| `custom_args` | `object` | No | Custom parameters for tracking |
|
| 102 |
+
|
| 103 |
+
### Template Variables
|
| 104 |
+
|
| 105 |
+
If the template contains `{{var}}` placeholders, populate them via `params`. For example, for template content `"Hi {{name}}, your code is {{code}}"`, pass:
|
| 106 |
+
|
| 107 |
+
```json
|
| 108 |
+
"params": { "name": "Alice", "code": "123456" }
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
Unpopulated variables are sent literally as `{{var}}`.
|
| 112 |
+
|
| 113 |
+
### Response
|
| 114 |
+
|
| 115 |
+
**Success (single target)**:
|
| 116 |
+
|
| 117 |
+
```json
|
| 118 |
+
{
|
| 119 |
+
"plan_id": "1972488990548348928",
|
| 120 |
+
"total_count": 1,
|
| 121 |
+
"accepted_count": 1,
|
| 122 |
+
"message_id": "1972488990804201472"
|
| 123 |
+
}
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
**Success (scheduled)**:
|
| 127 |
+
|
| 128 |
+
```json
|
| 129 |
+
{
|
| 130 |
+
"plan_id": "1972492618659033088",
|
| 131 |
+
"total_count": 1,
|
| 132 |
+
"accepted_count": 1,
|
| 133 |
+
"schedule_info": { "task_id": 1972492621368553472 }
|
| 134 |
+
}
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
**Error**: Contains `code` (non-zero) and `message` fields alongside `plan_id`.
|
| 138 |
+
|
| 139 |
+
For the full error code table, read `references/error-codes.md`.
|
| 140 |
+
|
| 141 |
+
## Template Management
|
| 142 |
+
|
| 143 |
+
Templates define the SMS content. Each template must pass review before it can be used for sending.
|
| 144 |
+
|
| 145 |
+
For full request/response details and field descriptions, read `references/template-and-signature-api.md`.
|
| 146 |
+
|
| 147 |
+
### Key Rules
|
| 148 |
+
|
| 149 |
+
- Template content **cannot** contain: `【`, `】`, `、`, `测试`, `test`, `[`, `]`
|
| 150 |
+
- After creation or update, templates enter **Pending Review** status (status=1) and cannot be used until **Approved** (status=2)
|
| 151 |
+
- Templates in Pending Review cannot be updated
|
| 152 |
+
- Templates tied to pending/running message plans cannot be updated or deleted
|
| 153 |
+
- Template types: `utility` (notification), `marketing` (marketing)
|
| 154 |
+
|
| 155 |
+
### CRUD Summary
|
| 156 |
+
|
| 157 |
+
**Create** — `POST /v1/template-configs`
|
| 158 |
+
|
| 159 |
+
```json
|
| 160 |
+
{
|
| 161 |
+
"template_name": "Order Notification",
|
| 162 |
+
"template_type": "utility",
|
| 163 |
+
"template_content": "Your order {order_no} has shipped, arriving by {delivery_time}.",
|
| 164 |
+
"country_codes": "CN,US",
|
| 165 |
+
"add_signature": true,
|
| 166 |
+
"sign_id": "SIGNATURE_ID",
|
| 167 |
+
"sign_position": 2
|
| 168 |
+
}
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
**List all** — `GET /v1/template-configs` (returns array)
|
| 172 |
+
|
| 173 |
+
**Get one** — `GET /v1/template-configs/:templateId`
|
| 174 |
+
|
| 175 |
+
**Update** — `PUT /v1/template-configs/:templateId` (same body as create, all fields required)
|
| 176 |
+
|
| 177 |
+
**Delete** — `DELETE /v1/template-configs/:templateId`
|
| 178 |
+
|
| 179 |
+
## Signature (Sender ID) Management
|
| 180 |
+
|
| 181 |
+
Signatures identify the sender and are attached to templates. They also go through a review process.
|
| 182 |
+
|
| 183 |
+
For full request/response details and field descriptions, read `references/template-and-signature-api.md`.
|
| 184 |
+
|
| 185 |
+
### Key Rules
|
| 186 |
+
|
| 187 |
+
- Signature name: 2–60 characters, cannot contain `【`, `】`, `[`, `]`
|
| 188 |
+
- Names must be unique within the same business
|
| 189 |
+
- After creation or update, signatures enter **Pending Review** (status=1)
|
| 190 |
+
- Signatures in Pending Review cannot be updated
|
| 191 |
+
- Signatures tied to pending/running plans cannot be updated or deleted
|
| 192 |
+
|
| 193 |
+
### CRUD Summary
|
| 194 |
+
|
| 195 |
+
**Create** — `POST /v1/sign-configs`
|
| 196 |
+
|
| 197 |
+
```json
|
| 198 |
+
{ "sign_name": "MyCompany" }
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
**List all** — `GET /v1/sign-configs` (returns array)
|
| 202 |
+
|
| 203 |
+
**Get one** — `GET /v1/sign-configs/:signId`
|
| 204 |
+
|
| 205 |
+
**Update** — `PUT /v1/sign-configs/:signId` (same body as create)
|
| 206 |
+
|
| 207 |
+
**Delete** — `DELETE /v1/sign-configs/:signId`
|
| 208 |
+
|
| 209 |
+
## Generating Code
|
| 210 |
+
|
| 211 |
+
When the user asks to send SMS or manage templates/signatures, generate working code. Default to `curl` unless the user specifies a language. Supported patterns:
|
| 212 |
+
|
| 213 |
+
- **curl** — Shell commands with proper auth header
|
| 214 |
+
- **Python** — Using `requests` library
|
| 215 |
+
- **Node.js** — Using `fetch` or `axios`
|
| 216 |
+
- **Java** — Using `HttpClient`
|
| 217 |
+
- **Go** — Using `net/http`
|
| 218 |
+
|
| 219 |
+
Always include the authentication header and proper error handling. Use placeholder values like `YOUR_DEV_KEY` and `YOUR_DEV_SECRET` if the user hasn't provided credentials.
|
| 220 |
+
|
| 221 |
+
## Status Codes Reference
|
| 222 |
+
|
| 223 |
+
| Value | Template/Signature Status |
|
| 224 |
+
|-------|--------------------------|
|
| 225 |
+
| 1 | Pending Review |
|
| 226 |
+
| 2 | Approved |
|
| 227 |
+
| 3 | Rejected |
|
| 228 |
+
|
| 229 |
+
| Value | Signature Position |
|
| 230 |
+
|-------|-------------------|
|
| 231 |
+
| 0 | No Signature |
|
| 232 |
+
| 1 | Prefix |
|
| 233 |
+
| 2 | Suffix |
|
| 234 |
+
|
| 235 |
+
| Value | Template Type |
|
| 236 |
+
|-------|--------------|
|
| 237 |
+
| `utility` | Notification |
|
| 238 |
+
| `marketing` | Marketing |
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/_export_skill_meta.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"slug": "engagelab-sms",
|
| 3 |
+
"displayName": "EngageLab SMS",
|
| 4 |
+
"sourceRef": "public-clawhub",
|
| 5 |
+
"version": "1.0.1",
|
| 6 |
+
"createdAt": 1773196612813,
|
| 7 |
+
"updatedAt": 1778491820342,
|
| 8 |
+
"stats": {
|
| 9 |
+
"comments": 0,
|
| 10 |
+
"downloads": 831,
|
| 11 |
+
"installsAllTime": 23,
|
| 12 |
+
"installsCurrent": 1,
|
| 13 |
+
"stars": 0,
|
| 14 |
+
"versions": 2
|
| 15 |
+
},
|
| 16 |
+
"owner": {
|
| 17 |
+
"handle": "devengagelab",
|
| 18 |
+
"displayName": "DevEngageLab"
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/references/error-codes.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# EngageLab SMS API Error Codes
|
| 2 |
+
|
| 3 |
+
## SMS Sending Errors
|
| 4 |
+
|
| 5 |
+
| Error Code | HTTP Code | Description |
|
| 6 |
+
|------------|-----------|-------------|
|
| 7 |
+
| 1000 | 500 | Internal Error |
|
| 8 |
+
| 2001 | 401 | Authentication failed — incorrect token |
|
| 9 |
+
| 2002 | 401 | Authentication failed — token expired or disabled |
|
| 10 |
+
| 2004 | 403 | No permission to call this API |
|
| 11 |
+
| 3001 | 400 | Invalid request parameter format (not valid JSON) |
|
| 12 |
+
| 3002 | 400 | Invalid request parameters (do not meet requirements) |
|
| 13 |
+
| 3003 | 400 | Business validation failed — see `message` field for details |
|
| 14 |
+
| 3004 | 400 | Frequency limit exceeded — cannot resend same template to same user within verification code validity period |
|
| 15 |
+
| 4001 | 400 | Resource not found (e.g., non-existent template ID) |
|
| 16 |
+
| 5001 | 400 | Verification code sending failed — see `message` field for details |
|
| 17 |
+
|
| 18 |
+
## Template & Signature Errors
|
| 19 |
+
|
| 20 |
+
| Error Code | HTTP Code | Description |
|
| 21 |
+
|------------|-----------|-------------|
|
| 22 |
+
| 0 | 200 | Success |
|
| 23 |
+
| 400 | 400 | Parameter error or business logic error |
|
| 24 |
+
| 500 | 500 | Internal server error |
|
| 25 |
+
|
| 26 |
+
### Common Error Messages
|
| 27 |
+
|
| 28 |
+
| Message | Meaning |
|
| 29 |
+
|---------|---------|
|
| 30 |
+
| `invalid templateId` | Template ID format is invalid |
|
| 31 |
+
| `template config not exist` | Template does not exist |
|
| 32 |
+
| `invalid signId` | Signature ID format is invalid |
|
| 33 |
+
| `sign config not exist` | Signature does not exist |
|
| 34 |
+
| `sign_name already exist` | Signature name is already taken |
|
| 35 |
+
| `can not update pending status template` | Templates in Pending Review cannot be updated |
|
| 36 |
+
| `can not update pending status sign` | Signatures in Pending Review cannot be updated |
|
| 37 |
+
| `there are pending or running plans using current template, can not update` | Template is in use by active plans |
|
| 38 |
+
| `there are pending or running plans using current sign, can not update` | Signature is in use by active plans |
|
| 39 |
+
| `sign status is not approved, can not use` | Only Approved signatures can be attached to templates |
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/references/template-and-signature-api.md
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Template & Signature API Reference
|
| 2 |
+
|
| 3 |
+
Detailed request/response specifications for template and signature management endpoints.
|
| 4 |
+
|
| 5 |
+
## Table of Contents
|
| 6 |
+
|
| 7 |
+
1. [Template Configuration APIs](#template-configuration-apis)
|
| 8 |
+
- [List Templates](#1-list-templates)
|
| 9 |
+
- [Get Template Details](#2-get-template-details)
|
| 10 |
+
- [Create Template](#3-create-template)
|
| 11 |
+
- [Update Template](#4-update-template)
|
| 12 |
+
- [Delete Template](#5-delete-template)
|
| 13 |
+
2. [Signature Configuration APIs](#signature-configuration-apis)
|
| 14 |
+
- [List Signatures](#1-list-signatures)
|
| 15 |
+
- [Get Signature Details](#2-get-signature-details)
|
| 16 |
+
- [Create Signature](#3-create-signature)
|
| 17 |
+
- [Update Signature](#4-update-signature)
|
| 18 |
+
- [Delete Signature](#5-delete-signature)
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
## Template Configuration APIs
|
| 23 |
+
|
| 24 |
+
### 1. List Templates
|
| 25 |
+
|
| 26 |
+
`GET /v1/template-configs`
|
| 27 |
+
|
| 28 |
+
No request parameters. Returns an array of all templates.
|
| 29 |
+
|
| 30 |
+
**Response fields**:
|
| 31 |
+
|
| 32 |
+
| Field | Type | Description |
|
| 33 |
+
|-------|------|-------------|
|
| 34 |
+
| template_id | string | Template ID |
|
| 35 |
+
| template_name | string | Template name |
|
| 36 |
+
| template_type | string | `utility` (notification) or `marketing` |
|
| 37 |
+
| template_content | string | Template content with variable placeholders |
|
| 38 |
+
| country_codes | string | Target country codes, comma-separated |
|
| 39 |
+
| status | int | 1=Pending Review, 2=Approved, 3=Rejected |
|
| 40 |
+
| sign_id | string | Attached signature ID (optional) |
|
| 41 |
+
| sign_name | string | Attached signature name (optional) |
|
| 42 |
+
| sign_position | int | 0=None, 1=Prefix, 2=Suffix (optional) |
|
| 43 |
+
| sign_status | int | Signature status (optional) |
|
| 44 |
+
| audit_remark | string | Review remarks |
|
| 45 |
+
| created_time | int64 | Unix timestamp |
|
| 46 |
+
| updated_time | int64 | Unix timestamp |
|
| 47 |
+
|
| 48 |
+
**Example response**:
|
| 49 |
+
|
| 50 |
+
```json
|
| 51 |
+
[
|
| 52 |
+
{
|
| 53 |
+
"template_id": "123456789",
|
| 54 |
+
"template_name": "Order Notification Template",
|
| 55 |
+
"template_type": "utility",
|
| 56 |
+
"template_content": "Your order {order_no} has been shipped and is expected to arrive by {delivery_time}.",
|
| 57 |
+
"country_codes": "CN,US",
|
| 58 |
+
"status": 2,
|
| 59 |
+
"sign_id": "987654321",
|
| 60 |
+
"sign_name": "Company Name",
|
| 61 |
+
"sign_position": 2,
|
| 62 |
+
"sign_status": 2,
|
| 63 |
+
"audit_remark": "",
|
| 64 |
+
"created_time": 1699000000,
|
| 65 |
+
"updated_time": 1699000000
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
### 2. Get Template Details
|
| 71 |
+
|
| 72 |
+
`GET /v1/template-configs/:templateId`
|
| 73 |
+
|
| 74 |
+
| Path Param | Type | Required | Description |
|
| 75 |
+
|------------|------|----------|-------------|
|
| 76 |
+
| templateId | string | Yes | Template ID |
|
| 77 |
+
|
| 78 |
+
Response fields same as List Templates (single object, not array).
|
| 79 |
+
|
| 80 |
+
**Errors**: `400` if template ID is invalid or template does not exist.
|
| 81 |
+
|
| 82 |
+
### 3. Create Template
|
| 83 |
+
|
| 84 |
+
`POST /v1/template-configs`
|
| 85 |
+
|
| 86 |
+
**Request body**:
|
| 87 |
+
|
| 88 |
+
| Field | Type | Required | Description |
|
| 89 |
+
|-------|------|----------|-------------|
|
| 90 |
+
| template_name | string | Yes | Up to 255 characters |
|
| 91 |
+
| template_type | string | Yes | `utility` or `marketing` |
|
| 92 |
+
| template_content | string | Yes | Cannot contain: `【`, `】`, `、`, `测试`, `test`, `[`, `]` |
|
| 93 |
+
| country_codes | string | Yes | Comma-separated country codes |
|
| 94 |
+
| add_signature | bool | No | Whether to attach a signature (default: false) |
|
| 95 |
+
| sign_id | string | Conditional | Required if add_signature is true |
|
| 96 |
+
| sign_position | int | Conditional | Required if add_signature is true. 1=Prefix, 2=Suffix |
|
| 97 |
+
|
| 98 |
+
**Example request**:
|
| 99 |
+
|
| 100 |
+
```json
|
| 101 |
+
{
|
| 102 |
+
"template_name": "Order Notification Template",
|
| 103 |
+
"template_type": "utility",
|
| 104 |
+
"template_content": "Your order {order_no} has been shipped and is expected to arrive by {delivery_time}.",
|
| 105 |
+
"country_codes": "CN,US",
|
| 106 |
+
"add_signature": true,
|
| 107 |
+
"sign_id": "987654321",
|
| 108 |
+
"sign_position": 2
|
| 109 |
+
}
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
**Response**: `{ "template_id": "123456789" }`
|
| 113 |
+
|
| 114 |
+
**Errors**: `400` for parameter errors, non-existent signature, or unapproved signature.
|
| 115 |
+
|
| 116 |
+
**Rules**:
|
| 117 |
+
- Template starts in Pending Review (status=1) after creation
|
| 118 |
+
- If adding a signature, the signature must already be Approved
|
| 119 |
+
|
| 120 |
+
### 4. Update Template
|
| 121 |
+
|
| 122 |
+
`PUT /v1/template-configs/:templateId`
|
| 123 |
+
|
| 124 |
+
| Path Param | Type | Required | Description |
|
| 125 |
+
|------------|------|----------|-------------|
|
| 126 |
+
| templateId | string | Yes | Template ID |
|
| 127 |
+
|
| 128 |
+
Request body is the same as Create — all fields are required.
|
| 129 |
+
|
| 130 |
+
**Response**: `{ "code": 0, "message": "success" }`
|
| 131 |
+
|
| 132 |
+
**Rules**:
|
| 133 |
+
- Cannot update templates in Pending Review status
|
| 134 |
+
- Cannot update templates tied to pending/running message plans
|
| 135 |
+
- After update, status reverts to Pending Review (status=1)
|
| 136 |
+
|
| 137 |
+
### 5. Delete Template
|
| 138 |
+
|
| 139 |
+
`DELETE /v1/template-configs/:templateId`
|
| 140 |
+
|
| 141 |
+
| Path Param | Type | Required | Description |
|
| 142 |
+
|------------|------|----------|-------------|
|
| 143 |
+
| templateId | string | Yes | Template ID |
|
| 144 |
+
|
| 145 |
+
**Response**: `{ "code": 0, "message": "success" }`
|
| 146 |
+
|
| 147 |
+
**Rules**: Cannot delete templates tied to pending/running message plans.
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## Signature Configuration APIs
|
| 152 |
+
|
| 153 |
+
### 1. List Signatures
|
| 154 |
+
|
| 155 |
+
`GET /v1/sign-configs`
|
| 156 |
+
|
| 157 |
+
No request parameters. Returns an array of all signatures.
|
| 158 |
+
|
| 159 |
+
**Response fields**:
|
| 160 |
+
|
| 161 |
+
| Field | Type | Description |
|
| 162 |
+
|-------|------|-------------|
|
| 163 |
+
| sign_id | string | Signature ID |
|
| 164 |
+
| sign_name | string | Signature name |
|
| 165 |
+
| status | int | 1=Pending Review, 2=Approved, 3=Rejected |
|
| 166 |
+
| related_template_count | int64 | Number of templates using this signature |
|
| 167 |
+
| audit_remark | string | Review remarks |
|
| 168 |
+
| created_time | int64 | Unix timestamp |
|
| 169 |
+
| updated_time | int64 | Unix timestamp |
|
| 170 |
+
|
| 171 |
+
**Example response**:
|
| 172 |
+
|
| 173 |
+
```json
|
| 174 |
+
[
|
| 175 |
+
{
|
| 176 |
+
"sign_id": "987654321",
|
| 177 |
+
"sign_name": "Company Name",
|
| 178 |
+
"status": 2,
|
| 179 |
+
"related_template_count": 5,
|
| 180 |
+
"audit_remark": "",
|
| 181 |
+
"created_time": 1699000000,
|
| 182 |
+
"updated_time": 1699000000
|
| 183 |
+
}
|
| 184 |
+
]
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
### 2. Get Signature Details
|
| 188 |
+
|
| 189 |
+
`GET /v1/sign-configs/:signId`
|
| 190 |
+
|
| 191 |
+
| Path Param | Type | Required | Description |
|
| 192 |
+
|------------|------|----------|-------------|
|
| 193 |
+
| signId | string | Yes | Signature ID |
|
| 194 |
+
|
| 195 |
+
Response fields same as List Signatures (single object, not array).
|
| 196 |
+
|
| 197 |
+
**Errors**: `400` if signature ID is invalid, does not exist, or does not belong to current business.
|
| 198 |
+
|
| 199 |
+
### 3. Create Signature
|
| 200 |
+
|
| 201 |
+
`POST /v1/sign-configs`
|
| 202 |
+
|
| 203 |
+
**Request body**:
|
| 204 |
+
|
| 205 |
+
| Field | Type | Required | Description |
|
| 206 |
+
|-------|------|----------|-------------|
|
| 207 |
+
| sign_name | string | Yes | 2–60 characters, cannot contain `【`, `】`, `[`, `]` |
|
| 208 |
+
|
| 209 |
+
**Example request**: `{ "sign_name": "Company Name" }`
|
| 210 |
+
|
| 211 |
+
**Response**: `{ "sign_id": "987654321" }`
|
| 212 |
+
|
| 213 |
+
**Rules**:
|
| 214 |
+
- Signature starts in Pending Review (status=1) after creation
|
| 215 |
+
- Names must be unique within the same business
|
| 216 |
+
|
| 217 |
+
### 4. Update Signature
|
| 218 |
+
|
| 219 |
+
`PUT /v1/sign-configs/:signId`
|
| 220 |
+
|
| 221 |
+
| Path Param | Type | Required | Description |
|
| 222 |
+
|------------|------|----------|-------------|
|
| 223 |
+
| signId | string | Yes | Signature ID |
|
| 224 |
+
|
| 225 |
+
Request body same as Create.
|
| 226 |
+
|
| 227 |
+
**Response**: `{ "code": 0, "message": "success" }`
|
| 228 |
+
|
| 229 |
+
**Rules**:
|
| 230 |
+
- Cannot update signatures in Pending Review status
|
| 231 |
+
- Cannot update signatures tied to pending/running message plans
|
| 232 |
+
- After update, status reverts to Pending Review (status=1)
|
| 233 |
+
|
| 234 |
+
### 5. Delete Signature
|
| 235 |
+
|
| 236 |
+
`DELETE /v1/sign-configs/:signId`
|
| 237 |
+
|
| 238 |
+
| Path Param | Type | Required | Description |
|
| 239 |
+
|------------|------|----------|-------------|
|
| 240 |
+
| signId | string | Yes | Signature ID |
|
| 241 |
+
|
| 242 |
+
**Response**: `{ "code": 0, "message": "success" }`
|
| 243 |
+
|
| 244 |
+
**Rules**: Cannot delete signatures tied to pending/running message plans.
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/scripts/sms_client.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
EngageLab SMS API client.
|
| 3 |
+
|
| 4 |
+
Wraps all SMS REST API endpoints: send messages, template CRUD, and
|
| 5 |
+
signature (sender ID) CRUD. Handles authentication, request construction,
|
| 6 |
+
and error handling.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
from sms_client import EngageLabSMS
|
| 10 |
+
|
| 11 |
+
client = EngageLabSMS("YOUR_DEV_KEY", "YOUR_DEV_SECRET")
|
| 12 |
+
|
| 13 |
+
# Send SMS
|
| 14 |
+
result = client.send_sms(["+6591234567"], "my-template", params={"code": "1234"})
|
| 15 |
+
|
| 16 |
+
# Manage templates
|
| 17 |
+
templates = client.list_templates()
|
| 18 |
+
detail = client.get_template("123456789")
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import base64
|
| 22 |
+
import json
|
| 23 |
+
import requests
|
| 24 |
+
from typing import Optional, Union
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
BASE_URL = "https://smsapi.engagelab.com"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class EngageLabSMSError(Exception):
|
| 31 |
+
"""Raised when the SMS API returns an error response."""
|
| 32 |
+
|
| 33 |
+
def __init__(self, code: int, message: str, http_status: int, plan_id: Optional[str] = None):
|
| 34 |
+
self.code = code
|
| 35 |
+
self.message = message
|
| 36 |
+
self.http_status = http_status
|
| 37 |
+
self.plan_id = plan_id
|
| 38 |
+
super().__init__(f"[{http_status}] Error {code}: {message}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class EngageLabSMS:
|
| 42 |
+
"""Client for the EngageLab SMS REST API."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, dev_key: str, dev_secret: str, base_url: str = BASE_URL):
|
| 45 |
+
auth = base64.b64encode(f"{dev_key}:{dev_secret}".encode()).decode()
|
| 46 |
+
self._headers = {
|
| 47 |
+
"Content-Type": "application/json",
|
| 48 |
+
"Authorization": f"Basic {auth}",
|
| 49 |
+
}
|
| 50 |
+
self._base_url = base_url.rstrip("/")
|
| 51 |
+
|
| 52 |
+
def _request(self, method: str, path: str, payload: Optional[dict] = None) -> Union[dict, list]:
|
| 53 |
+
url = f"{self._base_url}{path}"
|
| 54 |
+
resp = requests.request(method, url, headers=self._headers, json=payload)
|
| 55 |
+
|
| 56 |
+
if resp.status_code >= 400:
|
| 57 |
+
try:
|
| 58 |
+
body = resp.json()
|
| 59 |
+
except (ValueError, json.JSONDecodeError):
|
| 60 |
+
body = {"code": resp.status_code, "message": resp.text}
|
| 61 |
+
raise EngageLabSMSError(
|
| 62 |
+
code=body.get("code", resp.status_code),
|
| 63 |
+
message=body.get("message", resp.text),
|
| 64 |
+
http_status=resp.status_code,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if not resp.content:
|
| 68 |
+
return {}
|
| 69 |
+
return resp.json()
|
| 70 |
+
|
| 71 |
+
# ── Send SMS ────────────────────────────────────────────────────
|
| 72 |
+
|
| 73 |
+
def send_sms(
|
| 74 |
+
self,
|
| 75 |
+
to: list,
|
| 76 |
+
template_id: str,
|
| 77 |
+
params: Optional[dict] = None,
|
| 78 |
+
plan_name: Optional[str] = None,
|
| 79 |
+
schedule_time: Optional[int] = None,
|
| 80 |
+
custom_args: Optional[dict] = None,
|
| 81 |
+
) -> dict:
|
| 82 |
+
"""
|
| 83 |
+
Send SMS to one or more recipients.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
to: List of phone numbers with country code (e.g. ["+6591234567"]).
|
| 87 |
+
template_id: ID of an approved SMS template.
|
| 88 |
+
params: Template variable values (e.g. {"name": "Bob", "code": "1234"}).
|
| 89 |
+
plan_name: Optional plan name, defaults to "-".
|
| 90 |
+
schedule_time: Unix timestamp for scheduled delivery; omit for immediate.
|
| 91 |
+
custom_args: Custom tracking parameters.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
dict with plan_id, total_count, accepted_count, and optionally
|
| 95 |
+
message_id (single target) or schedule_info (scheduled send).
|
| 96 |
+
|
| 97 |
+
Raises:
|
| 98 |
+
EngageLabSMSError: If the API returns an error code.
|
| 99 |
+
"""
|
| 100 |
+
payload = {
|
| 101 |
+
"to": to,
|
| 102 |
+
"template": {"id": template_id},
|
| 103 |
+
}
|
| 104 |
+
if params:
|
| 105 |
+
payload["template"]["params"] = params
|
| 106 |
+
if plan_name is not None:
|
| 107 |
+
payload["plan_name"] = plan_name
|
| 108 |
+
if schedule_time is not None:
|
| 109 |
+
payload["schedule_time"] = schedule_time
|
| 110 |
+
if custom_args is not None:
|
| 111 |
+
payload["custom_args"] = custom_args
|
| 112 |
+
|
| 113 |
+
result = self._request("POST", "/v1/messages", payload)
|
| 114 |
+
|
| 115 |
+
if result.get("code") and result["code"] != 0:
|
| 116 |
+
raise EngageLabSMSError(
|
| 117 |
+
code=result["code"],
|
| 118 |
+
message=result.get("message", "Unknown error"),
|
| 119 |
+
http_status=200,
|
| 120 |
+
plan_id=result.get("plan_id"),
|
| 121 |
+
)
|
| 122 |
+
return result
|
| 123 |
+
|
| 124 |
+
# ── Template Management ─────────────────────────────────────────
|
| 125 |
+
|
| 126 |
+
def list_templates(self) -> list:
|
| 127 |
+
"""Return a list of all SMS templates."""
|
| 128 |
+
return self._request("GET", "/v1/template-configs")
|
| 129 |
+
|
| 130 |
+
def get_template(self, template_id: str) -> dict:
|
| 131 |
+
"""Return details of a specific template."""
|
| 132 |
+
return self._request("GET", f"/v1/template-configs/{template_id}")
|
| 133 |
+
|
| 134 |
+
def create_template(
|
| 135 |
+
self,
|
| 136 |
+
template_name: str,
|
| 137 |
+
template_type: str,
|
| 138 |
+
template_content: str,
|
| 139 |
+
country_codes: str,
|
| 140 |
+
add_signature: bool = False,
|
| 141 |
+
sign_id: Optional[str] = None,
|
| 142 |
+
sign_position: Optional[int] = None,
|
| 143 |
+
) -> dict:
|
| 144 |
+
"""
|
| 145 |
+
Create an SMS template. Returns dict with template_id.
|
| 146 |
+
|
| 147 |
+
Template enters Pending Review (status=1) after creation.
|
| 148 |
+
Content cannot contain: 【 】 、 测试 test [ ]
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
template_name: Up to 255 characters.
|
| 152 |
+
template_type: "utility" (notification) or "marketing".
|
| 153 |
+
template_content: SMS body with {var} placeholders.
|
| 154 |
+
country_codes: Comma-separated country codes (e.g. "CN,US").
|
| 155 |
+
add_signature: Whether to attach a sender ID signature.
|
| 156 |
+
sign_id: Required if add_signature is True.
|
| 157 |
+
sign_position: Required if add_signature is True. 1=Prefix, 2=Suffix.
|
| 158 |
+
"""
|
| 159 |
+
payload = {
|
| 160 |
+
"template_name": template_name,
|
| 161 |
+
"template_type": template_type,
|
| 162 |
+
"template_content": template_content,
|
| 163 |
+
"country_codes": country_codes,
|
| 164 |
+
"add_signature": add_signature,
|
| 165 |
+
}
|
| 166 |
+
if add_signature:
|
| 167 |
+
if sign_id:
|
| 168 |
+
payload["sign_id"] = sign_id
|
| 169 |
+
if sign_position is not None:
|
| 170 |
+
payload["sign_position"] = sign_position
|
| 171 |
+
return self._request("POST", "/v1/template-configs", payload)
|
| 172 |
+
|
| 173 |
+
def update_template(
|
| 174 |
+
self,
|
| 175 |
+
template_id: str,
|
| 176 |
+
template_name: str,
|
| 177 |
+
template_type: str,
|
| 178 |
+
template_content: str,
|
| 179 |
+
country_codes: str,
|
| 180 |
+
add_signature: bool = False,
|
| 181 |
+
sign_id: Optional[str] = None,
|
| 182 |
+
sign_position: Optional[int] = None,
|
| 183 |
+
) -> dict:
|
| 184 |
+
"""
|
| 185 |
+
Update an SMS template. All fields are required.
|
| 186 |
+
|
| 187 |
+
Cannot update templates in Pending Review or tied to active plans.
|
| 188 |
+
After update, status reverts to Pending Review.
|
| 189 |
+
"""
|
| 190 |
+
payload = {
|
| 191 |
+
"template_name": template_name,
|
| 192 |
+
"template_type": template_type,
|
| 193 |
+
"template_content": template_content,
|
| 194 |
+
"country_codes": country_codes,
|
| 195 |
+
"add_signature": add_signature,
|
| 196 |
+
}
|
| 197 |
+
if add_signature:
|
| 198 |
+
if sign_id:
|
| 199 |
+
payload["sign_id"] = sign_id
|
| 200 |
+
if sign_position is not None:
|
| 201 |
+
payload["sign_position"] = sign_position
|
| 202 |
+
return self._request("PUT", f"/v1/template-configs/{template_id}", payload)
|
| 203 |
+
|
| 204 |
+
def delete_template(self, template_id: str) -> dict:
|
| 205 |
+
"""Delete an SMS template. Cannot delete if tied to active plans."""
|
| 206 |
+
return self._request("DELETE", f"/v1/template-configs/{template_id}")
|
| 207 |
+
|
| 208 |
+
# ── Signature (Sender ID) Management ────────────────────────────
|
| 209 |
+
|
| 210 |
+
def list_signatures(self) -> list:
|
| 211 |
+
"""Return a list of all sender ID signatures."""
|
| 212 |
+
return self._request("GET", "/v1/sign-configs")
|
| 213 |
+
|
| 214 |
+
def get_signature(self, sign_id: str) -> dict:
|
| 215 |
+
"""Return details of a specific signature."""
|
| 216 |
+
return self._request("GET", f"/v1/sign-configs/{sign_id}")
|
| 217 |
+
|
| 218 |
+
def create_signature(self, sign_name: str) -> dict:
|
| 219 |
+
"""
|
| 220 |
+
Create a sender ID signature. Returns dict with sign_id.
|
| 221 |
+
|
| 222 |
+
Name must be 2–60 characters, cannot contain 【 】 [ ].
|
| 223 |
+
Names must be unique within the same business.
|
| 224 |
+
Enters Pending Review (status=1) after creation.
|
| 225 |
+
"""
|
| 226 |
+
return self._request("POST", "/v1/sign-configs", {"sign_name": sign_name})
|
| 227 |
+
|
| 228 |
+
def update_signature(self, sign_id: str, sign_name: str) -> dict:
|
| 229 |
+
"""
|
| 230 |
+
Update a signature's name.
|
| 231 |
+
|
| 232 |
+
Cannot update signatures in Pending Review or tied to active plans.
|
| 233 |
+
After update, status reverts to Pending Review.
|
| 234 |
+
"""
|
| 235 |
+
return self._request("PUT", f"/v1/sign-configs/{sign_id}", {"sign_name": sign_name})
|
| 236 |
+
|
| 237 |
+
def delete_signature(self, sign_id: str) -> dict:
|
| 238 |
+
"""Delete a sender ID signature. Cannot delete if tied to active plans."""
|
| 239 |
+
return self._request("DELETE", f"/v1/sign-configs/{sign_id}")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
DEV_KEY = "YOUR_DEV_KEY"
|
| 244 |
+
DEV_SECRET = "YOUR_DEV_SECRET"
|
| 245 |
+
|
| 246 |
+
client = EngageLabSMS(DEV_KEY, DEV_SECRET)
|
| 247 |
+
|
| 248 |
+
# -- Send SMS --
|
| 249 |
+
# result = client.send_sms(
|
| 250 |
+
# ["+6591234567"],
|
| 251 |
+
# "my-template-id",
|
| 252 |
+
# params={"code": "039487"},
|
| 253 |
+
# )
|
| 254 |
+
# print(f"Sent! plan_id={result['plan_id']}, message_id={result.get('message_id')}")
|
| 255 |
+
|
| 256 |
+
# -- Scheduled SMS --
|
| 257 |
+
# import time
|
| 258 |
+
# result = client.send_sms(
|
| 259 |
+
# ["+6591234567"],
|
| 260 |
+
# "my-template-id",
|
| 261 |
+
# params={"code": "039487"},
|
| 262 |
+
# schedule_time=int(time.time()) + 3600, # 1 hour from now
|
| 263 |
+
# )
|
| 264 |
+
# print(f"Scheduled! task_id={result['schedule_info']['task_id']}")
|
| 265 |
+
|
| 266 |
+
# -- Template management --
|
| 267 |
+
# new = client.create_template(
|
| 268 |
+
# template_name="Welcome SMS",
|
| 269 |
+
# template_type="utility",
|
| 270 |
+
# template_content="Hi {name}, welcome to our platform!",
|
| 271 |
+
# country_codes="US,GB",
|
| 272 |
+
# )
|
| 273 |
+
# print(f"Created template: {new['template_id']}")
|
| 274 |
+
|
| 275 |
+
# templates = client.list_templates()
|
| 276 |
+
# for t in templates:
|
| 277 |
+
# print(f" {t['template_id']}: {t['template_name']} (status={t['status']})")
|
| 278 |
+
|
| 279 |
+
# -- Signature management --
|
| 280 |
+
# sig = client.create_signature("MyCompany")
|
| 281 |
+
# print(f"Created signature: {sig['sign_id']}")
|
| 282 |
+
|
| 283 |
+
# signatures = client.list_signatures()
|
| 284 |
+
# for s in signatures:
|
| 285 |
+
# print(f" {s['sign_id']}: {s['sign_name']} (status={s['status']})")
|
| 286 |
+
|
| 287 |
+
pass
|
benchmarks/skillbench-venus-e/tasks/de0d341bc8e13144_q1/skill/skill-card.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Description: <br>
|
| 2 |
+
Call EngageLab SMS REST APIs to send SMS messages and manage SMS templates and signatures (sender IDs). <br>
|
| 3 |
+
|
| 4 |
+
This skill is ready for commercial/non-commercial use. <br>
|
| 5 |
+
|
| 6 |
+
## Publisher: <br>
|
| 7 |
+
[devengagelab](https://clawhub.ai/user/devengagelab) <br>
|
| 8 |
+
|
| 9 |
+
### License/Terms of Use: <br>
|
| 10 |
+
MIT-0 <br>
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
## Use Case: <br>
|
| 14 |
+
Developers and operators use this skill to generate requests, code, and guidance for sending EngageLab SMS messages and managing SMS templates and sender ID signatures. <br>
|
| 15 |
+
|
| 16 |
+
### Deployment Geography for Use: <br>
|
| 17 |
+
Global <br>
|
| 18 |
+
|
| 19 |
+
## Known Risks and Mitigations: <br>
|
| 20 |
+
Risk: The skill can help send real SMS messages, including scheduled sends. <br>
|
| 21 |
+
Mitigation: Require the agent to show recipients, template parameters, schedule time, and template ID before any live send. <br>
|
| 22 |
+
Risk: The skill can help create, update, or delete SMS templates and sender ID signatures. <br>
|
| 23 |
+
Mitigation: Require explicit review of the operation, target IDs, and requested changes before modifying or deleting messaging resources. <br>
|
| 24 |
+
Risk: EngageLab credentials may be exposed through shared logs, prompts, or shell history. <br>
|
| 25 |
+
Mitigation: Use limited-scope credentials where available and keep dev_key and dev_secret out of shared logs and command history. <br>
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
## Reference(s): <br>
|
| 29 |
+
- [Template & Signature API Reference](references/template-and-signature-api.md) <br>
|
| 30 |
+
- [EngageLab SMS API Error Codes](references/error-codes.md) <br>
|
| 31 |
+
- [EngageLab SMS API Base URL](https://smsapi.engagelab.com) <br>
|
| 32 |
+
- [EngageLab SMS Messages Endpoint](https://smsapi.engagelab.com/v1/messages) <br>
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
## Skill Output: <br>
|
| 36 |
+
**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance] <br>
|
| 37 |
+
**Output Format:** [Markdown with inline code blocks, API request examples, and configuration guidance] <br>
|
| 38 |
+
**Output Parameters:** [1D] <br>
|
| 39 |
+
**Other Properties Related to Output:** [May include placeholder credentials and resource IDs when live values are not supplied.] <br>
|
| 40 |
+
|
| 41 |
+
## Skill Version(s): <br>
|
| 42 |
+
1.0.1 (source: server release evidence) <br>
|
| 43 |
+
|
| 44 |
+
## Ethical Considerations: <br>
|
| 45 |
+
Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>
|
benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0",
|
| 4 |
+
"1",
|
| 5 |
+
"2",
|
| 6 |
+
"3",
|
| 7 |
+
"4"
|
| 8 |
+
],
|
| 9 |
+
"criterion_weights": {
|
| 10 |
+
"0": 1,
|
| 11 |
+
"1": 1,
|
| 12 |
+
"2": 1,
|
| 13 |
+
"3": 1,
|
| 14 |
+
"4": 1
|
| 15 |
+
}
|
| 16 |
+
}
|
benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "bounded-policy-v1",
|
| 3 |
+
"stdlib_only": true,
|
| 4 |
+
"forbid_network": true,
|
| 5 |
+
"forbid_subprocess": true,
|
| 6 |
+
"forbid_native": true,
|
| 7 |
+
"runtime_owner_ids": [
|
| 8 |
+
"4"
|
| 9 |
+
],
|
| 10 |
+
"require_execution": true,
|
| 11 |
+
"execution_budget_seconds": 60,
|
| 12 |
+
"total_evaluation_budget_seconds": 420
|
| 13 |
+
}
|
benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/e3dd25a62946fcd577bba1a9/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|