diff --git a/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..213d43572a41661fb20e26ffb552030de108108c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/skill/SKILL.md @@ -0,0 +1,112 @@ +--- +name: dyad:add-models +description: Add one or more AI models to the language model constants file, researching specs from official docs. +--- + +# Add Models + +Add one or more AI models to `src/ipc/shared/language_model_constants.ts`, researching correct specifications from official documentation. + +## Arguments + +- `$ARGUMENTS`: Comma-separated list of model names to add (e.g., "gemini 3.1 pro, glm 5, sonnet 4.6"). + +## Instructions + +1. **Parse the model list:** + + Split `$ARGUMENTS` by commas to get individual model names. Trim whitespace from each. + +2. **Read the current constants file:** + + Read `src/ipc/shared/language_model_constants.ts` to understand: + - Which providers exist and their current model entries + - The naming conventions for each provider (e.g., `claude-sonnet-4-20250514` for Anthropic, `gemini-2.5-pro` for Google) + - The structure of `ModelOption` entries (name, displayName, description, maxOutputTokens, contextWindow, temperature, dollarSigns) + +3. **Identify the provider for each model:** + + Map each model to its provider based on the model name: + - **Anthropic** (`anthropic`): Claude models (Opus, Sonnet, Haiku) + - **OpenAI** (`openai`): GPT models + - **Google** (`google`): Gemini models + - **xAI** (`xai`): Grok models + - **OpenRouter** (`openrouter`): Models from other providers (DeepSeek, Qwen, Moonshot/Kimi, Z-AI/GLM, etc.) + - **Azure** (`azure`): Azure-hosted OpenAI models + - **Bedrock** (`bedrock`): AWS Bedrock-hosted Anthropic models + - **Vertex** (`vertex`): Google Vertex AI-hosted models + + If a model could belong to multiple providers (e.g., a new Anthropic model should go in `anthropic` AND potentially `bedrock`), add it to the primary provider. Ask the user if they also want it added to secondary providers. + +4. **Research each model's specifications:** + + For each model, use WebSearch and WebFetch to look up the official documentation: + - **Anthropic models**: Search `docs.anthropic.com` for model specs + - **OpenAI models**: Search `platform.openai.com/docs/models` for model specs + - **Google Gemini models**: Search `ai.google.dev/gemini-api/docs/models` for model specs + - **xAI models**: Search `docs.x.ai/docs/models` for model specs + - **OpenRouter models**: Search `openrouter.ai//` for model specs and pricing + + For each model, determine: + - **API model name**: The exact string used in API calls (e.g., `claude-sonnet-4-5-20250929`, `gemini-2.5-pro`) + - **Display name**: Human-readable name (e.g., "Claude Sonnet 4.5", "Gemini 2.5 Pro") + - **Description**: Short description following the style of existing entries + - **Max output tokens**: The model's maximum output token limit + - **Context window**: The model's total context window size + - **Temperature**: Default temperature (0 for most models, 1 for OpenAI, 1.0 for Gemini 3.x models) + - **Dollar signs**: Cost tier from 0-6 based on pricing relative to other models in the same provider + + **Dollar signs guide** (approximate, based on per-million-token input pricing): + - 0: Free + - 1: Very cheap (<$0.50/M input tokens) + - 2: Cheap ($0.50-$2/M) + - 3: Moderate ($2-$8/M) + - 4: Expensive ($8-$15/M) + - 5: Very expensive ($15-$30/M) + - 6: Premium ($30+/M) + +5. **Follow provider-specific conventions:** + + Match the patterns used by existing entries: + - **OpenAI**: `maxOutputTokens: undefined` (OpenAI errors with `max_tokens`), `temperature: 1` + - **Anthropic**: `maxOutputTokens: 32_000`, `temperature: 0` + - **Google**: `maxOutputTokens: 65_536 - 1` (exclusive upper bound for Vertex), `temperature` varies + - **OpenRouter**: `maxOutputTokens: 32_000`, prefix model name with provider (e.g., `deepseek/deepseek-chat-v3.1`) + - **Azure**: `maxOutputTokens` commented out, `temperature: 1` + - **Bedrock**: Model names use ARN format (e.g., `us.anthropic.claude-sonnet-4-5-20250929-v1:0`) + - **xAI**: `maxOutputTokens: 32_000`, `temperature: 0` + +6. **Add the models to the constants file:** + + Insert each new model entry into the appropriate provider's array in `MODEL_OPTIONS`. Place new models: + - At the **top** of the provider's array if it's the newest/most capable model + - After existing models of the same family but before older generations + - Add a comment with a link to the model's documentation page + + Also check if related arrays need updating: + - `TURBO_MODELS`: If the model has a turbo variant + - `PROVIDERS_THAT_SUPPORT_THINKING`: If adding a new provider that supports thinking + +7. **Check for named constant exports:** + + If the new model is likely to be referenced elsewhere (like `SONNET_4_5` or `GPT_5_2_MODEL_NAME`), create a named constant export for it. Search the codebase for references to similar constants to determine if one is needed: + + ``` + grep -r "SONNET_4_5\|GPT_5_2_MODEL_NAME\|GEMINI_3_FLASH" src/ + ``` + +8. **Verify the changes compile:** + + ``` + npm run ts + ``` + + Fix any type errors if they occur. + +9. **Summarize what was added:** + + Report to the user: + - Which models were added and to which providers + - The key specs for each (context window, max output, pricing tier) + - Any models that couldn't be found or had ambiguous specifications + - Any decisions that were made (e.g., choosing between model versions) diff --git a/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/task.json b/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d302f591fb656db0d1ee30f6f809d4883faef80e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/task.json @@ -0,0 +1,48 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "521076110b959fa6", + "query_id": "521076110b959fa6_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/model_entry_conventions.json" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "6404a322975b114ac5a2fd0b1e79c7281b8f6afed04bece9ad92be7919056c75", + "name": "dyad:add-models", + "package_path": "skill", + "install_name": "dyad-add-models-404e77c5" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "6404a322975b114ac5a2fd0b1e79c7281b8f6afed04bece9ad92be7919056c75", + "files": { + "SKILL.md": "d33a7e5b8d2d3928118f41119ad6978786e90200f2cce68d9e4bb2e23426215d" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "404e77c5f5cbe92c8b9b8dcf8055ac174e51bb174fd976b0865cef1c1102cb06" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..f77164f6102520f73c75d3adb38fc7a54860b4e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1309 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + from r9_json import parse_file, strict_equal + actual = parse_file(path) + passed = strict_equal(actual, check.get("expected")) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..b84dc8f2b2af4bebe2eb4c48e55c3aeaef091cad --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,229 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + +def _nonzero_exit_body(statements): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _simple_argv(statement) + if not argv: + return False + if argv[0] == 'exit': + return (index == len(statements) - 1 and len(argv) == 2 + and argv[1].isdigit() and 1 <= int(argv[1]) <= 255) + if argv[0] not in ('echo', 'printf'): + return False + return False + + +def shell_invocations(text): + """Return ordered, actually evaluated invocation nodes in the supported subset. + + fail_fast is a structural proof: a simple command/assignment runs under + errexit, or a negated test exits nonzero on failure. This is not a complete + shell interpreter, and unsupported syntax earns no invocation credit. + """ + statements = _statements(text) + # Function definitions or dynamic shell mutation can shadow the command or + # `exit` itself. They are outside this objective subset, even if uncalled. + 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) + or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s) + for s in statements): + return [] + constants, result, index, errexit = {}, [], 0, False + assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while index < len(statements): + statement = statements[index] + literal = assignment.fullmatch(statement) + if literal: + constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None) + index += 1 + continue + statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement) + setting = _simple_argv(statement) + if setting and setting[0] == 'set': + flag_index = 1 + while flag_index < len(setting): + flag = setting[flag_index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Remaining words set positional parameters. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return [] # e.g. `set -n` suppresses execution entirely. + if 'e' in flag[1:]: + errexit = flag[0] == '-' + if 'o' in flag[1:]: + if flag_index + 1 >= len(setting): + return [] + option = setting[flag_index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return [] + if option == 'errexit': + errexit = flag[0] == '-' + flag_index += 1 + flag_index += 1 + index += 1 + continue + if re.match(r'^if\s', statement): + end = _guard_end(statements, index) + if end is None: + return [] + negated = re.fullmatch(r'if\s+!\s+(.+)', statement) + if (negated and index + 1 < end + and statements[index + 1] == 'then' + and _nonzero_exit_body(statements[index + 2:end])): + argv, kind = _invocation(negated.group(1).strip()) + if argv: + if argv[0] == 'false': + break + result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind, + 'fail_fast': True, 'statement_index': index}) + else: + return [] + else: + # Arbitrary conditions may terminate the script or shadow its + # commands. Do not infer a reachable suffix through them. + return [] + # Bodies are never credited and may have assigned local variables. + constants.clear() + index = end + 1 + continue + if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{': + # Unsupported compounds are not searched for command substrings. + return [] + argv, kind = _invocation(statement) + if not argv: + # An unparsed statement may change control flow or shell state. + # Skipping it would incorrectly credit an unreachable suffix. + return [] + if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare', + 'typeset', 'local', 'read', 'mapfile', 'readarray', + 'unset', 'readonly', '[', '[[', 'test'): + return [] + if argv[0] == 'exit' or (argv[0] == 'false' and errexit): + break + if kind == 'assignment_substitution': + assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement) + if assigned: + constants.pop(assigned.group(1), None) + result.append({'command': shlex.join(argv), 'kind': kind, + 'fail_fast': errexit, 'statement_index': index}) + index += 1 + return result diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}} +if [[ -z "$candidate" ]]; then + echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..ee151adc5f9a5cd589d675617f237523ead727a6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,520 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + return json.loads(text) + + +from r9_json import parse_single as _r9_parse_single +_json_value = _r9_parse_single + + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + pred = _atomic_prepare(_json_value(solver_output), + verifier.get("list_order", "ordered")) + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], _atomic_shape(pred)) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = (_path_value(actual) is not None and + _path_value(actual) == _path_value(assertion["expected"])) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/r9_json.py b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/r9_json.py new file mode 100644 index 0000000000000000000000000000000000000000..9038b5dcda483f3b1fb11794bb030669af07eccb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/r9_json.py @@ -0,0 +1,74 @@ +"""JSON wire parsing and native-type equality for the R9 task copies. + +No expected answers are defined here. Single complete JSON fences are accepted +only as a transport wrapper when requested by the calling task. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json +import math +import re + + +def no_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError('duplicate JSON key') + result[key] = value + return result + + +def _finite_tree(value): + if isinstance(value, float) and not math.isfinite(value): + raise ValueError('non-finite JSON number') + if isinstance(value, dict): + for item in value.values(): + _finite_tree(item) + elif isinstance(value, list): + for item in value: + _finite_tree(item) + return value + + +def parse_single(value, allow_fence=True): + """Parse the entire response; no prefix/suffix or duplicate keys allowed.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return _finite_tree(value) + if isinstance(value, bytes): + value = value.decode('utf-8-sig') + text = str(value).lstrip('\ufeff').strip() + if allow_fence and text.startswith('```'): + match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I) + if match is None: + raise ValueError('not one complete JSON fence') + text = match.group(1) + return _finite_tree(json.loads( + text, object_pairs_hook=no_duplicates, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number')))) + + +def parse_file(path): + """Files must contain raw JSON; Markdown fences are not JSON file bytes.""" + with open(path, 'r', encoding='utf-8-sig') as stream: + return parse_single(stream.read(), allow_fence=False) + + +def strict_equal(actual, expected, number_equivalence=False): + """Preserve keys, order and every native type; booleans never equal numbers. + + Set number_equivalence only if the public contract says a generic number + rather than an integer. It accepts finite integral numeric equivalents. + """ + if type(actual) is not type(expected): + if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float): + return math.isfinite(actual) and math.isfinite(expected) and actual == expected + return False + if isinstance(expected, dict): + return set(actual) == set(expected) and all( + strict_equal(actual[key], value, number_equivalence) for key, value in expected.items()) + if isinstance(expected, list): + return len(actual) == len(expected) and all( + strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected)) + if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)): + return False + return actual == expected diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..716680cd321f6b2950aa69c3cabc0b00f5cbc7f0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "52e614810e2bad9f_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "66f8d527eb56802793d2dc55390f3d6d9c0445167172be5795cd59ce87c584b8", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "r9_json.py": "4f895ed7b7bfa0dd87455d5d990214b0e17ebf2f28ab5bcce0aa9048b043bba8", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "0729550ea1b83711c780bffc9ecc9d8ffd8602047606a7306c6493506f8d93c1", + "legacy_tests/shell_invocations.py": "3c7c2abc8e502b942fe8e783064b2b94274aada578a749fe99952170367901ce", + "legacy_tests/verifiers.py": "8b1802268580f3d39a6cbf88a517ef7140c8e0f2d93afad31ee2cede41ff7499" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..553bf93ac00871dc75242374499e15d26b9ebe0f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/instruction.md @@ -0,0 +1 @@ +We're bringing up a VeChainThor full node and need to write firewall rules and Prometheus scrape config for it. Before I open anything, I need the node's default listen settings: q1: What is the default REST API listen address of a Thor node? q2: What is the default P2P network port (--p2p-port)? q3: What is the default Prometheus metrics endpoint address (--metrics-addr)? q4: What is the default admin server address (--admin-addr)? Return exactly one JSON object like {"answers":{"q1":"string","q2":"string","q3":"string","q4":"string"}}, replacing each placeholder with the bare default value. diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d219dbbfc6e5658cef1239ac3e2f937ae10c5040 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/SKILL.md @@ -0,0 +1,80 @@ +--- +name: thor +description: VeChainThor node internals — architecture, consensus (PoA/PoS/BFT), built-in contracts, REST API, storage, P2P networking, block production, transaction lifecycle, reward distribution, staking, and contributing to the Go codebase. +allowed-tools: [] +license: MIT +metadata: + author: VeChain + version: "0.1.0" +--- + +# Thor Skill + +## CRITICAL RULES + +1. **Read reference files FIRST.** When the user's request involves any topic in the reference table below, read those files before doing anything else. Briefly mention which files you are reading so the user can confirm the skill is active. +2. **Information priority:** (a) Reference files in this skill — always the primary source. (b) The thor repo source code at `github.com/vechain/thor/v2` for implementation details. (c) Web search — only as a last resort for topics NOT covered in references. +3. **Prefer working directly in the main conversation.** Plan mode and subagents do not inherit skill context and may produce stale answers. +4. **After compaction or context loss**, re-read this SKILL.md to restore awareness of the reference table. + +## Scope + +Use this Skill for anything related to the VeChainThor node (thor): + +- Architecture and package structure of the Go codebase +- Consensus: PoA v1/v2, PoS (Galactica), BFT finality +- Built-in contracts: Authority, Energy, Staker, Params, Prototype, Executor, Extension +- REST API endpoints and WebSocket subscriptions +- Storage: LevelDB, SQLite logdb, trie, pruning, node types +- P2P networking: discovery, block/tx propagation +- Cross-cutting flows: block production, transaction lifecycle, reward distribution, staking/delegation, chain sync +- Solo mode for local development +- Contributing to the thor codebase: build, test, add endpoints, fork config + +For application-level VeChain development, see the companion skills: + +- **vechain-core** — SDK usage, fee delegation, multi-clause transactions, dual-token model +- **vechain-kit** — VeChain Kit hooks, components, wallet connection, social login +- **smart-contract-development** — Solidity, Hardhat, testing, security +- **stargate** — NFT staking, validator delegation, VTHO rewards + +## Operating procedure + +### 1. Identify the question type + +- **PM/architecture question** → read `architecture.md` + relevant flow files +- **Contributor question** → read `contributing.md` + relevant package reference +- **"How does X work?"** → read the matching flow file(s) +- **API question** → read `api.md` +- **Node operations** → read `architecture.md` (node types, flags, ports) + +### 2. Read before answering + +Load the matching reference files from the table below. Cross-cutting questions may need multiple files. + +### 3. Answer with context + +- Reference specific packages, types, and files from the thor codebase +- For flows, trace through the packages step-by-step +- For PM audiences, lead with the high-level summary before diving into implementation +- For contributors, include package paths and key type names + +## Reference files + +Read the matching files BEFORE doing anything else. See Critical Rules above. + +| Topic | File | Read when user mentions... | +|-------|------|---------------------------| +| Architecture | [references/architecture.md](references/architecture.md) | overview, packages, node types, ports, flags, fork config, tech stack | +| Consensus | [references/consensus.md](references/consensus.md) | PoA, PoS, BFT, finality, proposer, validator selection, VRF, Galactica | +| Built-in contracts | [references/built-in-contracts.md](references/built-in-contracts.md) | Authority, Energy, VTHO, Staker, Params, Prototype, Executor, native contracts | +| REST API | [references/api.md](references/api.md) | API, endpoints, routes, subscriptions, WebSocket, Swagger | +| Storage | [references/storage.md](references/storage.md) | database, LevelDB, SQLite, logdb, trie, pruning, archive, disk | +| P2P networking | [references/p2p.md](references/p2p.md) | peers, discovery, discv5, propagation, sync protocol, bootstrap | +| Contributing | [references/contributing.md](references/contributing.md) | build, Makefile, tests, lint, add endpoint, fork config, PR, Go conventions | +| Solo mode | [references/solo.md](references/solo.md) | solo, local dev, test chain, pre-funded accounts, auto-mine | +| Flow: block production | [references/flow-block-production.md](references/flow-block-production.md) | block packing, scheduler, proposer, how blocks are created | +| Flow: transaction lifecycle | [references/flow-transaction-lifecycle.md](references/flow-transaction-lifecycle.md) | tx flow, txpool, clause execution, receipts, tx validation | +| Flow: reward distribution | [references/flow-reward-distribution.md](references/flow-reward-distribution.md) | rewards, VTHO generation, validator rewards, gas rewards, burning | +| Flow: staking & delegation | [references/flow-staking-delegation.md](references/flow-staking-delegation.md) | staking, delegation, unstaking, Staker contract, validator lifecycle | +| Flow: chain sync | [references/flow-sync.md](references/flow-sync.md) | sync, catch-up, peer download, fork handling, reorg, propagation | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/api.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/api.md new file mode 100644 index 0000000000000000000000000000000000000000..9d5e21dcd3cf325b7f911281c062c6afea99ba0d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/api.md @@ -0,0 +1,153 @@ +# REST API + +Thor exposes an HTTP API (default `localhost:8669`) plus a separate admin server (`localhost:2113`). +Uses **gorilla/mux** router. WebSocket endpoints for real-time subscriptions. + +## Route Organization + +``` +api/ +├── accounts/ # Account state, code, storage, contract calls +├── blocks/ # Block retrieval +├── transactions/ # Submit and fetch transactions +├── events/ # Event log queries (POST /logs/event) +├── transfers/ # Transfer log queries (POST /logs/transfer) +├── fees/ # Fee history and priority +├── node/ # Peers, txpool +├── debug/ # EVM tracers, storage range +├── subscriptions/ # WebSocket subscriptions +├── doc/ # OpenAPI spec, Swagger/Stoplight UI +├── middleware/ # CORS, metrics, logging, panic recovery +├── restutil/ # Shared HTTP helpers +└── admin/ # Separate admin server (health, loglevel, apilogs) +``` + +## Endpoint Groups + +### Accounts — `/accounts` + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/accounts/{address}` | Balance, energy, hasCode | +| GET | `/accounts/{address}/code` | Contract bytecode | +| GET | `/accounts/{address}/storage/{key}` | Storage slot value | +| GET | `/accounts/{address}/storage/raw/{key}` | Raw storage bytes | +| POST | `/accounts/*` | Batch contract call (multiple clauses) | + +Query param `revision` selects block (ID, number, or `best`). + +Deprecated (requires `--api-enable-deprecated`): `POST /accounts`, `POST /accounts/{address}` for single calls. + +### Blocks — `/blocks` + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/blocks/{revision}` | Block by ID or number. Query: `raw`, `expanded` | + +### Transactions — `/transactions` + +| Method | Path | Description | +|--------|------|-------------| +| POST | `/transactions` | Submit raw signed transaction | +| GET | `/transactions/{id}` | Fetch transaction. Query: `head`, `raw`, `pending` | +| GET | `/transactions/{id}/receipt` | Transaction receipt | + +### Events — `/logs/event` + +| Method | Path | Description | +|--------|------|-------------| +| POST | `/logs/event` | Filter event logs by criteria, block range, pagination | + +### Transfers — `/logs/transfer` + +| Method | Path | Description | +|--------|------|-------------| +| POST | `/logs/transfer` | Filter transfer logs by criteria, block range, pagination | + +Both log endpoints are disabled when `--skip-logs` is set. + +### Fees — `/fees` + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/fees/history` | Fee history. Query: `blockCount`, `newestBlock`, `rewardPercentiles` | +| GET | `/fees/priority` | Suggested max priority fee per gas | + +### Node — `/node` + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/node/network/peers` | Connected peer stats | +| GET | `/node/txpool` | Pending txs (requires `--api-enable-txpool`) | +| GET | `/node/txpool/status` | Txpool count (requires `--api-enable-txpool`) | + +### Debug — `/debug` + +| Method | Path | Description | +|--------|------|-------------| +| POST | `/debug/tracers` | Trace existing clause (target: blockID/txID/clauseIndex) | +| POST | `/debug/tracers/call` | Trace a simulated call | +| POST | `/debug/storage-range` | Storage range at clause execution point | + +Optional pprof endpoints at `/debug/pprof/*` when `--api-pprof` is set. + +### Subscriptions — `/subscriptions` (WebSocket) + +| Path | Query Params | Payload | +|------|-------------|---------| +| `/subscriptions/block` | `pos` | New blocks | +| `/subscriptions/event` | `pos`, `addr`, `t0`–`t4` | Event logs | +| `/subscriptions/transfer` | `pos`, `txOrigin`, `sender`, `recipient` | Transfers | +| `/subscriptions/beat2` | `pos` | Beat2 heartbeat messages | +| `/subscriptions/txpool` | — | Pending transaction IDs | + +`pos` (block ID) must be within backtrace limit (default 1000 blocks). + +Deprecated: `/subscriptions/beat` (requires `--api-enable-deprecated`). + +### Documentation — `/doc` + +| Path | Description | +|------|-------------| +| `/` | Redirects to Stoplight UI | +| `/doc/thor.yaml` | OpenAPI YAML spec | +| `/doc/*` | Static assets (Swagger UI, Stoplight UI) | + +Embedded via `//go:embed`. + +## Admin API (Separate Server) + +Runs on `--admin-addr` (default `localhost:2113`): + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/admin/health` | Health status (block lag tolerance, peer count) | +| GET/POST | `/admin/loglevel` | Get/set log level (debug/info/warn/error/trace/crit) | +| GET/POST | `/admin/apilogs` | Get/toggle API request logging | + +## Middleware Stack + +Applied in order: + +1. **RequestBodyLimit** — 200 KB max body +2. **APITimeout** — configurable, default 10s +3. **RequestLogger** — logs slow queries and 5xx responses +4. **Metrics** — counters and histograms (Prometheus) +5. **PanicRecovery** — recovers panics, optional stack trace logging +6. **XGenesisID** — validates/sets `x-genesis-id` header +7. **XThorestVersion** — sets `x-thorest-ver` header +8. **Compress** — gzip compression +9. **CORS** — configurable allowed origins (`--api-cors`), allows `content-type` and `x-genesis-id` headers + +## Server Configuration + +| Flag | Default | Description | +|------|---------|-------------| +| `--api-addr` | `localhost:8669` | API listen address | +| `--api-cors` | — | CORS allowed origins | +| `--api-timeout` | 10s | Request timeout | +| `--api-pprof` | false | Enable pprof endpoints | +| `--api-enable-txpool` | false | Enable txpool endpoints | +| `--api-enable-deprecated` | false | Enable deprecated endpoints | +| `--admin-addr` | `localhost:2113` | Admin server address | +| `--metrics-addr` | `localhost:2112` | Prometheus metrics address | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/architecture.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..d1a3754150b622520f453d53e686d485ad20df93 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/architecture.md @@ -0,0 +1,162 @@ +# Thor Node Architecture + +Module path: `github.com/vechain/thor/v2` + +## Tech Stack + +| Component | Technology | +|-----------|-----------| +| Language | Go (1.25+) | +| State DB | LevelDB via `muxdb` (multiplexed) | +| Log DB | SQLite (`logdb`) | +| EVM | Fork of go-ethereum, Shanghai hardfork compatible | +| Trie | Modified Merkle Patricia Trie with versioned nodes | +| P2P | devp2p (Ethereum-derived), RLPx | +| Hashing | Blake2b (not Keccak for most chain ops) | +| VRF | ECVRF-SECP256K1-SHA256-TAI | +| CLI | `urfave/cli/v3` | + +## Package Map + +| Package | Purpose | +|---------|---------| +| `cmd/thor` | CLI entry point — `main.go` (network node), `solo` subcommand, `master-key`, `reprocess` | +| `thor` | Core types (`Address`, `Bytes32`), constants, fork config, governance param keys | +| `block` | Block header/body structures, signature handling, VRF alpha/beta fields | +| `tx` | Transaction types (legacy + typed after Galactica), multi-clause model, fee delegation | +| `state` | State trie access — account balances, storage, code; `Stater` creates state snapshots from root | +| `muxdb` | Multiplexed DB layer over LevelDB — main state storage with optional metrics | +| `logdb` | SQLite-based event/transfer log storage (skippable via `--skip-logs`) | +| `chain` | Chain repository — block summaries, chain forks, tx lookups, chain tag | +| `consensus` | Block validation — header checks, proposer validation (PoA or PoS), tx execution, state root verification | +| `bft` | BFT finality engine — vote tracking, epoch quality, justified/finalized checkpoints | +| `scheduler` | Block proposer scheduling — `PoASchedulerV1`, `PoASchedulerV2`, `PoSScheduler` | +| `vrf` | Verifiable Random Function — seed generation for proposer shuffling (post-VIP-214) | +| `packer` | Block construction — assembles blocks with transactions for proposers | +| `runtime` | EVM execution environment — runs transactions, handles built-in contract calls | +| `builtin` | Built-in contracts: Authority, Energy, Params, Prototype, Extension, Executor, Staker, Measure | +| `txpool` | Transaction pool management with per-account limits and lifetime expiry | +| `api` | RESTful API server (OpenAPI spec in `api/doc/thor.yaml`) | +| `p2p` / `p2psrv` | P2P networking layer | +| `comm` | P2P communication — block/tx propagation between peers | +| `genesis` | Genesis block generation for mainnet, testnet, devnet | +| `vm` | Modified EVM (forked from go-ethereum) | +| `tracers` | Transaction tracers — JS, native, and logger tracers (forked from geth) | +| `trie` | Versioned Merkle Patricia Trie implementation | +| `kv` | Key-value store abstraction | +| `xenv` | Execution environment for built-in contract native calls | +| `metrics` | Prometheus metrics collection | +| `cache` | LRU and priority caches | +| `stackedmap` | Copy-on-write map used in state management | + +## Data Flow: Block Sync & Validation + +``` +P2P peers → comm (download blocks) + → consensus.Process() + → validateBlockHeader (timestamp, gas, score, VRF alpha/beta, baseFee) + → staker.SyncPOS() (check if PoS transition happened) + → validateAuthorityProposer OR validateStakingProposer + → scheduler picks correct Scheduler impl + → verify signer is scheduled for this timeslot + → verify score matches + → validateBlockBody (tx roots, chain tag, expiry, blocklist) + → verifyBlock (execute all txs, compare state root, receipts root) + → if PoS active: distribute rewards via Energy.DistributeRewards + → bft.CommitBlock (track votes, update quality, finalize checkpoints) + → chain.Repository saves block + → logdb records events/transfers (unless --skip-logs) + → pruner trims old state (unless --disable-pruner) +``` + +## Package Dependencies (Simplified) + +``` +cmd/thor + ├── consensus (uses: chain, state, scheduler, builtin, runtime, block, tx) + ├── bft (uses: chain, state, builtin, block) + ├── packer (uses: chain, state, builtin, runtime, txpool) + ├── txpool (uses: chain, state, tx) + ├── api (uses: chain, state, logdb, txpool, bft) + ├── comm (uses: chain, txpool, p2p) + ├── logdb (standalone SQLite) + └── muxdb (standalone LevelDB) + +builtin → state, thor, xenv, abi + ├── authority, energy, params, prototype (state-backed linked lists / storage) + └── staker (validation, delegation, aggregation, globalstats sub-packages) + +consensus → scheduler → thor (for constants, Blake2b) +bft → chain, builtin.Staker (for PoS weight queries) +``` + +## Node Types + +| Type | Flags | Storage | Notes | +|------|-------|---------|-------| +| **Full node** | `--network mainnet` | ~200 GB (Apr 2024), 1 TB SSD recommended | Logs + pruner enabled | +| **Full without logs** | `--skip-logs` | ~100 GB | Recommended for validators; `/logs` API disabled | +| **Archive node** | `--disable-pruner` | 400+ GB | Full state history preserved | +| **Validator** | `--skip-logs` + master key | ~100 GB, 500 GB NVMe SSD | Must be voted in via Authority contract, needs endorsement | +| **Solo** | `thor solo` | In-memory (or `--persist`) | Local dev/test; single node, no P2P; `--on-demand` for tx-triggered blocks | + +## Key Configuration + +### CLI Flags + +| Flag | Default | Description | +|------|---------|-------------| +| `--network` | — | `mainnet`/`testnet` or path/URL to genesis file | +| `--api-addr` | `localhost:8669` | REST API listen address | +| `--p2p-port` | `11235` | P2P network port | +| `--max-peers` | `25` | Max P2P peers (0 disables P2P) | +| `--skip-logs` | false | Skip event/transfer log writes | +| `--disable-pruner` | false | Keep all state history (archive mode) | +| `--cache` | `4096` | MB of RAM for trie node cache | +| `--beneficiary` | — | Address for block rewards | +| `--target-gas-limit` | `0` (adaptive) | Target block gas limit | +| `--enable-metrics` | false | Prometheus metrics | +| `--metrics-addr` | `localhost:2112` | Metrics endpoint | +| `--enable-admin` | false | Admin server | +| `--admin-addr` | `localhost:2113` | Admin endpoint | +| `--min-effective-priority-fee` | `0` | Min priority fee for packing txs | + +All flags support `THOR_` prefixed env vars (e.g., `THOR_NETWORK`, `THOR_API_ADDR`). + +### Ports + +| Port | Protocol | Purpose | +|------|----------|---------| +| 8669 | TCP (HTTP) | REST API | +| 11235 | TCP + UDP | P2P network | +| 2112 | TCP (HTTP) | Prometheus metrics (opt-in) | +| 2113 | TCP (HTTP) | Admin server (opt-in) | + +### Fork Config + +Fork activation is defined per-network by genesis block ID in `thor/fork_config.go`. Each fork activates at a specific block number. + +| Fork | Mainnet Block | What Changed | +|------|--------------|-------------| +| `VIP191` | 3,337,300 | Fee delegation (tx feature flag) | +| `ETH_CONST` | 3,337,300 | Ethereum-compatible constants | +| `BLOCKLIST` | 4,817,300 | Origin/delegator address blocklist | +| `ETH_IST` | 9,254,300 | Ethereum Istanbul EVM changes | +| `VIP214` | 10,653,500 | PoA2 — VRF-based proposer shuffling, complex block signatures | +| `FINALITY` | 13,815,000 | BFT finality engine — justified/finalized checkpoints | +| `GALACTICA` | 22,084,200 | EIP-1559 base fee, typed transactions, staker contract | +| `HAYABUSA` | 23,414,400 | PoA-to-PoS transition period begins; weight-based BFT | + +### Block Constants + +| Parameter | Value | +|-----------|-------| +| Block interval | 10 seconds | +| Initial gas limit | 10,000,000 | +| Min gas limit | 1,000,000 | +| Tx base gas | 5,000 | +| Clause gas | 16,000 | +| Max state history | 65,535 blocks | +| Epoch length | Used for BFT rounds | +| Max block proposers | 101 (initial) | +| Energy growth rate | ~0.000432 VTHO/VET/day | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/built-in-contracts.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/built-in-contracts.md new file mode 100644 index 0000000000000000000000000000000000000000..58cddf46e9e8078d8894202dd5d844d3fc1671d2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/built-in-contracts.md @@ -0,0 +1,261 @@ +# Built-in Contracts + +Built-in contracts are native to the VeChainThor blockchain. Unlike regular Solidity contracts, they: + +- Have **deterministic addresses** derived from their name: `thor.BytesToAddress([]byte("ContractName"))` +- Are **not deployed via transactions** — their bytecode is loaded at genesis +- Have **native method implementations** in Go that bypass the EVM for core operations +- Solidity ABI is still used for encoding/decoding — callers interact via normal contract calls +- Some older contracts (compiled with Solidity 0.4.24) return unused gas to the caller + +**Package**: `builtin/` — `builtin.go` defines all contract bindings, each `*_native.go` file registers native method handlers. + +## Contract Overview + +| Contract | Address | Purpose | +|----------|---------|---------| +| **Authority** | `0x...Authority` | PoA authority node registry | +| **Energy** | `0x...Energy` | VTHO token (ERC20-like) | +| **Params** | `0x...Params` | On-chain governance parameters | +| **Prototype** | `0x...Prototype` | Account metadata: master, sponsors, credit plans | +| **Extension** | `0x...Extension` | Block/tx introspection from Solidity | +| **Executor** | `0x...Executor` | On-chain governance executor | +| **Staker** | `0x...Staker` | PoS staking, delegation, rewards (post-GALACTICA) | +| **Measure** | `0x...Measure` | Block measurement contract | + +> Addresses are computed as `thor.BytesToAddress([]byte(name))`. For example, Authority's address = `BytesToAddress([]byte("Authority"))`. + +## Authority + +**File**: `builtin/authority_native.go`, `builtin/authority/authority.go` + +Manages the list of PoA authority nodes. Each entry has a master address, endorser, identity hash, and active flag. Stored as a linked list in contract storage. + +### Native Methods + +| Method | Description | +|--------|-------------| +| `native_executor` | Returns the executor address from Params | +| `native_add(nodeMaster, endorsor, identity)` | Register a new authority node | +| `native_revoke(nodeMaster)` | Remove an authority node | +| `native_get(nodeMaster)` | Get node info: listed, endorser, identity, active | +| `native_first` | First node in the linked list | +| `native_next(nodeMaster)` | Next node in the linked list | +| `native_isEndorsed(nodeMaster)` | Check if endorser meets the VET endorsement requirement | + +After HAYABUSA, `native_isEndorsed` also considers queued VET in the Staker contract (transition period logic). + +## Energy (VTHO) + +**File**: `builtin/energy_native.go`, `builtin/energy/energy.go` + +VTHO is the gas/fee token. It is generated automatically from VET holdings at a fixed growth rate (~0.000432 VTHO per VET per day). Energy also handles total supply tracking and reward distribution. + +### Native Methods + +| Method | Description | +|--------|-------------| +| `native_totalSupply` | Total VTHO supply | +| `native_totalBurned` | Total VTHO burned | +| `native_get(addr)` | VTHO balance of an address (includes accrued growth) | +| `native_add(addr, amount)` | Credit VTHO to an address | +| `native_sub(addr, amount)` | Debit VTHO from an address | +| `native_master(addr)` | Get the master address of an account | + +Post-GALACTICA, the Energy contract also handles `DistributeRewards` — splitting block rewards between the proposer, validator beneficiary, and delegator reward pools. + +### VTHO Generation + +VTHO is not minted per-block. Instead, each account's VTHO balance is calculated on-the-fly based on: +- Last recorded energy balance +- VET balance × growth rate × elapsed time since last update + +Growth rate: `5,000,000,000 wei VTHO per VET per second` ≈ 0.000432 VTHO/VET/day. + +## Params + +**File**: `builtin/params_native.go`, `builtin/params/params.go` + +Generic key-value store for on-chain governance parameters. Only the Executor contract can write to it. + +### Native Methods + +| Method | Description | +|--------|-------------| +| `native_executor` | Returns the executor address | +| `native_get(key)` | Read a parameter value | +| `native_set(key, value)` | Write a parameter value (executor only) | + +### Key Parameters + +| Key | Purpose | Initial Value | +|-----|---------|---------------| +| `executor` | Governance executor address | Set at genesis | +| `reward-ratio` | Block reward ratio | 30% (3e17) | +| `validator-reward-percentage` | Validator share of rewards | 30% | +| `base-gas-price` | Legacy tx default gas price | 1e15 wei | +| `proposer-endorsement` | VET required to endorse a proposer | 25,000,000 VET | +| `max-block-proposers` | Max authority/validator count | 101 | +| `curve-factor` | VTHO issuance curve factor (post-PoS) | 76,800 | +| `delegator-contract-address` | Delegator contract address | — | +| `staker-switches` | Bit flags to pause staker/stargate | — | + +## Prototype + +**File**: `builtin/prototype_native.go`, `builtin/prototype/prototype.go` + +Provides per-account metadata: master address, credit plans, user lists, and sponsor mechanism. Central to VeChain's multi-party payment protocol (MPP). + +### Native Methods + +| Method | Description | +|--------|-------------| +| `native_master(self)` | Get account's master address | +| `native_setMaster(self, newMaster)` | Set account's master | +| `native_balanceAtBlock(self, blockNum)` | Historical VET balance (within MaxStateHistory) | +| `native_energyAtBlock(self, blockNum)` | Historical VTHO balance | +| `native_hasCode(self)` | Check if account has contract code | +| `native_storageFor(self, key)` | Read account's storage slot | +| `native_creditPlan(self)` | Get credit plan (credit, recoveryRate) | +| `native_setCreditPlan(self, credit, rate)` | Set credit plan | +| `native_isUser(self, user)` | Check if address is a user of the contract | +| `native_addUser(self, user)` | Add user | +| `native_removeUser(self, user)` | Remove user | +| `native_sponsor(self, sponsor)` | Register as sponsor | +| `native_unsponsor(self, sponsor)` | Unregister as sponsor | +| `native_isSponsor(self, sponsor)` | Check sponsor status | +| `native_selectSponsor(self, sponsor)` | Select active sponsor | +| `native_currentSponsor(self)` | Get current sponsor | + +### Multi-Party Payment (MPP) + +A contract can set a credit plan so users get free gas up to a credit limit, with a recovery rate. Sponsors can volunteer to pay for a contract's users. This enables gasless UX. + +## Extension + +**File**: `builtin/extension_native.go` + +Provides Solidity-accessible introspection into block and transaction context. Has three versions (Extension, ExtensionV2, ExtensionV3) — V3 is the active native ABI. + +### Native Methods + +| Method | Description | +|--------|-------------| +| `native_blake2b256(data)` | Blake2b hash (VeChain's native hash) | +| `native_blockID(blockNum)` | Block ID by number | +| `native_blockTotalScore(blockNum)` | Total score at block | +| `native_blockTime(blockNum)` | Timestamp at block | +| `native_blockSigner(blockNum)` | Signer of a block | +| `native_totalSupply` | VET total supply | +| `native_txProvedWork` | PoW proved work of current tx | +| `native_txID` | Current transaction ID | +| `native_txBlockRef` | Current tx block reference | +| `native_txExpiration` | Current tx expiration | +| `native_txGasPayer` | Gas payer of current tx | +| `native_txClauseIndex` | Current clause index within multi-clause tx | +| `native_txClauseCount` | Total clause count of current tx | + +## Executor + +**File**: `builtin/builtin.go` (binding only — `executor_test.go` exists) + +The on-chain governance contract. Proposals can be voted on by authority nodes to change governance parameters, add/remove authorities, or execute arbitrary calls. It is the only entity authorized to call `Params.set()`. + +## Staker + +**File**: `builtin/staker_native.go`, `builtin/staker/staker.go` + +Introduced with GALACTICA. Manages PoS validator registration, staking, delegation, and rewards. + +### Architecture + +The Staker contract delegates to sub-services: + +| Sub-package | Purpose | +|-------------|---------| +| `staker/validation` | Validator registry — linked list of active/queued/exited validators | +| `staker/delegation` | Delegation records — delegators staking against validators | +| `staker/aggregation` | Per-validator aggregate stats (locked/pending VET + weight) | +| `staker/globalstats` | Global totals: locked, queued, withdrawable, cooldown | +| `staker/stakes` | Weighted stake calculation (stake × multiplier) | + +### Native Methods — Validation + +| Method | Description | +|--------|-------------| +| `native_addValidation(validator, endorser, period, stake)` | Register a new validator (25M–600M VET) | +| `native_signalExit(validator, endorser)` | Signal intent to exit (calculates exit block) | +| `native_increaseStake(validator, endorser, amount)` | Increase active validator's stake | +| `native_decreaseStake(validator, endorser, amount)` | Decrease stake (must stay ≥ 25M VET) | +| `native_withdrawStake(validator, endorser)` | Withdraw after exit | +| `native_setBeneficiary(validator, endorser, beneficiary)` | Set reward recipient address | +| `native_getValidation(validator)` | Get validator info: endorser, locked/queued VET, weight, status, period, blocks | +| `native_getWithdrawable(validator)` | Get withdrawable amount | +| `native_firstActive` / `native_firstQueued` | Linked list traversal | +| `native_next(prev)` | Next validator in list | +| `native_getValidationsNum` | Count of active + queued validators | +| `native_getValidationTotals(validator)` | Total locked/queued/exiting stake + weight for a validator | + +### Native Methods — Delegation + +| Method | Description | +|--------|-------------| +| `native_addDelegation(validator, stake, multiplier)` | Delegate VET to a validator | +| `native_signalDelegationExit(delegationID)` | Signal delegation exit | +| `native_withdrawDelegation(delegationID)` | Withdraw delegated stake | +| `native_getDelegation(delegationID)` | Get delegation info | +| `native_getDelegatorsRewards(validator, period)` | Accumulated delegator rewards | +| `native_getDelegatorContract` | Reads delegator contract address from Params | + +### Native Methods — Global + +| Method | Description | +|--------|-------------| +| `native_totalStake` | Total locked VET and weight across all validators | +| `native_queuedStake` | Total queued VET | +| `native_issuance` | Current block reward issuance amount | +| `native_getControlSwitches` | Staker/stargate pause flags | + +### Staking Rules + +| Rule | Value | +|------|-------| +| Min stake per validator | 25,000,000 VET | +| Max stake per validator | 600,000,000 VET (including delegations) | +| Staking periods | Low / Medium / High (governance-configurable) | +| Delegation multiplier | 1–N; affects weight calculation: `stake × multiplier` | +| PoS activation | ≥ 2/3 of `maxBlockProposers` queued → auto-activates at epoch boundary | +| Exit | Signal → wait for period end → exit block → withdraw | + +### Validator States + +``` +StatusQueued → (transition when 2/3 threshold met) → StatusActive → (signalExit) → StatusExit +``` + +- **Queued**: registered but not yet producing blocks +- **Active**: producing blocks, earning rewards, stake is locked +- **Exit**: waiting for/past exit block, stake can be withdrawn + +### Rewards + +Post-GALACTICA, block rewards are distributed via `Energy.DistributeRewards()`: +- `validator-reward-percentage` (default 30%) goes to the block proposer's beneficiary +- Remaining goes to the delegator reward pool for that validator +- VTHO issuance is calculated using the `curve-factor` parameter + +### Transition Period (HAYABUSA) + +During the HAYABUSA transition period: +- Authority nodes can register in the Staker contract (`AddValidation` requires existing authority listing) +- Queued VET counts toward endorsement checks in the Authority contract +- PoA remains active until ≥ 2/3 of maxBlockProposers have queued +- Once threshold is met, all queued validators activate and PoS takes over + +## How Native Calls Work + +1. When the EVM encounters a `CALL` to a built-in contract address, `FindNativeCall` in `builtin.go` matches the method selector +2. If a native method is found, the Go implementation runs directly (no EVM bytecode execution) +3. Native methods receive an `xenv.Environment` providing access to state, block context, gas metering, and event logging +4. For older contracts (Authority, Energy, Params, Prototype, Extension), unused gas is returned to the caller +5. The Staker contract uses a different pattern: errors that are `Revert` type cause the EVM to revert with a reason string; unexpected errors panic diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/consensus.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/consensus.md new file mode 100644 index 0000000000000000000000000000000000000000..554b92179a1a6b5f380dbcff5176974d1c33450d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/consensus.md @@ -0,0 +1,168 @@ +# Consensus Mechanisms + +Thor uses a hybrid consensus model that evolved through several forks: +**PoA v1** → **PoA v2** (VIP-214) → **BFT finality** (FINALITY fork) → **PoS** (HAYABUSA/GALACTICA). + +## Proof of Authority (PoA) + +Authority nodes are registered on-chain via the `Authority` built-in contract. Each authority node has a master address, an endorser (who stakes VET as collateral), and an identity hash. + +### Endorsement Requirement + +A proposer is only eligible if its endorser's VET balance meets the `proposer-endorsement` governance parameter (initially 25M VET). After HAYABUSA, queued stake in the Staker contract also counts toward this balance check. + +### PoA v1 (Pre-VIP-214) + +- **Packages**: `scheduler/poa_v1.go`, `consensus/poa_validator.go` +- Active authority nodes are collected from the `Authority` contract +- Proposer for each time slot determined by DPRP: `H(parentBlockNumber, blockTime)[:8] % len(actives)` + - `H` = Blake2b hash +- Each block time slot is `T` = 10 seconds apart +- If a scheduled proposer misses its slot, it gets deactivated; the producing proposer gets a score equal to the count of remaining active proposers +- No seed or VRF involved — deterministic from block number + time + +### PoA v2 (Post-VIP-214) + +- **Packages**: `scheduler/poa_v2.go` +- Proposer list is **shuffled** using a VRF-derived seed +- Shuffle key: `Blake2b(seed, parentBlockNumber, proposerAddress)` — sorted to create a deterministic sequence +- Seed comes from the `Beta` output of a previous block's VRF proof (via `scheduler/seed.go`) +- Time slot assignment: proposer at index `(offset) % len(shuffled)` where offset is derived from elapsed slots +- Missed proposers are still deactivated; score = remaining active count + +### PoA → PoS: Key Differences + +| Aspect | PoA v1 | PoA v2 | PoS | +|--------|--------|--------|-----| +| Proposer selection | DPRP hash | VRF-seeded shuffle | Weighted random sampling | +| Score model | Active count | Active count | Active weight / total weight × 10000 | +| Validator source | Authority contract | Authority contract | Staker contract (leader group) | +| Weight | Equal (1 per node) | Equal (1 per node) | Proportional to stake | + +## Proof of Stake (PoS) — HAYABUSA / GALACTICA + +### Transition to PoS + +The transition is managed by `builtin/staker/transition.go`: + +1. After HAYABUSA fork, authority nodes can register in the Staker contract (requires existing authority listing during transition period) +2. At each epoch boundary (every `EpochLength` blocks), `staker.SyncPOS()` checks if ≥ 2/3 of `maxBlockProposers` are queued in the Staker contract +3. When threshold is met, queued validators are activated and PoS takes over proposer selection +4. Once active, the Authority contract is no longer used for proposer selection + +### PoS Scheduler + +- **Package**: `scheduler/pos.go` +- Uses **A-Res reservoir sampling** for weighted random proposer ordering: + - For each validator: `score = -ln(random) / weight` + - Sort by score ascending — lower score = higher priority + - `random` is from a ChaCha8 PRNG seeded with `Blake2b(vrfSeed, parentBlockNumber)` +- Higher stake → higher weight → statistically more likely to get earlier slots +- Time slot and missed-proposer logic identical to PoA v2 + +### Validator Requirements + +| Parameter | Value | +|-----------|-------| +| Min stake | 25,000,000 VET | +| Max stake | 600,000,000 VET | +| Staking periods | Low / Medium / High (governance-defined) | +| Endorser | Required (same address manages the validation) | +| Beneficiary | Optional; directs block rewards to a different address | + +### Validator Lifecycle + +``` +AddValidation (queued) + → transition() activates when 2/3 threshold met + → active (producing blocks, earning rewards) + → SignalExit → ExitBlock calculated based on staking period + → exit status → WithdrawStake +``` + +Validators can also: `IncreaseStake`, `DecreaseStake`, `SetBeneficiary`, `SetOnline`/offline. + +### Delegation + +Delegators stake VET against an active or queued validator: +- `AddDelegation(validator, stake, multiplier)` — multiplier affects weight calculation +- `SignalDelegationExit` → waiting for period end → `WithdrawDelegation` +- Delegator rewards accumulate per-validator and per-staking-period + +## BFT Finality Engine + +- **Package**: `bft/` +- Activated at the `FINALITY` fork +- Implements Casper-like justified/finalized checkpoint logic (described in VIP-220) +- **Epoch**: a fixed number of blocks (`EpochLength`) + +### Core Concepts + +| Term | Meaning | +|------|---------| +| **Checkpoint** | First block of an epoch | +| **Quality** | Accumulated count of justified epochs | +| **Justified** | An epoch where >2/3 of validators (by count pre-HAYABUSA, by weight post-HAYABUSA) participated | +| **Committed** | An epoch where >2/3 voted COM (commit) | +| **Finalized** | A checkpoint whose quality is `current_quality - 1` after a committed epoch | +| **COM bit** | Block header flag — proposer votes to commit the current epoch's checkpoint | + +### Justification & Finality Flow + +``` +Epoch N blocks produced + → at store point (last block of epoch): computeState() + → justifier collects votes from all blocks in the epoch + → if unique signers > 2/3 of maxBlockProposers → epoch is JUSTIFIED (quality++) + → if COM voters > 2/3 → epoch is COMMITTED + → if committed AND quality > 1 → checkpoint at quality-1 becomes FINALIZED + → finalized block ID persisted to DB +``` + +### Vote Safety (VIP-220) + +`ShouldVote()` ensures a proposer never votes COM on conflicting checkpoints: +- Tracks past votes via `casts` +- Will not vote COM if a recent vote (within `quality ± 1`) conflicts with the current chain's justified checkpoint +- Prevents equivocation across forks + +### Pre-HAYABUSA vs Post-HAYABUSA BFT + +- **Pre-HAYABUSA**: threshold = `maxBlockProposers * 2/3` (vote count) +- **Post-HAYABUSA**: threshold = `totalWeight * 2/3` (stake-weighted); each validator's vote carries its staking weight + +### Solo Mode + +Solo uses a `soloMockedEngine` that simulates finality: +- Every epoch assumed committed +- `finalized = currentCheckpoint - 2 * EpochLength` +- `justified = currentCheckpoint - 1 * EpochLength` +- Enables pruner to work in solo mode + +## VRF (Verifiable Random Function) + +- **Package**: `vrf/` +- Algorithm: ECVRF-SECP256K1-SHA256-TAI (suite string `0xfe`) +- Uses `github.com/vechain/go-ecvrf` +- `Prove(sk, alpha)` → `(beta, pi)` — beta is the random output, pi is the proof +- `Verify(pk, alpha, pi)` → `beta` — anyone can verify without the private key + +### Chained VRF in Blocks (Post-VIP-214) + +- Block header contains `Alpha` (VRF input) and a VRF proof in the signature +- `Alpha` = parent block's `Beta` (VRF output), or parent's `StateRoot` for the initial value +- `Beta` is extracted from the block's complex signature +- The `Seeder` (`scheduler/seed.go`) uses Beta from a block one epoch behind as the seed for proposer shuffling + +## Fork History + +| Fork | Block (Mainnet) | Key Changes | +|------|----------------|-------------| +| **VIP-191** | 3,337,300 | Fee delegation — transactions can designate a gas payer | +| **ETH_CONST** | 3,337,300 | Align gas constants with Ethereum | +| **BLOCKLIST** | 4,817,300 | Blocked addresses cannot originate or delegate transactions | +| **ETH_IST** | 9,254,300 | Ethereum Istanbul EVM opcodes | +| **VIP-214** | 10,653,500 | PoA v2: VRF-seeded proposer shuffling, complex signatures (65→162 bytes), chained VRF | +| **FINALITY** | 13,815,000 | BFT finality engine: justified/finalized checkpoints, COM voting, epoch-based quality tracking | +| **GALACTICA** | 22,084,200 | EIP-1559 base fee, typed transactions, Staker built-in contract, reward distribution changes | +| **HAYABUSA** | 23,414,400 | PoA-to-PoS transition period; stake-weighted BFT (weight replaces vote count); authority nodes can migrate to Staker contract | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/contributing.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..ed243c0db82183b5c8e2e8452b0f380113e144a8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/contributing.md @@ -0,0 +1,262 @@ +# Contributing to Thor + +## Prerequisites + +- **Go 1.25+** (enforced by Makefile version check) +- `golangci-lint` — install from +- **Docker** — needed for Solidity compilation (`builtin/gen`) and license checks +- **GPG key** — all commits must be GPG-signed + +## Build System + +| Target | Description | +|---|---| +| `make` / `make thor` | Build `bin/thor` (blockchain node) | +| `make disco` | Build `bin/disco` (discovery bootnode) | +| `make all` | Build both binaries | +| `make test` | Run unit tests with coverage | +| `make fuzz` | Fuzz test tx/block encoding (default 1 min per target) | +| `make test-coverage` | Tests with race detector + HTML coverage report | +| `make lint` | Run `golangci-lint` + `gopls/modernize` | +| `make lint-fix` | Auto-fix lint issues + regenerate builtins | +| `make generate` | Regenerate `builtin` package from Solidity sources | +| `make license-check` | Check license headers via Docker (Apache SkyWalking Eyes) | +| `make install-hooks` | Install pre-commit hook (private key detection) | +| `make clean` | Remove binaries and purge build/test caches | + +Binaries are output to `bin/`. + +Version strings are injected via `-ldflags` from `cmd/thor/VERSION` (currently `2.4.2`) and `cmd/disco/VERSION`. + +## Running the Node Locally + +```bash +make thor +bin/thor --network main # mainnet +bin/thor --network test # testnet +bin/thor solo # solo (dev) mode — instant blocks, all forks enabled at genesis +``` + +Solo mode activates all forks at block 0 (`SoloFork` in `thor/fork_config.go`), making it ideal for local development. + +## Directory Organization + +``` +cmd/ + thor/ Main node binary (flags, solo mode, pruner, sync, p2p) + disco/ Bootnode discovery tool +api/ REST API layer (gorilla/mux) + accounts/ Account/contract endpoints + blocks/ Block query endpoints + transactions/ Tx submission/query + events/ Event log filtering + transfers/ Transfer log filtering + subscriptions/ WebSocket subscriptions + debug/ Debug/tracer endpoints + admin/ Admin endpoints + fees/ Fee delegation endpoints + node/ Node info endpoints + middleware/ HTTP middleware (metrics, logging) + restutil/ Shared REST utilities + doc/ OpenAPI spec +thor/ Core types (Address, Bytes32, ForkConfig) +tx/ Transaction model +block/ Block model +chain/ Chain repository (block storage, indexing) +state/ State trie access +runtime/ EVM execution runtime +vm/ EVM implementation (go-ethereum fork) +consensus/ Block validation / consensus rules +packer/ Block packing / proposal +scheduler/ Block scheduling +bft/ Byzantine fault tolerance (finality) +builtin/ Built-in smart contracts (native bindings) + gen/ Solidity sources + code generation +genesis/ Genesis block construction +logdb/ Event/transfer log database +muxdb/ Multiplexed database layer +trie/ Merkle Patricia trie +txpool/ Transaction pool +p2p/ Low-level P2P networking +p2psrv/ P2P server +comm/ P2P communication protocol +tracers/ EVM tracing (js, logger, native) +thorclient/ Go client library for thor API +metrics/ Prometheus metrics +test/ Test utilities + testchain/ In-memory chain for testing + testnode/ In-memory node for API testing + datagen/ Test data generators + bindcontract/ Contract binding helpers + eventcontract/ Test event contract +``` + +## Testing + +Tests use standard `go test` and `github.com/stretchr/testify`. + +### Test utilities (`test/`) + +| Package | Purpose | +|---|---| +| `testchain` | Spins up an in-memory chain with genesis, BFT engine, and block production helpers | +| `testnode` | Builds a full in-memory node with REST API for integration tests | +| `datagen` | Generates random addresses, hashes, bytes, and numbers for tests | +| `bindcontract` | Helpers for deploying and binding test contracts | +| `eventcontract` | Pre-built contract for event emission tests | + +`testchain.Chain` provides `MintBlock()` / `MintTransactions()` to produce blocks programmatically without P2P. + +### Fuzz targets + +Located in `tx/` and `block/` packages — test marshalling/unmarshalling roundtrips. + +## Code Style & Linting + +### Formatting + +Enforced via `golangci-lint` formatters (`.golangci.yml`): + +- `gofmt` (with simplify) +- `goimports` (local prefix: `github.com/vechain/thor`) +- `gofumpt` +- `golines` (max line length: 160) + +### Linters enabled + +`bidichk`, `copyloopvar`, `durationcheck`, `gosec`, `govet`, `ineffassign`, `misspell`, `revive`, `staticcheck`, `unconvert`, `unused`, `whitespace` + +Paths excluded from linting: `third_party`, `builtin`, `examples`, `p2p/*`. + +### Pre-commit hook + +`make install-hooks` installs a hook that scans for 64-char hex strings (potential private keys) in staged changes. Bypass with `SAFE_TO_IGNORE_KEY=1`. + +## CI Pipeline (Pull Requests) + +PRs trigger these checks (`.github/workflows/on-pull-request.yaml`): + +1. **Unit tests** — `make test` with codecov upload +2. **License check** — Apache SkyWalking Eyes header scan +3. **Lint** — `golangci-lint` via `lint-go.yaml` +4. **Go module check** — verifies `go.mod` / `go.sum` consistency +5. **Workflow scan** — security scan of GitHub Actions workflows +6. **Docker test suite** — integration tests via Docker +7. **Rosetta tests** — Coinbase Rosetta API compliance + +## Adding a REST API Endpoint + +Each API domain follows the same pattern in `api/`: + +1. **Create a package** under `api//` (e.g., `api/fees/`) +2. **Define the handler struct** with dependencies (repo, stater, etc.): + + ```go + type Fees struct { + repo *chain.Repository + stater *state.Stater + } + func New(repo *chain.Repository, stater *state.Stater) *Fees { ... } + ``` + +3. **Implement handler methods** returning `func(w http.ResponseWriter, req *http.Request) error`: + + ```go + func (f *Fees) handleGetFee(w http.ResponseWriter, req *http.Request) error { ... } + ``` + +4. **Add a `Mount` method** to register routes on a `mux.Router`: + + ```go + func (f *Fees) Mount(root *mux.Router, pathPrefix string) { + sub := root.PathPrefix(pathPrefix).Subrouter() + sub.Path("/{id}").Methods(http.MethodGet). + Name("GET /fees/{id}"). + HandlerFunc(restutil.WrapHandlerFunc(f.handleGetFee)) + } + ``` + +5. **Define request/response types** in `api/_types.go` (at the `api/` package level) +6. **Wire it up** in the main API router by calling `Mount()` + +Key conventions: + +- Use `restutil.WrapHandlerFunc` to wrap handlers (handles error responses) +- Parse path params with `mux.Vars(req)` +- Parse query params / block revision via shared utilities in `api/restutil/` + +## Fork Configuration + +Forks are defined in `thor/fork_config.go` as the `ForkConfig` struct: + +```go +type ForkConfig struct { + VIP191 uint32 + ETH_CONST uint32 + BLOCKLIST uint32 + ETH_IST uint32 + VIP214 uint32 + FINALITY uint32 + HAYABUSA uint32 + GALACTICA uint32 +} +``` + +Each field is a **block number** at which the fork activates. `math.MaxUint32` means disabled. + +To add a new fork: + +1. Add a new field to `ForkConfig` +2. Set it to `math.MaxUint32` in `NoFork` +3. Set it to `0` in `SoloFork` (enables immediately in dev mode) +4. Add activation block numbers in the `forkConfigs` map for mainnet/testnet genesis IDs +5. Update `String()` to include the new fork name +6. Reference `forkConfig.YourFork` in consensus/runtime code to gate new behavior + +Fork names follow VIP numbers (e.g., `VIP191`, `VIP214`) or codenames (e.g., `HAYABUSA`, `GALACTICA`). + +## Built-in Contracts + +Built-in (native) contracts live in `builtin/`: + +| Contract | File | Purpose | +|---|---|---| +| Authority | `authority_native.go` | Authority/validator management | +| Energy (VTHO) | `energy_native.go` | VTHO token operations | +| Params | `params_native.go` | On-chain governance parameters | +| Prototype | `prototype_native.go` | Account metadata/master | +| Extension | `extension_native.go` | Block/tx introspection helpers | +| Executor | (via Solidity) | On-chain governance execution | +| Staker | `staker_native.go` | PoS staking (Hayabusa+) | + +### Modifying built-in contracts + +1. Edit Solidity source in `builtin/gen/*.sol` +2. Compile: `docker run --rm -v ./builtin/gen:/solidity ghcr.io/argotorg/solc:0.4.24 ...` (see `gen.go` for exact flags — solc 0.4.24 for legacy contracts, solc 0.8.20 for staker) +3. Regenerate Go bindings: `make generate` (runs `go generate builtin/gen/gen.go`) +4. Implement native call handlers in `builtin/*_native.go` +5. Wire into `builtin/builtin.go` and `builtin/contract.go` + +Compiled ABI/bytecode lives in `builtin/gen/compiled/` (embedded via `//go:embed`). + +## Replaced Dependencies + +Two critical `replace` directives in `go.mod`: + +| Original | Fork | Why | +|---|---|---| +| `github.com/ethereum/go-ethereum` | `github.com/vechain/go-ethereum` | Customized EVM, crypto, RLP — diverged significantly from upstream | +| `github.com/syndtr/goleveldb` | `github.com/vechain/goleveldb` | Custom patches for VeChain's storage layer | + +When importing `go-ethereum` packages, the actual code comes from the VeChain fork. This affects `vm/`, `abi/`, `crypto/`, `rlp/`, `trie/` and related packages. + +## PR Requirements + +1. Fork repo → create feature branch (`feature/your-feature-name`) +2. Keep branch up-to-date with `master` +3. Run `make test` and `make lint` before pushing +4. **All commits must be GPG-signed** +5. PR targets `master` branch +6. PR description must clearly explain changes and rationale +7. Follow [Effective Go](https://golang.org/doc/effective_go) guidelines +8. VIPs (protocol changes) require a separate proposal at [vechain/VIPs](https://github.com/vechain/VIPs) first diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-block-production.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-block-production.md new file mode 100644 index 0000000000000000000000000000000000000000..bb7d7e04d529d83797a87f95356d48937cc7eed4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-block-production.md @@ -0,0 +1,190 @@ +# Block Production Flow + +How a new block is produced in VeChainThor, from scheduling through finality. + +## Overview + +``` +scheduler/ → packer/ → runtime/ → consensus/ → bft/ → chain/ + │ │ │ │ │ │ +Schedule Assemble Execute Validate Vote Store +``` + +## Step 1: Scheduling — Who Proposes Next + +**Package:** `scheduler/`, `packer/pos_scheduler.go`, `packer/poa_scheduler.go` + +The node's `packerLoop` (in `cmd/thor/node/packer_loop.go`) continuously calls `Packer.Schedule()` to determine when this node should propose. + +| Type | Scheduler | Selection Method | +|------|-----------|-----------------| +| PoA (pre-Galactica) | `PoASchedulerV1` / `PoASchedulerV2` | Round-robin from `Authority` candidates with endorsement balance check | +| PoS (post-Galactica) | `PoSScheduler` | Weighted random sampling (A-Res reservoir) from `Staker.LeaderGroup()` | + +**Key types:** +- `scheduler.Scheduler` — interface: `Schedule(nowTime) → newBlockTime`, `IsTheTime()`, `Updates()` +- `scheduler.Proposer` — `{Address, Active, Weight}` +- `scheduler.Seeder` — generates deterministic VRF-based seeds per block + +**PoS scheduling detail:** `NewPoSScheduler` generates a deterministic shuffle using `ChaCha8` PRNG seeded with `Blake2b(VRF_seed, blockNumber)`. Each validator gets score `-ln(random)/weight` (A-Res algorithm). Validators sorted by score determine the slot order. + +**Triggers next:** `Packer.Schedule()` returns a `*Flow` with the target block time. + +## Step 2: Packing — Assembling the Block + +**Package:** `packer/` + +`Packer.Schedule()` determines consensus mode (PoA vs PoS) by calling `Staker.SyncPOS()`, then delegates to `schedulePOS` or `schedulePOA`. Both return `(beneficiary, newBlockTime, score)`. + +A `Flow` is created with a `runtime.Runtime` initialized with: + +```go +xenv.BlockContext{ + Beneficiary, Signer, Number, Time, + GasLimit, TotalScore, BaseFee, +} +``` + +**Transaction adoption** (`Flow.Adopt`): +1. Check blocklist, chain tag, block ref, expiration +2. Check gas capacity (`gasUsed + tx.Gas ≤ GasLimit`) +3. Post-Galactica: validate `EffectiveGasPrice ≥ BaseFee` and priority fee +4. Check tx not duplicate, dependency resolved +5. Create state checkpoint → `runtime.ExecuteTransaction(tx)` → on error, revert +6. Accumulate `gasUsed`, append to `txs` and `receipts` + +The `packerLoop` calls `flow.Adopt(tx)` for each executable tx from the pool, stopping at `errGasLimitReached`. + +**Key types:** +- `packer.Packer` — holds repo, stater, nodeMaster, beneficiary, forkConfig +- `packer.Flow` — accumulates txs/receipts, tracks gas, calls runtime + +**Triggers next:** `Flow.Pack(privateKey, conflicts, shouldVote)` builds and signs the block. + +## Step 3: Runtime Execution + +**Package:** `runtime/` + +`Runtime.ExecuteTransaction` resolves the tx, buys gas (VTHO), then executes each clause sequentially. + +**Per-clause execution:** +1. `PrepareClause` creates a `statedb.StateDB` and EVM instance +2. If `clause.To() == nil` → contract creation; else → `evm.Call` +3. Collects `Output{Data, Events, Transfers, LeftOverGas, VMErr}` +4. On VM error → revert all clauses to checkpoint, mark `receipt.Reverted = true` + +**Gas payment:** `ResolvedTransaction.BuyGas` deducts VTHO from payer (delegator → sponsor → origin fallback). + +**Reward calculation (post-Galactica):** +- `priorityFeePerGas = min(maxFeePerGas - baseFee, maxPriorityFeePerGas)` +- `receipt.Reward = priorityFeePerGas × gasUsed` +- Reward credited to `Beneficiary` via `Energy.Add` + +**Key types:** +- `runtime.Runtime` — wraps EVM, chain, state, block context +- `runtime.ResolvedTransaction` — resolved origin, delegator, intrinsic gas, clauses +- `runtime.TransactionExecutor` — iterator over clauses with `HasNextClause/PrepareNext/Finalize` +- `tx.Receipt` — `{Type, Reverted, Outputs, GasUsed, GasPayer, Paid, Reward}` + +## Step 4: Consensus Validation + +**Package:** `consensus/` + +When receiving a block (not packing), `Consensus.Process()` validates it: + +1. **Header validation** (`validateBlockHeader`): + - Timestamp > parent, aligned to `BlockInterval` + - Not future (≤ now + BlockInterval) + - GasUsed ≤ GasLimit, valid gas limit delta + - TotalScore > parent + - Signature length (65 bytes pre-VIP214, complex sig post-VIP214) + - BaseFee matches `galactica.CalcBaseFee(parent)` post-Galactica + +2. **Proposer validation**: + - **PoA:** `validateAuthorityProposer` — checks signer is in Authority candidates, scheduled for this slot + - **PoS:** `validateStakingProposer` — checks signer is in `Staker.LeaderGroup()`, scheduled via `PoSScheduler` + - Both verify `TotalScore = parent.TotalScore + score` + +3. **Body validation** (`validateBlockBody`): + - `TxsRoot` matches merkle root of txs + - Each tx: valid origin, chain tag, block ref, expiration, features + +4. **Block verification** (`verifyBlock`): + - Re-execute all txs via `runtime.ExecuteTransaction` + - Verify `GasUsed`, `ReceiptsRoot`, `StateRoot` all match header + - Post-PoS: distribute rewards via `Energy.DistributeRewards` + +**Key types:** +- `consensus.Consensus` — holds repo, stater, seeder, forkConfig, validatorsCache + +## Step 5: BFT Finality + +**Package:** `bft/` + +The `bft.Engine` implements VIP-220 finality (epoch-based voting). + +**Concepts:** +- **Epoch:** `EpochLength` blocks (e.g., 100). Checkpoint = first block of epoch. +- **COM bit:** Block header flag indicating the proposer votes for current checkpoint. +- **Quality:** Count of epochs with sufficient votes. Stored at `storePoint` (last block of epoch). +- **Justified:** Checkpoint with quality ≥ threshold for current epoch. +- **Finalized:** When quality > 1, `findCheckpointByQuality(quality-1)` is finalized. + +**Key operations:** +- `ShouldVote(parentID)` — packer checks before setting COM bit +- `CommitBlock(header, isPacking)` — saves quality at epoch end, updates finalized +- `Select(header)` — fork choice: prefer higher quality, then `BetterThan` +- `Accepts(parentID)` — rejects blocks not descending from finalized checkpoint + +**Key types:** +- `bft.Committer` — interface for `Engine` +- `bft.Engine` — tracks casts (votes), finalized/justified checkpoints +- `bft.justifier` — per-epoch vote accumulator + +## Step 6: Chain Storage + +**Package:** `chain/` + +`Repository.AddBlock(block, receipts, conflicts, asBest)`: + +1. **Index block:** Update index trie (block number → block ID mapping) +2. **Save block:** + - Header summary → `hdrStore` + - Tx blobs → `bodyStore` + - Receipt blobs → `bodyStore` + - Tx metadata (index, reverted) → `txIndexer` + - Chain head → `headStore` +3. If `asBest`: update `bestBlockID` in `propStore`, broadcast via `tick.Signal` + +**Key types:** +- `chain.Repository` — thread-safe block/tx/receipt storage over `muxdb.MuxDB` +- `chain.Chain` — linked chain view from genesis to a given head, backed by index trie +- `chain.BlockSummary` — `{Header, Txs []Bytes32, Size, Conflicts}` +- `chain.TxMeta` — `{BlockNum, BlockConflicts, Index, Reverted}` + +## End-to-End Sequence (Packing Path) + +``` +1. packerLoop waits for sync, then loops: +2. Packer.Schedule(bestBlock, now) → Flow +3. Wait until flow.When() - BlockInterval/2 +4. For each txPool.Executables(): flow.Adopt(tx) +5. bft.ShouldVote() → shouldVote +6. flow.Pack(privateKey, conflicts, shouldVote) → block, stage, receipts +7. stage.Commit() → persist state trie +8. repo.AddBlock(block, receipts) → persist to DB +9. bft.CommitBlock(header, isPacking) → update finality +10. comm.BroadcastBlock(block) → propagate to peers +``` + +## End-to-End Sequence (Receiving Path) + +``` +1. comm.Sync downloads blocks from peers → handleBlockStream +2. node.processBlock(block): +3. bft.Accepts(parentID) → reject if not on finalized branch +4. consensus.Process(parent, block, now, conflicts) → stage, receipts +5. bft.Select(header) → fork choice (becomeBest?) +6. node.commitBlock: stage.Commit(), repo.AddBlock(), bft.CommitBlock() +7. If becomeBest: processFork (re-add orphaned txs to pool) +``` diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-reward-distribution.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-reward-distribution.md new file mode 100644 index 0000000000000000000000000000000000000000..698d6f1e80bda8118926e56c4c3d9b2cda64da6f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-reward-distribution.md @@ -0,0 +1,188 @@ +# Reward Distribution Flow + +How block rewards are calculated and distributed to validators and delegators. + +## Overview + +``` +runtime/ (per-tx reward) → energy/ (distribute) → staker/ (delegation split) + │ │ │ + Calculate Credit VTHO Split validator/delegator +``` + +## Two Reward Eras + +| Era | Condition | Mechanism | +|-----|-----------|-----------| +| Pre-Galactica | `blockNumber < forkConfig.GALACTICA` | `rewardRatio` × gas price per tx | +| Post-Galactica (PoS) | `blockNumber ≥ forkConfig.GALACTICA` | Priority fee per tx + block reward from staking curve | + +## Per-Transaction Reward (Both Eras) + +**Package:** `runtime/` — in `PrepareTransaction().Finalize()` + +### Pre-Galactica (PoA) + +```go +rewardRatio := Params.Get(KeyRewardRatio) // governance parameter +overallGasPrice := gasPrice + baseGasPrice * provedWork / txGas +reward := gasUsed * overallGasPrice * rewardRatio / 1e18 +``` + +The reward is a **fraction** of gas cost, controlled by on-chain `RewardRatio` parameter. The remainder (gas cost minus reward) is burned. + +### Post-Galactica (PoS) + +```go +priorityFeePerGas := min(maxFeePerGas - baseFee, maxPriorityFeePerGas) +receipt.Reward = priorityFeePerGas * gasUsed +``` + +Priority fee goes entirely to the block proposer. The `baseFee` portion is burned (never credited). + +### Crediting per-tx reward + +In both eras, after computing `receipt.Reward`: + +```go +Energy.Native(state, blockTime).Add(beneficiary, receipt.Reward) +``` + +This credits VTHO directly to the block's `Beneficiary` address. + +## Block-Level Reward Distribution (PoS Only) + +**Package:** `builtin/energy/energy.go` — `DistributeRewards()` + +Called at block finalization in two places: +- **Packing path:** `Flow.Pack()` in `packer/flow.go` +- **Validation path:** `verifyBlock()` in `consensus/validator.go` + +Both call: + +```go +energy.DistributeRewards(beneficiary, signer, staker, blockNumber) +``` + +### Reward Calculation (`CalculateRewards`) + +```go +totalStaked, _ := staker.LockedStake() // in VET (not wei) +sqrtStake := sqrt(totalStaked) * 1e18 // convert to wei precision +curveFactor := Params.Get(KeyCurveFactor) // governance parameter +reward := curveFactor * sqrtStake / blocksPerYear +``` + +The reward curve is sublinear (`reward ∝ √(totalStaked)`), incentivizing broad participation rather than stake concentration. + +### Validator vs Delegator Split + +```go +validatorRewardPerc := Params.Get(KeyValidatorRewardPercentage) // e.g., 30 +hasDelegations := staker.HasDelegations(signer) + +if hasDelegations && validatorRewardPerc < 100 { + proposerReward = reward * validatorRewardPerc / 100 + delegationReward = reward - proposerReward + + // Credit delegator reward to delegation contract address + delegatorAddr := Params.Get(KeyDelegatorContractAddress) + state.SetEnergy(delegatorAddr, existing + delegationReward) + staker.IncreaseDelegatorsReward(signer, delegationReward, blockNumber) +} + +// Credit validator reward to beneficiary +state.SetEnergy(beneficiary, existing + proposerReward) +energy.addIssued(reward) // track total supply +``` + +**Key points:** +- If the validator has **no delegations**, they receive 100% of the block reward +- If delegated, the split is governed by `KeyValidatorRewardPercentage` (on-chain parameter) +- Delegator rewards are held in a contract address and tracked per-validator by `staker.IncreaseDelegatorsReward` +- `addIssued(reward)` increases the tracked VTHO total supply (for `totalSupply()` queries) + +## VTHO (Energy) Generation + +**Package:** `builtin/energy/`, `state/` + +VTHO is generated in two ways: + +### 1. Growth from VET holdings (pre-Hayabusa) + +Every VET holder earns VTHO proportional to their balance over time: + +```go +func (acc Account) CalcEnergy(blockTime, stopTime uint64) *big.Int { + // energy += balance * (min(blockTime, stopTime) - acc.BlockTime) * energyGrowthRate +} +``` + +Rate: `5 × 10⁻⁸ VTHO per VET per second` (≈ 0.000432 VTHO/VET/day). + +**Hayabusa fork** calls `Energy.StopEnergyGrowth()` which freezes growth at the fork block time. After this, VTHO only comes from block rewards. + +### 2. Block rewards (post-Galactica) + +As described above — `DistributeRewards` mints new VTHO each block. + +## VTHO Burning + +VTHO is burned in two places: + +1. **Gas payment:** `ResolvedTransaction.BuyGas` deducts `gas × effectiveGasPrice` VTHO from payer. After execution, unused gas is refunded. The net burn = `gasUsed × effectiveGasPrice - receipt.Reward`. + +2. **BaseFee (post-Galactica):** The baseFee portion of gas cost is implicitly burned — it is deducted from the payer but never credited to anyone. Only the priority fee goes to the proposer. + +Burning is tracked via `Energy.totalAddSub` — `TotalBurned = TotalSub - TotalAdd`. + +## BaseFee Mechanism (EIP-1559 Adapted) + +**Package:** `consensus/upgrade/galactica/` + +```go +func CalcBaseFee(parent, forkConfig) *big.Int { + parentGasTarget = parent.GasLimit * GasTargetPercentage / 100 + if parentGasUsed > parentGasTarget: + baseFee increases (min delta = 1) + else: + baseFee decreases (floor = InitialBaseFee) +} +``` + +Adjustment rate: `baseFeeChangeDenominator` (governance parameter, similar to Ethereum's 8). + +## Reward Flow Diagram + +``` + ┌──────────────────────┐ + │ Per-Tx Priority Fee │ + │ (runtime/ Finalize) │ + └──────────┬───────────┘ + │ + ┌──────────▼───────────┐ + │ Block Staking Reward │ + │ (energy/ Calculate) │ + │ √(totalStaked)*curve │ + └──────────┬───────────┘ + │ + ┌────────────────┴────────────────┐ + │ │ + ┌─────────▼─────────┐ ┌─────────▼─────────┐ + │ Validator Share │ │ Delegator Share │ + │ validatorRewardPerc│ │ (100 - validatorRP)│ + │ → beneficiary VTHO│ │ → contract address │ + └───────────────────┘ │ → per-validator │ + │ reward tracking │ + └───────────────────┘ +``` + +## Key Parameters (On-Chain Governance) + +| Parameter | Key | Purpose | +|-----------|-----|---------| +| `KeyRewardRatio` | Pre-Galactica reward fraction | Fraction of gas cost given as reward | +| `KeyCurveFactor` | Block reward curve multiplier | Controls block reward magnitude | +| `KeyValidatorRewardPercentage` | Validator share of block reward | Split between validator and delegators | +| `KeyLegacyTxBaseGasPrice` | Base gas price for legacy txs | Floor price for legacy transactions | +| `KeyDelegatorContractAddress` | Delegator reward holding address | Where delegator rewards accumulate | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-staking-delegation.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-staking-delegation.md new file mode 100644 index 0000000000000000000000000000000000000000..5af8d174558d882a003ef1dacab2dd5651144c67 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-staking-delegation.md @@ -0,0 +1,246 @@ +# Staking and Delegation Flow + +How validators stake, delegators participate, and the PoS transition works (Galactica upgrade). + +## Overview + +``` +builtin/staker/ ← scheduler/ ← consensus/ + │ │ │ + Stake mgmt PoS scheduling Proposer validation +``` + +## Staker Contract Architecture + +**Package:** `builtin/staker/` + +The `Staker` struct composes four services: + +| Service | Package | Responsibility | +|---------|---------|---------------| +| `validationService` | `staker/validation/` | Validator lifecycle (add, activate, exit, renew) | +| `delegationService` | `staker/delegation/` | Delegation CRUD and exit signaling | +| `aggregationService` | `staker/aggregation/` | Per-validator delegation totals | +| `globalStatsService` | `staker/globalstats/` | System-wide stake counters | + +The contract is deployed at `builtin.Staker.Address` and uses native calls (Go code, not Solidity EVM). + +## Step 1: Becoming a Validator + +### Adding a Validation + +`Staker.AddValidation(validator, endorser, period, stake)` + +**Requirements:** +- Stake: `25M VET ≤ stake ≤ 600M VET` (`MinStakeVET` / `MaxStakeVET`) +- Validator address must not already exist +- Period must be one of: `LowStakingPeriod`, `MediumStakingPeriod`, `HighStakingPeriod` +- VET transferred to staker contract address + +**State changes:** +1. `validationService.Add()` — creates `validation.Validation` in queued list +2. `globalStatsService.AddQueued(stake)` — increment global queued counter +3. `ContractBalanceCheck()` — invariant: `locked + queued + withdrawable + cooldown = contract balance` + +### Validation States + +``` +Queued → Active → [Exit signaled] → Exit +``` + +| Status | Meaning | +|--------|---------| +| `StatusQueued` | Waiting for activation at next epoch boundary | +| `StatusActive` | In the leader group, eligible to produce blocks | +| `StatusExit` | Exited, stake withdrawable after cooldown | + +### Key Type: `validation.Validation` + +```go +type Validation struct { + Endorser thor.Address + LockedVET uint64 // currently locked stake + Weight uint64 // effective weight (may include multiplier) + QueuedVET uint64 // additional stake pending next period + PendingUnlockVET uint64 // stake pending unlock at period end + Status Status + Period uint32 // staking period in blocks + StartBlock uint32 // when activated + ExitBlock *uint32 // when exit takes effect (nil if not signaled) + OfflineBlock *uint32 // when marked offline (nil if online) + Beneficiary *thor.Address // reward recipient override +} +``` + +## Step 2: Activation — Queued to Active + +**Package:** `builtin/staker/housekeep.go` + +Activation happens during **epoch transitions** via `Staker.Housekeep(currentBlock)`, called by `Staker.SyncPOS()` at every block. + +Housekeep runs when `currentBlock % EpochLength == 0`: + +1. **Eviction check** (every `EvictionCheckInterval`): validators offline for > `ValidatorEvictionThreshold` blocks get force-exited +2. **Renewals** (`UpdateGroup`): active validators at period end get their weight recalculated, queued stake promoted to locked +3. **Exits**: validators with `ExitBlock == currentBlock` are moved to exit status +4. **Activations**: queued validators promoted to leader group up to `MaxBlockProposers` + +### Activation detail (`activateNextValidation`): + +```go +validator, validation := validationService.NextToActivate(maxLeaderGroupSize) +aggregationService.Renew(validator) // consolidate delegation totals +validationService.ActivateValidator(validator, ...) // set status=Active, startBlock +globalStatsService.ApplyRenewal(renewal) // move queued→locked in counters +``` + +## Step 3: Delegation + +### Adding a Delegation + +`Staker.AddDelegation(validator, stake, multiplier, currentBlock) → delegationID` + +**Requirements:** +- Validator must be `StatusQueued` or `StatusActive` (and not signaled exit) +- `stake > 0`, `multiplier > 0` +- Total TVL (validation + delegations) must not exceed `MaxStakeVET` (600M) + +**State changes:** +1. `delegationService.Add()` → assigns `delegationID`, stores delegation starting at next iteration +2. `aggregationService.AddPendingVET()` → adds weighted stake to per-validator pending totals +3. `globalStatsService.AddQueued(stake)` → increment system queued counter +4. If validator is active: `validationService.AddToRenewalList()` → ensure renewal at next epoch + +### Key Type: `delegation.Delegation` + +```go +type Delegation struct { + Validation thor.Address // validator this delegates to + StartIteration uint32 // iteration when delegation activates + LastIteration *uint32 // iteration when delegation exits (nil = auto-renew) + Stake uint64 // staked VET amount + Multiplier uint8 // weight multiplier (longer lock = higher weight) +} +``` + +### Delegation Exit + +`Staker.SignalDelegationExit(delegationID, currentBlock)`: +- Sets `LastIteration` to current iteration +- Updates aggregation to signal pending exit +- Delegation remains locked until iteration end, then becomes withdrawable + +### Delegation Withdrawal + +`Staker.WithdrawDelegation(delegationID, currentBlock) → amount`: +- Only if not started yet, or ended (past LastIteration) +- Returns VET to the delegator +- Updates global stats (remove from queued or withdrawable) + +## Step 4: PoS Consensus Participation + +### Leader Group Formation + +Active validators form the **leader group**, queried via `Staker.LeaderGroup()`: + +```go +type Leader struct { + Address thor.Address + Endorser thor.Address + Active bool // online status + Weight uint64 // stake weight for scheduling + Beneficiary *thor.Address // reward recipient +} +``` + +### PoS Scheduling + +**Package:** `scheduler/pos.go` + +`PoSScheduler` uses the leader group for weighted random block assignment: + +1. Seed from VRF chain: `Blake2b(VRF_beta, blockNumber)` +2. Each validator gets priority: `-ln(random) / weight` (A-Res weighted reservoir sampling) +3. Validators sorted by priority → deterministic slot order +4. Schedule advances in `BlockInterval` steps + +### PoS Consensus Validation + +**Package:** `consensus/pos_validator.go` + +`validateStakingProposer(header, parent, staker)`: +1. Get signer from header +2. Get leader group (cached or from `staker.LeaderGroup()`) +3. Build `PoSScheduler` with leader group and VRF seed +4. Verify `sched.IsTheTime(header.Timestamp())` — signer is scheduled for this slot +5. Compute `updates, score = sched.Updates(timestamp)` — mark skipped validators as inactive +6. Verify `parent.TotalScore + score == header.TotalScore` + +### Online/Offline Tracking + +`Staker.SetOnline(validator, blockNum, online)`: +- Called during scheduling — validators that miss their slot are marked `Active: false` +- Offline validators can be evicted after `ValidatorEvictionThreshold` blocks +- Coming back online (producing a block) resets the offline counter + +## Step 5: Reward Distribution for Stakers/Delegators + +See `flow-reward-distribution.md` for full detail. Summary: + +1. Block reward calculated: `curveFactor × √(totalStaked) / blocksPerYear` +2. If validator has delegations: split by `ValidatorRewardPercentage` +3. Validator share → beneficiary VTHO balance +4. Delegator share → delegation contract address, tracked per-validator via `IncreaseDelegatorsReward` + +## Step 6: Unstaking and Cooldown + +### Validator Exit + +``` +SignalExit(validator, endorser, currentBlock) + → sets ExitBlock (at next period boundary) + → at ExitBlock epoch: Housekeep moves to StatusExit + +WithdrawStake(validator, endorser, currentBlock) + → returns locked + queued + cooldown VET + → updates global stats +``` + +### Cooldown Period + +When a validator exits, their stake may go through a cooldown period before being withdrawable. The `globalStatsService` tracks three counters that reflect the lifecycle: + +| Counter | Meaning | +|---------|---------| +| `queued` | Stake waiting to become active | +| `locked` | Actively staked and earning rewards | +| `withdrawable` | Exited and available for withdrawal | +| `cooldown` | Exited but still in cooldown period | + +### Stake Increase/Decrease (Active Validators) + +- `IncreaseStake`: adds to `QueuedVET` (takes effect next period) +- `DecreaseStake`: reduces `LockedVET - PendingUnlockVET` (next period) +- Both require endorser authorization and add validator to renewal list + +## PoA → PoS Transition + +**Package:** `builtin/staker/`, `consensus/upgrade/galactica/` + +The transition is managed by `Staker.SyncPOS()`, called at every block: + +1. **Hayabusa fork:** Staker contract deployed, energy growth stopped +2. **Transition period:** Authorities can migrate to staker contract. Authority endorsement checked via `TransitionPeriodBalanceCheck` which accepts both PoA endorsement and staker contract balance +3. **Galactica fork:** BaseFee activated, `DynamicFee` tx type enabled, Shanghai EVM opcodes +4. **PoS activation:** When enough validators have staked, `SyncPOS` returns `Active: true` and scheduling switches from PoA to PoS + +### Contract Balance Invariant + +`ContractBalanceCheck(pendingWithdraw)` is called after every state-changing operation: + +``` +locked + queued + withdrawable + cooldown + pendingWithdraw == contract VET balance + == effectiveVET (slot 0) +``` + +Any mismatch is a consensus-level error. diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-sync.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-sync.md new file mode 100644 index 0000000000000000000000000000000000000000..49fbe018b9a49b329877e79dd31b5383ef49af3a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-sync.md @@ -0,0 +1,223 @@ +# Chain Synchronization Flow + +How a node discovers peers, downloads blocks, validates them, and handles forks. + +## Overview + +``` +p2p/p2psrv/ → comm/ → consensus/ → chain/ → bft/ + │ │ │ │ │ + Discover Download Validate Store Finalize +``` + +## Step 1: Peer Discovery and Connection + +**Package:** `p2p/`, `p2psrv/` + +The P2P layer uses a devp2p-compatible stack with Kademlia-based discovery (discv5). + +**Discovery topic:** `thor1@` — ensures peers are on the same network. + +**Handshake** (`Communicator.runPeer`): +1. 5-second timeout for status exchange +2. Verify `GenesisBlockID` matches +3. Verify system clock diff ≤ `2 × BlockInterval` +4. Exchange `{BestBlockID, TotalScore, SysTimestamp}` +5. Add to `PeerSet`, track head block and total score + +**Key types:** +- `comm.Communicator` — orchestrates sync, tx relay, block announcements +- `comm.Peer` — wraps `p2p.Peer` with block/tx knowledge tracking +- `comm.PeerSet` — thread-safe peer collection with filtering + +## Step 2: Initial Sync + +**Package:** `comm/communicator.go`, `comm/sync.go` + +`Communicator.Sync()` runs a timer-based sync loop: + +``` +1. Find peer with TotalScore ≥ our best block's TotalScore +2. download(ctx, repo, peer, headNum, handler) → stream blocks +3. Repeat until synced (best block time + BlockInterval ≥ now, or >2 sync rounds) +4. Close syncedCh → triggers packer loop and tx sync +``` + +### Download Pipeline (Three-Stage) + +``` +Stage 1: fetchRawBlockBatches → rawBatches channel (cap 10) +Stage 2: decodeAndWarmupBatches → warmedUp channel (cap 2048) +Stage 3: handler (processBlock) → commit to chain +``` + +**Stage 1** — fetches raw RLP-encoded blocks from peer via `proto.GetBlocksFromNumber`: +- Requests blocks starting from `ancestor + 1` +- Batches of raw bytes sent to channel +- Stops when peer returns empty result + +**Stage 2** — decodes and pre-warms caches in parallel: +- RLP decode each block +- Verify block number sequence +- Parallel cache warm-up: `header.ID()`, `header.Beta()`, `tx.ID()`, `tx.IntrinsicGas()`, `tx.Delegator()` +- Throttling: inserts nil blocks when buffer > 10% full to reduce memory pressure + +**Stage 3** — `node.handleBlockStream` processes each block through `processBlock` + +### Common Ancestor Discovery + +`findCommonAncestor(ctx, repo, peer, headNum)`: + +1. **Fast seek:** Exponential backward scan (1, 2, 4, 8, ... blocks back) using `proto.GetBlockIDByNumber` +2. **Binary search:** Between fast-seek result and head, find exact fork point +3. Returns the highest block number both nodes agree on + +## Step 3: Block Processing During Sync + +**Package:** `cmd/thor/node/block_exec.go` + +`Node.processBlock(block, stats)`: + +1. **Guard processing:** Lock + conflict detection + - If `blockNum > maxBlockNum + 1` → `errBlockTemporaryUnprocessable` + - Otherwise, count existing blocks at same height (`ScanConflicts`) + +2. **BFT acceptance:** `bft.Accepts(parentID)` — reject if parent not on finalized branch + +3. **Consensus processing:** `consensus.Process(parentSummary, block, now, conflicts)` → `stage, receipts` + - Full header, proposer, body, and execution validation (see block production flow) + +4. **Fork choice:** + - Post-FINALITY: `bft.Select(header)` — quality-based selection + - Pre-FINALITY: `header.BetterThan(prevBest)` — total score comparison + +5. **Commit:** `commitBlock(ctx)`: + - Write logs to `logdb` (if becoming best and logs enabled) + - `stage.Commit()` — persist state trie + - `repo.AddBlock(block, receipts, conflicts, becomeBest)` + - `bft.CommitBlock(header, isPacking=false)` + - If becoming best: `processFork` to re-add orphaned txs + +### Error Handling + +| Error | Action | +|-------|--------| +| `errKnownBlock` | Ignore (already stored) | +| `errFutureBlock` | Queue (block timestamp too far ahead) | +| `errParentMissing` | Queue (parent not yet received) | +| `errBlockTemporaryUnprocessable` | Queue (block number too far ahead) | +| `errBFTRejected` | Discard (conflicts with finalized checkpoint) | +| Consensus critical error | Log error, discard block | + +## Step 4: Steady-State Block Propagation + +**Package:** `comm/communicator.go`, `comm/announcement_loop.go` + +Once synced, new blocks arrive via two mechanisms: + +### Direct Block Push + +Peers call `proto.NotifyNewBlock(peer, block)` — sends full block to √N random peers: + +```go +p := int(math.Sqrt(float64(len(peers)))) +toPropagate := peers[:p] // send full block +toAnnounce := peers[p:] // send just block ID +``` + +### Block ID Announcement + +Remaining peers receive just the block ID via `proto.NotifyNewBlockID`. The announcement loop processes these: + +1. Receive announcement with `{blockID, senderPeer}` +2. If block unknown: fetch from peer via `proto.GetBlockByID` +3. Process via `processBlock` +4. If accepted as trunk: broadcast to our peers + +### Transaction Propagation + +**Package:** `comm/txs_loop.go` + +- After sync completes: `syncTxs(peer)` — bulk fetch txs from connected peer +- Ongoing: `txFeed` subscription relays new executable txs to peers +- Peer tracking: `peer.MarkTransaction(hash)` prevents duplicate sends + +## Step 5: Fork Handling + +### Fork Detection + +Forks are detected when `processBlock` finds the new block becomes best but the previous best was at the same height on a different branch. + +### Fork Resolution + +`Node.processFork(newBlock, oldBestBlockID)`: + +```go +oldTrunk := repo.NewChain(oldBestBlockID) +newTrunk := repo.NewChain(newBlock.ParentID()) +sideIDs := oldTrunk.Exclude(newTrunk) // blocks on old branch not on new + +for _, id := range sideIDs { + block := repo.GetBlock(id) + for _, tx := range block.Transactions() { + txPool.Add(tx) // re-add orphaned txs to pool + } +} +``` + +The `Chain.Exclude(other)` method walks backwards from the chain head, finding blocks present in one chain but not the other. + +### Log Rewriting on Fork + +```go +oldBranch := oldTrunk.Exclude(newTrunk) +if len(oldBranch) > 0 { + logDB.Writer.Truncate(forkPoint) // remove old branch logs +} +newBranch := newTrunk.Exclude(oldTrunk) +for _, id := range newBranch { + logDB.Writer.Write(block, receipts) // write new branch logs +} +``` + +### BFT Finality and Fork Prevention + +Post-FINALITY fork, the BFT engine prevents deep reorgs: + +- `bft.Accepts(parentID)` rejects blocks whose parent is not a descendant of the finalized checkpoint +- `bft.Select(header)` prefers higher quality (more epoch votes) over total score +- Once a checkpoint is finalized, all blocks not descending from it are permanently rejected + +## Node Startup Sequence + +**Package:** `cmd/thor/node/node.go` + +```go +func (n *Node) Run(ctx context.Context) error { + maxBlockNum := repo.GetMaxBlockNum() + txStash := newTxStash(db, 1000) + + // Four concurrent goroutines: + go n.comm.Sync(ctx, n.handleBlockStream) // sync + block processing + go n.houseKeeping(ctx) // periodic maintenance + go n.txStashLoop(ctx, txStash) // persist non-executable txs + go n.packerLoop(ctx) // block production (waits for sync) +} +``` + +The `packerLoop` blocks on `comm.Synced()` channel before starting block production. + +## Protocol Messages + +**Package:** `comm/proto/` + +| Message | Direction | Purpose | +|---------|-----------|---------| +| `GetStatus` | Request | Exchange genesis ID, best block, total score | +| `GetBlocksFromNumber` | Request | Batch download blocks for sync | +| `GetBlockIDByNumber` | Request | Common ancestor discovery | +| `GetBlockByID` | Request | Fetch single block | +| `NotifyNewBlock` | Push | Propagate full block | +| `NotifyNewBlockID` | Push | Announce new block (lightweight) | +| `GetTxs` | Request | Bulk tx sync after initial sync | +| `NotifyNewTx` | Push | Relay new executable transaction | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-transaction-lifecycle.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-transaction-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..936f768c8ebd1955321b5e9b44c58770f9b6ce86 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-transaction-lifecycle.md @@ -0,0 +1,198 @@ +# Transaction Lifecycle Flow + +End-to-end journey of a transaction from submission to on-chain finality. + +## Overview + +``` +API/P2P → txpool/ → packer/ → runtime/ → chain/ → logdb/ + │ │ │ │ │ │ +Receive Validate Select Execute Store Index logs +``` + +## Step 1: Transaction Receipt + +Transactions enter the node through two paths: + +| Entry Point | Package | Method | +|-------------|---------|--------| +| REST API `POST /transactions` | `api/transactions/` | `TxPool.AddLocal(tx)` | +| P2P propagation | `comm/handle_rpc.go` | `TxPool.Add(tx)` or `TxPool.StrictlyAdd(tx)` | +| Sync from peer | `comm/sync.go` | `TxPool.StrictlyAdd(tx)` | + +## Step 2: Transaction Types + +**Package:** `tx/` + +Two transaction types (starting from Galactica fork): + +| Field | `TypeLegacy` (0x00) | `TypeDynamicFee` (0x51) | +|-------|---------------------|------------------------| +| Gas pricing | `GasPriceCoef` (0–255) over `BaseGasPrice` | `MaxFeePerGas` + `MaxPriorityFeePerGas` | +| Encoding | RLP list | Type-prefix + RLP | +| Work proofs | `ProvedWork` for priority boost | Not applicable | + +**Common fields** (both types): +- `ChainTag` — last byte of genesis ID +- `BlockRef` — first 8 bytes of a recent block hash (establishes tx validity window) +- `Expiration` — valid from `BlockRef.Number` to `BlockRef.Number + Expiration` +- `Clauses` — array of `{To, Value, Data}` (multi-clause model) +- `Gas` — max gas +- `DependsOn` — optional tx dependency +- `Nonce` — replay protection (not sequential like Ethereum) +- `Reserved` — feature flags (e.g., `DelegationFeature` for VIP-191) + +**Key types:** +- `tx.Transaction` — immutable, caches signingHash/origin/id/intrinsicGas +- `tx.Clause` — `{To *Address, Value *big.Int, Data []byte}` +- `tx.BlockRef` — 8-byte block reference +- `tx.Features` — bit flags (delegation support) + +**ID calculation:** `tx.ID = Blake2b(signingHash, origin)` — unique per sender. + +## Step 3: TxPool Validation and Storage + +**Package:** `txpool/` + +`TxPool.add()` performs staged validation: + +### Static validation (`validateTxBasics`) +1. Signature low-S check (`EnforceSignatureLowS`) +2. Chain tag matches `repo.ChainTag()` +3. Size ≤ `MaxTxSize` (64 KB) + +### Blocklist check +- Origin and delegator checked against both hardcoded blocklist and fetched blocklist + +### Resolution +`ResolveTx(tx)` → `TxObject` with computed `origin`, `priorityGasPrice` + +### Executability check (when chain is synced) +`TxObject.Executable()` verifies against current state: +- Tx not already on chain +- Block ref in valid range, not expired +- Dependencies resolved (not reverted) +- Sufficient VTHO balance for gas cost +- Post-Galactica: effective gas price ≥ baseFee + +### Pool management +- Pool limit: `Options.Limit` (default ~10k) +- Per-account limit: `Options.LimitPerAccount` +- Non-executable cap: 20% of pool limit +- Priority eviction: sorted by `priorityGasPrice` descending + +### Housekeeping (every second) +The `wash()` routine: +1. Removes expired, settled, blocked, energy-depleted txs +2. Recalculates `priorityGasPrice` when baseFee changes +3. Produces sorted `Executables()` list for the packer + +**Key types:** +- `txpool.TxPool` — `{all *txObjectMap, executables atomic.Value}` +- `txpool.TxObject` — wraps `tx.Transaction` with `executable bool`, `priorityGasPrice` +- `txpool.TxEvent` — `{Tx, Executable *bool}` — published to subscribers (comm layer for P2P broadcast) + +## Step 4: Transaction Selection for Block + +**Package:** `packer/` + +In `proposeAndCommit` (node packer loop): + +```go +txs := n.txPool.Executables() // sorted by priority gas price desc +for _, tx := range txs { + err := flow.Adopt(tx) + if packer.IsGasLimitReached(err) { break } + if packer.IsTxNotAdoptableNow(err) { continue } + // bad tx → mark for removal +} +``` + +`Flow.Adopt` performs final checks (see block production flow) and calls `runtime.ExecuteTransaction`. + +Error categories: +- `badTxError` — permanent rejection (wrong chain tag, expired, blocked origin) +- `errTxNotAdoptableNow` — temporary (future block ref, gas too high for remaining space) +- `errGasLimitReached` — block full, stop adopting +- `errKnownTx` — already on chain + +## Step 5: Clause Execution + +**Package:** `runtime/` + +VeChain's multi-clause model executes multiple operations atomically in one tx. + +### Execution flow per transaction + +``` +ResolveTransaction(tx) → ResolvedTransaction + └─ BuyGas(state, blockTime, baseFee) → deduct VTHO from payer + └─ For each clause: + └─ PrepareClause → EVM.Call or EVM.Create + └─ Output{Events, Transfers, LeftOverGas, VMErr} + └─ Finalize → Receipt +``` + +### Gas payer resolution order (BuyGas) +1. **Delegator** (VIP-191) — if tx has delegation feature + delegator signature +2. **Sponsor** — if all clauses share same `To` and user has credit via `Prototype.Bind` +3. **Contract `To`** — if sponsor insufficient but user has credit +4. **Origin** — fallback + +### Clause execution detail +- Each clause gets its own EVM instance via `PrepareClause` +- Contract creation: `clause.To == nil` → `EVM.Create` +- Native contract calls intercepted via `InterceptContractCall` (builtin contracts) +- On any clause VM error: **all clauses revert** to checkpoint + +### Receipt generation +```go +Receipt{ + Type: tx.Type(), + Reverted: reverted, + Outputs: []{Events, Transfers}, // nil if reverted + GasUsed: tx.Gas() - leftOverGas, + GasPayer: payer, + Paid: gasUsed * effectiveGasPrice, + Reward: priorityFeePerGas * gasUsed, // post-Galactica +} +``` + +## Step 6: Storage and Indexing + +### Block storage (`chain/`) +When the block is committed via `Repository.AddBlock`: +- Tx blobs → `bodyStore` keyed by `(blockNum, conflicts, index, txFlag)` +- Receipt blobs → `bodyStore` keyed by `(blockNum, conflicts, index, receiptFlag)` +- Tx metadata → `txIndexer` keyed by `txID + varint(blockNum) + varint(conflicts)` +- Filter key → `txIndexer` keyed by first 8 bytes of txID (bloom-like fast lookup) + +### Log indexing (`logdb/`) +`LogDB` (SQLite) indexes events and transfers for query: +- **Events table:** `blockNum, txIndex, clauseIndex, address, topic0–4, data` +- **Transfers table:** `blockNum, txIndex, clauseIndex, sender, recipient, amount` +- Written by `node.writeLogs()` → `logdb.Writer.Write(block, receipts)` +- On fork: `Writer.Truncate(forkPoint)` then re-write new branch + +## Step 7: Query + +Transactions become queryable via: + +| Endpoint | Source | Key | +|----------|--------|-----| +| `GET /transactions/{id}` | `chain.Chain.GetTransaction(id)` | txID → txMeta → tx blob | +| `GET /transactions/{id}/receipt` | `chain.Chain.GetTransactionReceipt(id)` | txID → txMeta → receipt blob | +| `POST /logs/event` | `logdb.LogDB.FilterEvents()` | SQLite query with address/topic filters | +| `POST /logs/transfer` | `logdb.LogDB.FilterTransfers()` | SQLite query with sender/recipient filters | + +## Error Paths Summary + +| Stage | Error | Result | +|-------|-------|--------| +| TxPool add | Bad signature, wrong chain tag, too large | `badTxError` — rejected | +| TxPool add | Pool full, non-executable | `txRejectedError` — rejected | +| TxPool wash | Expired, settled, insufficient energy | Removed from pool | +| Packer adopt | Expired, duplicate, gas limit | Skip or stop packing | +| Runtime execute | Intrinsic gas > provided gas | Tx not included | +| Runtime clause | VM revert/error | Receipt with `Reverted: true`, all clauses rolled back | +| Consensus verify | Mismatched receipts root, state root | Block rejected | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/p2p.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/p2p.md new file mode 100644 index 0000000000000000000000000000000000000000..9383cd24148e1eb024f675f58514b5a0f3505ba9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/p2p.md @@ -0,0 +1,178 @@ +# P2P Networking + +Thor uses Ethereum-derived devp2p networking: **discv5** for peer discovery, **RLPx** for encrypted connections, +and a custom `thor/1` protocol for block and transaction propagation. Default P2P port: **11235**. + +## Discovery — discv5 + +Located in `p2p/discv5/`. Ethereum-style v5 topic discovery over UDP. + +- Kademlia-like DHT with XOR distance metric +- Topic-based: nodes register/search by `thor1@` +- 257 buckets, 16 nodes per bucket, concurrency factor (alpha) = 3 + +### UDP Packet Types + +| Packet | Purpose | +|--------|---------| +| `ping` / `pong` | Liveness check | +| `findnode` / `neighbors` | Node lookup | +| `findnodeHash` | v5 lookup by hash | +| `topicRegister` / `topicQuery` / `topicNodes` | Topic discovery | + +### Key Constants + +| Constant | Value | +|----------|-------| +| Protocol version | 4 | +| Response timeout | 500ms | +| Packet expiration | 20s | +| Max packet size | 1280 bytes | +| Max neighbors per response | ~12 | +| Max findnode failures | 5 | +| Seed count | 30 | +| Seed max age | 5 days | +| Bucket refresh interval | 1 min | +| Auto-refresh interval | 1 hour | + +## ENR (Ethereum Node Records) + +Located in `p2p/enr/`. EIP-778 style records, max 300 bytes. + +| Entry Key | Type | Purpose | +|-----------|------|---------| +| `id` | `"v4"` | Identity scheme | +| `secp256k1` | compressed pubkey | Node identity | +| `ip` | IPv4/IPv6 | Network address | +| `tcp` | uint16 | TCP port | +| `udp` | uint16 | UDP discovery port | + +Signing uses `secp256k1-keccak` identity scheme (Keccak256 of RLP-encoded record). + +## NAT Traversal + +Located in `p2p/nat/`. Interface for port mapping. + +| Value | Mechanism | +|-------|-----------| +| `none` / `off` / `""` | No mapping | +| `any` / `auto` / `on` | Auto-detect (UPnP or NAT-PMP) | +| `upnp` | UPnP | +| `pmp` / `natpmp` | NAT-PMP | +| `extip:` | Fixed external IP | + +Mapping timeout: 20 min, update interval: 15 min. Maps both TCP (P2P) and UDP (discovery). + +## P2P Server + +Two layers: + +### p2psrv.Server (`p2psrv/`) + +High-level wrapper that integrates discv5 with the devp2p server: + +- Starts discv5 UDP listener +- NAT mapping for UDP port +- Registers genesis topic (`thor1@`) +- Runs discovery loop → feeds discovered nodes to dial loop +- Manages peer caches: `discoveredNodes` (RandCache, 128), `knownNodes` (PrioCache, 5) + +### p2p.Server (`p2p/server.go`) + +Low-level devp2p server: + +- RLPx encrypted TCP connections +- Protocol negotiation via capabilities +- Connection flags: `dynDialedConn`, `staticDialedConn`, `inboundConn`, `trustedConn` + +### Connection Management + +| Setting | Value | +|---------|-------| +| `--max-peers` | 25 (default) | +| `--p2p-port` | 11235 | +| Max active dial tasks | 16 | +| Default max pending peers | 50 | +| Dial timeout | 15s | +| Frame read timeout | 30s | +| Frame write timeout | 20s | +| DialRatio | `sqrt(MaxPeers)` | + +Inbound limit: `MaxPeers - maxDialedConns`. Trusted peers bypass limits. + +Dial pacing: 500ms for first 20 dials, 2s after, 10s when >50% peers connected. + +## Comm Protocol — Block & Transaction Propagation + +Located in `comm/`. Protocol: `thor/1`, max message size 10 MB. + +### Message Types + +| Code | Message | Type | Purpose | +|------|---------|------|---------| +| 0 | `MsgGetStatus` | Call | Handshake / status exchange | +| 1 | `MsgNewBlockID` | Notify | Announce new block (ID only) | +| 2 | `MsgNewBlock` | Notify | Broadcast full block | +| 3 | `MsgNewTx` | Notify | Broadcast transaction | +| 4 | `MsgGetBlockByID` | Call | Request block by ID | +| 5 | `MsgGetBlockIDByNumber` | Call | Request block ID by number | +| 6 | `MsgGetBlocksFromNumber` | Call | Request batch of blocks (sync) | +| 7 | `MsgGetTxs` | Call | Sync transactions | + +### Block Propagation + +- `BroadcastBlock()`: `sqrt(peers)` receive `MsgNewBlock` (full block), remaining peers get `MsgNewBlockID` +- Announced block IDs trigger fetch via `MsgGetBlockByID` in the announcement loop + +### Transaction Propagation + +- `txsLoop` subscribes to the tx pool +- `MsgNewTx` sent to peers that haven't seen the transaction +- After sync completes: `syncTxs()` via `MsgGetTxs` for catch-up + +### Sync + +`Sync()` selects the best peer (highest total score) and runs `download()` using `MsgGetBlocksFromNumber` to fetch block batches. + +## Bootstrap Nodes + +### disco Command (`cmd/disco/`) + +Standalone bootstrap node — UDP-only discv5 listener, no TCP, no thor protocol. + +| Flag | Default | Purpose | +|------|---------|---------| +| `--addr` | `:55555` | Listen address | +| `--keyfile` | auto | Private key file | +| `--keyhex` | — | Private key as hex | +| `--nat` | `none` | NAT mechanism | +| `--netrestrict` | — | CIDR whitelist | + +### Node Sources + +1. **Hardcoded fallback**: 11 bootstrap nodes in `cmd/thor/p2p/bootstrap.go` (port 55555) +2. **Remote list**: `https://vechain.github.io/bootstraps/node.list` (HTTP enode URLs) +3. **Peer cache**: `peers.cache` in instance dir — known nodes saved on shutdown + +## Default Ports + +| Port | Protocol | Use | +|------|----------|-----| +| 11235 | TCP | P2P connections (RLPx) | +| 55555 | UDP | Bootstrap node discovery | + +## Component Wiring + +``` +cmd/thor/main.go + → newP2PCommunicator() + → p2psrv.New(opts) // wraps p2p.Server, manages discv5 + → comm.New(...) // block/tx propagation logic + → p2pCommunicator.Start() + → p2psrv.Start(comm.Protocols(), comm.DiscTopic()) + → p2p.Server.Start() // TCP listener + → discv5.ListenUDP() // UDP discovery + → RegisterTopic("thor1@") + → discoverLoop() + dialLoop() + → comm.Start() // sync, broadcast loops +``` diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/solo.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/solo.md new file mode 100644 index 0000000000000000000000000000000000000000..d56acc156b9f07aa259e3535a361c805f491cfa7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/solo.md @@ -0,0 +1,135 @@ +# Solo Mode + +Solo mode runs a local single-node VeChain chain for development and testing. +No P2P networking, no real consensus — just a local sandbox with pre-funded accounts. + +## Starting Solo + +```bash +thor solo [flags] +``` + +### Solo-Specific Flags + +| Flag | Default | Description | +|------|---------|-------------| +| `--on-demand` | false | Create blocks only when pending transactions exist | +| `--block-interval` | 10 | Block interval in seconds | +| `--persist` | false | Persist data to disk (otherwise in-memory) | +| `--gas-limit` | 40,000,000 | Block gas limit (0 = adaptive) | +| `--genesis` | — | Custom genesis file path/URL (default: builtin devnet) | +| `--txpool-limit` | 10,000 | Transaction pool size | + +### Common Examples + +```bash +thor solo # basic, in-memory, 10s blocks +thor solo --on-demand # blocks only when txs arrive +thor solo --persist --on-demand # persistent + on-demand +thor solo --api-addr 0.0.0.0:8669 # expose API externally +thor solo --gas-limit 0 --api-cors="*" # adaptive gas, open CORS +``` + +## Mining Modes + +### Auto-Mining (Default) + +- Loop runs every second +- Produces a block when `time.Now().Unix() % blockInterval == 0` +- Creates empty blocks if no transactions + +### On-Demand (`--on-demand`) + +- Uses `OnDemandTxPool` instead of the standard tx pool +- Block produced immediately when an executable transaction is submitted +- Empty blocks are skipped +- Can produce blocks with future timestamps if needed + +## Pre-Funded Accounts + +10 accounts, each with **1,000,000,000 VET** (1e27 wei) in both balance and energy. + +Generated from fixed private keys in `genesis/devnet.go`: + +| # | Private Key | +|---|-------------| +| 0 | `99f0500549792796c14fed62011a51081dc5b5e68fe8bd8a13b86be829c4fd36` | +| 1 | `7b067f53d350f1cf20ec13df416b7b73e88a1dc7331bc904b92108b1e76a08b1` | +| 2 | `f4a1a17039216f535d42ec23732c79943ffb45a089fbb78a14daad0dae93e991` | +| 3 | `35b5cc144faca7d7f220fca7ad3420090861d5231d80eb23e1013426847371c4` | +| 4 | `10c851d8d6c6ed9e6f625742063f292f4cf57c2dbeea8099fa3aca53ef90aef1` | +| 5 | `2dd2c5b5d65913214783a6bd5679d8c6ef29ca9f2e2eae98b4add061d0b85ea0` | +| 6 | `e1b72a1761ae189c10ec3783dd124b902ffd8c6b93cd9ff443d5490ce70047ff` | +| 7 | `35cbc5ac0c3a2de0eb4f230ced958fd6a6c19ed36b5d2b1803a9f11978f96072` | +| 8 | `b639c258292096306d2f60bc1a8da9bc434ad37f15cd44ee9a2526685f592220` | +| 9 | `9d68178cdc934178cca0a0051f40ed46be153cf23cb1805b59cc612c0ad2bbe0` | + +Account #0 (`0xf077b491b355E64048cE21E3A6Fc4751eEeA77fa`) also serves as the executor and block signer (PoA validator). + +## Persistence + +| Mode | Storage | Behavior | +|------|---------|----------| +| Default (no `--persist`) | In-memory | Data lost on restart | +| `--persist` | Disk | Written to `--data-dir`, survives restarts | + +With `--persist`, instance directory follows the standard naming: `instance--`. + +## API Access + +Same HTTP API as a full node, default `localhost:8669`. Differences in solo: + +- **Debug API**: PoA checks skipped during trace replay (`skipPoA: true`) +- **Admin health**: always reports healthy (peer count check bypassed) +- **No P2P**: `solo.Communicator{}` is a no-op stub + +All standard flags work: `--api-addr`, `--api-cors`, `--api-timeout`, `--api-pprof`, etc. + +## Genesis Configuration + +Default solo genesis is the **devnet** config (`genesis/devnet.go`): + +- Genesis ID: `0x00000000bb55405beed90df9fea5acdb1cb7caba61b0d7513395f42efd30e558` +- All forks enabled from block 0 (`SoloFork`) +- Initial gas limit: 10,000,000 (overridable via `--gas-limit`) + +```go +SoloFork = ForkConfig{ + VIP191: 0, ETH_CONST: 0, BLOCKLIST: 0, ETH_IST: 0, + VIP214: 0, FINALITY: 0, GALACTICA: 0, HAYABUSA: 0, +} +``` + +Custom genesis can be provided via `--genesis `. + +## Solo vs Testnet/Mainnet + +| Aspect | Solo | Testnet/Mainnet | +|--------|------|-----------------| +| P2P networking | None | Full discv5 + RLPx | +| Consensus | Mocked BFT engine | Real BFT with PoA/PoS | +| Genesis | Devnet (all forks at block 0) | Network-specific fork schedule | +| Block production | Local packer (auto or on-demand) | Committee-based | +| Master key | Not required | Required for block signing | +| Persistence | Optional (in-memory default) | Always on disk | +| Pre-funded accounts | 10 × 1B VET | None | + +## Use Cases + +- **Smart contract development**: deploy and test contracts with instant feedback +- **dApp development**: full API available locally, no sync delay +- **Integration testing**: deterministic blocks, predictable behavior +- **CI pipelines**: lightweight, fast startup, no external dependencies +- **On-demand mode**: block only when you transact, ideal for scripted tests + +## Key Source Files + +| File | Purpose | +|------|---------| +| `cmd/thor/solo/solo.go` | Solo entry point and main loop | +| `cmd/thor/solo/core.go` | Block packing logic | +| `cmd/thor/solo/txpool.go` | On-demand transaction pool | +| `cmd/thor/solo/types.go` | Solo communicator stub | +| `genesis/devnet.go` | Devnet genesis, DevAccounts, SoloConfig | +| `thor/fork_config.go` | SoloFork definition | +| `bft/engine.go` | soloMockedEngine | diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/storage.md b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/storage.md new file mode 100644 index 0000000000000000000000000000000000000000..4287b8e18a7e27e1fa699cfbd70aff42f056c5db --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/storage.md @@ -0,0 +1,203 @@ +# Storage Architecture + +Thor uses a layered storage design: **MuxDB** (LevelDB) for blockchain state and chain data, +**LogDB** (SQLite) for event/transfer logs, and a Merkle-Patricia trie for state management. + +## MuxDB — Main Database + +Central storage abstraction in `muxdb/`. Wraps LevelDB and manages trie nodes + named KV stores. + +### Key Spaces + +| Space | Byte Prefix | Purpose | +|-------|-------------|---------| +| `trieHistSpace` | 0 | Historical trie nodes (versioned, prunable) | +| `trieDedupedSpace` | 1 | Deduplicated trie nodes (checkpointed, permanent) | +| `namedStoreSpace` | 2 | Named KV stores for chain data | + +### Named KV Stores + +| Store | Contents | +|-------|----------| +| `chain.hdr` | Block headers | +| `chain.body` | Block bodies | +| `chain.props` | Chain properties | +| `chain.heads` | Chain head pointers | +| `chain.txi` | Transaction index | +| `state.code` | Contract bytecode | +| `muxdb.props` | DB config (partition factors) | +| `pruner.props` | Pruner checkpoint state | + +### Trie Names + +| Name | Purpose | +|------|---------| +| `"a"` | Account trie (address → account + metadata) | +| `"i"` | Index trie (block index) | +| `"s"` + storageID | Per-contract storage tries | + +## LevelDB — Underlying Engine + +Engine: `syndtr/goleveldb` via `engine.LevelEngine`. + +| Setting | Default | Description | +|---------|---------|-------------| +| BlockCacheCapacity | `ReadCacheMB` (256 MB) | Read cache | +| WriteBuffer | `WriteBufferMB` (128 MB) | Write buffer | +| Filter | Bloom 10-bit | Block filter | +| BlockSize | 32 KB | Data block size | +| CompactionTableSize | 4 MB | SST file size | +| OverflowPrefix | `trieHistSpace` | Compaction hint (when pruning enabled) | + +Configured via `--cache` flag (default 4096 MB total). + +## LogDB — Event and Transfer Logs (SQLite) + +SQLite database (`mattn/go-sqlite3`) with WAL journal mode. + +### Schema + +**ref table** — blob deduplication for blockID, txID, addresses, topics: + +```sql +CREATE TABLE ref (id INTEGER PRIMARY KEY, data BLOB NOT NULL UNIQUE); +``` + +**event table:** + +```sql +CREATE TABLE event ( + seq INTEGER PRIMARY KEY, + blockID, blockTime, txID, txOrigin, clauseIndex, + address, topic0, topic1, topic2, topic3, topic4, + data BLOB +); +``` + +Indexes on address, topic combinations (6 indexes total, one optional via `--logdb-additional-indexes`). + +**transfer table:** + +```sql +CREATE TABLE transfer ( + seq INTEGER PRIMARY KEY, + blockID, blockTime, txID, txOrigin, clauseIndex, + sender, recipient, amount BLOB(32) +); +``` + +Indexes on txOrigin, sender, recipient. + +### Query API + +- `FilterEvents(ctx, *EventFilter)` — range (block from/to), criteria (address, topics), order, limit +- `FilterTransfers(ctx, *TransferFilter)` — same pattern + +`seq` encodes block number + tx index + log index for ordering. + +Journal size limit: 50 MB. Separate read-only and write connections. + +## Merkle-Patricia Trie + +Located in `trie/`. Versioned Merkle-Patricia trie for state management. + +### Node Types + +| Type | Description | +|------|-------------| +| `fullNode` | 17 children (16 hex nibbles + value) | +| `shortNode` | Compressed path key + single child | +| `refNode` | Hash + version (database reference) | +| `valueNode` | Leaf value + metadata | + +### Version + +`Version{Major, Minor uint32}` — major is block number, minor is sub-index within block. + +### Read Path + +cache → hist space → deduped space (with fallback handling for account/index roots). + +### Write Path + +`Commit()` writes to hist space, optionally populates cache. `Checkpoint()` copies nodes from hist to deduped space for a version range. + +Empty root: `thor.Blake2b(rlp.EmptyString)`. + +## State Management + +Located in `state/`. Connects tries to the EVM execution layer. + +``` +revert-able state → stacked map → journal → playback → updated trie + → trie cache → read-only trie +``` + +**State** struct holds: +- Account trie (`"a"`) +- Per-address cached objects (account data, code, storage trie, storage map) +- `StackedMap` for revertable changes (EVM snapshots) + +**Stage/Commit**: `Stage(newVersion)` computes state root, returns `Stage` with `commit()` that writes code and commits all tries. + +## Pruning + +Located in `cmd/thor/pruner/`. Removes historical trie nodes to reclaim disk space. + +### How It Works + +1. Runs periodically: every 65536 blocks (or 8192 when nearly synced) +2. **Checkpoint**: copies trie nodes from hist → deduped space for `[base, target)` range +3. **Delete**: removes hist nodes in that range via `DeleteTrieHistoryNodes()` +4. Preserves `MaxStateHistory` (65535 blocks) of recent history for EVM access + +### Configuration + +| Flag | Effect | +|------|--------| +| `--disable-pruner` | Stops pruner, keeps all history (archive mode) | + +When disabled: `TrieHistPartitionFactor` = 524288 (vs 256 for pruning), instance dir gets `-full` suffix. + +### Partition Factors + +| Setting | Pruning | Archive | +|---------|---------|---------| +| `TrieHistPartitionFactor` | 256 | 524288 | +| `TrieDedupedPartitionFactor` | MaxUint32 | MaxUint32 | +| `TrieCachedNodeTTL` | 30 | 30 | + +## Node Types vs Storage + +| Type | Flags | Disk Size | Notes | +|------|-------|-----------|-------| +| **Full** | (default) | ~200 GB | Pruned trie history + logs | +| **Full without logs** | `--skip-logs` | ~100 GB | No event/transfer logs, `/logs` API disabled | +| **Archive** | `--disable-pruner` | >400 GB | All trie history preserved | + +Instance directory naming: `instance--[-full]`. + +## Cache Layer + +| Cache | Implementation | Size | Purpose | +|-------|---------------|------|---------| +| Trie node cache | `directcache` | 1/4 queried + 3/4 committed | Hot trie nodes | +| Root cache | Map + TTL eviction | — | Trie roots | +| Chain summaries | ARC | 512 | Block summaries | +| Chain txs | ARC | 2048 | Transactions | +| Chain receipts | ARC | 2048 | Receipts | +| Code cache | ARC | 512 | Contract bytecode | +| Future blocks | `RandCache` | 32 | Blocks ahead of head | +| Base fee | Custom | — | Cached base fee calculations | +| LevelDB | Block cache + write buffer | Configurable | Engine-level I/O cache | + +## Component Wiring + +``` +main.go + → openMainDB() → muxdb.Open(path, opts) → LevelDB engine + → openLogDB() → logdb.New(path) → SQLite + → chain.NewRepository(mainDB, genesis) → named KV stores for headers/bodies/txindex + → state.NewStater(mainDB) → account trie + storage tries + → pruner.New(mainDB, repo, bftEngine) // unless --disable-pruner +``` diff --git a/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/task.json b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d5b89d1a208d47be552b2d119e4f0a8f39d9d2d6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/task.json @@ -0,0 +1,59 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "52e614810e2bad9f", + "query_id": "52e614810e2bad9f_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "6e03e0e08a473fdaf2863f69c3c6cdf65c07d2b5616413605762ad220c51eb05", + "name": "thor", + "package_path": "skill", + "install_name": "thor-bac1a51b" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "6e03e0e08a473fdaf2863f69c3c6cdf65c07d2b5616413605762ad220c51eb05", + "files": { + "SKILL.md": "9ba94f15b3e339d679c1b327fb70518c7db5341d7d89bb755a079fa32e45b8a6", + "references/api.md": "606bf39075cb5d68d3818cbfdbc5343fdd73cb23039d0d7b4b53d2dfc965df87", + "references/architecture.md": "c2e7013dbcf530c3a5031c96c7402edcbd010c4f95a06881163dbfc6051a861a", + "references/built-in-contracts.md": "072772cb4eba8cfe4dc0dc43726df5f8e196589a68f78e27b44522068a7f1231", + "references/consensus.md": "cf9308b0efba984d0cfe397572a16f99e2ddcc8d7cae9571956f43193987871f", + "references/contributing.md": "19902dae3ce9390fdf99981c2c05c7e1ef6f63a0e0e14c3dcb94ea19fae2a9c5", + "references/flow-block-production.md": "9994ccd82fc056abaf6bbd14217e7f2a6af966ede9c0b7b1d42eb7be1ecd60d4", + "references/flow-reward-distribution.md": "82162db97b58b0c1558d32ab76bca8cd480808387cf9957f5c5f44869acbea3a", + "references/flow-staking-delegation.md": "5dbf9aa93c97bc2d257fe83ae3517a91a4281f3e061a60211eed97ecad2aa043", + "references/flow-sync.md": "f00921750fe3df7f9a42119b3eabf23237148c05f153f37fedf0c0a214e58e04", + "references/flow-transaction-lifecycle.md": "6d87684d24459bfdfdccec2f5f04b96976ce6a6c57c0d8e0385b23bd491ae983", + "references/p2p.md": "5692b798f7dd9917e146224d371cab33e65b983b579d1bb5790051fcc38dd0c7", + "references/solo.md": "5b4a0ae18ac3366babe96c49bdafaa28cad5f22edf8f57beaba58a95b801344b", + "references/storage.md": "ada58c7a339cc3cb5f99e3eace56d9ba877feeac4cb125e01dd252d546f95276" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "bac1a51be2671cbd77342bd8ae09d996ef03c3a8d62bbff3444600d966fc8029" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..4ceeece0450bce94cfe0f2be0809fb33708d5b5b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1308 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + actual = json.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..954d08b8187699c9486e6e9e10703e47cc899d5e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,378 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + + +# R7: unwrap only execution wrappers whose effect is proved in this subset. +# In particular `command -v/-V` queries do not run their operand, and `builtin` +# cannot run an external tool. Keep these distinctions before inspecting state. +_BASH_BUILTINS = frozenset({ + ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', + 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs', + 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', + 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', + 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', + 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', + 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', + 'unset', 'wait', +}) +_UNSUPPORTED_STATE = frozenset({ + '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap', + 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local', + 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift', + '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts', +}) + + +def _bash_dialect(text): + """No shebang uses the evaluator's Bash syntax contract; sh is not Bash.""" + first = str(text).splitlines()[0] if str(text).splitlines() else '' + if not first.startswith('#!'): + return True + try: + words = shlex.split(first[2:]) + except ValueError: + return False + if not words: + return False + executable = words[0].rsplit('/', 1)[-1] + if executable == 'env': + words = words[1:] + if words[:1] == ['-S']: + words = words[1:] + executable = words[0] if words else '' + return executable.rsplit('/', 1)[-1] == 'bash' + + +def _execution_argv(argv, bash=True): + """Normalize a finite chain; unsupported wrappers get no command credit.""" + if not argv: + return None + argv = list(argv) + while argv and argv[0] in ('command', 'builtin'): + wrapper = argv[0] + if wrapper == 'builtin': + if not bash: + return None + argv = argv[1:] + if argv[:1] == ['--']: + argv = argv[1:] + if not argv or argv[0] not in _BASH_BUILTINS: + return None + continue + index, query, default_path = 1, False, False + while index < len(argv) and argv[index].startswith('-'): + option = argv[index] + index += 1 + if option == '--': + break + if not re.fullmatch(r'-[pvV]+', option): + return None + query = query or 'v' in option or 'V' in option + default_path = default_path or 'p' in option + if query: + return argv # Query is an invocation of command, not its target. + if index == len(argv): + return None + argv = argv[index:] + # -p changes external PATH lookup. It is transparent for builtins only. + if default_path and argv[0] not in _BASH_BUILTINS: + return None + return argv or None + + +def _set_errexit(argv, current): + """Return the proven option state, or None for unsupported set options.""" + if not argv or argv[0] != 'set': + return None + index = 1 + while index < len(argv): + flag = argv[index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Positional arguments cannot enable errexit. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return None # Includes noexec (-n), which suppresses later work. + if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1): + return None + if 'e' in flag[1:]: + current = flag[0] == '-' + if 'o' in flag[1:]: + if index + 1 >= len(argv): + return None + option = argv[index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return None + if option == 'errexit': + current = flag[0] == '-' + index += 1 + index += 1 + return current + + +def shell_option_setting(text, bash=True): + """Recognize valid option setup for task-specific operation counters.""" + argv = _execution_argv(_simple_argv(text), bash) + return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None) + + +def _exit_status(argv): + """A literal shell exit status; no-argument exit is handled by its caller.""" + args = argv[1:] + if args[:1] == ['--']: + args = args[1:] + if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0]) + or len(args[0]) > 20): + return None + value = int(args[0]) + if not -(2**63) <= value <= 2**63 - 1: + return 2 # Bash exits for an out-of-range numeric argument. + return value % 256 + + + +def _nonzero_exit_body(statements, bash=True): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _execution_argv(_simple_argv(statement), bash) + if not argv: + return False + if argv[0] == 'exit': + status = _exit_status(argv) + return index == len(statements) - 1 and status is not None and status != 0 + if argv[0] not in ('echo', 'printf'): + return False + return False + + +def shell_invocations(text): + """Return ordered, actually evaluated invocation nodes in the supported subset. + + fail_fast is a structural proof: a simple command/assignment runs under + errexit, or a negated test exits nonzero on failure. This is not a complete + shell interpreter, and unsupported syntax earns no invocation credit. + """ + statements = _statements(text) + bash = _bash_dialect(text) + # Function definitions or dynamic shell mutation can shadow the command or + # `exit` itself. They are outside this objective subset, even if uncalled. + 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) + or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s) + for s in statements): + return [] + constants, result, index, errexit = {}, [], 0, False + assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while index < len(statements): + statement = statements[index] + literal = assignment.fullmatch(statement) + if literal: + constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None) + index += 1 + continue + statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement) + if re.match(r'^if\s', statement): + end = _guard_end(statements, index) + if end is None: + return [] + negated = re.fullmatch(r'if\s+!\s+(.+)', statement) + if (negated and index + 1 < end + and statements[index + 1] == 'then' + and _nonzero_exit_body(statements[index + 2:end], bash)): + argv, kind = _invocation(negated.group(1).strip()) + argv = _execution_argv(argv, bash) + if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')): + return [] + if argv: + if argv[0] == 'false': + break + result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind, + 'fail_fast': True, 'statement_index': index, 'expanded_statement': statement}) + else: + return [] + else: + # Arbitrary conditions may terminate the script or shadow its + # commands. Do not infer a reachable suffix through them. + return [] + # Bodies are never credited and may have assigned local variables. + constants.clear() + index = end + 1 + continue + if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{': + # Unsupported compounds are not searched for command substrings. + return [] + argv, kind = _invocation(statement) + argv = _execution_argv(argv, bash) + if not argv: + # An unparsed statement may change control flow or shell state. + # Skipping it would incorrectly credit an unreachable suffix. + return [] + if argv[0] in _UNSUPPORTED_STATE: + return [] + if argv[0] == 'hash': + # Clearing/querying/cache lookup preserves the command's selected + # executable. An explicit -p binding can replace a required tool. + operands, flags = [], '' + option_mode = True + for word in argv[1:]: + if option_mode and word == '--': + option_mode = False + elif option_mode and word.startswith('-'): + if not re.fullmatch(r'-[lrdt]+', word): + return [] + flags += word[1:] + else: + option_mode = False + if '$' in word: + return [] + operands.append(word) + if ('d' in flags or 't' in flags) and not operands: + return [] + if argv[0] == 'set': + new_errexit = _set_errexit(argv, errexit) + if new_errexit is None: + return [] + if kind == 'simple': + errexit = new_errexit + index += 1 + continue + # An assignment substitution runs in a subshell: set cannot change + # the parent's flags. Keep it as an ordinary evaluated node. + if argv[0] == 'exit': + if kind == 'simple': + # Only a literal, zero/one-argument exit is proved terminal. + # An invalid multi-argument exit can return and is unsupported. + if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None: + break + return [] + status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv) + if status is None: + return [] + if status and errexit: + break + if argv[0] == 'false' and errexit: + break + if kind == 'assignment_substitution': + assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement) + if assigned: + constants.pop(assigned.group(1), None) + result.append({'command': shlex.join(argv), 'kind': kind, + 'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement}) + index += 1 + return result diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}} +if [[ -z "$candidate" ]]; then + echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..47053a177ac7435d8351341ac7cc728b048a2e67 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,516 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + return json.loads(text) + + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + pred = _atomic_prepare(_json_value(solver_output), + verifier.get("list_order", "ordered")) + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], _atomic_shape(pred)) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = (_path_value(actual) is not None and + _path_value(actual) == _path_value(assertion["expected"])) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..4df26c2ffaf32ee54a18bcb00381e1aef3ec640d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""Task-scoped semantic equivalences for the 112 legacy verifier repairs. + +No solver, oracle label, historical score or answer hash influences comparison. +The original private rubric, completeness checks and binary aggregation remain. +""" +from __future__ import annotations +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import copy +import json +import re +import shlex +import shutil +import tempfile +from decimal import Decimal, InvalidOperation +from pathlib import Path + + +def argv(value): + if not isinstance(value, str): + return None + try: + result = shlex.split(value, posix=True) + except ValueError: + return None + # Only the Bash execution wrapper is transparent. command -v/-V are queries. + while len(result) > 1 and result[0] == 'command': + if result[1] == '--': + result = result[2:] + elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]): + break + else: + result = result[1:] + return result or None + + +def git_limit(tokens): + if not tokens or tokens[:2] != ['git', 'log']: + return tokens + out, index = [], 0 + while index < len(tokens): + token = tokens[index] + compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token) + if compact: + out.append('--max-count=' + next(x for x in compact.groups() if x is not None)) + elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit(): + index += 1 + out.append('--max-count=' + tokens[index]) + else: + out.append(token) + index += 1 + return out + + +def shell_equal(expected, actual, normalize_env=False): + wanted, found = argv(expected), argv(actual) + if normalize_env and wanted and found: + wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted] + found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found] + wanted, found = git_limit(wanted), git_limit(found) + if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + if (index == 1 and '/' in token and + observed.rstrip('/').endswith('/' + token.lstrip('./'))): + continue # Existing package-path anchoring; no changed basename/arguments. + return False + return True + + +def command_equal(expected, value): + # Response command questions ask for one invocation, with no extra commands. + return argv(expected) is not None and argv(expected) == argv(value) + + +def convex_equal(expected, value): + a, b = argv(expected), argv(value) + if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]: + return False + def no_duplicates(pairs): + result = {} + for k, v in pairs: + if k in result: + raise ValueError('duplicate JSON key') + result[k] = v + return result + try: + return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates) + except (ValueError, TypeError): + return False + + +def docker_network_equal(expected, value): + tokens = argv(value) + return tokens in (['--network', 'none'], ['--network=none']) + + +def zar_amount(value): + if not isinstance(value, str): + return None + m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I) + if not m: + return None + number = m.group(1) + if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number): + return None + try: + amount = Decimal(number.replace(',', '')) + except InvalidOperation: + return None + return amount * (Decimal(1000000) if m.group(2) else 1) + + +def zar_equal(expected, value): + return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value) + + +def rust_attribute_equal(expected, value): + return isinstance(value, str) and re.fullmatch(r'\s*#\s*\[\s*serde\s*\(\s*rename_all\s*=\s*"camelCase"\s*,?\s*\)\s*\]\s*', value) is not None + + +def header_equal(expected, value): + return isinstance(value, str) and value.casefold() == expected.casefold() + + +def zero_arg_js_equal(expected, value): + name = expected[:-2] + return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None + + +RESPONSE_RULES = { + '82e94ae96e04ff71_q1': {'q1': convex_equal}, + 'df978907fa6f0eea_q1': {'q1': docker_network_equal}, + 'dee0c878f5707477_q1': {'q1': command_equal}, + 'c51259d0062454b2_q1': {'q1': command_equal}, + 'd25a8956477141f2_q1': {'q2': zar_equal}, + '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal}, + 'a4926e403c8165e9_q1': {'q2': header_equal}, + '2b3bd5786727f2fb_q1': {'q1': command_equal}, +} + + +def dashboard_contract(evaluator, candidate, objective): + root = Path(candidate) + path = evaluator['reference_files'][0]['path'] + try: + text = (root / path).read_text() + except (OSError, UnicodeError): + return False + lines = objective._shell_lines(text) + # Public contract explicitly says no other commands/flags. Single quotes + # would suppress environment expansion; only the correctly quoted form counts. + return (len(lines) == 2 and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None) + + +def install(task): + import objective_evaluators as objective + import verifiers + task_id = task['query_id'] + original_verify = verifiers.verify + original_matcher = objective._shell_command_matches + objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1') + + def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None): + if evaluator.get('type') == 'workspace_objective': + # A text occurrence after exit/return, in echo output or within a + # non-executed branch does not prove the requested command runs. + grouped = {} + for check in evaluator.get('checks', []): + if check.get('type') == 'shell_command': + grouped.setdefault(check['path'], []).append(check['value']) + for path, expected_commands in grouped.items(): + try: + text = (Path(solver_output) / path).read_text() + invocations = objective.shell_invocations(text) + for expected_command in expected_commands: + tokens = argv(expected_command) + if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]): + continue # Required scalar assignment is checked by original rubric. + if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations): + return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command} + except (OSError, UnicodeError, ValueError): + return False, {'error': 'cannot inspect required shell artifact', 'path': path} + if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective): + return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'} + normalizations = [] + if task_id in RESPONSE_RULES: + try: + predicted = verifiers._json_value(solver_output) + gold = gt_answer + if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict): + for key, comparator in RESPONSE_RULES[task_id].items(): + value = predicted['answers'].get(key) + expected = gold['answers'][key] + if value != expected and comparator(expected, value): + predicted['answers'][key] = expected + normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected}) + solver_output = json.dumps(predicted) + except (KeyError, ValueError, TypeError): + pass # Preserve original malformed-answer rejection. + if task_id == '59f410a185c510f3_q1': + path = evaluator['reference_files'][0]['path'] + try: + file_path = Path(solver_output) / path + predicted = json.loads(file_path.read_text()) + expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact') + if isinstance(predicted, dict): + for widget in ('chart', 'banner'): + row = predicted.get(widget) + if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')): + if row.get('hydrate') != expected[widget]['hydrate']: + normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']}) + row['hydrate'] = expected[widget]['hydrate'] + if normalizations: + with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary: + view = Path(temporary) / 'candidate' + shutil.copytree(solver_output, view, symlinks=True) + copied = view / path + resolved = copied.resolve() + if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink(): + return False, {'error': 'candidate output parent symlink escapes temporary comparison view'} + if copied.is_symlink(): + copied.unlink() # Do not write through a frozen source symlink. + copied.write_text(json.dumps(predicted)) + passed, details = original_verify(evaluator, gt_answer, str(view), material_paths) + if isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + except (KeyError, ValueError, TypeError, OSError, UnicodeError): + pass + passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths) + if normalizations and isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + + verifiers.verify = repaired_verify diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..cc8adeba4c7883fb9be1bd45cda69cee6e854614 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "555c52aee32b7374_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "1ab5d1c0966e010dd8c55d70c5c024f4f4097343431b31cf06ba6d0240137977", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "87c49a2c75c4819f004e3f93ac799589f1da35cf858f8c2674da27525a5d9b6d", + "legacy_tests/shell_invocations.py": "707d70e83b224c39a727afbd10f4d76c38dc50a2346444757ddfe392c1f4e75e", + "legacy_tests/verifiers.py": "4d95b3ac680fa9d32f50039e435b31e044e05087f587b9f8e00c8118da6483f6" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..657392986c4fb57c9e13aad6121b5555b4caad21 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/instruction.md @@ -0,0 +1 @@ +I'm about to run a sweep over our WhatsApp inbox and I need a small pre-flight script first. Please create output/wacli_preflight.sh that does two things in order, straight-line at the top level with no control flow: first, check the WhatsApp CLI's auth and connection status as JSON (covering auth, connected, lock, and FTS status), and then list all chats as JSON so the sweep can filter on each chat's JID, Name, Kind, and LastMessageTS fields. If any command fails, the script must stop immediately and exit nonzero — no continuing past a failure and no suppressing errors. Follow our repo's shell conventions for the script contents. diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/CHANNELS.md b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/CHANNELS.md new file mode 100644 index 0000000000000000000000000000000000000000..268875b5933ae5ebc6195707568e2cadfe608e55 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/CHANNELS.md @@ -0,0 +1,267 @@ +# Channel Configuration Guide + +This document explains how to configure each communication channel for the `/ops:ops-inbox` skill. All credentials come from environment variables or CLI auth — **no secrets are committed to this repo**. + +## WhatsApp (wacli) + +**Status:** CLI-based (wacli), no MCP needed. + +**Setup:** + +```bash +# Install latest version from source (brew version may be outdated) +git clone https://github.com/steipete/wacli.git /tmp/wacli-src +cd /tmp/wacli-src +go build -o wacli ./cmd/wacli/ +cp wacli /usr/local/bin/ + +# Authenticate (scans QR code with phone) +wacli auth + +# Verify +wacli doctor +# Expected: AUTHENTICATED true, CONNECTED false (until sync runs) + +# Initial sync (takes a minute for 142+ conversations) +wacli sync +``` + +**Troubleshooting:** + +- `Client outdated (405)`: Rebuild from source above +- `store is locked`: Kill stale process: `kill $(pgrep wacli)` +- After version upgrade: `wacli auth logout && wacli auth` + +**History limitations:** +wacli only captures messages **received while connected**. It cannot reliably backfill historical messages after the fact: + +- `wacli history backfill --chat ` requires ≥1 existing local message per chat and often times out on the WhatsApp on-demand sync response. +- Chats in the new `@lid` (Linked Device) format frequently return empty message queries because their history was never captured during an active sync session. +- For ongoing inbox management, run `wacli sync --follow` in a persistent terminal (outside Claude Code) so new messages land in the local DB in real-time. + +**Env vars (optional):** + +- `WACLI_STORE` — default `~/.wacli` + +**Run sync persistently (recommended):** + +```bash +# In a dedicated terminal tab — keeps wacli connected so new messages are captured +wacli sync --follow +``` + +--- + +## Email (gog) + +**Status:** CLI-based (gog), optional MCP fallback. + +**Setup:** + +```bash +# Install gog (gogcli — public CLI from steipete/gogcli, used by the OpenClaw ecosystem) +case "$(uname -s)" in + Darwin*) brew install gogcli ;; + Linux*) brew install gogcli 2>/dev/null \ + || (command -v yay >/dev/null 2>&1 && yay -S gogcli) \ + || (git clone https://github.com/steipete/gogcli.git /tmp/gogcli && cd /tmp/gogcli && make) ;; + MINGW*|MSYS*|CYGWIN*) winget install -e --id steipete.gogcli ;; + *) echo "Unsupported OS — see https://gogcli.sh/ for install instructions" ;; +esac + +# Authorize once per Google account (uses your OS keyring for refresh tokens) +gog auth credentials /path/to/client_secret.json +gog auth add you@example.com --services gmail,calendar,drive,contacts,docs,sheets +``` + +**Env vars (optional):** + +- `GMAIL_ACCOUNT` — Gmail account (auto-detected if unset) + +--- + +## Slack + +**Status:** ⚠️ Not configured. Requires Slack MCP server. + +**Requirements:** + +- Slack MCP server installed and configured in `~/.claude/settings.json` under `mcpServers` +- Bot token with `channels:history`, `im:history`, `chat:write`, `search:read` scopes + +**Setup:** + +1. Install a Slack MCP server: + ```bash + # Option A: Official reference + npm install -g @modelcontextprotocol/server-slack + ``` +2. Add to `~/.claude/settings.json`: + ```json + { + "mcpServers": { + "slack": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-slack"], + "env": { + "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}", + "SLACK_TEAM_ID": "${SLACK_TEAM_ID}" + } + } + } + } + ``` +3. Export env vars (from Doppler, 1Password, or direnv — never commit): + ```bash + export SLACK_BOT_TOKEN="xoxb-..." + export SLACK_TEAM_ID="T..." + export SLACK_MCP_ENABLED=true + ``` +4. Restart Claude Code to load the MCP server + +**Env vars:** + +- `SLACK_BOT_TOKEN` — Bot token (starts with `xoxb-`) +- `SLACK_TEAM_ID` — Workspace ID +- `SLACK_MCP_ENABLED` — Set `true` to enable in ops-unread + +--- + +## Telegram + +**Status:** ⚠️ Not configured. Requires USER-AUTH MCP server (NOT a bot). + +**CRITICAL:** Do NOT use BotFather bots. The inbox skill must read the owner's **personal** conversations, which bots cannot access. Required: tdlib or MTProto user-auth integration. + +**Requirements:** + +- Telegram API ID and hash from https://my.telegram.org/apps +- User-auth MCP server (e.g., `mcp-telegram-user` or custom tdlib wrapper) + +**Setup:** + +1. Get API credentials from https://my.telegram.org/apps (for personal app, not bot) +2. Install a user-auth Telegram MCP server (tdlib-based): + ```bash + # Example: custom tdlib MCP wrapper + npm install -g mcp-telegram-user + ``` +3. Add to `~/.claude/settings.json`: + ```json + { + "mcpServers": { + "telegram": { + "command": "mcp-telegram-user", + "env": { + "TELEGRAM_API_ID": "${TELEGRAM_API_ID}", + "TELEGRAM_API_HASH": "${TELEGRAM_API_HASH}", + "TELEGRAM_PHONE": "${TELEGRAM_PHONE}", + "TELEGRAM_SESSION_PATH": "${HOME}/.telegram-mcp-session" + } + } + } + } + ``` +4. Authenticate on first run (prompts for SMS code) +5. Export env vars and enable: + ```bash + export TELEGRAM_API_ID="..." + export TELEGRAM_API_HASH="..." + export TELEGRAM_PHONE="+1..." + export TELEGRAM_ENABLED=true + ``` + +**Env vars:** + +- `TELEGRAM_API_ID` — from my.telegram.org/apps +- `TELEGRAM_API_HASH` — from my.telegram.org/apps +- `TELEGRAM_PHONE` — phone number for auth +- `TELEGRAM_ENABLED` — Set `true` to enable in ops-unread + +**⚠️ The existing `telegram-server/index.js` in this repo uses a bot token and is NOT suitable for personal inbox management. It needs replacement with a tdlib-based user-auth implementation.** + +--- + +## Notion + +**Status:** MCP-based (claude.ai integration or self-hosted MCP server). + +Notion acts as a knowledge base and task management channel. The integration surfaces: +- **Comments needing reply** — mentions, questions, and comments on pages/databases you own +- **Recently updated pages** — changes in databases you track (e.g., project boards, CRM) +- **Assigned tasks** — items assigned to you across Notion databases + +**Requirements:** + +- Notion MCP server configured via one of: + - **Claude.ai integration** (recommended): Add Notion via claude.ai > Settings > Integrations + - **Self-hosted MCP**: Install `@notionhq/notion-mcp-server` or similar + +**Setup (Claude.ai integration — recommended):** + +1. Go to claude.ai > Settings > Integrations > Notion +2. Authorize access to your Notion workspace +3. Set env var in `~/.claude/settings.json`: + ```json + { + "env": { + "NOTION_MCP_ENABLED": "true" + } + } + ``` +4. Restart Claude Code to load the integration + +**Setup (Self-hosted MCP server):** + +1. Install the Notion MCP server: + ```bash + npm install -g @notionhq/notion-mcp-server + ``` +2. Create a Notion integration at https://www.notion.so/my-integrations +3. Add to `~/.claude/settings.json`: + ```json + { + "mcpServers": { + "notion": { + "command": "npx", + "args": ["-y", "@notionhq/notion-mcp-server"], + "env": { + "NOTION_API_KEY": "${NOTION_API_KEY}" + } + } + } + } + ``` +4. Export env vars: + ```bash + export NOTION_API_KEY="ntn_..." + export NOTION_MCP_ENABLED=true + ``` + +**Env vars:** + +- `NOTION_API_KEY` — Integration token (starts with `ntn_`, only for self-hosted MCP) +- `NOTION_MCP_ENABLED` — Set `true` to enable in ops-unread + +**MCP tools used:** + +| Tool | Purpose | +|------|---------| +| `notion-search` | Search across workspace and connected sources (Slack, Drive, etc.) | +| `notion-fetch` | Fetch full page/database content by URL or ID | +| `notion-get-comments` | Get comments on a specific page | +| `notion-create-comment` | Reply to a comment thread on a page | +| `notion-update-page` | Update page properties (status, assignee, etc.) | +| `notion-create-pages` | Create new pages in databases | + +--- + +## Verification + +After configuring any channel, verify with: + +```bash +${CLAUDE_PLUGIN_ROOT}/bin/ops-unread +``` + +Expected output shows each channel's `available: true/false` status. diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..af569d306cd5b71eba8451b4ca70854c3379cd1a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/SKILL.md @@ -0,0 +1,591 @@ +--- +name: ops-inbox +description: Full inbox management across all channels — WhatsApp (wacli), Email (Gmail MCP), Slack (MCP), Telegram (user-auth MCP), Discord (webhook + REST read), Notion (MCP — comments, mentions, assigned tasks). Scans FULL inbox (not just unread), identifies messages needing replies, archives handled conversations. +argument-hint: "[channel: whatsapp|email|slack|telegram|discord|notion|all]" +allowed-tools: + - Bash + - Read + - Grep + - Glob + - Skill + - Agent + - AskUserQuestion + - TeamCreate + - SendMessage + - TaskCreate + - TaskUpdate + - TaskList + - CronCreate + - CronList + - mcp__gog__gmail_search + - mcp__gog__gmail_read_thread + - mcp__gog__gmail_send + - mcp__gog__gmail_labels + # Slack: MCP tools added when configured + # Telegram: user-auth MCP tools added when configured + # Notion: MCP tools (claude.ai integration or self-hosted) + - mcp__claude_ai_Notion__notion-search + - mcp__claude_ai_Notion__notion-fetch + - mcp__claude_ai_Notion__notion-get-comments + - mcp__claude_ai_Notion__notion-create-comment + - mcp__claude_ai_Notion__notion-update-page + - mcp__claude_ai_Notion__notion-create-pages +effort: high +maxTurns: 60 +--- + +# OPS ► INBOX ZERO + +## Runtime Context + +Before executing, load available context: + +1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json` + - `default_channels` — which channels to scan by default + - `secrets_manager` / `doppler` — how to resolve channel credentials if not in env + +2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json` + - Check `wacli-sync` status — if not running or auth needed, skip WhatsApp and surface the issue + - Also check `~/.wacli/.health` for live auth status before any wacli command + +3. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/` before drafting any reply: + - `contact_*.md` — load profile for the contact you're about to reply to + - `preferences.md` — apply user's communication style and language preferences + - `topics_active.md` — check for active threads or deadlines related to this contact + - `donts.md` — never violate these restrictions in drafts + +## CLI/API Reference + +### wacli (WhatsApp) + +**Health file** — check `~/.wacli/.health` BEFORE any wacli command: +- `status=connected` → proceed normally +- `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR" +- `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair" +- File missing → fall back to `wacli doctor --json` + +| Command | Usage | Output | +|---------|-------|--------| +| `wacli doctor --json` | Check auth/connected/lock/FTS | `{data: {authenticated, connected, lock_held, fts_enabled}}` | +| `wacli chats list --json` | All chats | `{data: [{JID, Name, Kind, LastMessageTS}]}` | +| `wacli messages list --chat "" --limit N --json` | Messages for chat | `{data: {messages: [{FromMe, Text, Timestamp, SenderName, ChatName}]}}` | +| `wacli messages search --query "" --json` | FTS search | Same as above | +| `wacli contacts --search "" --json` | Contact lookup | Contact objects | +| `wacli send --to "" --message ""` | Send text | Success/error | +| `wacli history backfill --chat="" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages | Backfill result | + +### gog CLI (Gmail/Calendar) + +| Command | Usage | Output | +|---------|-------|--------| +| `gog gmail search "in:inbox" --max 50 -j --results-only --no-input` | Full inbox scan | JSON array of threads | +| `gog gmail thread get -j` | Get full thread with all messages | Full message JSON | +| `gog gmail get -j` | Get single message | Message JSON | +| `gog gmail archive ... --no-input --force` | Archive messages (remove from inbox) | Archive result | +| `gog gmail archive --query "" --max N --force` | Archive by query | Archive result | +| `gog gmail send --to "" --subject "" --body ""` | Send email | Send result | +| `gog gmail send --reply-to-message-id --reply-all --body "text"` | Reply all | Send result | +| `gog gmail mark-read ... --no-input` | Mark as read | Result | +| `gog gmail labels list -j` | List all labels | Labels JSON | + +--- + + +## Agent Teams support + +If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** when processing "all channels" mode. This enables: +- Channel agents run in parallel but can share context (e.g., WhatsApp agent finds a message referencing an email thread → email agent can prioritize it) +- You can steer agents: "skip WhatsApp for now, focus on email first" +- Agents report completion per-channel so you can process replies as they come in + +**Team setup** (only when flag is enabled, "all channels" mode): +``` +TeamCreate("inbox-channels") +Agent(team_name="inbox-channels", name="whatsapp-scanner", ...) +Agent(team_name="inbox-channels", name="email-scanner", ...) +Agent(team_name="inbox-channels", name="slack-scanner", ...) +Agent(team_name="inbox-channels", name="telegram-scanner", ...) +Agent(team_name="inbox-channels", name="notion-scanner", ...) +``` + +Each agent scans its channel and reports back classified results. You then process NEEDS_REPLY items across all channels in priority order. + +If the flag is NOT set, process channels sequentially or use fire-and-forget subagents. + +## Pre-gathered data + +```! +${CLAUDE_PLUGIN_ROOT}/../../bin/ops-unread 2>/dev/null || echo '{}' +``` + +## Environment variables + +All channel credentials come from env vars or CLI auth — no hardcoded secrets. + +| Variable | Default | Purpose | +| ------------------- | ----------- | ---------------------------------------------------- | +| `GMAIL_ACCOUNT` | auto-detect | Gmail account for `gog` CLI | +| `SLACK_MCP_ENABLED` | `false` | Set `true` when Slack MCP server is configured | +| `TELEGRAM_ENABLED` | `false` | Set `true` when Telegram user-auth MCP is configured | +| `NOTION_MCP_ENABLED`| `false` | Set `true` when Notion MCP integration is configured | +| `WACLI_STORE` | `~/.wacli` | wacli store directory | + +## Core principle: FULL INBOX SCAN + +Do NOT just check unread. Scan the FULL recent inbox for each channel and classify every conversation: + +## Core principle: FULL CONTEXT — NEVER ASSUME + +**CRITICAL SAFETY RULE — NEVER SEND WITHOUT UNDERSTANDING:** +Before drafting or sending ANY reply on ANY channel, you MUST have read the FULL conversation history (20+ messages) and PROVEN you understand it by summarizing: +1. What the conversation is about +2. What each party said (distinguish user messages from contact messages) +3. What the contact is actually asking/saying in their last message +4. What a sensible reply would address + +**Failure mode this prevents:** An agent reads only the last message "je kan het toch uit Klaviyo halen?" and replies "Welke data heb je nodig?" — completely wrong because the contact was telling the user to pull data themselves (they have 2FA), not asking for data. Without the full thread, the reply was nonsensical and confused the contact. + +**Hard rule: if you cannot summarize the conversation arc in 2 sentences, you have not read enough messages. Go back and read more.** + +The user does NOT remember every thread. For EVERY message you present, you MUST build full context BEFORE showing it. Never show just a subject line and ask "what do you want to do?" — the user needs to understand what it's about first. + +**For every NEEDS REPLY item, gather this context automatically:** + +1. **Full thread body** — read the ENTIRE thread (`gog gmail thread get` / `wacli messages list --limit 20`), not just the last message. Summarize the full conversation arc. +2. **Contact profile** — search across channels to build a card: + - `gog gmail search "from:" --max 10` — recent email history + - `wacli contacts --search "" --json` — WhatsApp presence + - `wacli messages search --query "" --json --limit 5` — recent WhatsApp mentions + - If Linear configured: search for issues assigned to or mentioning this contact + - Present: who they are, role/company, last N interactions, relationship context +3. **Topic context** — identify the subject matter and search for related threads: + - `gog gmail search "subject:" --max 5` — related email threads + - `wacli messages search --query "" --json --limit 5` — related WA messages + - Summarize: what this topic is about, any deadlines, any pending decisions +4. **ops-memories** (if available) — check `~/.claude/plugins/data/ops-ops-marketplace/memories/` for any stored context about this contact or topic + +**When presenting a NEEDS REPLY item:** +``` +━━━ [Contact Name] — [Subject] ━━━ + Who: [role, company, relationship — from contact search] + History: [last 3 interactions across channels] + Thread: [2-3 sentence summary of full conversation arc] + Last msg: [full body of their last message] + Context: [related threads/decisions/deadlines found] + + Draft reply: "[contextually aware draft based on all above]" + + [Send] [Edit] [Read full thread] [Skip] +``` + +**When drafting replies:** +- Use the full thread history to maintain conversation continuity +- Reference specific points from their message +- Match the contact's communication style (formal/casual, language) +- If ops-memories has preferences for this contact, apply them +- Never generate a generic reply — every draft must show you read the full thread + +- **NEEDS REPLY** — other party sent last message, awaiting your response +- **WAITING** — you sent last message, waiting for them (no action needed) +- **HANDLED** — conversation concluded, can be archived +- **FYI** — newsletters, notifications, automated messages (bulk archive) + +## Channel availability + fallback + +For each channel, detect availability at runtime: + +1. **Email**: Try `gog` CLI first. If `gog` unavailable, try `mcp__gog__gmail_*` MCP tools. If neither, report unavailable. +2. **WhatsApp**: First check `~/.wacli/.health` for keepalive daemon status. If `status=needs_auth` or `status=needs_reauth`, do NOT attempt wacli commands — instead prompt the user: "WhatsApp needs re-authentication. Run `wacli auth` in a separate terminal and scan the QR code, then type 'done'." Use `AskUserQuestion`: `[Done — re-paired]`, `[Skip WhatsApp]`. On Done, restart the daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive`, wait 5s, re-check health. If no health file exists, fall back to `wacli doctor` for auth/connection status. If outdated (405 error), advise rebuilding from source. +3. **Slack**: Only via MCP tools (`mcp__claude_ai_Slack__*`). Check `SLACK_MCP_ENABLED` env var. +4. **Telegram**: Only via user-auth MCP (tdlib/MTProto). Check `TELEGRAM_ENABLED` env var. Never use BotFather bots. +5. **Discord**: Via `${CLAUDE_PLUGIN_ROOT}/bin/ops-discord read --limit 20 --json`. Requires `DISCORD_BOT_TOKEN` (v1 is channel-scoped — no DM/gateway support yet). Pre-configured read list lives at `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` under `discord.inbox_channels` (array of channel IDs). If neither a bot token nor a read list is configured, skip Discord with a one-line note ("Discord not configured — run `/ops:setup discord`") rather than prompting — ops-inbox is not a setup flow. Rule 3 still applies to `/ops:setup`. +6. **Notion**: Only via MCP tools (`mcp__claude_ai_Notion__*` or self-hosted Notion MCP). Check `NOTION_MCP_ENABLED` env var. Searches workspace for recent comments, mentions, and assigned tasks. + +## Your task + +1. **Parse pre-gathered data** for initial counts (unread is just a starting signal). + +2. **For each channel, run a FULL scan** (not just unread): + - **Email**: Search `in:inbox` (not `is:unread`) via `gog gmail search -a $GMAIL_ACCOUNT -j --results-only --no-input --max 30 "in:inbox"`. For each thread, read the last message to determine who sent it last. Check for DRAFT or SENT labels. **Before suggesting to send a draft, verify no reply was already sent in the thread.** + - **WhatsApp**: Run `wacli chats list --json` to get all chats. Filter to non-archived chats with `LastMessageTS` in the last 7 days. For each, fetch the FULL conversation via `wacli messages list --chat --limit 20 --json` (20 messages, not 5 — you need the full thread). Parse `data.messages[]` with fields `FromMe`, `Text`, `Timestamp`, `ChatName`. Understand which messages are from the user (`FromMe: true`) vs the contact (`FromMe: false`). Classify by last message `FromMe` field. + - **Slack**: Search via Slack MCP tools. Check who sent last message in each thread. + - **Telegram**: Use user-auth MCP (NOT bot API) to read recent conversations. + +3. **Display the full inbox:** + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + OPS ► INBOX MANAGER +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + 📱 WhatsApp [N need reply] | [N waiting] | [N archive] + 📧 Email [N need reply] | [N waiting] | [N FYI] + 💬 Slack [N need reply] | [N waiting] + ✈️ Telegram [N need reply] | [N waiting] + +────────────────────────────────────────────────────── +``` + +Use **batched AskUserQuestion calls** (max 4 options each). Only show channels that are configured and have messages. If <=4 total options, use a single call. + +AskUserQuestion call 1: +``` + [All channels (fastest — one pass)] + [WhatsApp only] + [Email only] + [More...] +``` + +AskUserQuestion call 2 (only if "More..."): +``` + [Slack only] + [Telegram only] + [Skip — already done] +``` + +If only 3 channels are configured, "All channels" + 3 channel options = 4, fits in one call. Then process the selected channel(s). + +--- + +## Processing each channel + +### WhatsApp (FULL SCAN + DEEP CONTEXT) + +**Phase 1 — Classify:** +1. Get all chats: `wacli chats list --json` +2. Filter to chats with `LastMessageTS` in the last 7 days +3. For each, fetch the FULL recent conversation: `wacli messages list --chat "" --limit 20 --json` — get 20 messages, NOT 5. You need the full conversation thread to understand context. +4. Parse `data.messages[]` — fields: `FromMe`, `Text`, `Timestamp`, `ChatName`, `SenderName` +5. For EVERY chat, understand the conversation: + - Read ALL messages in order. Know which are `FromMe: true` (user sent) vs `FromMe: false` (contact sent) + - Understand what the conversation is about, what was discussed, what's pending + - Identify the user's tone and style in their sent messages +6. Classify each chat: + - **NEEDS REPLY**: Last message has `FromMe: false` (they sent last) + - **WAITING**: Last message has `FromMe: true` (you sent last) + - **ARCHIVE**: Old conversation, no recent activity, or concluded + +**Phase 2 — Build context for NEEDS REPLY chats (run in parallel):** +For each NEEDS REPLY chat: +1. **Full conversation summary** — read all 20 messages, summarize the arc: what was discussed, key decisions, open questions +2. **Contact profile** — search for this person: + - `wacli messages search --query "" --json --limit 10` — mentions in other chats + - `gog gmail search -j --results-only --no-input --max 5 "from: OR to:"` — email history + - Check `~/.claude/plugins/data/ops-ops-marketplace/memories/contact_*.md` for stored profile + - Build: who they are, relationship, communication history across channels +3. **Topic context** — extract keywords from the conversation and search: + - `wacli messages search --query "" --json --limit 5` — related WA messages + - `gog gmail search -j --results-only --no-input --max 3 ""` — related emails +4. **User's messaging style** — from the `FromMe: true` messages in this chat, note: language (NL/EN), formality, emoji usage, typical response length + +**Phase 3 — Present with full context:** + +``` +📱 WHATSAPP — NEEDS REPLY (with context) + +━━━ 1. [Contact Name] ━━━ + Who: [role, company, relationship — from contact search] + History: [last 3 interactions across channels] + Conversation: [2-3 sentence summary of the full chat thread] + Their message: [full text of their last message(s)] + Your last msg: [what you said before they replied] + Context: [related threads/topics found] + Language: [NL/EN — match the user's previous messages in this chat] + + Draft reply: "[context-aware draft matching user's style + language]" + + [Send] [Edit] [Read full thread] [More...] + +If "More...": + [Archive] [Skip] + +📱 WHATSAPP — WAITING (no action needed) + N. [Contact] — you said: "[your last message]" — [time ago] + Thread: [1-line summary of what you're waiting for] +``` + +Use `AskUserQuestion` for each NEEDS REPLY chat. + +**When drafting WhatsApp replies:** +- Match the user's language (if they wrote Dutch to this contact, draft in Dutch) +- Match the user's style (casual/formal, emoji usage, message length) +- Reference specific points from the contact's message +- If ops-memories has preferences for this contact, apply them +- Never generate a generic reply — every draft must show you understood the full conversation + +Reply via: `wacli send --to "" --message ""` + +**wacli CLI reference (v0.5.0):** + +| Command | Usage | Notes | +|---------|-------|-------| +| `wacli doctor` | `wacli doctor --json` | Check auth/connected/lock/FTS status | +| `wacli auth` | `wacli auth` | QR pairing (interactive — shows QR in terminal) | +| `wacli sync` | `wacli sync --follow --refresh-contacts --refresh-groups` | Persistent sync (managed by launchd keepalive) | +| `wacli sync --once` | `wacli sync --once --idle-exit=10s` | One-shot sync, exits when idle | +| `wacli chats list` | `wacli chats list --json` | All chats with JID, Name, Kind, LastMessageTS | +| `wacli messages list` | `wacli messages list --chat "" --limit 5 --json` | Messages: ChatJID, FromMe, Text, Timestamp, SenderName | +| `wacli messages search` | `wacli messages search --query "" --json` | FTS5 search across all messages | +| `wacli contacts` | `wacli contacts --search "" --json` | Contact lookup by name | +| `wacli send` | `wacli send --to "" --message ""` | Send text message | +| `wacli history backfill` | `wacli history backfill --chat="" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages from phone (needs store lock) | + +**Health file contract (`~/.wacli/.health`):** + +Before ANY wacli command, read `~/.wacli/.health`: +- `status=connected` → proceed normally +- `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR" +- `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair" +- File missing → fall back to `wacli doctor --json` + +**Requesting backfill for @lid chats with empty messages:** + +The keepalive daemon holds the store lock, so you can't run backfill directly. Instead: +1. Write JIDs to `~/.wacli/.backfill_jids` (one per line) +2. Restart the daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive` +3. The daemon runs backfill before starting persistent sync + +**wacli troubleshooting:** + +- `@lid` JIDs (linked device format) may return empty messages → request backfill via the daemon (see above) +- "Client outdated (405)" → rebuild from source: `cd /tmp && git clone https://github.com/Lifecycle-Innovations-Limited/wacli.git && cd wacli && go build -o /usr/local/bin/wacli ./cmd/wacli/` +- "store is locked" → the keepalive daemon holds the lock; to release: `launchctl bootout gui/$(id -u)/com.claude-ops.wacli-keepalive` +- Auth expired → daemon writes `needs_auth` to health file; prompt user for QR scan +- Key desync (0 messages synced) → daemon writes `needs_reauth`; user needs `wacli auth` re-pair + +### Email (FULL SCAN + DEEP CONTEXT) + +**Phase 1 — Classify:** +1. Search `in:inbox` (NOT `is:unread`) via `gog gmail search -a $GMAIL_ACCOUNT -j --results-only --no-input --max 30 "in:inbox"` +2. For each thread, read the FULL thread via `gog gmail thread get -a $GMAIL_ACCOUNT -j` — read ALL messages, not just the last one +3. Check the last message's `From` header and `labelIds` (SENT, DRAFT) +4. Classify: + - **NEEDS REPLY**: Last sender is NOT you AND no unsent draft exists → action needed + - **WAITING**: Last sender IS you (SENT label) → waiting for response + - **DRAFT**: Unsent draft exists → verify no reply already sent, then offer to send + - **FYI**: Newsletters, automated notifications, receipts → bulk archive + +**Phase 2 — Build context for NEEDS REPLY items (run in parallel):** +For each NEEDS REPLY thread, gather: +1. **Full thread summary** — read every message in the thread, summarize the conversation arc (who said what, key decisions, open questions) +2. **Contact profile** — for the sender: + - `gog gmail search -j --results-only --no-input --max 10 "from:"` — their recent emails to you + - `wacli contacts --search "" --json` — WhatsApp contact + - `wacli messages search --query "" --json --limit 5` — recent WhatsApp mentions + - Build: name, role/company, relationship history, last N interactions +3. **Topic search** — extract key terms from subject + body, then: + - `gog gmail search -j --results-only --no-input --max 5 "subject:"` — related threads + - Identify: pending decisions, deadlines, action items from related threads + +**Phase 3 — Present with full context:** + +``` +📧 EMAIL — NEEDS REPLY (with context) + +━━━ 1. [Sender] — [Subject] ━━━ + Who: [sender's role, company — from contact search] + History: [last 3 email exchanges with this person] + Thread summary: [2-3 sentences covering the full conversation arc] + Their message: [full body of their last message — NOT truncated] + Related: [any related threads or pending decisions found] + + Draft reply: "[context-aware draft using full thread + contact history]" + + [Send draft] [Edit draft] [Read full thread] [More...] + +If "More...": + [Archive] [Skip] + +📧 EMAIL — DRAFTS (unsent) + N. [Recipient] — [Subject] (draft ready to send) + +📧 EMAIL — FYI / ARCHIVE + N. [Sender] — [Subject] (newsletter/notification) + + For each NEEDS REPLY: + a) Read full thread + draft reply + b) Archive (no reply needed) + c) Skip + + For FYI section: + x) Archive all FYI at once +``` + +Use `AskUserQuestion` for each NEEDS REPLY email with options `[Read + Reply]` / `[Archive]` / `[Skip]`. + +When replying, draft the reply and use `AskUserQuestion` to confirm: +``` +Reply to [Sender] — [Subject]: + "[drafted reply]" + + [Send] [Edit] [Skip] +``` + +For FYI bulk archive, use `AskUserQuestion`: +``` +Archive N FYI/newsletter emails? + [list of subjects] + + [Archive all N] [Review each] [Skip] +``` + +Draft replies via `gog gmail send`. Archive via `gog gmail archive ... --no-input --force`. + +### Slack + +Use Slack MCP tools with `query: "in:*"` (NOT `is:unread` — scan full recent activity, not just unread) for mentions. +For each result, show channel, sender, preview. Read thread for context. + +``` + a) Read thread + b) Reply + c) Mark read / skip +``` + +### Telegram (FULL SCAN — User Account, NOT Bot) + +Telegram integration must authenticate as the user's personal account (user-auth via tdlib/MTProto), NOT a BotFather bot. The goal is to manage real conversations just like WhatsApp via wacli. + +Use the Telegram user-auth MCP server if available. + +1. List recent dialogs/conversations (last 7 days) +2. For each, check who sent the last message +3. Classify: NEEDS REPLY / WAITING / HANDLED + +``` +✈️ TELEGRAM — NEEDS REPLY + 1. [Contact] — [preview] — [time ago] + + a) Read thread + reply + b) Archive + c) Skip +``` + +If no Telegram user-auth tool is available, report: "Telegram not configured — needs user-auth MCP server (tdlib/MTProto)". + +### Notion (MCP — comments, mentions, assigned tasks) + +Notion serves as a knowledge base and task management channel. Unlike messaging channels, Notion "inbox" items are: +- **Comments on pages you own or are mentioned in** +- **Tasks assigned to you** in tracked databases +- **Recently updated pages** in databases you monitor + +**Phase 1 — Discover and scan:** + +1. Search for recent activity using `mcp__claude_ai_Notion__notion-search`: + - Use broad queries like `query: ""` (empty string returns recent pages) or topic-specific terms + - Use `filter: {"property": "object", "value": "page"}` to limit to pages (not databases) + - Sort by `last_edited_time` descending to surface recent activity + - Note: Notion search is full-text over titles/content — it does NOT support mention-based queries or date range filters +2. For each result, fetch full content: `mcp__claude_ai_Notion__notion-fetch` with the page URL/ID +3. Get comments on active pages: `mcp__claude_ai_Notion__notion-get-comments` with the page ID — scan comment authors and timestamps to determine which need replies + +**Phase 2 — Classify:** + +For each page with comments or mentions: +- **NEEDS REPLY**: Someone commented/mentioned you and you haven't responded +- **WAITING**: You commented last, waiting for others +- **FYI**: Page updated but no direct mention or action needed +- **TASK**: Item assigned to you in a database (check status property) + +**Phase 3 — Present with context:** + +``` +📓 NOTION — NEEDS REPLY + +━━━ 1. [Page Title] — [Database Name] ━━━ + Page: [page URL] + Comment by: [commenter name] — [time ago] + Comment: "[full comment text]" + Page context: [2-3 sentence summary of the page content] + + Draft reply: "[context-aware reply to the comment]" + + [Reply] [View page] [Skip] [More...] + +If "More...": + [Mark resolved] [Archive] + +📓 NOTION — ASSIGNED TASKS + + N. [Task title] — [database] — Status: [status] — Due: [date] + Context: [1-line summary] + +📓 NOTION — RECENTLY UPDATED (FYI) + + N. [Page title] — updated by [person] — [time ago] +``` + +Use `AskUserQuestion` for each NEEDS REPLY item. + +**When replying to Notion comments:** +- Use `mcp__claude_ai_Notion__notion-create-comment` with the page ID and reply text +- Match the formality of the original comment +- Reference specific page content when relevant + +**When updating tasks:** +- Use `mcp__claude_ai_Notion__notion-update-page` to change status, add notes +- Only update properties the user explicitly approves + +**API fallback (when MCP is down):** +If Notion MCP tools fail or are unavailable but `NOTION_API_KEY` is set, fall back to direct API: +```bash +curl -s -H "Authorization: Bearer $NOTION_API_KEY" -H "Notion-Version: 2022-06-28" \ + -H "Content-Type: application/json" \ + -X POST https://api.notion.com/v1/search \ + -d '{"sort":{"direction":"descending","timestamp":"last_edited_time"},"page_size":10}' +``` + +If `NOTION_MCP_ENABLED` is not set or Notion MCP tools are unavailable, report: "Notion not configured — set NOTION_MCP_ENABLED=true and add Notion integration via claude.ai or self-hosted MCP". + +### Discord (v1 — REST channel scan) + +Discord v1 support is channel-scoped (webhook send + REST read). DM + gateway are deferred to a v2 issue. + +1. Resolve the read list: read `${CLAUDE_PLUGIN_DATA_DIR}/preferences.json` → `discord.inbox_channels[]`. If empty and `DISCORD_GUILD_ID` is set, fall back to `bin/ops-discord channels --json` (list the guild's text channels and let the user pick via `AskUserQuestion`, ≤4 per Rule 1 — paginate with `[More...]`). +2. For each channel ID: + ```bash + ${CLAUDE_PLUGIN_ROOT}/bin/ops-discord read "" --limit 20 --json + ``` +3. Classify each channel's recent messages: + - **NEEDS REPLY**: Latest non-bot message mentions the operator (`<@user-id>`) or is a direct question. + - **FYI**: Bot-posted notifications (CI, alerts) — summarize counts and skip. +4. For replies, reuse the `send` path documented in `skills/ops-comms/SKILL.md` → **Discord send**. + +If `bin/ops-discord` exits 1 with `{"error":"no discord credential configured — run /ops:setup discord"}`, print a single-line note and continue to the next channel — do not prompt inside the inbox flow. + +``` +💬 DISCORD — activity (last 7d) + #channel-name [N messages] | [M need reply] +``` + +--- + +## Completion + +After all selected channels are processed, print: + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + INBOX ZERO ✓ — [timestamp] + Processed: [N] messages | Replied: [N] | Archived: [N] +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +If `$ARGUMENTS` specifies a channel (e.g. `whatsapp`), skip the menu and go directly to that channel. + +--- + +## Native tool usage + +### Tasks — inbox progress + +Use `TaskCreate` for each channel being processed. Update with `TaskUpdate` as messages are replied/archived/skipped. Gives the user a live inbox-zero progress bar. + +### Cron — scheduled inbox checks + +After processing, offer to schedule recurring inbox checks via `AskUserQuestion`: +``` + [Schedule inbox check every 2 hours] [Schedule morning + evening] [No schedule] +``` +Use `CronCreate` if selected. Show existing schedules with `CronList`. diff --git a/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/task.json b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..aa9d40881f9fc2b048dfc45258fcc15391f91fb6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/task.json @@ -0,0 +1,49 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "555c52aee32b7374", + "query_id": "555c52aee32b7374_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/wacli_preflight.sh" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "910cae0331e5a0218ed7d67a15becd780febb55f9230a60a2e0f105cec47070d", + "name": "ops-inbox", + "package_path": "skill", + "install_name": "ops-inbox-39a2c604" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "910cae0331e5a0218ed7d67a15becd780febb55f9230a60a2e0f105cec47070d", + "files": { + "CHANNELS.md": "75f3ac160460e8fa8a71ff1d3ccef1c652e42099149d3095e8637c5ec81e66ed", + "SKILL.md": "5ac34ec3914c5768dfead9be58809de390d53a76f2d17064a8173e830b8e0a77" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "39a2c604a3b990f4f7ac973f13dd3558f3e702b45de26cb7d06c72e7016484a5" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..27a58f3c3d272ec8f5617b77eb33dcce4f07532c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_contract.json @@ -0,0 +1,22 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..71736b89e9eabb41976ae58e77b1f6afbaecbce7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.json @@ -0,0 +1,14 @@ +{ + "stdlib_only": false, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "runtime_owner_ids": [ + "0" + ], + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' --log-failed + +# Watch run in progress +gh run watch +``` + +## Quality Gates + +- No PR should decrease overall coverage +- New features must include tests +- Bug fixes must include regression tests +- Breaking changes require test updates + +## Tips + +- **Focus on branch coverage**, not just line coverage +- **Test the sad path** - error conditions matter +- **Golden tests** for complex outputs (parser, codegen) +- **Property tests** for mathematical invariants diff --git a/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/task.json b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b1a0fefcf4340fa2c498edfcf9ceab3baa6bec62 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/561cdbf5d0fe59f3cbc6a568/task.json @@ -0,0 +1,63 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "561cdbf5d0fe59f3cbc6a568", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "561cdbf5d0fe59f3cbc6a568", + "outputs": [ + "analyze_coverage.py", + "coverage_findings." + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "0720471f03b9276219142f9859da7b1abfea60cd6479faae422251f237f92a9b", + "files": { + "SKILL.md": "d1ac66c02cb9cd5247fceebe1a56856398a9d991f6defee881edeaef0878dbc7" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/coverage_report.txt", + "workspace_target": "coverage_report.txt", + "sha256": "f81ab53ad48690964d4ee718d57a146cbff3a662c4dcd68ab17195a534d4a03b" + }, + { + "source": "inputs/modules.txt", + "workspace_target": "modules.txt", + "sha256": "8d078b84ad483cc90613a00592924961e5e415a89c3ce7685be6ae9a8f19abd6" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "0720471f03b9276219142f9859da7b1abfea60cd6479faae422251f237f92a9b" + } + ] + }, + "automatic_evaluation_runtime": { + "stdlib_only": false, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "runtime_owner_ids": [ + "0" + ], + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score." + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..25e1c4bb69e4f7edc4c0cfe7d08ff23610207dff --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_contract.json @@ -0,0 +1,32 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "public_root_uuid_class_template_identity", + "public_all_text_bom", + "public_all_template_types", + "public_all_failure_cases", + "native_requested_execution" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "public_root_uuid_class_template_identity": 1, + "public_all_text_bom": 1, + "public_all_template_types": 1, + "public_all_failure_cases": 1, + "native_requested_execution": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..75c15aa648831182fdf767fe2654b19bc661fb0d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.json @@ -0,0 +1,14 @@ +{ + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "runtime_owner_ids": [ + "0" + ], + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith('=2, "constructor must take repository"') + src = src.replace('getattr(r,"error_message",None) is None', 'getattr(r,"error_message",None) in (None,"")') + src = src.replace('assert name=="New Name", "response must carry updated name"', 'assert name=="New Name" or any(v=="New Name" for v in dataclasses.asdict(r).values()), "response must carry updated name"') + if q.startswith('bc8f'): + src = src.replace('all(s.get(k)==c for k,c in counts.items())', 'summary_counts_ok(s, fs)') + src = src.replace('import json,os,shutil,subprocess,sys,tempfile', 'import json,os,shutil,subprocess,sys,tempfile\nfrom grade import summary_counts_ok') + if q.startswith('fdc4'): + # The original code made no-op scripts pass by reusing copied outputs. + src = src.replace(' # Check 0: runs, exits 0',' for stale in ("e2e-evidence/verdict.md", "commit-message.txt"):\n try: os.unlink(os.path.join(work,stale))\n except FileNotFoundError: pass\n # Check 0: runs, exits 0') + g={'__name__':'__main__','__file__':str(original)} + # Execute evaluator-owned source only; it launches candidate code in sandbox. + captured=io.StringIO() + with contextlib.redirect_stdout(captured): + try: exec(compile(src,g['__file__'],'exec'),g) + except SystemExit as e: + if e.code not in (None,0): raise + # Two original scripts print function-local checks rather than globals. + if q.startswith(('7bc7','fdc4')): + return g, json.loads(captured.getvalue().strip().splitlines()[-1])['checks'] + return g, g['checks'] + +def summary_counts_ok(s, findings): + if not isinstance(s,dict) or s.get('total') != len(findings): return False + actual=dict(collections.Counter(f.get('rule_id') for f in findings)) + counts=s.get('per_rule',s.get('counts',s)) + return isinstance(counts,dict) and all(counts.get(k)==v for k,v in actual.items()) and all(v==actual.get(k,0) for k,v in counts.items() if k!='total') + +def root_xml_contract(c): + MD='http://v8.1c.ru/8.3/MDClasses'; V8='http://v8.1c.ru/8.1/data/core' + name='ОбработкаЗагрузки'; tn='ПФ_MXL_М11' + try: + r=ET.parse(c/'src'/f'{name}.xml').getroot() + obj=r.find('.//{%s}ExternalDataProcessor'%MD) + cls=next((n for n in r.iter()if n.tag.split('}')[-1]=='ClassId'),None) + uid=str(uuid.UUID(obj.attrib.get('uuid',''))) + ok=bool(cls is not None and (cls.text or '').strip()=='c3831ec8-d8d5-4f93-8a22-f9bfae07327f' and uid) + t=ET.parse(c/'src'/name/'Templates'/f'{tn}.xml').getroot(); objt=t.find('.//{%s}Template'%MD) + nt=objt.find('{%s}Properties/{%s}Name'%(MD,MD)); st=objt.find('.//{%s}Synonym/{%s}item/{%s}content'%(MD,V8,V8)) + tuid=str(uuid.UUID(objt.attrib.get('uuid',''))) + return ok and bool(tuid) and tuid!=uid and nt is not None and (nt.text or '').strip()==tn and st is not None + except (OSError,ET.ParseError,ValueError,AttributeError): return False + +def artifact_boms(c): + try: + fs=[p for p in (c/'src').rglob('*') if p.is_file() and p.suffix in ('.xml','.bsl','.html','.txt')] + return bool(fs) and all(p.read_bytes().startswith(b'\xef\xbb\xbf') for p in fs) + except OSError:return False + +def domain_delegation(src): + t=tree(src) + if t is None:return False + calls=[n for n in ast.walk(t) if isinstance(n,ast.Call)] + return any(isinstance(n.func,ast.Attribute) and n.func.attr=='rename' for n in calls) and not any((isinstance(n.func,ast.Name)and n.func.id=='len')or(isinstance(n.func,ast.Attribute)and n.func.attr=='strip')for n in calls) + +def scaffold_variations(c): + MD='http://v8.1c.ru/8.3/MDClasses';src=c/'scaffold.py' + if not src.is_file():return False,False + types={'HTML':('HTMLDocument','html'),'Text':('TextDocument','txt'),'SpreadsheetDocument':('SpreadsheetDocument','xml'),'BinaryData':('BinaryData','bin'),'DataCompositionSchema':('DataCompositionSchema','xml')} + types_ok=True;failure_ok=True + with tempfile.TemporaryDirectory()as td: + td=pathlib.Path(td);__import__('r10_support').copy_modules(c,td);rc,_,_=command(['scaffold.py','init','Other','Other synonym','src'],td) + types_ok=rc==0 + try: + root_obj=ET.parse(td/'src/Other.xml').getroot().find('.//{%s}ExternalDataProcessor'%MD);seen_uuids={str(uuid.UUID(root_obj.attrib['uuid']))} + except(OSError,ET.ParseError,ValueError,AttributeError,KeyError):types_ok=False;seen_uuids=set() + for k,(mapping,ext)in types.items(): + rc,_,_=command(['scaffold.py','add-template','Other','T_'+k,k,'src'],td) + meta=td/'src/Other/Templates'/('T_'+k+'.xml');content=td/'src/Other/Templates'/('T_'+k)/'Ext'/('Template.'+ext) + try: + obj=ET.parse(meta).getroot().find('.//{%s}Template'%MD);uid=str(uuid.UUID(obj.attrib['uuid']));unique_uuid=uid not in seen_uuids;seen_uuids.add(uid);v=obj.find('.//{%s}TemplateType'%MD) + ok=rc==0 and unique_uuid and v is not None and v.text==mapping and content.is_file() + raw=content.read_bytes() + if k=='BinaryData':ok &= raw in (b'',b'\xef\xbb\xbf') + else:ok &= raw.startswith(b'\xef\xbb\xbf') + if k=='HTML':ok &= ''in raw.decode('utf-8-sig').lower() + if k=='Text':ok &= not raw.decode('utf-8-sig') + if k=='SpreadsheetDocument':ok &= ET.parse(content).getroot().tag=='{http://v8.1c.ru/spreadsheet/document}SpreadsheetDocument' + if k=='DataCompositionSchema': + cr=ET.parse(content).getroot();ds=[n for n in cr.iter()if n.tag.split('}')[-1].lower()=='datasource'] + ok &= len(ds)==1 and any((n.text or '').strip()=='ИсточникДанных1'for n in ds[0].iter())and('local'in ET.tostring(ds[0],encoding='unicode').lower()) + root=ET.parse(td/'src/Other.xml').getroot();children=root.find('.//{%s}ChildObjects'%MD) + registered=[(n.text or '').strip()for n in list(children)if n.tag.split('}')[-1]=='Template']if children is not None else [] + expected_registered=['T_'+name for name in list(types)[:list(types).index(k)+1]] + ok &= registered==expected_registered + types_ok &= bool(ok) + except (OSError,ET.ParseError,ValueError,AttributeError,KeyError):types_ok=False + for args in [['add-template','Other','T_Text','Text','src'],['remove-template','Missing','T','src'],['add-help','Missing','ru','src']]: + rc,_,_=command(['scaffold.py']+args,td);failure_ok &= rc!=0 + rc,_,_=command(['scaffold.py','add-help','Other','ru','src'],td);failure_ok &= rc==0 + rc,_,_=command(['scaffold.py','add-help','Other','ru','src'],td);failure_ok &= rc!=0 + return bool(types_ok),bool(failure_ok) + +def renamed_tests_contract(src): + t=tree(src) + if t is None:return False + tests=[n for n in ast.walk(t) if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef)) and n.name.startswith('test_')] + blobs=[ast.unparse(n).lower() for n in tests] + valid=any(('asserttrue' in s or 'assertEqual'.lower() in s) and 'success' in s for s in blobs) + unknown=any(any(x in s for x in ('unknown','missing','nonexistent','does-not-exist','not-found','non-existent','bad-id','uuid')) and ('assertfalse' in s or 'error_message' in s) for s in blobs) + invalid=any(('assertfalse' in s or 'error_message' in s) and any(x in s for x in ("' '",'81','invalid','empty','over','blank')) for s in blobs) + return 'inmemoryprojectrepository' in src.lower() and valid and unknown and invalid and not any(x in src.lower() for x in ('unittest.mock','magicmock','patch(')) + +def backend_test_scenarios(c): + src=read(c/'backend/tests/test_rename_project.py') + if tree(src) is None or any(x in src.lower()for x in ('unittest.mock','magicmock','patch(')):return False + # Observe actual calls made by the submitted unittest suite using the real + # repository. No lexical test-name requirement or invented parameter name. + code=''' +import dataclasses,unittest,sys,json +from backend.use_cases.rename_project import RenameProjectUseCase,RenameProjectRequest +from backend.adapters.memory_repository import InMemoryProjectRepository +events=[]; repos=[] +init=InMemoryProjectRepository.__init__ +def rinit(self,*args,**kw): + init(self,*args,**kw);repos.append(self) +InMemoryProjectRepository.__init__=rinit +execute=RenameProjectUseCase.execute +fields=[f.name for f in dataclasses.fields(RenameProjectRequest)if f.name!='project_id'] +def observe(self,request): + name=getattr(request,fields[0]) if len(fields)==1 else None + result=execute(self,request) + events.append((name,getattr(result,'success',None))) + return result +RenameProjectUseCase.execute=observe +suite=unittest.defaultTestLoader.discover('backend/tests',pattern='test_rename_project.py') +result=unittest.TextTestRunner(stream=sys.stderr).run(suite) +valid=lambda n:isinstance(n,str)and 0i),default=len(lines))])for cid,i in positions.items()} + +def citations_ok(c,report,spec): + if not isinstance(spec,dict):return False + criteria=spec.get('criteria',[]); blocks=criterion_blocks(report,[x['id']for x in criteria]) + for cr in criteria: + b=blocks.get(cr['id'],''); rel=cr['evidence_file']; actual=read(c/rel).splitlines() + # Accept :3, :L3, line 3 and markdown punctuation, but bind a quoted + # actual line to that same cited file/line; a bare numeral is not proof. + if rel not in b:return False + good=False + for n,line in enumerate(actual,1): + if not line.strip():continue + marker=re.search(re.escape(rel)+r'(?:[`*\s]*)?(?::\s*L?\s*'+str(n)+r'\b|[^\n]{0,35}\b(?:line|lines|行)\s*'+str(n)+r'\b)',b,re.I) + if marker and line.strip() in b: good=True + if not good:return False + return True + +def gate_original(c): + v=read(c/'e2e-evidence/verdict.md');spec=load(c/'docs/requirements/job-to-be-done.json');ids=['CRIT-001','CRIT-002','CRIT-003'];b=criterion_blocks(v,ids) + states=[] + for cid in ids: + m=re.search(r'\b(VALIDATED|PARTIAL|FAILED)\b',b.get(cid,''));states.append(m.group()if m else None) + debt=re.search(r'REMAINING DEBT:\s*(.*)',v) + return [states==['PARTIAL','FAILED','FAILED'],citations_ok(c,v,spec),'OVERALL: FAIL'in v and bool(debt)and all(x in debt.group(1)for x in ids),bool(re.fullmatch(r'fix:\s+[^\n]*[\u4e00-\u9fff][^\n]*',read(c/'commit-message.txt').strip()))] + +def review_submission(c): + d=load(c/'review_report.json');rules=load(c/'rules.json') + if not isinstance(d,dict)or not isinstance(rules,dict):return [False]*3 + fs=d.get('findings',[]);s=d.get('summary',{});v=d.get('verify',{}) + clean=isinstance(fs,list)and all(isinstance(f,dict)for f in fs) + counts=dict(collections.Counter(f.get('rule_id')for f in fs))if clean else{} + vactual=v.get('actual')if isinstance(v,dict)else None;vexpected=v.get('expected')if isinstance(v,dict)else None + def same(x):return summary_counts_ok(x,fs)if isinstance(x,dict)else False + return [clean and bool(fs)and all(f.get('rule_id')in rules.get('rules',{})for f in fs),clean and summary_counts_ok(s,fs)and same(vactual)and same(vexpected)and v.get('match')is True, clean and fs==sorted(fs,key=lambda f:(f.get('line',0),f.get('column',0)))] + +def review_variations(c,g): + src=c/'review.py' + if not src.is_file():return False,False,False + with tempfile.TemporaryDirectory()as td: + td=pathlib.Path(td);shutil.copyfile(src,td/'review.py');(td/'target.py').write_text(g['TARGET']) + r=json.loads(g['RULES']);r['rules']={f'ALT{j:02}':name for j,name in enumerate(r['rules'].values())};(td/'rules.json').write_text(json.dumps(r)) + rc,_,_=command(['review.py','target.py','rules.json','out.json'],td);d=load(td/'out.json');fs=d.get('findings',[])if isinstance(d,dict)else[] + renamed=rc==0 and bool(fs)and all(isinstance(f,dict)and f.get('rule_id')in r['rules']for f in fs)and set(r['rules']).issubset({f.get('rule_id')for f in fs if isinstance(f,dict)}) + r=json.loads(g['RULES']);r['max_parameters']=99;r['max_nesting_depth']=99;r['forbidden_literals']=[];(td/'rules.json').write_text(json.dumps(r)) + rc,_,_=command(['review.py','target.py','rules.json','out2.json'],td);d=load(td/'out2.json');fs=d.get('findings',[])if isinstance(d,dict)else[] + thresholds=rc==0 and isinstance(fs,list)and all(isinstance(f,dict)and f.get('rule_id')not in('R001','R004','R005')for f in fs)and any(f.get('rule_id')=='R002'for f in fs if isinstance(f,dict)) + error_ok=True + for bad,rf in [('bad.py','rules.json'),('target.py','bad.json'),('target.py','missing.json')]: + (td/'bad.py').write_text('def f(:\n');(td/'bad.json').write_text('{bad json') + rc,_,err=command(['review.py',bad,rf,'invalid.json'],td);error_ok &= rc==2 and bool(err.strip())and'Traceback'not in err + return renamed,thresholds,error_ok + +def lint_dynamic(c,g): + src=read(c/'lint.py') + if not src:return False,False + with tempfile.TemporaryDirectory()as td: + td=pathlib.Path(td);g['setup'](str(td),src) + # New recursively nested file, line-changing additions, positive and + # negative AST controls. A constant fixture report cannot satisfy this. + (td/'project/extra/deep').mkdir(parents=True) + (td/'project/extra/deep/control.py').write_text('# print(os.getenv("x"))\n\nimport os\nprint("ok")\nx = os.getenv("X")\nasync def typed(db) -> None:\n for item in []:\n await db.execute("SELECT 1")\n') + rc,_,_=command(['lint.py'],td); d=load(td/'report.json');norm=g['norm'];entries=norm(d)if isinstance(d,list)else None + extra=[('extra/deep/control.py',4,'print_usage'),('extra/deep/control.py',5,'env_access'),('extra/deep/control.py',7,'n1_query')] + recursive=rc==0 and entries is not None and all(e in entries for e in extra)and not any(e[0]=='extra/deep/control.py'and e[1]in(1,6)for e in(entries or[])) + (td/'project/app/services/sync.py').write_text('import datetime\n\ndef typed() -> None:\n """print(datetime.datetime.utcnow())"""\n return None\n') + rc,_,_=command(['lint.py'],td);d=load(td/'report.json');entries=norm(d)if isinstance(d,list)else None + responds=rc==0 and entries is not None and not any(e[0]=='app/services/sync.py'for e in entries) + return recursive,responds + +def executable_shell_tokens(command): + """Command argv only: exclude heredoc file bodies and echo/read strings.""" + kept=[];delimiter=None + for line in command.replace('\\\n',' ').splitlines(): + if delimiter is not None: + if line.strip()==delimiter:delimiter=None + continue + kept.append(line) + m=re.search(r'<<-?\s*([\'\"]?)([A-Za-z_][A-Za-z0-9_]*)\1',line) + if m:delimiter=m.group(2) + try: + lex=shlex.shlex('\n'.join(kept),posix=True,punctuation_chars=';&|()\n') + lex.whitespace=' \t\r' + lex.whitespace_split=True;tokens=list(lex) + except ValueError:return [] + segments=[];current=[] + for tok in tokens: + if tok and all(c in ';&|()\n'for c in tok): + if current:segments.append(current);current=[] + else:current.append(tok) + if current:segments.append(current) + out=[] + for seg in segments: + while seg and ('='in seg[0]or seg[0]in('env','command')):seg=seg[1:] + if seg and pathlib.PurePosixPath(seg[0]).name in('python','python3','python3.12','python3.11'): + out.append(seg[1:]) + return out + +def native_execution(q,c): + if not q.startswith('565a'):raise RuntimeError('Unexpected route in task-owned grader') + expected=[['init','ОбработкаЗагрузки','Обработка загрузки данных','src'],['add-template','ОбработкаЗагрузки','МакетЗагрузки','Text','src'],['add-template','ОбработкаЗагрузки','ПФ_MXL_М11','SpreadsheetDocument','src'],['add-help','ОбработкаЗагрузки','ru','src'],['remove-template','ОбработкаЗагрузки','МакетЗагрузки','src']] + with tempfile.TemporaryDirectory(prefix='canonical-scaffold-')as td: + root=pathlib.Path(td);__import__('r10_support').copy_modules(c,root) + if not(root/'scaffold.py').is_file():return False + for argv in expected: + rc,_,_=command(['scaffold.py']+argv,root) + if rc!=0:return False + return root_xml_contract(root)and artifact_boms(root)and not(root/'src/ОбработкаЗагрузки/Templates/МакетЗагрузки.xml').exists()and not(root/'src/ОбработкаЗагрузки/Templates/МакетЗагрузки').exists()and(root/'src/ОбработкаЗагрузки/Ext/Help.xml').is_file()and(root/'src/ОбработкаЗагрузки/Ext/Help/ru.html').is_file() + +def grade(q,c): + g,checks=run_original(q,c) + def add(name,ok,reason):checks.append({'id':name,'passed':bool(ok),'reason':reason}) + if q.startswith('565a'): + add('public_root_uuid_class_template_identity',root_xml_contract(c),'actual root ClassId/UUID and template UUID/Name/Synonym required by public commands') + add('public_all_text_bom',artifact_boms(c),'all actual generated XML/BSL/HTML/text files start with UTF-8 BOM') + types_ok,failure_ok=scaffold_variations(c) + add('public_all_template_types',types_ok,'five public type mappings produce required minimal content') + add('public_all_failure_cases',failure_ok,'duplicate template/help, missing object/Ext/root failures exit nonzero') + elif q.startswith('6401'): + ok=domain_delegation(read(c/'backend/use_cases/rename_project.py')) + checks[1]['passed']=checks[1]['passed'] and ok;checks[1]['reason']+='; actual AST rename delegation='+str(ok) + ok=backend_test_scenarios(c) + checks[5]['passed']=checks[5]['passed'] and ok;checks[5]['reason']+='; three semantic test scenarios='+str(ok) + elif q.startswith('7e93'): + s=audit_submission_checks(g,load(c/'audit-report.json')) + for j,ok in enumerate(s):add('submission_'+str(j),ok,'actual submitted report public finding/schema criterion '+str(j)) + add('stdlib_imports',stdlib(read(c/'audit.py')),'stdlib-only imports in audit.py') + elif q.startswith('c7bd'): + for j,ok in enumerate(plan_submission(c,g)):add('submission_'+str(j),ok,'actual report/plans archival/index/executed-count criterion '+str(j)) + # Stop statuses and unsatisfiable dependencies must be handled on fresh + # isolated fixtures; existing implementation behavior remains separate. + stop=True; unsched=True + for status in ('needs-fix','needs-assessing','needs-revision','blocked'): + with tempfile.TemporaryDirectory()as td: + mod={'plans/02-api.md':g['FILES']['plans/02-api.md'].replace('Status: ready-to-build','Status: '+status)};g['make_env'](td,mod); before=g['snap'](td);rc,r=g['run_tool'](td) + stop &= rc==2 and isinstance(r,dict)and r.get('gate')=='blocked'and'02-api'in json.dumps(r)and before==g['snap'](td) + with tempfile.TemporaryDirectory()as td: + mod={'plans/02-api.md':g['FILES']['plans/02-api.md'].replace('blocked-by: 01-auth','blocked-by: 99-missing')};g['make_env'](td,mod);rc,r=g['run_tool'](td) + unsched=rc==0 and isinstance(r,dict)and'02-api'in g['names'](r.get('unschedulable'))and not os.path.exists(os.path.join(td,'plans/done/20260412/02-api.md')) + add('public_stop_statuses',stop,'four public stop statuses block whole run without mutating plans') + add('public_missing_dependency',unsched,'missing dependency is unschedulable and not executed') + elif q.startswith('fdc4'): + for j,ok in enumerate(gate_original(c)):add('submission_'+str(j),ok,'actual delivered states/citations/all debt/fix commit '+str(j)) + add('stdlib_imports',stdlib(read(c/'gate_check.py')),'stdlib-only imports in gate_check.py') + elif q.startswith('bc8f'): + for j,ok in enumerate(review_submission(c)):add('submission_'+str(j),ok,'actual delivered report IDs/recomputed verification/sort '+str(j)) + renamed,thresholds,error_ok=review_variations(c,g) + add('public_json_rule_binding',renamed,'rule identifiers loaded from same JSON categories under renamed rule IDs') + add('public_thresholds',thresholds,'changing configured maxima/literals changes findings') + add('public_input_errors',error_ok,'bad target/bad rules/missing rules exit 2 with diagnostic, no traceback') + add('public_ast_stdlib',uses_ast(read(c/'review.py'))and stdlib(read(c/'review.py')),'AST parse with stdlib-only imports') + elif q.startswith('7bc7'): + src=read(c/'lint.py');rep=load(c/'report.json');entries=g['norm'](rep)if isinstance(rep,list)else None + add('actual_submitted_report',entries==g['EXPECTED'],'actual report matches supplied project expected violation set') + add('public_ast_parse',uses_ast(src),'AST parsing is used by scanner') + recur,respond=lint_dynamic(c,g) + add('public_recursive_ast_controls',recur,'new nested file detections and comment negative control') + add('public_changed_project',respond,'removing all violations from a file removes its reports') + add('native_requested_execution',native_execution(q,c),'grader independently executes exact canonical sequence on fresh source modules and validates final artifacts; historical tool trace is not scored') + return {'schema':'repaired-verified-grader-v1','checks':checks,'scoreable':all(x['passed'] is not None for x in checks),'score':None if any(x['passed'] is None for x in checks)else sum(x['passed']for x in checks)/len(checks),'passed_checks':sum(x['passed'] is True for x in checks),'total_checks':len(checks),'candidate_execution':'sandbox_required','denominator_fixed_per_task':True} + +def main(): + p=argparse.ArgumentParser();p.add_argument('--query-id',required=True);p.add_argument('--candidate',default=os.environ.get('CANDIDATE_DIR','/candidate'));a=p.parse_args() + try:print(json.dumps(grade(a.query_id,pathlib.Path(a.candidate)),ensure_ascii=False)) + except Exception as e: + print(json.dumps({'status':'evaluation_error','score':None,'error':type(e).__name__+': '+str(e)}));return 1 + return 0 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/original.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/original.py new file mode 100644 index 0000000000000000000000000000000000000000..990ce7c454d2583de7124c2e5c8320a4ef8b628f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/original.py @@ -0,0 +1,163 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import ast, json, os, shutil, subprocess, sys, tempfile +import xml.etree.ElementTree as ET + +CAND = "/candidate" +checks = [] +def add(i, ok, reason): + checks.append({"id": str(i), "passed": None if ok is None else bool(ok), "reason": reason}) + +def run(args, cwd): + try:return subprocess.run([sys.executable,'scaffold.py']+args,cwd=cwd,capture_output=True,timeout=60) + except subprocess.TimeoutExpired:return subprocess.CompletedProcess(args,124,b'',b'candidate timeout') + +# ---- locate scaffold.py ---- +sp = None +for root, dirs, files in os.walk(CAND): + if "scaffold.py" in files: + sp = os.path.join(root, "scaffold.py") + break +if sp is None: + for i in range(8): + add(i, False, "scaffold.py not found in candidate workspace") + print(json.dumps({"checks": checks})) + sys.exit(0) + +base = os.path.dirname(sp) + +def p(*parts): + return os.path.join(base, *parts) + +# ---- criterion 0: stdlib only + four subcommands work ---- +from r10_support import dependency,copy_modules,tri +stdlib_ok=dependency(base,'scaffold.py') + +sub_ok = False +sub_detail = "" +try: + with tempfile.TemporaryDirectory(dir="/tmp") as td: + copy_modules(base,td) + r = run(["init", "ТестОбр", "Тест Синоним", "src"], td) + r2 = run(["add-template", "ТестОбр", "МакетТ", "Text", "src"], td) + r3 = run(["add-help", "ТестОбр", "ru", "src"], td) + r4 = run(["remove-template", "ТестОбр", "МакетТ", "src"], td) + ok = all(x.returncode == 0 for x in (r, r2, r3, r4)) + ok = ok and os.path.isfile(os.path.join(td, "src", "ТестОбр.xml")) + ok = ok and os.path.isfile(os.path.join(td, "src", "ТестОбр", "Ext", "ObjectModule.bsl")) + ok = ok and os.path.isfile(os.path.join(td, "src", "ТестОбр", "Ext", "Help.xml")) + ok = ok and not os.path.exists(os.path.join(td, "src", "ТестОбр", "Templates", "МакетТ.xml")) + sub_ok = ok + if not ok: + sub_detail = "one of init/add-template/add-help/remove-template failed in sandbox" +except Exception as e: + raise RuntimeError("Trusted scaffold execution probe failed")from e +add(0, tri([stdlib_ok,sub_ok]), "stdlib-only: %s; four subcommands runnable: %s %s" % (stdlib_ok, sub_ok, sub_detail)) + +# ---- criterion 1: root XML content ---- +MD = "http://v8.1c.ru/8.3/MDClasses" +V8 = "http://v8.1c.ru/8.1/data/core" +root_xml_path = p("src", "ОбработкаЗагрузки.xml") +c1_ok, c1_msg = False, "root XML missing" +try: + t = ET.parse(root_xml_path) + r = t.getroot() + name_el = r.find(".//{%s}ExternalDataProcessor/{%s}Properties/{%s}Name" % (MD, MD, MD)) + syn_el = r.find(".//{%s}Synonym/{%s}item/{%s}content" % (MD, V8, V8)) + cos = r.findall(".//{%s}ChildObjects/{%s}Template" % (MD, MD)) + texts = [(c.text or "").strip() for c in cos] + c1_ok = (name_el is not None and name_el.text == "ОбработкаЗагрузки" + and syn_el is not None and syn_el.text == "Обработка загрузки данных" + and texts == ["ПФ_MXL_М11"]) + c1_msg = "Name=%s Synonym=%s Templates=%s" % ( + name_el.text if name_el is not None else None, + syn_el.text if syn_el is not None else None, texts) +except Exception as e: + c1_msg = "parse error: %s" % e +add(1, c1_ok, c1_msg) + +# ---- criterion 2: ObjectModule.bsl regions ---- +bsl_path = p("src", "ОбработкаЗагрузки", "Ext", "ObjectModule.bsl") +c2_ok, c2_msg = False, "ObjectModule.bsl missing" +try: + txt = open(bsl_path, encoding="utf-8-sig").read() + regions = ["ОписаниеПеременных", "ПрограммныйИнтерфейс", "СлужебныеПроцедурыИФункции"] + missing = [x for x in regions if ("#Область " + x) not in txt] + n_end = txt.count("#КонецОбласти") + c2_ok = not missing and n_end >= 3 + c2_msg = "missing regions: %s; #КонецОбласти count=%d" % (missing or "none", n_end) +except Exception as e: + c2_msg = "read error: %s" % e +add(2, c2_ok, c2_msg) + +# ---- criterion 3: template metadata + spreadsheet content ---- +tmeta_path = p("src", "ОбработкаЗагрузки", "Templates", "ПФ_MXL_М11.xml") +tcont_path = p("src", "ОбработкаЗагрузки", "Templates", "ПФ_MXL_М11", "Ext", "Template.xml") +c3_ok, c3_msg = False, "template files missing" +try: + tm = ET.parse(tmeta_path).getroot() + tt = tm.find(".//{%s}TemplateType" % MD) + c3_ok = tt is not None and tt.text == "SpreadsheetDocument" + ss_ns = "http://v8.1c.ru/spreadsheet/document" + tc = ET.parse(tcont_path).getroot() + c3_ok = c3_ok and tc.tag == "{%s}SpreadsheetDocument" % ss_ns + c3_msg = "TemplateType=%s; content root=%s" % (tt.text if tt is not None else None, tc.tag) +except Exception as e: + c3_msg = "parse error: %s" % e +add(3, c3_ok, c3_msg) + +# ---- criterion 4: МакетЗагрузки removed ---- +m1 = os.path.exists(p("src", "ОбработкаЗагрузки", "Templates", "МакетЗагрузки.xml")) +m2 = os.path.isdir(p("src", "ОбработкаЗагрузки", "Templates", "МакетЗагрузки")) +add(4, not m1 and not m2, "meta exists=%s, dir exists=%s" % (m1, m2)) + +# ---- criterion 5: help files ---- +help_xml_path = p("src", "ОбработкаЗагрузки", "Ext", "Help.xml") +help_html_path = p("src", "ОбработкаЗагрузки", "Ext", "Help", "ru.html") +c5_ok, c5_msg = False, "help files missing" +try: + h = ET.parse(help_xml_path).getroot() + page = h.find("{%s}Page" % "http://v8.1c.ru/8.3/xcf/extrnprops") + html = open(help_html_path, encoding="utf-8-sig").read() + has_h1 = ("

" in html and "ОбработкаЗагрузки" in html.split("

", 1)[1].split("

")[0]) + has_css = "v8help://service_book/service_style" in html + c5_ok = (page is not None and page.text == "ru" and has_h1 and has_css) + c5_msg = "Page=%s h1=%s css=%s" % (page.text if page is not None else None, has_h1, has_css) +except Exception as e: + c5_msg = "error: %s" % e +add(5, c5_ok, c5_msg) + +# ---- criterion 6: BOMs ---- +bom_files = [root_xml_path, help_xml_path, tmeta_path, bsl_path] +bom_ok, bom_msg = True, "" +for f in bom_files: + try: + if open(f, "rb").read(3) != b"\xef\xbb\xbf": + bom_ok = False + bom_msg += "no BOM: %s; " % os.path.basename(f) + except Exception: + bom_ok = False + bom_msg += "unreadable: %s; " % f +add(6, bom_ok, bom_msg or "all four files start with EF BB BF") + +# ---- criterion 7: public failure modes exit nonzero ---- +c7_ok, c7_msg = False, "" +try: + with tempfile.TemporaryDirectory(dir="/tmp") as td: + copy_modules(base,td) + # add-template on nonexistent object + r = run(["add-template", "НетОбъекта", "М", "Text", "src"], td) + partial = os.path.exists(os.path.join(td, "src", 'НетОбъекта')) + # remove-template with missing template on existing object + run(["init", "Обр2", "", "src"], td) + r2 = run(["remove-template", "Обр2", "НетМакета", "src"], td) + # init duplicate + r3 = run(["init", "Обр2", "", "src"], td) + c7_ok = (r.returncode != 0 + and r2.returncode != 0 and r3.returncode != 0) + c7_msg = "add-template rc=%d partial=%s remove-missing rc=%d init-dup rc=%d" % ( + r.returncode, partial, r2.returncode, r3.returncode) +except Exception as e: + raise RuntimeError("Trusted scaffold failure-mode probe failed")from e +add(7, c7_ok, c7_msg) + +print(json.dumps({"checks": checks})) diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_support.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_support.py new file mode 100644 index 0000000000000000000000000000000000000000..3556e9bcca3973535b715a64aa685f1c492439f1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_support.py @@ -0,0 +1,28 @@ +"""Evaluator-only workspace and dependency helpers; candidate execution is external.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from pathlib import Path +import shutil,json +from dependency_scan import scan_stdlib + +def tri(values): + values=list(values) + return False if any(v is False for v in values) else None if any(v is None for v in values) else True + +def dependency(root,entry): + value,modules,why=scan_stdlib(root,[entry]) + return None if str(why).startswith('unknown:') else value + +def copy_modules(root,destination): + """Copy authored Python and package resources; exclude generated src trees.""" + root=Path(root);destination=Path(destination) + ignored={'src','__pycache__','.git','.venv','skill','skills','.skill-search'} + for source in root.iterdir(): + if source.name in ignored:continue + target=destination/source.name + if source.resolve()==target.resolve():continue + if source.is_symlink(): + if target.exists()or target.is_symlink():target.unlink() + target.symlink_to(__import__('os').readlink(source)) + elif source.is_dir(): + shutil.copytree(source,target,dirs_exist_ok=True,symlinks=True,ignore=shutil.ignore_patterns('__pycache__','.git','.venv')) + elif source.is_file():shutil.copy2(source,target) diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_trace.py b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..093e087f70bd29f8c70f8a1c0a1785297f025ba5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/evaluator/r10_trace.py @@ -0,0 +1,224 @@ +"""Read parent-bound, completed native tool calls without running shell text.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import hashlib,json,os,re,shlex +from pathlib import Path +def shell_continuations(text): + """Remove only shell-active backslash/newline pairs, preserving single quotes.""" + out=[];quote=None;i=0 + while i':return True + return False + +def following_status(groups,index,content): + """Use an immediate shell echo of $? only when its literal marker is unique. + + A literal printed 0 is never a status witness. The echo's argument may only + be an ASCII identifier, '=', and the shell's previous-status expansion. + The marker is required exactly once in actual paired tool output, so child + output imitating the marker cannot hide the real nonzero echo. + """ + if index+1>=len(groups) or len(groups[index+1])!=1:return None + argv=groups[index+1][0] + if len(argv)!=2 or argv[0]!='echo':return None + match=re.fullmatch(r'([A-Za-z_][A-Za-z_0-9]*=)\$\?',argv[1]) + if not match:return None + prefix=match.group(1) + lines=[line for line in content.splitlines() if line.startswith(prefix)] + if len(lines)!=1:return None + result=re.fullmatch(re.escape(prefix)+r'([0-9]{1,3})',lines[0]) + if not result:return None + code=int(result.group(1)) + return code if 0<=code<=255 else None + +def command_exit_status(call,argv): + """Status of one exact standalone command, never an inferred AND member.""" + if call.get('control_flow_uncertain',call.get('uncertain')):return None + try: + rows=shell_segments(shell_comments(shell_continuations(call['source']))) + except (KeyError,TypeError,ValueError):return None + compound={'if','then','else','elif','fi','for','while','until','do','done','case','esac','function','{','}'} + if any(row and(row[0]in compound or row[0].startswith(('(',')')) or re.fullmatch(r'[A-Za-z_]\w*\(\)',row[0]))for row in rows):return None + groups=[];group=[] + for row in rows: + if row in [[';'],['\n']]: + if group:groups.append(group);group=[] + else:group.append(row) + if group:groups.append(group) + # Re-parsing must not revive an unreachable command after exit/return. + # Completed failed tools carry no credited segments; only an exact single + # standalone probe may use their overall status. + if argv not in call.get('segments',[]) and groups!=[[argv]]:return None + matches=[i for i,g in enumerate(groups) if g==[argv]] + if len(matches)!=1:return None + index=matches[0];status=following_status(groups,index,call.get('output','')) + if status is not None:return status + status=call.get('exit_code') + return status if index==len(groups)-1 and type(status)is int and 0<=status<=255 else None + +def trusted_calls(): + path=Path(os.environ.get('MYBENCH_TRUSTED_TRACE',os.environ.get('MYBENCH_TOOL_TRAJECTORY','/tool_trajectory.json'))) + sha=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256')or os.environ.get('MYBENCH_TOOL_TRAJECTORY_SHA256') + try: + if path.resolve().is_relative_to(Path('/candidate').resolve())or not sha:return None + raw=path.read_bytes() + if hashlib.sha256(raw).hexdigest()!=sha:return None + obj=json.loads(raw) + if not isinstance(obj,dict)or not isinstance(obj.get('steps'),list):return None + except (OSError,ValueError):return None + found=[] + for step in obj['steps']: + if step.get('source')!='agent':continue + observations={str(x.get('source_call_id')):x for x in step.get('observation',{}).get('results',[])if isinstance(x,dict)} + for call in step.get('tool_calls',[]): + if call.get('function_name')not in ['bash','exec_command','shell','run_shell_command']:continue + args=call.get('arguments',{});source=args.get('command',args.get('cmd',''))if isinstance(args,dict)else'' + observation=observations.get(str(call.get('tool_call_id'))) + if not isinstance(source,str)or observation is None: + found.append(dict(segments=[],source=source,output='',tool_call_id=call.get('tool_call_id'),uncertain=True));continue + content=observation.get('content','');content=content if isinstance(content,str)else json.dumps(content) + if observation.get('exit_code')not in(None,0): + # A later failing command does not prove that an earlier + # requested invocation failed. Preserve its status as unknown. + try: + failed=shell_segments(shell_comments(shell_continuations(source))) + standalone=len(failed)==1 and not has_redirection(source) and failed[0] and failed[0][0]not in ['if','for','while','until','case','function','{','}'] and not failed[0][0].startswith(('(',')')) + except ValueError:standalone=False + found.append(dict(segments=[],source=source,output=content,tool_call_id=call.get('tool_call_id'),exit_code=observation.get('exit_code'),control_flow_uncertain=not standalone,uncertain=not standalone));continue + if observation.get('exit_code')is None and 'Traceback (most recent call last)'in content: + found.append(dict(segments=[],source=source,output=content,tool_call_id=call.get('tool_call_id'),uncertain=True));continue + lines=[];heredoc=None;heredoc_seen=False + for line in shell_continuations(source).splitlines(): + if heredoc: + if line.strip()==heredoc:heredoc=None + continue + match=re.search(r"<<-?\s*['\"]?([A-Za-z_][A-Za-z_0-9]*)['\"]?",line) + if match:heredoc=match[1];heredoc_seen=True;continue + lines.append(line) + clean=shell_comments('\n'.join(lines)) + try: + segments=shell_segments(clean) + except ValueError: + found.append(dict(segments=[],source=source,output=content,tool_call_id=call.get('tool_call_id'),uncertain=True));continue + # Unsupported branch/function structure must never credit quoted text. + compound={'if','then','else','elif','fi','for','while','until','do','done','case','esac','function','{','}'} + if any(row and(row[0]in compound or row[0].startswith(('(',')')) or re.fullmatch(r'[A-Za-z_]\w*\(\)',row[0]))for row in segments): + found.append(dict(segments=[],source=source,output=content,tool_call_id=call.get('tool_call_id'),uncertain=True));continue + # Separate complete top-level command lists from conditional chains. + # A trailing successful `true` cannot prove an earlier && RHS ran. + groups=[];group=[] + for row in segments: + if row in [[';'],['\n']]: + if group:groups.append(group);group=[] + else:group.append(row) + if group:groups.append(group) + safe=[];uncertain=heredoc_seen;halt=False + for group_index,group in enumerate(groups): + if halt:break + if any(row in [['||'],['|'],['&']]for row in group): + uncertain=True + continue + commands=[row for row in group if row!=['&&']] + chained=any(row==['&&']for row in group) + status=following_status(groups,group_index,content) + proved_chain=(not chained or status==0 or group_index==len(groups)-1 and observation.get('exit_code')==0) + for command_index,row in enumerate(commands): + if command_index and not proved_chain: + uncertain=True;break + if row and row[0]in ['exit','return']: + halt=True;break + while row and re.fullmatch(r'[A-Za-z_]\w*=[^$`]*',row[0]):row=row[1:] + if len(row)>1 and row[0]=='command'and row[1]not in ['-v','-V']:row=row[1:] + if row and row[0]=='env': + row=row[1:] + while row and re.fullmatch(r'[A-Za-z_]\w*=[^$`]*',row[0]):row=row[1:] + if row and row[0]in ['eval','source','.','set','trap','exec','shopt','enable','alias']: + uncertain=True;halt=True;break + if row:safe.append(row) + if chained and row and row[0]=='false': + # Literal false proves that all later && terms are skipped. + break + found.append(dict(segments=safe,source=source,output=content,tool_call_id=call.get('tool_call_id'),exit_code=observation.get('exit_code'),control_flow_uncertain=uncertain or any(any(ch in row[0]for ch in '$`')for row in safe),uncertain=uncertain or has_redirection(clean) or any(any(ch in row[0]for ch in '$`')for row in safe))) + return found +def invocation(argv,script): + if not argv:return None + if Path(argv[0]).name==script:return argv[1:] + if len(argv)>1 and re.fullmatch(r'python(?:3(?:[.][0-9]+)?)?|bash|sh|dash',Path(argv[0]).name)and Path(argv[1]).name==script:return argv[2:] + return None +def bound_file(relative): + try: + meta=json.loads(Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text()) + b=meta.get('trusted_trace_binding',{}) + if b.get('schema')!='mybench_native_trace_binding_v1':return None + if b.get('trajectory_sha256')!=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256'):return None + sha=b.get('candidate_file_sha256',{}).get(relative) + return None if not sha else sha==hashlib.sha256((Path('/candidate')/relative).read_bytes()).hexdigest() + except (OSError,ValueError,TypeError):return None diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..21ee69268abb42060fadec352c1ed5cb67623304 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/grading/verified_config.json @@ -0,0 +1,102 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "565a86de4451341fda2e5b02", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "r10_trace.py": "ba74c78a0f6a7f29201af61722f60bb1f51c7e760a8f20a26888e2529b25142b", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "c407f5128570c0bc85009aff91d6b7366831997fdaf968d62fb40b2d7fe25371", + "r10_support.py": "eb3055e89ef46d1ac0cf7c8e2a4db755f7b090b6d4b005fda521a730c7c3da09", + "dependency_scan.py": "6196b667b8494069b859cc5b1f2f18374cefbde917267666bf36f2d6da145b22", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "ca0ed84b405f4cdd1033bb21afbd37434e14203460fc51c021f14786f3337b13", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "grade.py": "2362dfcade4f14b16f9ab15c6e1e687c07177edcf5b83b018779a74cbe0d6a7b", + "expected_check_ids.json": "f39f4f0a71c700a6ec9daf84d6acf90334c9da7b09291e96068785ac4472b208", + "original.py": "86baa952b0bb63a2a8eb2b19c46f69c37e27836b7872008b9258c5cddbc3e52a", + "auto_contract.json": "9e15d831b7110ad31b2c117fd1b8c1ef86f8dc50a32a2e7e43139f811504e06d" + }, + "runtime_requirements": { + "family": "selected_multi7_native_contract", + "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "read_only_mounts": [ + "task:/source", + "task:/task", + "evaluator:/grader", + "candidate:/candidate", + "answer:/answer.txt" + ], + "writable_tmpfs": [ + "/app", + "/workspace", + "/tmp" + ], + "copy_completed_candidate_children_to_app_before_grader": true, + "entrypoint": [ + "python3", + "/grader/check.py" + ], + "working_directory": "/candidate", + "environment": { + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_CANDIDATE_PATH": "/candidate", + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1" + }, + "environment_names_detected": [ + "CANDIDATE_DIR", + "MYBENCH_TOOL_TRAJECTORY" + ], + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "public_root_uuid_class_template_identity", + "public_all_text_bom", + "public_all_template_types", + "public_all_failure_cases", + "native_requested_execution" + ], + "criterion_count": 13, + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "public_root_uuid_class_template_identity": 1, + "public_all_text_bom": 1, + "public_all_template_types": 1, + "public_all_failure_cases": 1, + "native_requested_execution": 1 + }, + "actual_original_success_criteria_count": 8, + "original_task_metadata_must_not_define_override_criterion_count": true, + "requires_external_actual_native_trace": false, + "requires_external_trusted_snapshot_binding": false, + "fresh_native_binding_must_not_require_historical_run_id": true, + "checker_can_execute_candidate_subprocesses": true, + "host_execution_forbidden": true, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "docker_image_payload_in_source_tree": false, + "runtime_missing": [], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "grader_timeout_seconds": 600 + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/instruction.md b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f44b2284e662d350e4af2ac50c69a145b2391f9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/565a86de4451341fda2e5b02/instruction.md @@ -0,0 +1,22 @@ +Write a Python 3 (standard library only) command-line tool `scaffold.py` that manages XML sources of a 1C external data processor, then run it to build a small project. The tool must support four subcommands, all writing files as UTF-8 with BOM: + +1. `python3 scaffold.py init [Synonym] [SrcDir]` — create `/.xml` (root metadata XML with a fresh UUID on ExternalDataProcessor, the ExternalDataProcessor ClassId from the frozen init Skill's scripts/init.py, Properties Name/Synonym with v8:item ru content, empty ChildObjects), plus `//Ext/ObjectModule.bsl` containing the three standard regions from that frozen initialization script, with their closing directives. Synonym defaults to Name. Fail with nonzero exit if the root XML already exists. +2. `python3 scaffold.py add-template [SrcDir]` — TemplateType is one of HTML, Text, SpreadsheetDocument, BinaryData, DataCompositionSchema (map to HTMLDocument/.html, TextDocument/.txt, SpreadsheetDocument/.xml, BinaryData/.bin, DataCompositionSchema/.xml). Create `//Templates/.xml` (Template metadata with one UUID, Name, Synonym, TemplateType) and `//Templates//Ext/Template.` with minimal content per type (empty HTML skeleton; empty text; minimal SpreadsheetDocument XML; empty binary; minimal DataCompositionSchema with one local dataSource named ИсточникДанных1). Append `` at the end of ChildObjects in the root XML. Fail if the template already exists or the root XML is missing. +3. `python3 scaffold.py add-help [Lang] [SrcDir]` — create `//Ext/Help.xml` (Help namespace http://v8.1c.ru/8.3/xcf/extrnprops with `Lang`) and `//Ext/Help/.html` (HTML page with `

ObjectName

` and stylesheet link v8help://service_book/service_style). Help is NOT registered in ChildObjects. Fail if help already exists or the object's Ext dir is missing. +4. `python3 scaffold.py remove-template [SrcDir]` — delete `Templates/.xml` and the `Templates//` directory recursively, and remove the matching `