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

Upload Skill-Venus Data as released (part 8)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/skill/SKILL.md +112 -0
  2. benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/task.json +48 -0
  3. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_contract.json +8 -0
  4. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_entry.py +38 -0
  5. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy.py +133 -0
  6. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy_guard.py +86 -0
  7. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/autograde_task_check.py +12 -0
  8. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/check.py +2 -0
  9. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy-task.json +136 -0
  10. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/evaluate.py +159 -0
  11. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/objective_evaluators.py +1309 -0
  12. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/shell_invocations.py +229 -0
  13. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/test.sh +8 -0
  14. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/verifiers.py +520 -0
  15. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/r9_json.py +74 -0
  16. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/grading/verified_config.json +99 -0
  17. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/instruction.md +1 -0
  18. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/SKILL.md +80 -0
  19. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/api.md +153 -0
  20. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/architecture.md +162 -0
  21. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/built-in-contracts.md +261 -0
  22. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/consensus.md +168 -0
  23. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/contributing.md +262 -0
  24. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-block-production.md +190 -0
  25. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-reward-distribution.md +188 -0
  26. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-staking-delegation.md +246 -0
  27. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-sync.md +223 -0
  28. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-transaction-lifecycle.md +198 -0
  29. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/p2p.md +178 -0
  30. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/solo.md +135 -0
  31. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/storage.md +203 -0
  32. benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/task.json +59 -0
  33. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_contract.json +8 -0
  34. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_entry.py +38 -0
  35. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy.py +133 -0
  36. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy_guard.py +86 -0
  37. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/autograde_task_check.py +14 -0
  38. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/check.py +2 -0
  39. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy-task.json +139 -0
  40. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/evaluate.py +159 -0
  41. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/objective_evaluators.py +1308 -0
  42. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/shell_invocations.py +378 -0
  43. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/test.sh +8 -0
  44. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/verifiers.py +516 -0
  45. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/repair_equivalences.py +240 -0
  46. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/grading/verified_config.json +99 -0
  47. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/instruction.md +1 -0
  48. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/CHANNELS.md +267 -0
  49. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/SKILL.md +591 -0
  50. benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/task.json +49 -0
benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/skill/SKILL.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: dyad:add-models
3
+ description: Add one or more AI models to the language model constants file, researching specs from official docs.
4
+ ---
5
+
6
+ # Add Models
7
+
8
+ Add one or more AI models to `src/ipc/shared/language_model_constants.ts`, researching correct specifications from official documentation.
9
+
10
+ ## Arguments
11
+
12
+ - `$ARGUMENTS`: Comma-separated list of model names to add (e.g., "gemini 3.1 pro, glm 5, sonnet 4.6").
13
+
14
+ ## Instructions
15
+
16
+ 1. **Parse the model list:**
17
+
18
+ Split `$ARGUMENTS` by commas to get individual model names. Trim whitespace from each.
19
+
20
+ 2. **Read the current constants file:**
21
+
22
+ Read `src/ipc/shared/language_model_constants.ts` to understand:
23
+ - Which providers exist and their current model entries
24
+ - The naming conventions for each provider (e.g., `claude-sonnet-4-20250514` for Anthropic, `gemini-2.5-pro` for Google)
25
+ - The structure of `ModelOption` entries (name, displayName, description, maxOutputTokens, contextWindow, temperature, dollarSigns)
26
+
27
+ 3. **Identify the provider for each model:**
28
+
29
+ Map each model to its provider based on the model name:
30
+ - **Anthropic** (`anthropic`): Claude models (Opus, Sonnet, Haiku)
31
+ - **OpenAI** (`openai`): GPT models
32
+ - **Google** (`google`): Gemini models
33
+ - **xAI** (`xai`): Grok models
34
+ - **OpenRouter** (`openrouter`): Models from other providers (DeepSeek, Qwen, Moonshot/Kimi, Z-AI/GLM, etc.)
35
+ - **Azure** (`azure`): Azure-hosted OpenAI models
36
+ - **Bedrock** (`bedrock`): AWS Bedrock-hosted Anthropic models
37
+ - **Vertex** (`vertex`): Google Vertex AI-hosted models
38
+
39
+ 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.
40
+
41
+ 4. **Research each model's specifications:**
42
+
43
+ For each model, use WebSearch and WebFetch to look up the official documentation:
44
+ - **Anthropic models**: Search `docs.anthropic.com` for model specs
45
+ - **OpenAI models**: Search `platform.openai.com/docs/models` for model specs
46
+ - **Google Gemini models**: Search `ai.google.dev/gemini-api/docs/models` for model specs
47
+ - **xAI models**: Search `docs.x.ai/docs/models` for model specs
48
+ - **OpenRouter models**: Search `openrouter.ai/<provider>/<model-name>` for model specs and pricing
49
+
50
+ For each model, determine:
51
+ - **API model name**: The exact string used in API calls (e.g., `claude-sonnet-4-5-20250929`, `gemini-2.5-pro`)
52
+ - **Display name**: Human-readable name (e.g., "Claude Sonnet 4.5", "Gemini 2.5 Pro")
53
+ - **Description**: Short description following the style of existing entries
54
+ - **Max output tokens**: The model's maximum output token limit
55
+ - **Context window**: The model's total context window size
56
+ - **Temperature**: Default temperature (0 for most models, 1 for OpenAI, 1.0 for Gemini 3.x models)
57
+ - **Dollar signs**: Cost tier from 0-6 based on pricing relative to other models in the same provider
58
+
59
+ **Dollar signs guide** (approximate, based on per-million-token input pricing):
60
+ - 0: Free
61
+ - 1: Very cheap (<$0.50/M input tokens)
62
+ - 2: Cheap ($0.50-$2/M)
63
+ - 3: Moderate ($2-$8/M)
64
+ - 4: Expensive ($8-$15/M)
65
+ - 5: Very expensive ($15-$30/M)
66
+ - 6: Premium ($30+/M)
67
+
68
+ 5. **Follow provider-specific conventions:**
69
+
70
+ Match the patterns used by existing entries:
71
+ - **OpenAI**: `maxOutputTokens: undefined` (OpenAI errors with `max_tokens`), `temperature: 1`
72
+ - **Anthropic**: `maxOutputTokens: 32_000`, `temperature: 0`
73
+ - **Google**: `maxOutputTokens: 65_536 - 1` (exclusive upper bound for Vertex), `temperature` varies
74
+ - **OpenRouter**: `maxOutputTokens: 32_000`, prefix model name with provider (e.g., `deepseek/deepseek-chat-v3.1`)
75
+ - **Azure**: `maxOutputTokens` commented out, `temperature: 1`
76
+ - **Bedrock**: Model names use ARN format (e.g., `us.anthropic.claude-sonnet-4-5-20250929-v1:0`)
77
+ - **xAI**: `maxOutputTokens: 32_000`, `temperature: 0`
78
+
79
+ 6. **Add the models to the constants file:**
80
+
81
+ Insert each new model entry into the appropriate provider's array in `MODEL_OPTIONS`. Place new models:
82
+ - At the **top** of the provider's array if it's the newest/most capable model
83
+ - After existing models of the same family but before older generations
84
+ - Add a comment with a link to the model's documentation page
85
+
86
+ Also check if related arrays need updating:
87
+ - `TURBO_MODELS`: If the model has a turbo variant
88
+ - `PROVIDERS_THAT_SUPPORT_THINKING`: If adding a new provider that supports thinking
89
+
90
+ 7. **Check for named constant exports:**
91
+
92
+ 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:
93
+
94
+ ```
95
+ grep -r "SONNET_4_5\|GPT_5_2_MODEL_NAME\|GEMINI_3_FLASH" src/
96
+ ```
97
+
98
+ 8. **Verify the changes compile:**
99
+
100
+ ```
101
+ npm run ts
102
+ ```
103
+
104
+ Fix any type errors if they occur.
105
+
106
+ 9. **Summarize what was added:**
107
+
108
+ Report to the user:
109
+ - Which models were added and to which providers
110
+ - The key specs for each (context window, max output, pricing tier)
111
+ - Any models that couldn't be found or had ambiguous specifications
112
+ - Any decisions that were made (e.g., choosing between model versions)
benchmarks/skillbench-venus-e/tasks/521076110b959fa6_q1/task.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "521076110b959fa6",
4
+ "query_id": "521076110b959fa6_q1",
5
+ "environment": {
6
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
7
+ "network": "none"
8
+ },
9
+ "outputs": [
10
+ "output/model_entry_conventions.json"
11
+ ],
12
+ "success_criteria": [
13
+ "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json."
14
+ ],
15
+ "evaluation": {
16
+ "kind": "python",
17
+ "type": "verified"
18
+ },
19
+ "workspace": {
20
+ "input_mappings": [],
21
+ "skill_packages": [
22
+ {
23
+ "content_hash": "6404a322975b114ac5a2fd0b1e79c7281b8f6afed04bece9ad92be7919056c75",
24
+ "name": "dyad:add-models",
25
+ "package_path": "skill",
26
+ "install_name": "dyad-add-models-404e77c5"
27
+ }
28
+ ],
29
+ "default_skill_target": ".claude/skills",
30
+ "candidate_mode": "workspace"
31
+ },
32
+ "source_skill": {
33
+ "sha256": "6404a322975b114ac5a2fd0b1e79c7281b8f6afed04bece9ad92be7919056c75",
34
+ "files": {
35
+ "SKILL.md": "d33a7e5b8d2d3928118f41119ad6978786e90200f2cce68d9e4bb2e23426215d"
36
+ }
37
+ },
38
+ "migration": {
39
+ "source_schema": "mybench-portable-task-v2",
40
+ "legacy_task_json": "provenance/legacy-package/task.json",
41
+ "historical_gain_protocol": "legacy; not Harbor certified",
42
+ "reference_available": true,
43
+ "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task",
44
+ "original_skill_content_hashes": [
45
+ "404e77c5f5cbe92c8b9b8dcf8055ac174e51bb174fd976b0865cef1c1102cb06"
46
+ ]
47
+ }
48
+ }
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_contract.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expected_check_ids": [
3
+ "0"
4
+ ],
5
+ "criterion_weights": {
6
+ "0": 1
7
+ }
8
+ }
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_entry.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable result protocol; candidate failures and evaluator errors stay distinct."""
2
+ from pathlib import Path
3
+ import contextlib,io,json,runpy,sys
4
+ from auto_policy import install,finalize
5
+ HERE=Path(__file__).resolve().parent
6
+
7
+ def main():
8
+ captured=io.StringIO()
9
+ try:
10
+ install()
11
+ with contextlib.redirect_stdout(captured):
12
+ try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
13
+ except SystemExit as error:
14
+ if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
15
+ body=None
16
+ for line in reversed(captured.getvalue().splitlines()):
17
+ try:value=json.loads(line)
18
+ except(ValueError,TypeError):continue
19
+ if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
20
+ if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
21
+ if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
22
+ cfgfile=HERE/'auto_policy.json'
23
+ if cfgfile.is_file():
24
+ cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
25
+ if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
26
+ checks=body['checks']
27
+ if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
28
+ ids=[str(c['id'])for c in checks]
29
+ if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
30
+ contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
31
+ if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
32
+ weights=contract['criterion_weights']
33
+ body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
34
+ print(json.dumps(body,ensure_ascii=True));return 0
35
+ except Exception as error:
36
+ print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
37
+
38
+ if __name__=='__main__':raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted bounded-invocation policy; never infer whole-program properties."""
2
+ from pathlib import Path
3
+ import hashlib,json,os,subprocess,sys,tempfile,time,uuid
4
+
5
+ HERE=Path(__file__).resolve().parent
6
+ ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
7
+ DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
8
+ class PolicyInfrastructureError(RuntimeError): pass
9
+ _installed=False
10
+ _original_popen=subprocess.Popen
11
+ _original_run=subprocess.run
12
+
13
+ def _config():
14
+ p=HERE/'auto_policy.json'
15
+ if not p.is_file():return None
16
+ value=json.loads(p.read_text())
17
+ if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
18
+ return value
19
+
20
+ def _folder():
21
+ if ENV not in os.environ:
22
+ os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
23
+ p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
24
+
25
+ def _python_target(command,cwd):
26
+ if not isinstance(command,(list,tuple))or not command:return None
27
+ argv=[os.fspath(x)for x in command]
28
+ if 'python'not in Path(argv[0]).name.lower():return None
29
+ i=1;flags=[]
30
+ while i<len(argv)and argv[i].startswith('-'):
31
+ flag=argv[i]
32
+ if flag=='-m':
33
+ if i+1>=len(argv):return None
34
+ name=argv[i+1];p=Path(cwd)/name.replace('.','/')
35
+ if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
36
+ return argv[0],flags,'module',name,argv[i+2:]
37
+ if flag in ['-c','-']:return None
38
+ flags.append(flag);i+=1
39
+ if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
40
+ if i>=len(argv)or not argv[i].endswith('.py'):return None
41
+ path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
42
+ path=path.resolve()
43
+ if path==HERE or HERE in path.parents:
44
+ if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
45
+ for value in argv[i+1:]:
46
+ if not value.endswith('.py')or value.startswith('-'):continue
47
+ subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
48
+ subject=subject.resolve()
49
+ if HERE not in subject.parents:
50
+ return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
51
+ return None
52
+ return argv[0],flags,'script',str(path),argv[i+1:]
53
+
54
+ def install():
55
+ global _installed
56
+ if _installed:return
57
+ _installed=True
58
+ cfg=_config()
59
+ if cfg is None:return
60
+ _folder()
61
+ os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
62
+ class GuardedPopen(_original_popen):
63
+ def __init__(self,args,*pos,**kwargs):
64
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
65
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
66
+ receipt=None
67
+ if target:
68
+ executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
69
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
70
+ if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
71
+ args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
72
+ env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
73
+ if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
74
+ try:super().__init__(args,*pos,**kwargs)
75
+ except OSError as error:
76
+ if receipt:
77
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
78
+ raise
79
+ subprocess.Popen=GuardedPopen
80
+ def bounded_run(*pos,**kwargs):
81
+ command=pos[0]if pos else kwargs.get('args')
82
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
83
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
84
+ if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
85
+ if target is not None and cfg.get('execution_budget_seconds')is not None:
86
+ budget=cfg['execution_budget_seconds']
87
+ if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
88
+ kwargs['timeout']=budget
89
+ remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
90
+ if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
91
+ try:
92
+ if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
93
+ result=_original_run(*pos,**kwargs)
94
+ if target is not None and result.returncode<0:
95
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
96
+ return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
97
+ return result
98
+ except subprocess.TimeoutExpired as error:
99
+ if target is None:raise
100
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
101
+ textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
102
+ empty=''if textual else b''
103
+ def output(value):
104
+ if value is None:return empty
105
+ return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
106
+ return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
107
+ subprocess.run=bounded_run
108
+
109
+ def status(require_execution=True):
110
+ install();p=_folder();rows=[]
111
+ for receipt in sorted(p.glob('*.json')):
112
+ try:row=json.loads(receipt.read_text())
113
+ except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
114
+ if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
115
+ raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
116
+ rows.append(row)
117
+ if require_execution and not any(r.get('target_present')for r in rows):return False
118
+ return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
119
+
120
+ def finalize(body,owner_ids,require_execution=True):
121
+ observed=status(require_execution=require_execution)
122
+ wanted=set(map(str,owner_ids))
123
+ for row in body.get('checks',[]):
124
+ if str(row['id'])in wanted:
125
+ if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
126
+ row['passed']=row['passed']and observed
127
+ row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
128
+ body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
129
+ body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
130
+ return body
131
+
132
+ def run(*args,**kwargs):
133
+ install();return subprocess.run(*args,**kwargs)
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/auto_policy_guard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child-side observer for the exact public bounded-invocation policy."""
2
+ from pathlib import Path
3
+ import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
4
+
5
+ receipt,config_file,kind,target,*arguments=sys.argv[1:]
6
+ subject=arguments.pop(0)if kind=='probe'else target
7
+ subject_filename=os.path.abspath(subject)
8
+ receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
9
+ local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
10
+ if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
11
+ if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
12
+ candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
13
+ observer_filename=__file__
14
+ stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
15
+ stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
16
+ if not getattr(sys,'stdlib_module_names',None):
17
+ for p in stdlib_root.iterdir():
18
+ if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
19
+ state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
20
+ busy=False
21
+ def save():
22
+ global busy
23
+ was=busy;busy=True
24
+ try:
25
+ temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
26
+ finally:busy=was
27
+ def violation(code,detail):
28
+ state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
29
+ def local_module(name):
30
+ first=name.partition('.')[0]
31
+ roots=list(local_roots)
32
+ for value in sys.path:
33
+ try:p=Path(value or cwd).resolve()
34
+ except (OSError,TypeError,ValueError):continue
35
+ if any(p==r or r in p.parents for r in local_roots):roots.append(p)
36
+ return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
37
+ def subject_active():
38
+ if kind!='probe':return True
39
+ frame=sys._getframe(1)
40
+ while frame:
41
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
42
+ if isinstance(filename,str):
43
+ absolute=os.path.abspath(filename)
44
+ if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
45
+ frame=frame.f_back
46
+ return False
47
+ def audit(event,args):
48
+ relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
49
+ if busy or not relevant or not subject_active():return
50
+ if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
51
+ check_import(str(args[0]))
52
+ if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
53
+ if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
54
+ if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
55
+ def check_import(name):
56
+ if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
57
+ base=name.partition('.')[0]
58
+ if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
59
+ def import_requested_by_candidate():
60
+ frame=sys._getframe(1)
61
+ while frame:
62
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
63
+ if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
64
+ absolute=os.path.abspath(filename)
65
+ return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
66
+ return False
67
+ original_import=builtins.__import__;original_import_module=importlib.import_module
68
+ def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
69
+ if not busy and subject_active()and import_requested_by_candidate():
70
+ absolute=name
71
+ if level:
72
+ package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
73
+ try:absolute=importlib.util.resolve_name('.'*level+name,package)
74
+ except(ImportError,ValueError):absolute=name
75
+ check_import(absolute)
76
+ return original_import(name,globals,locals,fromlist,level)
77
+ def bounded_import_module(name,package=None):
78
+ if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
79
+ return original_import_module(name,package)
80
+ save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
81
+ @atexit.register
82
+ def finish():state['state']='finished';save()
83
+ for p in reversed(local_roots):sys.path.insert(0,str(p))
84
+ sys.argv=[target,*arguments]
85
+ if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
86
+ else:runpy.run_path(target,run_name='__main__')
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ import sys,json
3
+ from pathlib import Path
4
+ root=Path(__file__).resolve().parent
5
+ sys.path.insert(0,str(root/'legacy_tests'))
6
+ from evaluate import evaluate
7
+ t=json.loads((root/'legacy-task.json').read_text())
8
+ mode=t['workspace']['candidate_mode']
9
+ r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
10
+ if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
11
+ if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
12
+ print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy-task.json ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "mybench-portable-task-v2",
3
+ "task_id": "52e614810e2bad9f",
4
+ "query_id": "52e614810e2bad9f_q1",
5
+ "prompt": {
6
+ "path": "instruction.md",
7
+ "sha256": "9c603c8ee0df50d6b81abd4fbbe50165527ccfebf6b217e7a1298470c5a78fa0"
8
+ },
9
+ "workspace": {
10
+ "input_mappings": [],
11
+ "skill_packages": [
12
+ {
13
+ "content_hash": "bac1a51be2671cbd77342bd8ae09d996ef03c3a8d62bbff3444600d966fc8029",
14
+ "name": "thor",
15
+ "package_path": "environment/skills/thor-bac1a51b",
16
+ "install_name": "thor-bac1a51b",
17
+ "archive_provenance": {
18
+ "archive_id": "logical-skill-058f530494c923eae6584f4b",
19
+ "archive_schema": "skill-release-v1",
20
+ "release_skill_id": "logical-skill-058f530494c923eae6584f4b",
21
+ "site": "skills-sh",
22
+ "local_path": "skills/05/logical-skill-058f530494c923eae6584f4b",
23
+ "skill_md_sha256": "9ba94f15b3e339d679c1b327fb70518c7db5341d7d89bb755a079fa32e45b8a6",
24
+ "release_payload_sha256": "bac1a51be2671cbd77342bd8ae09d996ef03c3a8d62bbff3444600d966fc8029",
25
+ "license": "MIT",
26
+ "license_status": "detected",
27
+ "canonical_source_id": "skills-sh:vechain/vechain-ai-skills/thor"
28
+ },
29
+ "omitted_entries": []
30
+ }
31
+ ],
32
+ "default_skill_target": ".claude/skills",
33
+ "candidate_mode": "response"
34
+ },
35
+ "ground_truth_skills": [
36
+ "bac1a51be2671cbd77342bd8ae09d996ef03c3a8d62bbff3444600d966fc8029"
37
+ ],
38
+ "evaluation": {
39
+ "type": "verified",
40
+ "ground_truth_answer": {
41
+ "answers": {
42
+ "q1": "localhost:8669",
43
+ "q2": "11235",
44
+ "q3": "localhost:2112",
45
+ "q4": "localhost:2113"
46
+ }
47
+ },
48
+ "verifier": {
49
+ "type": "atomic_json",
50
+ "version": 1,
51
+ "list_order": "ordered",
52
+ "float_tolerance": 0.01,
53
+ "completeness": {
54
+ "forbid_extra": true,
55
+ "shape": {
56
+ "type": "object",
57
+ "keys": {
58
+ "answers": {
59
+ "type": "object",
60
+ "keys": {
61
+ "q1": {
62
+ "type": "string"
63
+ },
64
+ "q2": {
65
+ "type": "string"
66
+ },
67
+ "q3": {
68
+ "type": "string"
69
+ },
70
+ "q4": {
71
+ "type": "string"
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ },
78
+ "assertions": [
79
+ {
80
+ "id": "leaf_001",
81
+ "path": "$.answers.q1",
82
+ "tokens": [
83
+ "answers",
84
+ "q1"
85
+ ],
86
+ "operator": "eq",
87
+ "expected": "localhost:8669"
88
+ },
89
+ {
90
+ "id": "leaf_002",
91
+ "path": "$.answers.q2",
92
+ "tokens": [
93
+ "answers",
94
+ "q2"
95
+ ],
96
+ "operator": "eq",
97
+ "expected": "11235"
98
+ },
99
+ {
100
+ "id": "leaf_003",
101
+ "path": "$.answers.q3",
102
+ "tokens": [
103
+ "answers",
104
+ "q3"
105
+ ],
106
+ "operator": "eq",
107
+ "expected": "localhost:2112"
108
+ },
109
+ {
110
+ "id": "leaf_004",
111
+ "path": "$.answers.q4",
112
+ "tokens": [
113
+ "answers",
114
+ "q4"
115
+ ],
116
+ "operator": "eq",
117
+ "expected": "localhost:2113"
118
+ }
119
+ ],
120
+ "self_test_passed": true
121
+ },
122
+ "dependency_contract": {
123
+ "version": 2,
124
+ "mode": "core_answer",
125
+ "dependency_type": "package_knowledge",
126
+ "requirement_ids": [
127
+ "skill_a063",
128
+ "skill_a242",
129
+ "skill_a156",
130
+ "skill_a132"
131
+ ],
132
+ "forbid_meta_reference": true,
133
+ "forbid_answer_leakage": true
134
+ }
135
+ }
136
+ }
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/evaluate.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a candidate response for one portable MyBench task."""
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+
14
+ def _load_verify():
15
+ try:
16
+ from verifiers import verify
17
+ return verify
18
+ except ImportError:
19
+ project_src = Path(__file__).resolve().parents[1] / "src"
20
+ if project_src.is_dir():
21
+ sys.path.insert(0, str(project_src))
22
+ from verifiers import verify
23
+ return verify
24
+ raise
25
+
26
+
27
+ def _emit(result, output=None):
28
+ text = json.dumps(result, ensure_ascii=False)
29
+ print(text)
30
+ if output:
31
+ Path(output).write_text(text + "\n", encoding="utf-8")
32
+
33
+
34
+ def _judge_contract(judge):
35
+ if not isinstance(judge, dict):
36
+ return "Judge output must be a JSON object"
37
+ if type(judge.get("passed")) is not bool:
38
+ return "Judge field passed must be a JSON boolean"
39
+ for key in ("score", "max_score"):
40
+ value = judge.get(key, 100 if key == "max_score" else None)
41
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
42
+ return f"Judge field {key} must be a finite number"
43
+ if not math.isfinite(float(value)):
44
+ return f"Judge field {key} must be a finite number"
45
+ score = float(judge["score"])
46
+ max_score = float(judge.get("max_score", 100))
47
+ if max_score <= 0:
48
+ return "Judge field max_score must be greater than zero"
49
+ if score < 0 or score > max_score:
50
+ return "Judge score must be between zero and max_score"
51
+ return None
52
+
53
+
54
+ def evaluate(task_json, candidate_path, open_judge_command=None,
55
+ open_judge_timeout=None):
56
+ task_json = Path(task_json).resolve()
57
+ candidate_path = Path(candidate_path).resolve()
58
+ task = json.loads(task_json.read_text(encoding="utf-8"))
59
+ evaluation = task.get("evaluation") or {}
60
+ track = evaluation.get("type")
61
+ base = {
62
+ "schema_version": task.get("schema_version"),
63
+ "task_id": task.get("task_id"),
64
+ "query_id": task.get("query_id"),
65
+ "track": track,
66
+ }
67
+ if track == "verified":
68
+ workspace_mode = ((evaluation.get("verifier") or {}).get("type") ==
69
+ "workspace_objective")
70
+ if workspace_mode and not candidate_path.is_dir():
71
+ return {**base, "status": "candidate_contract_error", "passed": False,
72
+ "score": 0, "max_score": 1,
73
+ "details": "workspace evaluator requires a candidate directory"}, 2
74
+ if not workspace_mode and not candidate_path.is_file():
75
+ return {**base, "status": "candidate_contract_error", "passed": False,
76
+ "score": 0, "max_score": 1,
77
+ "details": "response evaluator requires a candidate file"}, 2
78
+ if workspace_mode:
79
+ candidate = str(candidate_path)
80
+ else:
81
+ try:
82
+ candidate = candidate_path.read_text(encoding="utf-8")
83
+ except UnicodeError:
84
+ return {**base, "status": "candidate_contract_error", "passed": False,
85
+ "score": 0, "max_score": 1,
86
+ "details": "candidate response must use valid UTF-8"}, 2
87
+ passed, detail = _load_verify()(
88
+ evaluation.get("verifier") or {},
89
+ evaluation.get("ground_truth_answer"),
90
+ candidate,
91
+ None,
92
+ )
93
+ return {**base, "status": "scored", "passed": bool(passed),
94
+ "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1
95
+ if track != "open":
96
+ return {**base, "status": "unsupported_track", "passed": False,
97
+ "score": None, "details": f"unsupported track: {track}"}, 2
98
+ if not candidate_path.is_file():
99
+ return {**base, "status": "candidate_contract_error", "passed": False,
100
+ "score": None, "details": "open judge requires a candidate response file"}, 2
101
+ candidate_file = candidate_path
102
+ command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND")
103
+ if not command:
104
+ return {**base, "status": "requires_external_judge", "passed": None,
105
+ "score": None, "details": (
106
+ "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads "
107
+ "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2
108
+ environment = os.environ.copy()
109
+ environment["MYBENCH_TASK_JSON"] = str(task_json)
110
+ environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file)
111
+ timeout = float(open_judge_timeout or os.environ.get(
112
+ "MYBENCH_OPEN_JUDGE_TIMEOUT", 600))
113
+ if not math.isfinite(timeout) or timeout <= 0:
114
+ return {**base, "status": "judge_contract_error", "passed": False,
115
+ "score": None, "details": "Judge timeout must be a positive number"}, 2
116
+ try:
117
+ completed = subprocess.run(
118
+ shlex.split(command), cwd=str(task_json.parent), env=environment,
119
+ text=True, capture_output=True, timeout=timeout)
120
+ except (OSError, subprocess.TimeoutExpired) as exc:
121
+ return {**base, "status": "judge_error", "passed": False,
122
+ "score": None, "details": str(exc)}, 2
123
+ if completed.returncode:
124
+ return {**base, "status": "judge_error", "passed": False, "score": None,
125
+ "details": completed.stderr.strip() or completed.stdout.strip()}, 2
126
+ try:
127
+ judge = json.loads(completed.stdout)
128
+ except json.JSONDecodeError as exc:
129
+ return {**base, "status": "judge_contract_error", "passed": False,
130
+ "score": None, "details": str(exc)}, 2
131
+ contract_error = _judge_contract(judge)
132
+ if contract_error:
133
+ return {**base, "status": "judge_contract_error", "passed": False,
134
+ "score": None, "details": contract_error}, 2
135
+ result = {**base, "status": "scored", "passed": judge.get("passed"),
136
+ "score": judge.get("score"), "max_score": judge.get("max_score", 100),
137
+ "details": judge.get("details", judge)}
138
+ return result, 0 if result["passed"] else 1
139
+
140
+
141
+ def main():
142
+ parser = argparse.ArgumentParser()
143
+ parser.add_argument("--task-json", required=True)
144
+ candidates = parser.add_mutually_exclusive_group(required=True)
145
+ candidates.add_argument("--candidate-path")
146
+ candidates.add_argument("--candidate-file") # v1 compatibility
147
+ parser.add_argument("--result-output")
148
+ parser.add_argument("--open-judge-command")
149
+ parser.add_argument("--open-judge-timeout", type=float)
150
+ args = parser.parse_args()
151
+ result, code = evaluate(args.task_json,
152
+ args.candidate_path or args.candidate_file,
153
+ args.open_judge_command, args.open_judge_timeout)
154
+ _emit(result, args.result_output)
155
+ raise SystemExit(code)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/objective_evaluators.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composable objective evaluators for response and workspace tasks.
2
+
3
+ Task semantics are deliberately *not* enumerated here. A task may describe any
4
+ real user goal; verified membership depends on whether its deliverables compile
5
+ to one of these small, trusted evaluator primitives and pass counterfactual
6
+ execution. This keeps the objective surface closed and auditable without
7
+ turning the benchmark's task ontology into a closed template list.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import copy
13
+ import builtins
14
+ import json
15
+ import os
16
+ import re
17
+ import shlex
18
+ import subprocess
19
+ import tempfile
20
+ import tomllib
21
+ from pathlib import Path, PurePosixPath
22
+ try:
23
+ from .shell_invocations import shell_invocations
24
+ except ImportError:
25
+ from shell_invocations import shell_invocations
26
+
27
+
28
+ WORKSPACE_EVALUATOR = "workspace_objective"
29
+ WORKSPACE_EVALUATOR_VERSION = 15
30
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
31
+ ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
32
+ _DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
33
+
34
+
35
+ class ObjectiveEvaluatorError(ValueError):
36
+ pass
37
+
38
+
39
+ def safe_relative_path(value):
40
+ """Return a normalized portable relative path or fail closed."""
41
+ text = str(value or "").strip().replace("\\", "/")
42
+ path = PurePosixPath(text)
43
+ if (not text or text.startswith("/") or path.is_absolute() or
44
+ any(part in {"", ".", ".."} for part in path.parts)):
45
+ raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
46
+ if len(path.parts) > 8 or len(text) > 180:
47
+ raise ObjectiveEvaluatorError("workspace path is too deep or long")
48
+ return path.as_posix()
49
+
50
+
51
+ def _json_value(value):
52
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
53
+ return value
54
+ return json.loads(str(value))
55
+
56
+
57
+ def _canonical(value):
58
+ if isinstance(value, dict):
59
+ return {key: _canonical(value[key]) for key in sorted(value)}
60
+ if isinstance(value, list):
61
+ return [_canonical(item) for item in value]
62
+ return value
63
+
64
+
65
+ def _file_content(item):
66
+ fmt = str(item.get("format") or "").casefold()
67
+ content = item.get("content")
68
+ if fmt == "json":
69
+ parsed = _json_value(content)
70
+ return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
71
+ if not isinstance(content, str):
72
+ raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
73
+ return content.rstrip() + "\n"
74
+
75
+
76
+ def _ast_name(node):
77
+ if isinstance(node, ast.Name):
78
+ return node.id
79
+ if isinstance(node, ast.Attribute):
80
+ parent = _ast_name(node.value)
81
+ return f"{parent}.{node.attr}" if parent else node.attr
82
+ return ""
83
+
84
+
85
+ def _python_inventory(text):
86
+ tree = ast.parse(text)
87
+ imports, calls = set(), set()
88
+ for node in ast.walk(tree):
89
+ if isinstance(node, ast.Import):
90
+ imports.update(alias.name for alias in node.names)
91
+ elif isinstance(node, ast.ImportFrom):
92
+ module = node.module or ""
93
+ for alias in node.names:
94
+ imports.add(f"{module}.{alias.name}".strip("."))
95
+ elif isinstance(node, ast.Call):
96
+ name = _ast_name(node.func)
97
+ if name:
98
+ calls.add(name)
99
+ return imports, calls
100
+
101
+
102
+ def _literal_value(node, constants=None):
103
+ constants = constants or {}
104
+ if isinstance(node, ast.Constant) and isinstance(
105
+ node.value, (str, int, float, bool, type(None))):
106
+ return node.value
107
+ if isinstance(node, ast.Name) and node.id in constants:
108
+ return constants[node.id]
109
+ if isinstance(node, (ast.Tuple, ast.List)):
110
+ values = [_literal_value(item, constants) for item in node.elts]
111
+ if all(value is not _UNRESOLVED for value in values):
112
+ return tuple(values) if isinstance(node, ast.Tuple) else values
113
+ return _UNRESOLVED
114
+
115
+
116
+ _UNRESOLVED = object()
117
+
118
+
119
+ def _python_semantics(text):
120
+ tree = ast.parse(text)
121
+ _annotate_assignment_contexts(tree)
122
+ imports, calls = _python_inventory(text)
123
+ constants = {}
124
+ for node in tree.body:
125
+ name = None
126
+ value_node = None
127
+ if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
128
+ isinstance(node.targets[0], ast.Name)):
129
+ name, value_node = node.targets[0].id, node.value
130
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
131
+ name, value_node = node.target.id, node.value
132
+ if name and value_node is not None:
133
+ value = _literal_value(value_node, constants)
134
+ if value is not _UNRESOLVED:
135
+ constants[name] = value
136
+ elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
137
+ isinstance(node.targets[0], (ast.Tuple, ast.List)) and
138
+ isinstance(node.value, (ast.Tuple, ast.List)) and
139
+ len(node.targets[0].elts) == len(node.value.elts)):
140
+ # Treat ordinary constant unpacking as semantically equivalent to
141
+ # separate assignments. Generated implementation files commonly
142
+ # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
143
+ # test formatting rather than the required repository values.
144
+ for target, value_node in zip(node.targets[0].elts, node.value.elts):
145
+ if not isinstance(target, ast.Name):
146
+ continue
147
+ value = _literal_value(value_node, constants)
148
+ if value is not _UNRESOLVED:
149
+ constants[target.id] = value
150
+ call_nodes = []
151
+ for node in ast.walk(tree):
152
+ if isinstance(node, ast.Call):
153
+ call_nodes.append((_ast_name(node.func), node))
154
+ return imports, calls, constants, call_nodes
155
+
156
+
157
+ def _python_resolved_call_nodes(text):
158
+ """Resolve call targets through imports and simple constructor bindings.
159
+
160
+ The evaluator intentionally supports a small static subset: imports,
161
+ local definitions, direct aliases, and names assigned from calls. That is
162
+ enough to recognize semantic equivalents such as ``import datetime`` vs
163
+ ``from datetime import timedelta as td`` and instance-variable renames,
164
+ without pretending to perform general Python type inference.
165
+ """
166
+ tree = ast.parse(text)
167
+ _annotate_assignment_contexts(tree)
168
+ bindings = {}
169
+ nodes = sorted(ast.walk(tree), key=lambda node: (
170
+ int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
171
+
172
+ def resolve(node):
173
+ if isinstance(node, ast.Name):
174
+ return bindings.get(node.id, node.id)
175
+ if isinstance(node, ast.Attribute):
176
+ parent = resolve(node.value)
177
+ return f"{parent}.{node.attr}" if parent else node.attr
178
+ return ""
179
+
180
+ # A few fixed-point passes cover aliases declared after an imported name
181
+ # and ordinary ``client = Client()`` instance construction.
182
+ for _ in range(4):
183
+ changed = False
184
+ for node in nodes:
185
+ updates = {}
186
+ if isinstance(node, ast.Import):
187
+ for alias in node.names:
188
+ local = alias.asname or alias.name.split(".")[0]
189
+ updates[local] = alias.name if alias.asname else local
190
+ elif isinstance(node, ast.ImportFrom):
191
+ module = node.module or ""
192
+ for alias in node.names:
193
+ if alias.name == "*":
194
+ continue
195
+ updates[alias.asname or alias.name] = \
196
+ f"{module}.{alias.name}".strip(".")
197
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
198
+ ast.ClassDef)):
199
+ updates[node.name] = "__local__." + node.name
200
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
201
+ targets = (node.targets if isinstance(node, ast.Assign)
202
+ else [node.target])
203
+ value = node.value
204
+ if isinstance(value, ast.Call):
205
+ provenance = resolve(value.func)
206
+ elif isinstance(value, (ast.Name, ast.Attribute)):
207
+ provenance = resolve(value)
208
+ else:
209
+ provenance = ""
210
+ if provenance:
211
+ for target in targets:
212
+ if isinstance(target, ast.Name):
213
+ updates[target.id] = provenance
214
+ for name, value in updates.items():
215
+ if bindings.get(name) != value:
216
+ bindings[name] = value
217
+ changed = True
218
+ if not changed:
219
+ break
220
+ return [(_ast_name(node.func), resolve(node.func), node)
221
+ for node in ast.walk(tree) if isinstance(node, ast.Call)]
222
+
223
+
224
+ def _call_name_matches(observed, expected):
225
+ return observed == expected or observed.endswith("." + expected)
226
+
227
+
228
+ def _objective_call_targets(kind, check, resolved_calls, constants):
229
+ """Return canonical targets satisfying one already-validated call check."""
230
+ function = str(check.get("function") or check.get("value") or "")
231
+ targets = set()
232
+ for name, target, node in resolved_calls:
233
+ if not _call_name_matches(name, function):
234
+ continue
235
+ if kind == "python_call_literal" and not _node_contains_literal(
236
+ node, check.get("value"), constants):
237
+ continue
238
+ if kind == "python_call_keyword_literal" and not _call_keyword_matches(
239
+ node, str(check.get("keyword") or ""), check.get("value"),
240
+ constants):
241
+ continue
242
+ if kind == "python_call_signature" and not _call_signature_matches(
243
+ node, check.get("arguments") or [],
244
+ check.get("keywords") or {}, constants,
245
+ check.get("argument_expressions") or [],
246
+ check.get("keyword_expressions") or {},
247
+ check.get("assignment")):
248
+ continue
249
+ if target:
250
+ targets.add(target)
251
+ return targets
252
+
253
+
254
+ def python_unbound_call_roots(text):
255
+ """Return call-root names that have no static binding in the module.
256
+
257
+ Objective call checks must not accept a syntactically valid file that will
258
+ immediately raise ``NameError``. This deliberately proves only the
259
+ conservative prerequisite that a root is imported, assigned, declared,
260
+ passed as an argument, or provided by Python builtins; it does not claim to
261
+ execute or type-check the program.
262
+ """
263
+ tree = ast.parse(text)
264
+ bound = set(dir(builtins))
265
+ for node in ast.walk(tree):
266
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
267
+ bound.add(node.id)
268
+ elif isinstance(node, ast.arg):
269
+ bound.add(node.arg)
270
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
271
+ ast.ClassDef)):
272
+ bound.add(node.name)
273
+ elif isinstance(node, ast.Import):
274
+ for alias in node.names:
275
+ bound.add(alias.asname or alias.name.split(".")[0])
276
+ elif isinstance(node, ast.ImportFrom):
277
+ for alias in node.names:
278
+ bound.add(alias.asname or alias.name)
279
+ elif isinstance(node, ast.ExceptHandler) and node.name:
280
+ bound.add(node.name)
281
+ unbound = set()
282
+ for node in ast.walk(tree):
283
+ if not isinstance(node, ast.Call):
284
+ continue
285
+ root = node.func
286
+ while isinstance(root, ast.Attribute):
287
+ root = root.value
288
+ if isinstance(root, ast.Name) and root.id not in bound:
289
+ unbound.add(root.id)
290
+ return sorted(unbound)
291
+
292
+
293
+ def _node_contains_literal(node, expected, constants):
294
+ for child in ast.walk(node):
295
+ value = _literal_value(child, constants)
296
+ if value is _UNRESOLVED:
297
+ continue
298
+ if value == expected:
299
+ return True
300
+ if isinstance(value, (list, tuple)) and expected in value:
301
+ return True
302
+ return False
303
+
304
+
305
+ def _call_keyword_matches(node, keyword, expected, constants):
306
+ """Return whether a direct call keyword resolves to the expected scalar."""
307
+ return any(
308
+ item.arg == keyword and _literal_value(item.value, constants) == expected
309
+ for item in getattr(node, "keywords", [])
310
+ if item.arg is not None)
311
+
312
+
313
+ def _portable_literal(value):
314
+ if isinstance(value, tuple):
315
+ return [_portable_literal(item) for item in value]
316
+ if isinstance(value, list):
317
+ return [_portable_literal(item) for item in value]
318
+ return value
319
+
320
+
321
+ def _expression_text(node):
322
+ """Return a formatting-independent, non-executed Python expression."""
323
+ return ast.unparse(node).strip()
324
+
325
+
326
+ def _expression_fingerprint(value):
327
+ if not isinstance(value, str) or not value.strip() or len(value) > 500:
328
+ return None
329
+ try:
330
+ tree = ast.parse(value, mode="eval")
331
+ except SyntaxError:
332
+ return None
333
+ return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
334
+
335
+
336
+ def _expression_matches(node, expected):
337
+ fingerprint = _expression_fingerprint(expected)
338
+ return bool(fingerprint and ast.dump(
339
+ node, annotate_fields=True, include_attributes=False) == fingerprint)
340
+
341
+
342
+ def _annotate_assignment_contexts(tree):
343
+ """Attach one conservative simple-assignment context to nested calls."""
344
+ for statement in ast.walk(tree):
345
+ target, value = None, None
346
+ if (isinstance(statement, ast.Assign) and
347
+ len(statement.targets) == 1 and
348
+ isinstance(statement.targets[0], ast.Name)):
349
+ target, value = statement.targets[0].id, statement.value
350
+ elif (isinstance(statement, ast.AnnAssign) and
351
+ isinstance(statement.target, ast.Name) and
352
+ statement.value is not None):
353
+ target, value = statement.target.id, statement.value
354
+ if not target or value is None:
355
+ continue
356
+ context = {"target": target, "expression": _expression_text(value)}
357
+ for child in ast.walk(value):
358
+ if isinstance(child, ast.Call):
359
+ setattr(child, "_mybench_assignment", context)
360
+
361
+
362
+ def _call_signature(node, constants):
363
+ arguments = []
364
+ argument_expressions = []
365
+ for index, argument in enumerate(getattr(node, "args", [])):
366
+ value = _literal_value(argument, constants)
367
+ if value is not _UNRESOLVED:
368
+ arguments.append({"index": index,
369
+ "value": _portable_literal(value)})
370
+ else:
371
+ argument_expressions.append({
372
+ "index": index, "expression": _expression_text(argument)})
373
+ keywords = {}
374
+ keyword_expressions = {}
375
+ for keyword in getattr(node, "keywords", []):
376
+ if keyword.arg is None:
377
+ continue
378
+ value = _literal_value(keyword.value, constants)
379
+ if value is not _UNRESOLVED:
380
+ keywords[keyword.arg] = _portable_literal(value)
381
+ else:
382
+ keyword_expressions[keyword.arg] = _expression_text(keyword.value)
383
+ signature = {"arguments": arguments, "keywords": keywords,
384
+ "argument_expressions": argument_expressions,
385
+ "keyword_expressions": keyword_expressions}
386
+ assignment = getattr(node, "_mybench_assignment", None)
387
+ if isinstance(assignment, dict):
388
+ signature["assignment"] = dict(assignment)
389
+ return signature
390
+
391
+
392
+ def _call_signature_matches(node, arguments, keywords, constants,
393
+ argument_expressions=None,
394
+ keyword_expressions=None, assignment=None):
395
+ for expected in arguments or []:
396
+ index = expected.get("index")
397
+ if (not isinstance(index, int) or index < 0 or
398
+ index >= len(getattr(node, "args", []))):
399
+ return False
400
+ actual = _literal_value(node.args[index], constants)
401
+ if (actual is _UNRESOLVED or
402
+ _canonical(_portable_literal(actual)) !=
403
+ _canonical(expected.get("value"))):
404
+ return False
405
+ for keyword, expected in (keywords or {}).items():
406
+ if not _call_keyword_matches(node, keyword, expected, constants):
407
+ return False
408
+ for expected in argument_expressions or []:
409
+ index = expected.get("index")
410
+ if (not isinstance(index, int) or index < 0 or
411
+ index >= len(getattr(node, "args", [])) or
412
+ not _expression_matches(
413
+ node.args[index], expected.get("expression"))):
414
+ return False
415
+ node_keywords = {item.arg: item.value for item in
416
+ getattr(node, "keywords", []) if item.arg is not None}
417
+ for keyword, expected in (keyword_expressions or {}).items():
418
+ if (keyword not in node_keywords or
419
+ not _expression_matches(node_keywords[keyword], expected)):
420
+ return False
421
+ if assignment:
422
+ actual = getattr(node, "_mybench_assignment", None)
423
+ if (not isinstance(actual, dict) or
424
+ actual.get("target") != assignment.get("target") or
425
+ _expression_fingerprint(actual.get("expression")) !=
426
+ _expression_fingerprint(assignment.get("expression"))):
427
+ return False
428
+ return bool(arguments or keywords or argument_expressions or
429
+ keyword_expressions or assignment)
430
+
431
+
432
+ def python_call_literal_signatures(text, function, expected, keyword=None):
433
+ """Return full literal signatures for matching reference call sites."""
434
+ _, _, constants, call_nodes = _python_semantics(text)
435
+ out = []
436
+ for name, node in call_nodes:
437
+ if not (name == function or name.endswith("." + function)):
438
+ continue
439
+ matches = (_call_keyword_matches(node, keyword, expected, constants)
440
+ if keyword else
441
+ _node_contains_literal(node, expected, constants))
442
+ if matches:
443
+ out.append(_call_signature(node, constants))
444
+ return out
445
+
446
+
447
+ def python_signature_expression_coverage_issues(evaluator, requirements=None):
448
+ """Detect anchored call expressions omitted by a static verifier.
449
+
450
+ Literal-only call checks used to silently discard non-literal positional
451
+ and keyword expressions from the same package-owned call. That allowed a
452
+ candidate to retain one easy literal while replacing the actual callback,
453
+ input binding, or argument tuple. Only expressions present in the
454
+ selected requirement text are required here; unrelated reference-file
455
+ context remains outside the objective contract.
456
+ """
457
+ if not isinstance(evaluator, dict) or evaluator.get("type") != \
458
+ WORKSPACE_EVALUATOR:
459
+ return []
460
+ reference_files = {
461
+ str(item.get("path") or ""): str(item.get("content") or "")
462
+ for item in evaluator.get("reference_files") or []
463
+ if isinstance(item, dict)}
464
+ requirement_texts = [
465
+ re.sub(r"\s+", "", str(item.get("requirement") or ""))
466
+ for item in requirements or [] if isinstance(item, dict)]
467
+ issues = []
468
+ for check in evaluator.get("checks") or []:
469
+ if (not isinstance(check, dict) or
470
+ check.get("type") != "python_call_signature"):
471
+ continue
472
+ function = str(check.get("function") or "")
473
+ source = reference_files.get(str(check.get("path") or ""), "")
474
+ if not function or not source:
475
+ continue
476
+ try:
477
+ _, _, constants, call_nodes = _python_semantics(source)
478
+ except SyntaxError:
479
+ issues.append("Python signature reference content is invalid")
480
+ continue
481
+ matches = [node for name, node in call_nodes
482
+ if _call_name_matches(name, function) and
483
+ _call_signature_matches(
484
+ node, check.get("arguments") or [],
485
+ check.get("keywords") or {}, constants,
486
+ check.get("argument_expressions") or [],
487
+ check.get("keyword_expressions") or {},
488
+ check.get("assignment"))]
489
+ if len(matches) != 1:
490
+ issues.append(
491
+ "Python call signature does not identify one reference call")
492
+ continue
493
+ reference_signature = _call_signature(matches[0], constants)
494
+ function_tokens = {re.sub(r"\s+", "", function),
495
+ re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
496
+
497
+ def positional_is_anchored(expression):
498
+ compact = re.sub(r"\s+", "", str(expression or ""))
499
+ return any(compact and compact in text and any(
500
+ token and token in text for token in function_tokens)
501
+ for text in requirement_texts)
502
+
503
+ def keyword_is_anchored(name, expression):
504
+ compact = re.sub(r"\s+", "", str(expression or ""))
505
+ needle = f"{name}={compact}"
506
+ return any(compact and needle in text and any(
507
+ token and token in text for token in function_tokens)
508
+ for text in requirement_texts)
509
+
510
+ expected_arguments = {
511
+ item["index"]: item.get("expression")
512
+ for item in reference_signature.get("argument_expressions") or []
513
+ if positional_is_anchored(item.get("expression"))}
514
+ expected_keywords = {
515
+ name: expression for name, expression in
516
+ (reference_signature.get("keyword_expressions") or {}).items()
517
+ if keyword_is_anchored(name, expression)}
518
+ actual_arguments = {
519
+ item.get("index"): item.get("expression")
520
+ for item in check.get("argument_expressions") or []
521
+ if isinstance(item, dict)}
522
+ actual_keywords = check.get("keyword_expressions") or {}
523
+ expected_assignment = reference_signature.get("assignment")
524
+ if expected_assignment:
525
+ compact_assignment = re.sub(
526
+ r"\s+", "", f"{expected_assignment.get('target')}="
527
+ f"{expected_assignment.get('expression')}")
528
+ assignment_is_anchored = any(
529
+ compact_assignment and compact_assignment in text and any(
530
+ token and token in text for token in function_tokens)
531
+ for text in requirement_texts)
532
+ else:
533
+ assignment_is_anchored = False
534
+ actual_assignment = check.get("assignment")
535
+ missing_argument = any(
536
+ index not in actual_arguments or
537
+ _expression_fingerprint(actual_arguments[index]) !=
538
+ _expression_fingerprint(expression)
539
+ for index, expression in expected_arguments.items())
540
+ missing_keyword = any(
541
+ name not in actual_keywords or
542
+ _expression_fingerprint(actual_keywords[name]) !=
543
+ _expression_fingerprint(expression)
544
+ for name, expression in expected_keywords.items())
545
+ missing_assignment = bool(
546
+ assignment_is_anchored and (
547
+ not isinstance(actual_assignment, dict) or
548
+ actual_assignment.get("target") !=
549
+ expected_assignment.get("target") or
550
+ _expression_fingerprint(actual_assignment.get("expression")) !=
551
+ _expression_fingerprint(
552
+ expected_assignment.get("expression"))))
553
+ if missing_argument or missing_keyword or missing_assignment:
554
+ issues.append(
555
+ "Python call signature omits an anchored expression or assignment")
556
+ return issues
557
+
558
+
559
+ def _shell_lines(text):
560
+ """Return executable lines with conservative local scalar substitution.
561
+
562
+ Shell authors routinely name a fixed argument before using it (for example
563
+ ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
564
+ assignments; never evaluate shell expressions, commands, or defaults.
565
+ """
566
+ logical, pending = [], ""
567
+ for raw in str(text or "").splitlines():
568
+ line = " ".join(raw.strip().split())
569
+ if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
570
+ continue
571
+ pending = (pending + " " + line).strip() if pending else line
572
+ if pending.endswith("\\"):
573
+ pending = pending[:-1].rstrip()
574
+ continue
575
+ logical.append(pending)
576
+ pending = ""
577
+ if pending:
578
+ logical.append(pending)
579
+
580
+ constants, out = {}, []
581
+ assignment = re.compile(
582
+ r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
583
+ r"([A-Za-z0-9_./:+-]+))$")
584
+ variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
585
+ for line in logical:
586
+ match = assignment.fullmatch(line)
587
+ if match:
588
+ constants[match.group(1)] = next(
589
+ value for value in match.groups()[1:] if value is not None)
590
+ out.append(line)
591
+ continue
592
+
593
+ def replace(match):
594
+ name = match.group(1) or match.group(2)
595
+ return constants.get(name, match.group(0))
596
+
597
+ out.append(variable.sub(replace, line))
598
+ return out
599
+
600
+
601
+ def _shell_command_matches(expected, actual):
602
+ """Accept the frozen invocation plus documented optional arguments/path prefixes."""
603
+ try:
604
+ wanted = shlex.split(str(expected))
605
+ found = shlex.split(str(actual))
606
+ except ValueError:
607
+ return False
608
+ def normalize_git_log_limit(tokens):
609
+ if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
610
+ return tokens
611
+ normalized, index = [], 0
612
+ while index < len(tokens):
613
+ token = tokens[index]
614
+ short = re.fullmatch(r"-(\d+)", token)
615
+ long = re.fullmatch(r"--max-count=(\d+)", token)
616
+ if short or long:
617
+ normalized.append("--max-count=" + (short or long).group(1))
618
+ elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
619
+ re.fullmatch(r"\d+", tokens[index + 1])):
620
+ normalized.append("--max-count=" + tokens[index + 1])
621
+ index += 1
622
+ else:
623
+ normalized.append(token)
624
+ index += 1
625
+ return normalized
626
+
627
+ wanted = normalize_git_log_limit(wanted)
628
+ found = normalize_git_log_limit(found)
629
+ if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
630
+ return False
631
+ for index, token in enumerate(wanted[1:], 1):
632
+ observed = found[index]
633
+ if observed == token:
634
+ continue
635
+ # A solver may anchor a package-relative script at $REPO_ROOT while
636
+ # preserving the exact package path selected by the Skill.
637
+ if (index == 1 and "/" in token and
638
+ observed.rstrip("/").endswith(token.lstrip("./"))):
639
+ continue
640
+ return False
641
+ return True
642
+
643
+
644
+ def _shell_command_sequence_matches(expected, actual_lines):
645
+ """Require every frozen command in order while allowing extra lines."""
646
+ cursor = 0
647
+ for command in expected:
648
+ for index in range(cursor, len(actual_lines)):
649
+ if _shell_command_matches(command, actual_lines[index]):
650
+ cursor = index + 1
651
+ break
652
+ else:
653
+ return False
654
+ return True
655
+
656
+
657
+ def _shell_unconditional_lines(text):
658
+ """Return conservative top-level command lines from a shell artifact.
659
+
660
+ Checked commands hidden in a conditional branch or an uncalled function do
661
+ not establish that the requested script performs them. This is not a full
662
+ shell parser: unsupported control flow simply makes nested lines
663
+ ineligible, which is appropriate for the small straight-line command
664
+ artifacts compiled by this evaluator.
665
+ """
666
+ lines = _shell_lines(text)
667
+ depth = 0
668
+ out = []
669
+ opener = re.compile(
670
+ r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
671
+ r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
672
+ closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
673
+ for line in lines:
674
+ if closer.match(line):
675
+ depth = max(0, depth - 1)
676
+ continue
677
+ if depth == 0 and not opener.match(line):
678
+ out.append(line)
679
+ if opener.match(line):
680
+ depth += 1
681
+ return out
682
+
683
+
684
+ def _shell_is_straight_line(text):
685
+ """Return whether every executable logical line is top-level.
686
+
687
+ This deliberately reuses the conservative control-flow recognizer used by
688
+ unconditional command checks. Any recognized conditional, loop, case, or
689
+ function makes the whole-script straight-line contract fail closed.
690
+ """
691
+ lines = _shell_lines(text)
692
+ return lines == _shell_unconditional_lines(text)
693
+
694
+
695
+ def compile_workspace_evaluator(deliverables):
696
+ """Compile trusted checks from validated deliverable specifications."""
697
+ if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
698
+ raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
699
+ reference_files, checks, paths = [], [], set()
700
+ for index, raw in enumerate(deliverables, 1):
701
+ if not isinstance(raw, dict):
702
+ raise ObjectiveEvaluatorError("deliverable is not an object")
703
+ path = safe_relative_path(raw.get("path"))
704
+ if path in paths:
705
+ raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
706
+ paths.add(path)
707
+ fmt = str(raw.get("format") or "").strip().casefold()
708
+ if fmt not in ARTIFACT_FORMATS:
709
+ raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
710
+ content = _file_content({**raw, "format": fmt})
711
+ if len(content.encode("utf-8")) > 200_000:
712
+ raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
713
+ reference_files.append({"path": path, "format": fmt, "content": content})
714
+ checks.append({"id": f"file_{index:03d}", "type": "file_exists",
715
+ "path": path})
716
+ if fmt == "json":
717
+ checks.append({"id": f"json_{index:03d}", "type": "json_exact",
718
+ "path": path, "expected": _json_value(raw.get("content"))})
719
+ elif fmt == "toml":
720
+ try:
721
+ expected = tomllib.loads(content)
722
+ except (tomllib.TOMLDecodeError, ValueError) as exc:
723
+ raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
724
+ checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
725
+ "path": path, "expected": expected})
726
+ elif fmt == "python":
727
+ try:
728
+ _, _, constants, call_nodes = _python_semantics(content)
729
+ resolved_calls = _python_resolved_call_nodes(content)
730
+ except SyntaxError as exc:
731
+ raise ObjectiveEvaluatorError("reference Python is invalid") from exc
732
+ checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
733
+ "path": path})
734
+ checks.append({"id": f"python_{index:03d}_bindings",
735
+ "type": "python_bound_calls", "path": path})
736
+ raw_checks = raw.get("checks") or []
737
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
738
+ raise ObjectiveEvaluatorError(
739
+ "Python deliverable requires 1-12 objective import/call checks")
740
+ for check_index, check in enumerate(raw_checks, 1):
741
+ if not isinstance(check, dict):
742
+ raise ObjectiveEvaluatorError("Python check is not an object")
743
+ kind = str(check.get("type") or "").strip().casefold()
744
+ if kind in {"python_import", "python_call"}:
745
+ value = str(check.get("value") or "").strip()
746
+ if not _DOTTED.fullmatch(value):
747
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
748
+ compiled = {"type": kind, "path": path, "value": value}
749
+ elif kind == "python_constant":
750
+ name = str(check.get("name") or "").strip()
751
+ value = check.get("value")
752
+ if (not _DOTTED.fullmatch(name) or "." in name or
753
+ isinstance(value, (dict, list)) or value is None or
754
+ constants.get(name, _UNRESOLVED) != value):
755
+ raise ObjectiveEvaluatorError(
756
+ "Python constant check is invalid or fails reference content")
757
+ compiled = {"type": kind, "path": path, "name": name,
758
+ "value": value}
759
+ elif kind == "python_call_literal":
760
+ function = str(check.get("function") or "").strip()
761
+ value = check.get("value")
762
+ if (not _DOTTED.fullmatch(function) or
763
+ isinstance(value, (dict, list)) or value is None or
764
+ not any(
765
+ (name == function or name.endswith("." + function)) and
766
+ _node_contains_literal(node, value, constants)
767
+ for name, node in call_nodes)):
768
+ raise ObjectiveEvaluatorError(
769
+ "Python call-literal check is invalid or fails reference content")
770
+ compiled = {"type": kind, "path": path,
771
+ "function": function, "value": value}
772
+ elif kind == "python_call_keyword_literal":
773
+ function = str(check.get("function") or "").strip()
774
+ keyword = str(check.get("keyword") or "").strip()
775
+ value = check.get("value")
776
+ if (not _DOTTED.fullmatch(function) or
777
+ not _DOTTED.fullmatch(keyword) or "." in keyword or
778
+ isinstance(value, (dict, list)) or value is None or
779
+ not any(
780
+ (name == function or name.endswith("." + function)) and
781
+ _call_keyword_matches(node, keyword, value, constants)
782
+ for name, node in call_nodes)):
783
+ raise ObjectiveEvaluatorError(
784
+ "Python call-keyword check is invalid or fails reference content")
785
+ compiled = {"type": kind, "path": path,
786
+ "function": function, "keyword": keyword,
787
+ "value": value}
788
+ elif kind == "python_call_signature":
789
+ function = str(check.get("function") or "").strip()
790
+ arguments = check.get("arguments") or []
791
+ keywords = check.get("keywords") or {}
792
+ argument_expressions = check.get(
793
+ "argument_expressions") or []
794
+ keyword_expressions = check.get(
795
+ "keyword_expressions") or {}
796
+ assignment = check.get("assignment")
797
+ if (not _DOTTED.fullmatch(function) or
798
+ not isinstance(arguments, list) or
799
+ not isinstance(keywords, dict) or
800
+ not isinstance(argument_expressions, list) or
801
+ not isinstance(keyword_expressions, dict) or
802
+ not (arguments or keywords or
803
+ argument_expressions or keyword_expressions or
804
+ assignment) or
805
+ any(not isinstance(item, dict) or
806
+ not isinstance(item.get("index"), int) or
807
+ item.get("index") < 0 or
808
+ isinstance(item.get("value"), dict)
809
+ for item in arguments) or
810
+ len({item["index"] for item in arguments}) !=
811
+ len(arguments) or
812
+ any(not _DOTTED.fullmatch(str(name)) or
813
+ "." in str(name) or isinstance(value, dict)
814
+ for name, value in keywords.items()) or
815
+ any(not isinstance(item, dict) or
816
+ not isinstance(item.get("index"), int) or
817
+ item.get("index") < 0 or
818
+ not _expression_fingerprint(
819
+ item.get("expression"))
820
+ for item in argument_expressions) or
821
+ len({item["index"] for item in
822
+ argument_expressions}) !=
823
+ len(argument_expressions) or
824
+ ({item["index"] for item in arguments} &
825
+ {item["index"] for item in
826
+ argument_expressions}) or
827
+ any(not _DOTTED.fullmatch(str(name)) or
828
+ "." in str(name) or
829
+ not _expression_fingerprint(value)
830
+ for name, value in
831
+ keyword_expressions.items()) or
832
+ (set(keywords) & set(keyword_expressions)) or
833
+ (assignment is not None and (
834
+ not isinstance(assignment, dict) or
835
+ not _DOTTED.fullmatch(str(
836
+ assignment.get("target") or "")) or
837
+ "." in str(assignment.get("target") or "") or
838
+ not _expression_fingerprint(
839
+ assignment.get("expression")))) or
840
+ not any(
841
+ (name == function or
842
+ name.endswith("." + function)) and
843
+ _call_signature_matches(
844
+ node, arguments, keywords, constants,
845
+ argument_expressions,
846
+ keyword_expressions, assignment)
847
+ for name, node in call_nodes)):
848
+ raise ObjectiveEvaluatorError(
849
+ "Python call-signature check is invalid or fails reference content")
850
+ compiled = {"type": kind, "path": path,
851
+ "function": function,
852
+ "arguments": arguments,
853
+ "keywords": keywords,
854
+ "argument_expressions": argument_expressions,
855
+ "keyword_expressions": keyword_expressions,
856
+ "assignment": assignment}
857
+ else:
858
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
859
+ if kind in {"python_call", "python_call_literal",
860
+ "python_call_keyword_literal",
861
+ "python_call_signature"}:
862
+ targets = _objective_call_targets(
863
+ kind, compiled, resolved_calls, constants)
864
+ if len(targets) != 1:
865
+ raise ObjectiveEvaluatorError(
866
+ "Python call check has no unique canonical target")
867
+ compiled["target"] = next(iter(targets))
868
+ checks.append({"id": f"python_{index:03d}_{check_index:03d}",
869
+ **compiled})
870
+ else:
871
+ raw_checks = raw.get("checks") or []
872
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
873
+ raise ObjectiveEvaluatorError(
874
+ "shell deliverable requires 1-12 objective command checks")
875
+ checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
876
+ "path": path})
877
+ reference_sequence = _shell_lines(content)
878
+ reference_lines = set(reference_sequence)
879
+ unconditional_lines = _shell_unconditional_lines(content)
880
+ command_checks = []
881
+ for check in raw_checks:
882
+ value = " ".join(str(check.get("value") or "").strip().split())
883
+ if (not isinstance(check, dict) or
884
+ str(check.get("type") or "").strip().casefold() != "shell_command" or
885
+ not value or value not in reference_lines):
886
+ raise ObjectiveEvaluatorError("unsupported shell objective check")
887
+ command_checks.append({"type": "shell_command", "path": path,
888
+ "value": value})
889
+ if len({item["value"] for item in command_checks}) != len(command_checks):
890
+ raise ObjectiveEvaluatorError("shell objective checks must be unique")
891
+ command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
892
+ if not all(any(_shell_command_matches(
893
+ item["value"], line) for line in unconditional_lines)
894
+ for item in command_checks):
895
+ raise ObjectiveEvaluatorError(
896
+ "checked shell commands must be top-level and unconditional")
897
+ for check_index, check in enumerate(command_checks, 1):
898
+ checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
899
+ **check})
900
+ if len(command_checks) >= 2:
901
+ checks.append({
902
+ "id": f"shell_{index:03d}_sequence",
903
+ "type": "shell_command_sequence", "path": path,
904
+ "values": [item["value"] for item in command_checks],
905
+ })
906
+ checks.append({
907
+ "id": f"shell_{index:03d}_unconditional",
908
+ "type": "shell_unconditional_commands", "path": path,
909
+ "values": [item["value"] for item in command_checks],
910
+ })
911
+ # Preserve the reference's fail-fast behavior when accepting normal
912
+ # command-substitution/guard wrappers. Never turn `|| true` into a
913
+ # passing preflight simply because it contains the correct argv.
914
+ reference_calls = shell_invocations(content)
915
+ protected = [item["value"] for item in command_checks if any(
916
+ call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
917
+ for call in reference_calls)]
918
+ if protected:
919
+ checks.append({"id": f"shell_{index:03d}_failure_propagation",
920
+ "type": "shell_failure_propagation", "path": path,
921
+ "values": protected})
922
+ # Candidate workspaces may also contain root-level public inputs and
923
+ # installed Skill packages. Deliverables use dedicated top-level output
924
+ # directories, so enforce an exact file set inside those namespaces while
925
+ # leaving the read-only environment outside them untouched.
926
+ output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
927
+ if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
928
+ checks.insert(0, {
929
+ "id": "workspace_file_set", "type": "workspace_file_set",
930
+ "paths": sorted(paths), "roots": output_roots,
931
+ })
932
+ return {
933
+ "type": WORKSPACE_EVALUATOR,
934
+ "version": WORKSPACE_EVALUATOR_VERSION,
935
+ "output_mode": "workspace",
936
+ "reference_files": reference_files,
937
+ "checks": checks,
938
+ }
939
+
940
+
941
+ def reference_bundle(evaluator):
942
+ if evaluator.get("type") != WORKSPACE_EVALUATOR:
943
+ raise ObjectiveEvaluatorError("not a workspace evaluator")
944
+ return {"files": [
945
+ {"path": item["path"], "content": item["content"]}
946
+ for item in evaluator.get("reference_files") or []
947
+ ]}
948
+
949
+
950
+ def hidden_workspace_values(evaluator):
951
+ """Return decisive package-owned values that public queries must not leak."""
952
+ values = []
953
+ for check in (evaluator or {}).get("checks") or []:
954
+ kind = check.get("type")
955
+ if kind in {"json_exact", "toml_exact"}:
956
+ values.extend(value for _, value in _flatten(check.get("expected")))
957
+ elif kind in {"python_import", "python_call", "shell_command",
958
+ "python_constant", "python_call_literal",
959
+ "python_call_keyword_literal"}:
960
+ values.append(check.get("value"))
961
+ elif kind == "python_call_signature":
962
+ values.extend(value for _, value in _flatten({
963
+ "arguments": [item.get("value") for item in
964
+ check.get("arguments") or []],
965
+ "keywords": check.get("keywords") or {},
966
+ "argument_expressions": [item.get("expression") for item in
967
+ check.get("argument_expressions") or []],
968
+ "keyword_expressions": check.get("keyword_expressions") or {},
969
+ "assignment": check.get("assignment"),
970
+ }))
971
+ return [value for value in values if value is not None]
972
+
973
+
974
+ def _flatten(value, path=()):
975
+ if isinstance(value, dict):
976
+ out = []
977
+ for key, item in value.items():
978
+ out.extend(_flatten(item, path + (str(key),)))
979
+ return out
980
+ if isinstance(value, list):
981
+ out = []
982
+ for index, item in enumerate(value):
983
+ out.extend(_flatten(item, path + (index,)))
984
+ return out
985
+ return [(path, value)]
986
+
987
+
988
+ def _bundle_rows(candidate):
989
+ if isinstance(candidate, str):
990
+ text = candidate.strip()
991
+ # Chat solvers often wrap the requested file bundle in a Markdown fence
992
+ # or append a duplicate FINAL_ANSWER object. Decode one complete JSON
993
+ # value at a time instead of requiring the entire response to be JSON;
994
+ # only an object carrying the explicit ``files`` transport field is
995
+ # eligible, so unrelated prose/objects are not silently accepted.
996
+ decoder = json.JSONDecoder()
997
+ candidate = None
998
+ for match in re.finditer(r"\{", text):
999
+ try:
1000
+ parsed, _ = decoder.raw_decode(text, match.start())
1001
+ except json.JSONDecodeError:
1002
+ continue
1003
+ if isinstance(parsed, dict) and "files" in parsed:
1004
+ candidate = parsed
1005
+ break
1006
+ if candidate is None:
1007
+ raise ObjectiveEvaluatorError(
1008
+ "workspace response contains no complete JSON file bundle")
1009
+ if not isinstance(candidate, dict):
1010
+ raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
1011
+ files = candidate.get("files")
1012
+ if isinstance(files, dict):
1013
+ files = [{"path": path, "content": content}
1014
+ for path, content in files.items()]
1015
+ if not isinstance(files, list) or len(files) > 30:
1016
+ raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
1017
+ return files
1018
+
1019
+
1020
+ def materialize_bundle(candidate, workspace):
1021
+ root = Path(workspace).resolve()
1022
+ root.mkdir(parents=True, exist_ok=True)
1023
+ seen = set()
1024
+ for item in _bundle_rows(candidate):
1025
+ if not isinstance(item, dict):
1026
+ raise ObjectiveEvaluatorError("candidate file entry is not an object")
1027
+ relative = safe_relative_path(item.get("path"))
1028
+ if relative in seen:
1029
+ raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
1030
+ seen.add(relative)
1031
+ content = item.get("content")
1032
+ if isinstance(content, (dict, list)):
1033
+ content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
1034
+ if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
1035
+ raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
1036
+ target = (root / relative).resolve()
1037
+ if root not in target.parents:
1038
+ raise ObjectiveEvaluatorError("candidate file escapes workspace")
1039
+ target.parent.mkdir(parents=True, exist_ok=True)
1040
+ target.write_text(content, encoding="utf-8")
1041
+ return root
1042
+
1043
+
1044
+ def evaluate_workspace(evaluator, workspace):
1045
+ if (not isinstance(evaluator, dict) or
1046
+ evaluator.get("type") != WORKSPACE_EVALUATOR or
1047
+ int(evaluator.get("version") or 0) not in
1048
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
1049
+ return False, {"error": "invalid workspace evaluator contract"}
1050
+ root = Path(workspace).resolve()
1051
+ results = []
1052
+ for check in evaluator.get("checks") or []:
1053
+ kind = check.get("type")
1054
+ relative, path = "", None
1055
+ if kind != "workspace_file_set":
1056
+ relative = safe_relative_path(check.get("path"))
1057
+ path = (root / relative).resolve()
1058
+ if root not in path.parents:
1059
+ return False, {"error": "evaluator path escapes workspace"}
1060
+ passed, detail = False, ""
1061
+ try:
1062
+ if kind == "workspace_file_set":
1063
+ expected = {safe_relative_path(value)
1064
+ for value in check.get("paths") or []}
1065
+ roots = [safe_relative_path(value)
1066
+ for value in check.get("roots") or []]
1067
+ actual = set()
1068
+ for relative_root in roots:
1069
+ scan_root = (root / relative_root).resolve()
1070
+ if root not in scan_root.parents:
1071
+ raise ObjectiveEvaluatorError(
1072
+ "workspace file-set root escapes workspace")
1073
+ if not scan_root.exists():
1074
+ continue
1075
+ for candidate in scan_root.rglob("*"):
1076
+ if candidate.is_file() or candidate.is_symlink():
1077
+ actual.add(candidate.relative_to(root).as_posix())
1078
+ passed = bool(expected) and actual == expected
1079
+ detail = ("exact deliverable file set" if passed else
1080
+ f"expected_files={sorted(expected)}; "
1081
+ f"actual_files={sorted(actual)}")
1082
+ elif kind == "file_exists":
1083
+ passed = path.is_file()
1084
+ detail = "present" if passed else "missing"
1085
+ elif kind == "json_exact":
1086
+ from r9_json import parse_file, strict_equal
1087
+ actual = parse_file(path)
1088
+ passed = strict_equal(actual, check.get("expected"))
1089
+ detail = "semantic JSON match" if passed else "JSON value mismatch"
1090
+ elif kind == "toml_exact":
1091
+ actual = tomllib.loads(path.read_text(encoding="utf-8"))
1092
+ passed = _canonical(actual) == _canonical(check.get("expected"))
1093
+ detail = "semantic TOML match" if passed else "TOML value mismatch"
1094
+ elif kind in {"python_syntax", "python_bound_calls",
1095
+ "python_import", "python_call",
1096
+ "python_constant", "python_call_literal",
1097
+ "python_call_keyword_literal",
1098
+ "python_call_signature"}:
1099
+ source = path.read_text(encoding="utf-8")
1100
+ imports, calls, constants, call_nodes = _python_semantics(source)
1101
+ resolved_calls = _python_resolved_call_nodes(source)
1102
+ if kind == "python_syntax":
1103
+ passed, detail = True, "valid Python syntax"
1104
+ elif kind == "python_bound_calls":
1105
+ unbound = python_unbound_call_roots(
1106
+ path.read_text(encoding="utf-8"))
1107
+ passed = not unbound
1108
+ detail = ("all call roots are statically bound" if passed else
1109
+ "unbound call roots=" + repr(unbound))
1110
+ elif kind == "python_import":
1111
+ expected = str(check.get("value") or "")
1112
+ passed = expected in imports or any(
1113
+ value == expected or value.startswith(expected + ".")
1114
+ for value in imports)
1115
+ detail = f"imports={sorted(imports)}"
1116
+ elif kind == "python_call":
1117
+ expected = str(check.get("value") or "")
1118
+ target = str(check.get("target") or "")
1119
+ passed = (any(
1120
+ canonical == target
1121
+ for _, canonical, _ in resolved_calls)
1122
+ if target else expected in calls or any(
1123
+ value.endswith("." + expected)
1124
+ for value in calls))
1125
+ detail = f"calls={sorted(calls)}"
1126
+ elif kind == "python_constant":
1127
+ name, expected = str(check.get("name") or ""), check.get("value")
1128
+ actual = constants.get(name, _UNRESOLVED)
1129
+ passed = actual is not _UNRESOLVED and actual == expected
1130
+ detail = f"constant {name}={actual!r}"
1131
+ elif kind == "python_call_literal":
1132
+ function, expected = (str(check.get("function") or ""),
1133
+ check.get("value"))
1134
+ target = str(check.get("target") or "")
1135
+ source_calls = (resolved_calls if target else
1136
+ [(name, "", node) for name, node in call_nodes])
1137
+ passed = any(
1138
+ (bool(target) or _call_name_matches(name, function)) and
1139
+ (not target or canonical == target) and
1140
+ _node_contains_literal(node, expected, constants)
1141
+ for name, canonical, node in source_calls)
1142
+ detail = f"call={function} literal={expected!r}"
1143
+ elif kind == "python_call_keyword_literal":
1144
+ function = str(check.get("function") or "")
1145
+ keyword = str(check.get("keyword") or "")
1146
+ expected = check.get("value")
1147
+ target = str(check.get("target") or "")
1148
+ source_calls = (resolved_calls if target else
1149
+ [(name, "", node) for name, node in call_nodes])
1150
+ passed = any(
1151
+ (bool(target) or _call_name_matches(name, function)) and
1152
+ (not target or canonical == target) and
1153
+ _call_keyword_matches(node, keyword, expected, constants)
1154
+ for name, canonical, node in source_calls)
1155
+ detail = (f"call={function} keyword={keyword} "
1156
+ f"literal={expected!r}")
1157
+ else:
1158
+ function = str(check.get("function") or "")
1159
+ arguments = check.get("arguments") or []
1160
+ keywords = check.get("keywords") or {}
1161
+ argument_expressions = check.get(
1162
+ "argument_expressions") or []
1163
+ keyword_expressions = check.get(
1164
+ "keyword_expressions") or {}
1165
+ assignment = check.get("assignment")
1166
+ target = str(check.get("target") or "")
1167
+ source_calls = (resolved_calls if target else
1168
+ [(name, "", node) for name, node in call_nodes])
1169
+ passed = any(
1170
+ (bool(target) or _call_name_matches(name, function)) and
1171
+ (not target or canonical == target) and
1172
+ _call_signature_matches(
1173
+ node, arguments, keywords, constants,
1174
+ argument_expressions, keyword_expressions,
1175
+ assignment)
1176
+ for name, canonical, node in source_calls)
1177
+ detail = (f"call={function} arguments={arguments!r} "
1178
+ f"keywords={keywords!r} "
1179
+ f"argument_expressions={argument_expressions!r} "
1180
+ f"keyword_expressions={keyword_expressions!r} "
1181
+ f"assignment={assignment!r}")
1182
+ elif kind == "shell_syntax":
1183
+ completed = subprocess.run(
1184
+ ["bash", "-n", str(path)], capture_output=True, text=True,
1185
+ timeout=5, check=False)
1186
+ passed = completed.returncode == 0
1187
+ detail = ("valid shell syntax" if passed else
1188
+ (completed.stderr or "invalid shell syntax").strip())
1189
+ elif kind == "shell_command":
1190
+ source = path.read_text(encoding="utf-8")
1191
+ lines = ([call["command"] for call in shell_invocations(source)]
1192
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1193
+ expected = " ".join(str(check.get("value") or "").split())
1194
+ passed = any(_shell_command_matches(expected, line) for line in lines)
1195
+ detail = f"executable_lines={lines[:30]}"
1196
+ elif kind == "shell_command_sequence":
1197
+ source = path.read_text(encoding="utf-8")
1198
+ lines = ([call["command"] for call in shell_invocations(source)]
1199
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1200
+ expected = [" ".join(str(value).split())
1201
+ for value in check.get("values") or []]
1202
+ passed = (len(expected) >= 2 and
1203
+ _shell_command_sequence_matches(expected, lines))
1204
+ detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
1205
+ elif kind == "shell_unconditional_commands":
1206
+ source = path.read_text(encoding="utf-8")
1207
+ lines = ([call["command"] for call in shell_invocations(source)]
1208
+ if int(evaluator.get("version", 0)) >= 15
1209
+ else _shell_unconditional_lines(source))
1210
+ expected = [" ".join(str(value).split())
1211
+ for value in check.get("values") or []]
1212
+ passed = (bool(expected) and all(
1213
+ any(_shell_command_matches(command, line) for line in lines)
1214
+ for command in expected))
1215
+ detail = (f"expected_unconditional={expected}; "
1216
+ f"top_level_lines={lines[:30]}")
1217
+ elif kind == "shell_failure_propagation":
1218
+ calls = shell_invocations(path.read_text(encoding="utf-8"))
1219
+ expected = [" ".join(str(value).split())
1220
+ for value in check.get("values") or []]
1221
+ passed = bool(expected) and all(any(
1222
+ call["fail_fast"] and _shell_command_matches(command, call["command"])
1223
+ for call in calls) for command in expected)
1224
+ detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
1225
+ elif kind == "shell_straight_line":
1226
+ source = path.read_text(encoding="utf-8")
1227
+ passed = _shell_is_straight_line(source)
1228
+ detail = ("all executable lines are top-level" if passed else
1229
+ "shell contains conditional, loop, case, or function")
1230
+ else:
1231
+ detail = f"unsupported check: {kind}"
1232
+ except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
1233
+ json.JSONDecodeError,
1234
+ tomllib.TOMLDecodeError) as exc:
1235
+ detail = str(exc)
1236
+ results.append({"id": check.get("id"), "type": kind,
1237
+ "path": relative, "passed": bool(passed),
1238
+ "detail": detail[:1000]})
1239
+ return bool(results) and all(item["passed"] for item in results), {
1240
+ "type": WORKSPACE_EVALUATOR,
1241
+ "assertions_passed": sum(item["passed"] for item in results),
1242
+ "assertions_total": len(results),
1243
+ "assertions": results,
1244
+ }
1245
+
1246
+
1247
+ def evaluate_candidate(evaluator, candidate):
1248
+ if isinstance(candidate, os.PathLike):
1249
+ try:
1250
+ return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
1251
+ False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
1252
+ except (OSError, ValueError) as exc:
1253
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1254
+ if isinstance(candidate, str):
1255
+ # A chat file-bundle can be much longer than a filesystem path. Avoid
1256
+ # passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
1257
+ stripped = candidate.strip()
1258
+ if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
1259
+ and not stripped.startswith(("{", "[", "```"))):
1260
+ try:
1261
+ if Path(stripped).is_dir():
1262
+ return evaluate_workspace(evaluator, stripped)
1263
+ except (OSError, ValueError):
1264
+ # Python/platform versions differ on ENAMETOOLONG and invalid
1265
+ # path errors. It is still candidate text: parse it unchanged.
1266
+ pass
1267
+ try:
1268
+ with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
1269
+ materialize_bundle(candidate, temp)
1270
+ return evaluate_workspace(evaluator, temp)
1271
+ except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
1272
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1273
+
1274
+
1275
+ def self_test_workspace_evaluator(evaluator):
1276
+ correct = reference_bundle(evaluator)
1277
+ ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
1278
+ rows = list(correct.get("files") or [])
1279
+ perturbed = {"files": rows[1:] if len(rows) > 1 else []}
1280
+ ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
1281
+ mutations = []
1282
+ # Exact JSON fields must each matter, not merely the file's existence.
1283
+ for check in evaluator.get("checks") or []:
1284
+ if check.get("type") != "json_exact":
1285
+ continue
1286
+ for path, value in _flatten(check.get("expected")):
1287
+ candidate = copy.deepcopy(correct)
1288
+ file_row = next(row for row in candidate["files"]
1289
+ if row["path"] == check["path"])
1290
+ data = json.loads(file_row["content"])
1291
+ replacement = (not value if isinstance(value, bool) else
1292
+ value + 1 if isinstance(value, (int, float)) else
1293
+ str(value) + "__mutation__")
1294
+ if not path:
1295
+ data = replacement
1296
+ else:
1297
+ container = data
1298
+ for key in path[:-1]:
1299
+ container = container[key]
1300
+ container[path[-1]] = replacement
1301
+ file_row["content"] = json.dumps(data)
1302
+ passed, _ = evaluate_candidate(evaluator, candidate)
1303
+ mutations.append({"path": check["path"], "field": list(path),
1304
+ "rejected": not passed})
1305
+ return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
1306
+ "correct": correct_detail,
1307
+ "perturbed": wrong_detail,
1308
+ "scalar_mutations": mutations,
1309
+ }
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/shell_invocations.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A deliberately bounded, non-executing shell structure recognizer.
2
+
3
+ Supports simple commands, literal scalar assignments, one command substitution
4
+ on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
5
+ It does not interpret shell code or credit commands in branch bodies/functions.
6
+ Pipelines, command lists, substitutions within substitutions, and swallowed
7
+ failures are outside this grammar. bash -n remains a separate required check.
8
+ """
9
+ import re
10
+ import shlex
11
+
12
+
13
+ def _statements(text):
14
+ out, current = [], []
15
+ quote, escaped, comment, depth = None, False, False, 0
16
+ for ch in str(text):
17
+ if comment:
18
+ if ch == '\n':
19
+ comment = False
20
+ else:
21
+ continue
22
+ if escaped:
23
+ if ch != '\n':
24
+ current.extend(('\\', ch))
25
+ escaped = False
26
+ continue
27
+ if ch == '\\' and quote != "'":
28
+ escaped = True
29
+ continue
30
+ if quote:
31
+ current.append(ch)
32
+ if ch == quote:
33
+ quote = None
34
+ continue
35
+ if ch in "'\"":
36
+ quote = ch
37
+ current.append(ch)
38
+ elif ch == '#' and (not current or current[-1].isspace()):
39
+ comment = True
40
+ elif ch == '(':
41
+ depth += 1
42
+ current.append(ch)
43
+ elif ch == ')':
44
+ depth -= 1
45
+ if depth < 0:
46
+ return []
47
+ current.append(ch)
48
+ elif ch in '\n;' and depth == 0:
49
+ value = ''.join(current).strip()
50
+ if value:
51
+ out.append(value)
52
+ current = []
53
+ else:
54
+ current.append(ch)
55
+ if quote or escaped or depth:
56
+ return []
57
+ if ''.join(current).strip():
58
+ out.append(''.join(current).strip())
59
+ expanded = []
60
+ for statement in out:
61
+ inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
62
+ expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
63
+ return expanded
64
+
65
+
66
+ def _simple_argv(text):
67
+ if '$(' in text or '`' in text:
68
+ return None
69
+ try:
70
+ lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
71
+ lexer.whitespace_split = True
72
+ tokens = list(lexer)
73
+ except ValueError:
74
+ return None
75
+ argv, index = [], 0
76
+ redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
77
+ while index < len(tokens):
78
+ token = tokens[index]
79
+ if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
80
+ index += 1
81
+ token = tokens[index]
82
+ if token in redirects:
83
+ if index + 1 >= len(tokens):
84
+ return None
85
+ target = tokens[index + 1]
86
+ if (not target or any(c in target for c in '$`;&|<>()')
87
+ or target in ('{', '}')):
88
+ return None
89
+ index += 2
90
+ continue
91
+ if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
92
+ return None
93
+ argv.append(token)
94
+ index += 1
95
+ return argv or None
96
+
97
+
98
+ def _invocation(text):
99
+ substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
100
+ if substitution:
101
+ inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
102
+ argv = _simple_argv(inner)
103
+ return (argv, 'assignment_substitution') if argv else (None, None)
104
+ return _simple_argv(text), 'simple'
105
+
106
+
107
+ def _guard_end(statements, start):
108
+ depth = 1
109
+ for index in range(start + 1, len(statements)):
110
+ item = statements[index]
111
+ if re.match(r'^if\s', item):
112
+ depth += 1
113
+ elif item == 'fi':
114
+ depth -= 1
115
+ if depth == 0:
116
+ return index
117
+ return None
118
+
119
+
120
+ def _nonzero_exit_body(statements):
121
+ """Only literal logging followed by a final unconditional nonzero exit."""
122
+ if not statements:
123
+ return False
124
+ for index, statement in enumerate(statements):
125
+ argv = _simple_argv(statement)
126
+ if not argv:
127
+ return False
128
+ if argv[0] == 'exit':
129
+ return (index == len(statements) - 1 and len(argv) == 2
130
+ and argv[1].isdigit() and 1 <= int(argv[1]) <= 255)
131
+ if argv[0] not in ('echo', 'printf'):
132
+ return False
133
+ return False
134
+
135
+
136
+ def shell_invocations(text):
137
+ """Return ordered, actually evaluated invocation nodes in the supported subset.
138
+
139
+ fail_fast is a structural proof: a simple command/assignment runs under
140
+ errexit, or a negated test exits nonzero on failure. This is not a complete
141
+ shell interpreter, and unsupported syntax earns no invocation credit.
142
+ """
143
+ statements = _statements(text)
144
+ # Function definitions or dynamic shell mutation can shadow the command or
145
+ # `exit` itself. They are outside this objective subset, even if uncalled.
146
+ 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)
147
+ or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
148
+ for s in statements):
149
+ return []
150
+ constants, result, index, errexit = {}, [], 0, False
151
+ assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
152
+ variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
153
+ while index < len(statements):
154
+ statement = statements[index]
155
+ literal = assignment.fullmatch(statement)
156
+ if literal:
157
+ constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
158
+ index += 1
159
+ continue
160
+ statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement)
161
+ setting = _simple_argv(statement)
162
+ if setting and setting[0] == 'set':
163
+ flag_index = 1
164
+ while flag_index < len(setting):
165
+ flag = setting[flag_index]
166
+ if flag == '--' or not flag.startswith(('-', '+')):
167
+ break # Remaining words set positional parameters.
168
+ if not re.fullmatch(r'[-+][eufxEo]+', flag):
169
+ return [] # e.g. `set -n` suppresses execution entirely.
170
+ if 'e' in flag[1:]:
171
+ errexit = flag[0] == '-'
172
+ if 'o' in flag[1:]:
173
+ if flag_index + 1 >= len(setting):
174
+ return []
175
+ option = setting[flag_index + 1]
176
+ if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
177
+ return []
178
+ if option == 'errexit':
179
+ errexit = flag[0] == '-'
180
+ flag_index += 1
181
+ flag_index += 1
182
+ index += 1
183
+ continue
184
+ if re.match(r'^if\s', statement):
185
+ end = _guard_end(statements, index)
186
+ if end is None:
187
+ return []
188
+ negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
189
+ if (negated and index + 1 < end
190
+ and statements[index + 1] == 'then'
191
+ and _nonzero_exit_body(statements[index + 2:end])):
192
+ argv, kind = _invocation(negated.group(1).strip())
193
+ if argv:
194
+ if argv[0] == 'false':
195
+ break
196
+ result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
197
+ 'fail_fast': True, 'statement_index': index})
198
+ else:
199
+ return []
200
+ else:
201
+ # Arbitrary conditions may terminate the script or shadow its
202
+ # commands. Do not infer a reachable suffix through them.
203
+ return []
204
+ # Bodies are never credited and may have assigned local variables.
205
+ constants.clear()
206
+ index = end + 1
207
+ continue
208
+ if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
209
+ # Unsupported compounds are not searched for command substrings.
210
+ return []
211
+ argv, kind = _invocation(statement)
212
+ if not argv:
213
+ # An unparsed statement may change control flow or shell state.
214
+ # Skipping it would incorrectly credit an unreachable suffix.
215
+ return []
216
+ if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare',
217
+ 'typeset', 'local', 'read', 'mapfile', 'readarray',
218
+ 'unset', 'readonly', '[', '[[', 'test'):
219
+ return []
220
+ if argv[0] == 'exit' or (argv[0] == 'false' and errexit):
221
+ break
222
+ if kind == 'assignment_substitution':
223
+ assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
224
+ if assigned:
225
+ constants.pop(assigned.group(1), None)
226
+ result.append({'command': shlex.join(argv), 'kind': kind,
227
+ 'fail_fast': errexit, 'statement_index': index})
228
+ index += 1
229
+ return result
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/test.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}}
4
+ if [[ -z "$candidate" ]]; then
5
+ echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2
6
+ exit 64
7
+ fi
8
+ python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate"
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/legacy_tests/verifiers.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier execution engine and fail-closed self-tests.
2
+
3
+ New verified tasks use atomic_json (complete shape plus scalar assertions).
4
+ Legacy verifier types remain readable so historical runs can still be audited.
5
+ 自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
6
+ """
7
+ import json
8
+ import logging
9
+ import os
10
+ import re
11
+
12
+ try:
13
+ from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
14
+ reference_bundle,
15
+ self_test_workspace_evaluator)
16
+ except ImportError: # portable task copies these modules beside each other
17
+ from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
18
+ reference_bundle,
19
+ self_test_workspace_evaluator)
20
+
21
+ log = logging.getLogger("pipeline")
22
+
23
+
24
+ def _norm(s):
25
+ return str(s).strip().lower()
26
+
27
+
28
+ def _json_value(value):
29
+ """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
30
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
31
+ return value
32
+ text = str(value).strip()
33
+ match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
34
+ if match:
35
+ text = match.group(1).strip()
36
+ text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
37
+ text = re.sub(r"\s*```$", "", text)
38
+ start_obj, start_arr = text.find("{"), text.find("[")
39
+ starts = [x for x in (start_obj, start_arr) if x >= 0]
40
+ if starts:
41
+ start = min(starts)
42
+ closing = "}" if text[start] == "{" else "]"
43
+ end = text.rfind(closing)
44
+ if end >= start:
45
+ text = text[start:end + 1]
46
+ return json.loads(text)
47
+
48
+
49
+ from r9_json import parse_single as _r9_parse_single
50
+ _json_value = _r9_parse_single
51
+
52
+
53
+ def _canonical_json(value):
54
+ if isinstance(value, dict):
55
+ return {key: _canonical_json(value[key]) for key in sorted(value)}
56
+ if isinstance(value, list):
57
+ values = [_canonical_json(item) for item in value]
58
+ return sorted(values, key=lambda item: json.dumps(
59
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
60
+ return value
61
+
62
+
63
+ def _atomic_prepare(value, list_order):
64
+ if isinstance(value, dict):
65
+ return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
66
+ if isinstance(value, list):
67
+ values = [_atomic_prepare(item, list_order) for item in value]
68
+ if list_order == "unordered":
69
+ values.sort(key=lambda item: json.dumps(
70
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
71
+ return values
72
+ return value
73
+
74
+
75
+ def _atomic_shape(value):
76
+ if isinstance(value, dict):
77
+ return {"type": "object", "keys": {
78
+ key: _atomic_shape(item) for key, item in value.items()}}
79
+ if isinstance(value, list):
80
+ return {"type": "array", "length": len(value),
81
+ "items": [_atomic_shape(item) for item in value]}
82
+ if isinstance(value, bool):
83
+ return {"type": "boolean"}
84
+ if value is None:
85
+ return {"type": "null"}
86
+ if isinstance(value, (int, float)):
87
+ return {"type": "number"}
88
+ return {"type": "string"}
89
+
90
+
91
+ def _atomic_leaves(value, path="$", tokens=()):
92
+ if isinstance(value, dict):
93
+ out = []
94
+ for key, item in value.items():
95
+ out.extend(_atomic_leaves(
96
+ item, path + "." + key, tokens + (key,)))
97
+ return out
98
+ if isinstance(value, list):
99
+ out = []
100
+ for index, item in enumerate(value):
101
+ out.extend(_atomic_leaves(
102
+ item, f"{path}[{index}]", tokens + (index,)))
103
+ return out
104
+ return [(path, tokens, value)]
105
+
106
+
107
+ def _normalize_path_equivalence_tokens(values):
108
+ """Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
109
+ normalized = []
110
+ for tokens in values or []:
111
+ if (not isinstance(tokens, (list, tuple)) or not tokens or
112
+ any(not isinstance(token, (str, int)) for token in tokens)):
113
+ raise ValueError("path equivalence tokens must be non-empty JSON paths")
114
+ item = list(tokens)
115
+ if item not in normalized:
116
+ normalized.append(item)
117
+ return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
118
+
119
+
120
+ def _path_value(value):
121
+ """Normalize only portable path spelling, not general answer text."""
122
+ if not isinstance(value, str):
123
+ return None
124
+ text = value.strip().replace("\\", "/")
125
+ if text != "/":
126
+ text = text.rstrip("/")
127
+ return text
128
+
129
+
130
+ def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
131
+ path_equivalence_tokens=None):
132
+ """Freeze a complete JSON shape plus one assertion for every scalar leaf."""
133
+ if list_order not in {"ordered", "unordered"}:
134
+ raise ValueError(f"unsupported atomic list_order: {list_order}")
135
+ tolerance = float(float_tolerance)
136
+ prepared = _atomic_prepare(_json_value(expected), list_order)
137
+ path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
138
+ assertions = []
139
+ for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
140
+ assertion = {"id": f"leaf_{index:03d}", "path": path,
141
+ "tokens": list(tokens), "operator": "eq", "expected": value}
142
+ if isinstance(value, float):
143
+ assertion.update({"operator": "abs_diff", "tolerance": tolerance})
144
+ elif list(tokens) in path_tokens:
145
+ if not isinstance(value, str):
146
+ raise ValueError("path equivalence can only target string leaves")
147
+ assertion["operator"] = "path_eq"
148
+ assertions.append(assertion)
149
+ compiled = {
150
+ "type": "atomic_json", "version": 2 if path_tokens else 1,
151
+ "list_order": list_order,
152
+ "float_tolerance": tolerance,
153
+ "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
154
+ "assertions": assertions,
155
+ }
156
+ if path_tokens:
157
+ compiled["path_equivalence_tokens"] = path_tokens
158
+ return compiled
159
+
160
+
161
+ def _shape_differences(expected, actual, path="$"):
162
+ if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
163
+ return [f"{path}: expected {expected.get('type')}, got "
164
+ f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
165
+ kind = expected.get("type")
166
+ if kind == "object":
167
+ expected_keys = set((expected.get("keys") or {}))
168
+ actual_keys = set((actual.get("keys") or {}))
169
+ differences = [f"{path}: missing key {key}" for key in sorted(
170
+ expected_keys - actual_keys)]
171
+ differences.extend(f"{path}: extra key {key}" for key in sorted(
172
+ actual_keys - expected_keys))
173
+ for key in sorted(expected_keys & actual_keys):
174
+ differences.extend(_shape_differences(
175
+ expected["keys"][key], actual["keys"][key], path + "." + key))
176
+ return differences
177
+ if kind == "array":
178
+ differences = []
179
+ if actual.get("length") != expected.get("length"):
180
+ differences.append(
181
+ f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
182
+ for index, (expected_item, actual_item) in enumerate(zip(
183
+ expected.get("items") or [], actual.get("items") or [])):
184
+ differences.extend(_shape_differences(
185
+ expected_item, actual_item, f"{path}[{index}]"))
186
+ return differences
187
+ return []
188
+
189
+
190
+ def _atomic_get(value, tokens):
191
+ current = value
192
+ for token in tokens:
193
+ current = current[token]
194
+ return current
195
+
196
+
197
+ def _int_values(value):
198
+ if isinstance(value, (list, tuple)):
199
+ out = []
200
+ for item in value:
201
+ out.extend(_int_values(item))
202
+ return out
203
+ if isinstance(value, int) and not isinstance(value, bool):
204
+ return [value]
205
+ return [int(number) for number in re.findall(r"\d+", str(value or ""))]
206
+
207
+
208
+ def _finding_type(value):
209
+ text = str(value or "").lower().replace("-", "_")
210
+ if "duplicate" in text:
211
+ return "duplicate_rows"
212
+ if ("none" in text or "null" in text) and "check" in text:
213
+ return "none_check"
214
+ if "missing" in text or "empty" in text or "null" in text:
215
+ return "missing"
216
+ if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
217
+ return "outlier"
218
+ if "invalid" in text and "config" in text:
219
+ return "invalid_config"
220
+ if "off" in text and "one" in text:
221
+ return "off_by_one"
222
+ return text.strip().replace(" ", "_")
223
+
224
+
225
+ def _normalized_findings(value, family):
226
+ obj = _json_value(value)
227
+ findings = obj.get("findings") if isinstance(obj, dict) else None
228
+ if not isinstance(findings, list):
229
+ raise ValueError("answer must contain a findings array")
230
+ normalized = set()
231
+ for finding in findings:
232
+ if not isinstance(finding, dict):
233
+ raise ValueError("each finding must be an object")
234
+ # The public contract uses type/function. Accept common semantically
235
+ # equivalent aliases as a robustness layer, while still comparing the
236
+ # normalized values and exact locations against generator-owned GT.
237
+ kind = _finding_type(finding.get("type", finding.get(
238
+ "defect_type", finding.get("defect"))))
239
+ if family == "csv":
240
+ if kind == "duplicate_rows":
241
+ rows = _int_values(finding.get("rows", finding.get("row")))
242
+ if len(rows) != 2:
243
+ raise ValueError("duplicate finding requires exactly two row numbers")
244
+ normalized.add((kind, *sorted(rows)))
245
+ elif kind in {"missing", "outlier"}:
246
+ rows = _int_values(finding.get("row"))
247
+ column = str(finding.get("column") or "").strip().lower()
248
+ if len(rows) != 1 or not column:
249
+ raise ValueError(f"{kind} requires one row and column")
250
+ normalized.add((kind, rows[0], column))
251
+ else:
252
+ raise ValueError(f"unsupported CSV finding type: {kind}")
253
+ elif family == "config":
254
+ if kind != "invalid_config":
255
+ raise ValueError(f"unsupported config finding type: {kind}")
256
+ normalized.add((kind, str(finding.get("path") or "").lower(),
257
+ json.dumps(finding.get("value"), sort_keys=True),
258
+ str(finding.get("expected") or "").lower()))
259
+ elif family == "code":
260
+ if kind not in {"off_by_one", "none_check"}:
261
+ raise ValueError(f"unsupported code finding type: {kind}")
262
+ function = finding.get("function", finding.get("function_name"))
263
+ function = str(function or "").strip().lower()
264
+ if not function:
265
+ raise ValueError(f"{kind} requires a function")
266
+ normalized.add((kind, function))
267
+ else:
268
+ raise ValueError(f"unsupported findings family: {family}")
269
+ return normalized
270
+
271
+
272
+ def _normalized_facts(value):
273
+ obj = _json_value(value)
274
+ facts = obj.get("facts") if isinstance(obj, dict) else None
275
+ if not isinstance(facts, list):
276
+ raise ValueError("answer must contain a facts array")
277
+ def textual(item):
278
+ # The document generator serializes scalar values as visible text. JSON
279
+ # has no way to infer whether the source token "30" was authored from an
280
+ # integer or a string, so facts_match compares that surface text. Nested
281
+ # values retain structural JSON comparison.
282
+ if isinstance(item, (dict, list)):
283
+ return json.dumps(item, sort_keys=True, ensure_ascii=False,
284
+ separators=(",", ":"))
285
+ if item is None:
286
+ return "None"
287
+ return str(item)
288
+ return {(str(fact.get("key") or ""), textual(fact.get("value")))
289
+ for fact in facts if isinstance(fact, dict)}
290
+
291
+
292
+ def verify(verifier, gt_answer, solver_output, material_paths=None):
293
+ """执行 verifier。返回 (passed, detail)。"""
294
+ vtype = verifier.get("type")
295
+ try:
296
+ if vtype == WORKSPACE_EVALUATOR:
297
+ return evaluate_candidate(verifier, solver_output)
298
+
299
+ if vtype == "json_exact":
300
+ pred = _canonical_json(_json_value(solver_output))
301
+ gold = _canonical_json(_json_value(gt_answer))
302
+ ok = pred == gold
303
+ return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
304
+
305
+ if vtype == "atomic_json":
306
+ pred = _atomic_prepare(_json_value(solver_output),
307
+ verifier.get("list_order", "ordered"))
308
+ compiled = compile_atomic_verifier(
309
+ gt_answer, verifier.get("list_order", "ordered"),
310
+ verifier.get("float_tolerance", 0.01),
311
+ verifier.get("path_equivalence_tokens"))
312
+ frozen = {key: verifier.get(key) for key in
313
+ ("type", "version", "list_order", "float_tolerance",
314
+ "completeness", "assertions", "path_equivalence_tokens")}
315
+ expected_frozen = {key: compiled.get(key) for key in frozen}
316
+ if frozen != expected_frozen:
317
+ return False, {"error": "atomic verifier does not match ground truth"}
318
+ shape_failures = _shape_differences(
319
+ verifier["completeness"]["shape"], _atomic_shape(pred))
320
+ assertion_results = []
321
+ for assertion in verifier.get("assertions") or []:
322
+ try:
323
+ actual = _atomic_get(pred, assertion["tokens"])
324
+ if assertion["operator"] == "abs_diff":
325
+ passed = abs(float(actual) - float(assertion["expected"])) <= float(
326
+ assertion.get("tolerance", 0.0))
327
+ elif assertion["operator"] == "path_eq":
328
+ passed = (_path_value(actual) is not None and
329
+ _path_value(actual) == _path_value(assertion["expected"]))
330
+ else:
331
+ passed = (actual is assertion["expected"] if
332
+ isinstance(assertion["expected"], bool) else
333
+ actual == assertion["expected"])
334
+ message = "" if passed else (
335
+ f"actual={actual!r} expected={assertion['expected']!r}")
336
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
337
+ actual, passed, message = None, False, f"lookup/compare failed: {exc}"
338
+ assertion_results.append({
339
+ "id": assertion["id"], "path": assertion["path"],
340
+ "operator": assertion["operator"], "expected": assertion["expected"],
341
+ "actual": actual, "passed": passed, "message": message})
342
+ passed_count = sum(item["passed"] for item in assertion_results)
343
+ ok = not shape_failures and passed_count == len(assertion_results)
344
+ return ok, {
345
+ "type": "atomic_json", "completeness_passed": not shape_failures,
346
+ "completeness_failures": shape_failures,
347
+ "assertions_passed": passed_count,
348
+ "assertions_total": len(assertion_results),
349
+ "assertion_pass_rate": (passed_count / len(assertion_results)
350
+ if assertion_results else 1.0),
351
+ "assertions": assertion_results,
352
+ }
353
+
354
+ if vtype == "findings_match":
355
+ family = verifier.get("family")
356
+ pred = _normalized_findings(solver_output, family)
357
+ gold = _normalized_findings(gt_answer, family)
358
+ ok = pred == gold
359
+ return ok, ("findings_match: pass" if ok else
360
+ f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
361
+
362
+ if vtype == "facts_match":
363
+ pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
364
+ ok = pred == gold
365
+ return ok, ("facts_match: pass" if ok else
366
+ f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
367
+
368
+ if vtype == "exact_match":
369
+ ok = _norm(solver_output) == _norm(gt_answer)
370
+ return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
371
+
372
+ if vtype == "numeric":
373
+ tol = verifier.get("tolerance") or 1e-6
374
+ pred = float(str(solver_output).strip().split()[0])
375
+ gold = float(gt_answer)
376
+ ok = abs(pred - gold) <= tol
377
+ return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
378
+
379
+ if vtype == "set_match":
380
+ pred = set(_as_list(solver_output))
381
+ gold = set(_as_list(gt_answer))
382
+ ok = pred == gold
383
+ return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
384
+
385
+ if vtype == "structured_match":
386
+ pred = _json_value(solver_output)
387
+ gold = _json_value(gt_answer)
388
+ if not isinstance(pred, dict) or not isinstance(gold, dict):
389
+ return False, "structured_match requires JSON objects"
390
+ missing = [f for f in verifier.get("required_fields", []) if f not in pred]
391
+ wrong = [f for f in verifier.get("required_fields", [])
392
+ if f in pred and f in gold and pred[f] != gold[f]]
393
+ ok = not missing and not wrong
394
+ return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
395
+
396
+ if vtype == "execution":
397
+ return False, "execution verifier is disabled in verified-first v2"
398
+
399
+ if vtype == "constraint":
400
+ fails = _check_constraints(verifier.get("criteria", []), solver_output)
401
+ return not fails, f"constraint: failed={fails[:5]}"
402
+
403
+ if vtype == "file_inspection":
404
+ fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
405
+ return not fails, f"file_inspection: failed={fails[:5]}"
406
+
407
+ return False, f"unknown verifier type: {vtype}"
408
+ except Exception as e:
409
+ return False, f"verifier error: {e}"
410
+
411
+
412
+ def _as_list(x):
413
+ if isinstance(x, list):
414
+ return [_norm(i) for i in x]
415
+ # 逗号/换行分隔的字符串
416
+ return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
417
+
418
+
419
+ def _check_constraints(criteria, solver_output):
420
+ """criteria: ["must contain X", "must be valid json", "length <= 500"]"""
421
+ fails = []
422
+ text = str(solver_output)
423
+ for c in criteria:
424
+ cl = c.lower()
425
+ if cl.startswith("must contain "):
426
+ needle = c[len("must contain "):]
427
+ if needle.lower() not in text.lower():
428
+ fails.append(c)
429
+ elif "valid json" in cl:
430
+ try:
431
+ json.loads(text)
432
+ except Exception:
433
+ fails.append(c)
434
+ elif cl.startswith("length <="):
435
+ limit = int(cl.split("<=")[1].strip())
436
+ if len(text) > limit:
437
+ fails.append(c)
438
+ else:
439
+ # Deterministic verifier DSL is closed-world: unknown checks fail.
440
+ fails.append(f"unsupported criterion: {c}")
441
+ return fails
442
+
443
+
444
+ def _inspect_files(expected, material_paths):
445
+ fails = []
446
+ paths = set(material_paths or [])
447
+ for e in expected:
448
+ fname = e.get("filename") if isinstance(e, dict) else str(e)
449
+ if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
450
+ fails.append(f"missing file: {fname}")
451
+ return fails
452
+
453
+
454
+ # ---------------- 自测 ----------------
455
+
456
+ def build_correct_solution(verifier, gt_answer, planted_info):
457
+ """由埋点/ground truth 直接构造正确解。"""
458
+ vtype = verifier.get("type")
459
+ if vtype == WORKSPACE_EVALUATOR:
460
+ return reference_bundle(verifier)
461
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
462
+ "set_match", "structured_match"):
463
+ return gt_answer
464
+ if vtype == "constraint":
465
+ parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
466
+ if c.lower().startswith("must contain ")]
467
+ return " ".join(parts) if parts else str(gt_answer)
468
+ # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
469
+ return None
470
+
471
+
472
+ def build_perturbed_solution(verifier, gt_answer, planted_info):
473
+ """破坏埋点构造扰动解。"""
474
+ vtype = verifier.get("type")
475
+ if vtype == WORKSPACE_EVALUATOR:
476
+ files = list(reference_bundle(verifier).get("files") or [])
477
+ return {"files": files[1:] if len(files) > 1 else []}
478
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
479
+ gold = _json_value(gt_answer)
480
+ if isinstance(gold, dict):
481
+ perturbed = dict(gold)
482
+ key = next(iter(perturbed), "__missing__")
483
+ if key in perturbed:
484
+ perturbed.pop(key)
485
+ else:
486
+ perturbed["__wrong__"] = True
487
+ return perturbed
488
+ if isinstance(gold, list):
489
+ return gold[:-1] if gold else ["__wrong__"]
490
+ return "__wrong__"
491
+ if vtype in ("exact_match", "numeric"):
492
+ return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
493
+ if vtype == "set_match":
494
+ gold = _as_list(gt_answer)
495
+ return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
496
+ if vtype == "structured_match":
497
+ fields = verifier.get("required_fields", [])
498
+ return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
499
+ if vtype == "constraint":
500
+ return "perturbed output lacking required content"
501
+ return None
502
+
503
+
504
+ def self_test(verifier, gt_answer, planted_info, material_paths):
505
+ """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
506
+
507
+ 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
508
+ 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
509
+ """
510
+ if verifier.get("type") == WORKSPACE_EVALUATOR:
511
+ return self_test_workspace_evaluator(verifier)
512
+ correct = build_correct_solution(verifier, gt_answer, planted_info)
513
+ perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
514
+ if correct is None or perturbed is None:
515
+ return False, (f"cannot self-test verifier type {verifier.get('type')} "
516
+ "(execution/file_inspection need real correct/perturbed solutions)")
517
+ ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
518
+ ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
519
+ passed = ok1 and not ok2
520
+ return passed, {"correct": d1, "perturbed": d2}
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/evaluator/r9_json.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JSON wire parsing and native-type equality for the R9 task copies.
2
+
3
+ No expected answers are defined here. Single complete JSON fences are accepted
4
+ only as a transport wrapper when requested by the calling task.
5
+ """
6
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
7
+ import json
8
+ import math
9
+ import re
10
+
11
+
12
+ def no_duplicates(pairs):
13
+ result = {}
14
+ for key, value in pairs:
15
+ if key in result:
16
+ raise ValueError('duplicate JSON key')
17
+ result[key] = value
18
+ return result
19
+
20
+
21
+ def _finite_tree(value):
22
+ if isinstance(value, float) and not math.isfinite(value):
23
+ raise ValueError('non-finite JSON number')
24
+ if isinstance(value, dict):
25
+ for item in value.values():
26
+ _finite_tree(item)
27
+ elif isinstance(value, list):
28
+ for item in value:
29
+ _finite_tree(item)
30
+ return value
31
+
32
+
33
+ def parse_single(value, allow_fence=True):
34
+ """Parse the entire response; no prefix/suffix or duplicate keys allowed."""
35
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
36
+ return _finite_tree(value)
37
+ if isinstance(value, bytes):
38
+ value = value.decode('utf-8-sig')
39
+ text = str(value).lstrip('\ufeff').strip()
40
+ if allow_fence and text.startswith('```'):
41
+ match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I)
42
+ if match is None:
43
+ raise ValueError('not one complete JSON fence')
44
+ text = match.group(1)
45
+ return _finite_tree(json.loads(
46
+ text, object_pairs_hook=no_duplicates,
47
+ parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number'))))
48
+
49
+
50
+ def parse_file(path):
51
+ """Files must contain raw JSON; Markdown fences are not JSON file bytes."""
52
+ with open(path, 'r', encoding='utf-8-sig') as stream:
53
+ return parse_single(stream.read(), allow_fence=False)
54
+
55
+
56
+ def strict_equal(actual, expected, number_equivalence=False):
57
+ """Preserve keys, order and every native type; booleans never equal numbers.
58
+
59
+ Set number_equivalence only if the public contract says a generic number
60
+ rather than an integer. It accepts finite integral numeric equivalents.
61
+ """
62
+ if type(actual) is not type(expected):
63
+ if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float):
64
+ return math.isfinite(actual) and math.isfinite(expected) and actual == expected
65
+ return False
66
+ if isinstance(expected, dict):
67
+ return set(actual) == set(expected) and all(
68
+ strict_equal(actual[key], value, number_equivalence) for key, value in expected.items())
69
+ if isinstance(expected, list):
70
+ return len(actual) == len(expected) and all(
71
+ strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected))
72
+ if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)):
73
+ return False
74
+ return actual == expected
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/grading/verified_config.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "52e614810e2bad9f_q1",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
8
+ "legacy-task.json": "66f8d527eb56802793d2dc55390f3d6d9c0445167172be5795cd59ce87c584b8",
9
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
10
+ "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278",
11
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
12
+ "r9_json.py": "4f895ed7b7bfa0dd87455d5d990214b0e17ebf2f28ab5bcce0aa9048b043bba8",
13
+ "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
14
+ "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
15
+ "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
16
+ "legacy_tests/objective_evaluators.py": "0729550ea1b83711c780bffc9ecc9d8ffd8602047606a7306c6493506f8d93c1",
17
+ "legacy_tests/shell_invocations.py": "3c7c2abc8e502b942fe8e783064b2b94274aada578a749fe99952170367901ce",
18
+ "legacy_tests/verifiers.py": "8b1802268580f3d39a6cbf88a517ef7140c8e0f2d93afad31ee2cede41ff7499"
19
+ },
20
+ "runtime_requirements": {
21
+ "candidate_mode": "response",
22
+ "candidate_snapshot_copy_to_ephemeral_app": true,
23
+ "container_private_entry": "/grader/check.py",
24
+ "environment": {
25
+ "CANDIDATE_DIR": "/candidate",
26
+ "CANDIDATE_ROOT": "/candidate",
27
+ "MYBENCH_ANSWER": "/answer.txt",
28
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
29
+ "MYBENCH_CANDIDATE": "/candidate",
30
+ "MYBENCH_EPHEMERAL_APP": "1",
31
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1",
32
+ "MYBENCH_RUN_METADATA": "/run_metadata.json",
33
+ "MYBENCH_SOURCE_TASK": "/source",
34
+ "SOURCE_TASK_DIR": "/source"
35
+ },
36
+ "expected_check_ids": [
37
+ "0"
38
+ ],
39
+ "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
40
+ "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
41
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
42
+ "image_included": false,
43
+ "legacy_adapter": true,
44
+ "mounts_readonly": [
45
+ "/candidate",
46
+ "/source",
47
+ "/grader",
48
+ "/answer.txt"
49
+ ],
50
+ "network": "none",
51
+ "original_declared_resources": {
52
+ "agent": {
53
+ "basis": "advisory_not_measured",
54
+ "cpus": 2,
55
+ "memory_mib": 4096,
56
+ "timeout_sec": 1200
57
+ },
58
+ "oracle": {
59
+ "timeout_sec": 120
60
+ },
61
+ "source_agent": {
62
+ "command_timeout_sec": null,
63
+ "max_steps": null
64
+ },
65
+ "verifier": {
66
+ "cpus": 1,
67
+ "memory_mib": 1024,
68
+ "pids": 64,
69
+ "timeout_sec": 900,
70
+ "tmpfs_mib": 128
71
+ }
72
+ },
73
+ "private_entry": "evaluator/check.py",
74
+ "private_tree_environment_tokens": [
75
+ "MYBENCH_CANDIDATE_FILE",
76
+ "MYBENCH_OPEN_JUDGE_COMMAND",
77
+ "MYBENCH_OPEN_JUDGE_TIMEOUT",
78
+ "MYBENCH_TASK_JSON"
79
+ ],
80
+ "trusted_trace_environment_aliases": [
81
+ "MYBENCH_TOOL_TRAJECTORY",
82
+ "MYBENCH_TRUSTED_TRACE",
83
+ "TOOL_TRAJECTORY",
84
+ "TOOL_TRAJECTORY_FILE"
85
+ ],
86
+ "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
87
+ "working_directory": "/candidate",
88
+ "writable_ephemeral_roots": [
89
+ "/app",
90
+ "/workspace",
91
+ "/tmp"
92
+ ],
93
+ "criterion_weights": {
94
+ "0": 1
95
+ },
96
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair."
97
+ },
98
+ "engine": "portable_verified_v1"
99
+ }
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/instruction.md ADDED
@@ -0,0 +1 @@
 
 
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.
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/SKILL.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: thor
3
+ 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.
4
+ allowed-tools: []
5
+ license: MIT
6
+ metadata:
7
+ author: VeChain
8
+ version: "0.1.0"
9
+ ---
10
+
11
+ # Thor Skill
12
+
13
+ ## CRITICAL RULES
14
+
15
+ 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.
16
+ 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.
17
+ 3. **Prefer working directly in the main conversation.** Plan mode and subagents do not inherit skill context and may produce stale answers.
18
+ 4. **After compaction or context loss**, re-read this SKILL.md to restore awareness of the reference table.
19
+
20
+ ## Scope
21
+
22
+ Use this Skill for anything related to the VeChainThor node (thor):
23
+
24
+ - Architecture and package structure of the Go codebase
25
+ - Consensus: PoA v1/v2, PoS (Galactica), BFT finality
26
+ - Built-in contracts: Authority, Energy, Staker, Params, Prototype, Executor, Extension
27
+ - REST API endpoints and WebSocket subscriptions
28
+ - Storage: LevelDB, SQLite logdb, trie, pruning, node types
29
+ - P2P networking: discovery, block/tx propagation
30
+ - Cross-cutting flows: block production, transaction lifecycle, reward distribution, staking/delegation, chain sync
31
+ - Solo mode for local development
32
+ - Contributing to the thor codebase: build, test, add endpoints, fork config
33
+
34
+ For application-level VeChain development, see the companion skills:
35
+
36
+ - **vechain-core** — SDK usage, fee delegation, multi-clause transactions, dual-token model
37
+ - **vechain-kit** — VeChain Kit hooks, components, wallet connection, social login
38
+ - **smart-contract-development** — Solidity, Hardhat, testing, security
39
+ - **stargate** — NFT staking, validator delegation, VTHO rewards
40
+
41
+ ## Operating procedure
42
+
43
+ ### 1. Identify the question type
44
+
45
+ - **PM/architecture question** → read `architecture.md` + relevant flow files
46
+ - **Contributor question** → read `contributing.md` + relevant package reference
47
+ - **"How does X work?"** → read the matching flow file(s)
48
+ - **API question** → read `api.md`
49
+ - **Node operations** → read `architecture.md` (node types, flags, ports)
50
+
51
+ ### 2. Read before answering
52
+
53
+ Load the matching reference files from the table below. Cross-cutting questions may need multiple files.
54
+
55
+ ### 3. Answer with context
56
+
57
+ - Reference specific packages, types, and files from the thor codebase
58
+ - For flows, trace through the packages step-by-step
59
+ - For PM audiences, lead with the high-level summary before diving into implementation
60
+ - For contributors, include package paths and key type names
61
+
62
+ ## Reference files
63
+
64
+ Read the matching files BEFORE doing anything else. See Critical Rules above.
65
+
66
+ | Topic | File | Read when user mentions... |
67
+ |-------|------|---------------------------|
68
+ | Architecture | [references/architecture.md](references/architecture.md) | overview, packages, node types, ports, flags, fork config, tech stack |
69
+ | Consensus | [references/consensus.md](references/consensus.md) | PoA, PoS, BFT, finality, proposer, validator selection, VRF, Galactica |
70
+ | Built-in contracts | [references/built-in-contracts.md](references/built-in-contracts.md) | Authority, Energy, VTHO, Staker, Params, Prototype, Executor, native contracts |
71
+ | REST API | [references/api.md](references/api.md) | API, endpoints, routes, subscriptions, WebSocket, Swagger |
72
+ | Storage | [references/storage.md](references/storage.md) | database, LevelDB, SQLite, logdb, trie, pruning, archive, disk |
73
+ | P2P networking | [references/p2p.md](references/p2p.md) | peers, discovery, discv5, propagation, sync protocol, bootstrap |
74
+ | Contributing | [references/contributing.md](references/contributing.md) | build, Makefile, tests, lint, add endpoint, fork config, PR, Go conventions |
75
+ | Solo mode | [references/solo.md](references/solo.md) | solo, local dev, test chain, pre-funded accounts, auto-mine |
76
+ | Flow: block production | [references/flow-block-production.md](references/flow-block-production.md) | block packing, scheduler, proposer, how blocks are created |
77
+ | Flow: transaction lifecycle | [references/flow-transaction-lifecycle.md](references/flow-transaction-lifecycle.md) | tx flow, txpool, clause execution, receipts, tx validation |
78
+ | Flow: reward distribution | [references/flow-reward-distribution.md](references/flow-reward-distribution.md) | rewards, VTHO generation, validator rewards, gas rewards, burning |
79
+ | Flow: staking & delegation | [references/flow-staking-delegation.md](references/flow-staking-delegation.md) | staking, delegation, unstaking, Staker contract, validator lifecycle |
80
+ | Flow: chain sync | [references/flow-sync.md](references/flow-sync.md) | sync, catch-up, peer download, fork handling, reorg, propagation |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/api.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # REST API
2
+
3
+ Thor exposes an HTTP API (default `localhost:8669`) plus a separate admin server (`localhost:2113`).
4
+ Uses **gorilla/mux** router. WebSocket endpoints for real-time subscriptions.
5
+
6
+ ## Route Organization
7
+
8
+ ```
9
+ api/
10
+ ├── accounts/ # Account state, code, storage, contract calls
11
+ ├── blocks/ # Block retrieval
12
+ ├── transactions/ # Submit and fetch transactions
13
+ ├── events/ # Event log queries (POST /logs/event)
14
+ ├── transfers/ # Transfer log queries (POST /logs/transfer)
15
+ ├── fees/ # Fee history and priority
16
+ ├── node/ # Peers, txpool
17
+ ├── debug/ # EVM tracers, storage range
18
+ ├── subscriptions/ # WebSocket subscriptions
19
+ ├── doc/ # OpenAPI spec, Swagger/Stoplight UI
20
+ ├── middleware/ # CORS, metrics, logging, panic recovery
21
+ ├── restutil/ # Shared HTTP helpers
22
+ └── admin/ # Separate admin server (health, loglevel, apilogs)
23
+ ```
24
+
25
+ ## Endpoint Groups
26
+
27
+ ### Accounts — `/accounts`
28
+
29
+ | Method | Path | Description |
30
+ |--------|------|-------------|
31
+ | GET | `/accounts/{address}` | Balance, energy, hasCode |
32
+ | GET | `/accounts/{address}/code` | Contract bytecode |
33
+ | GET | `/accounts/{address}/storage/{key}` | Storage slot value |
34
+ | GET | `/accounts/{address}/storage/raw/{key}` | Raw storage bytes |
35
+ | POST | `/accounts/*` | Batch contract call (multiple clauses) |
36
+
37
+ Query param `revision` selects block (ID, number, or `best`).
38
+
39
+ Deprecated (requires `--api-enable-deprecated`): `POST /accounts`, `POST /accounts/{address}` for single calls.
40
+
41
+ ### Blocks — `/blocks`
42
+
43
+ | Method | Path | Description |
44
+ |--------|------|-------------|
45
+ | GET | `/blocks/{revision}` | Block by ID or number. Query: `raw`, `expanded` |
46
+
47
+ ### Transactions — `/transactions`
48
+
49
+ | Method | Path | Description |
50
+ |--------|------|-------------|
51
+ | POST | `/transactions` | Submit raw signed transaction |
52
+ | GET | `/transactions/{id}` | Fetch transaction. Query: `head`, `raw`, `pending` |
53
+ | GET | `/transactions/{id}/receipt` | Transaction receipt |
54
+
55
+ ### Events — `/logs/event`
56
+
57
+ | Method | Path | Description |
58
+ |--------|------|-------------|
59
+ | POST | `/logs/event` | Filter event logs by criteria, block range, pagination |
60
+
61
+ ### Transfers — `/logs/transfer`
62
+
63
+ | Method | Path | Description |
64
+ |--------|------|-------------|
65
+ | POST | `/logs/transfer` | Filter transfer logs by criteria, block range, pagination |
66
+
67
+ Both log endpoints are disabled when `--skip-logs` is set.
68
+
69
+ ### Fees — `/fees`
70
+
71
+ | Method | Path | Description |
72
+ |--------|------|-------------|
73
+ | GET | `/fees/history` | Fee history. Query: `blockCount`, `newestBlock`, `rewardPercentiles` |
74
+ | GET | `/fees/priority` | Suggested max priority fee per gas |
75
+
76
+ ### Node — `/node`
77
+
78
+ | Method | Path | Description |
79
+ |--------|------|-------------|
80
+ | GET | `/node/network/peers` | Connected peer stats |
81
+ | GET | `/node/txpool` | Pending txs (requires `--api-enable-txpool`) |
82
+ | GET | `/node/txpool/status` | Txpool count (requires `--api-enable-txpool`) |
83
+
84
+ ### Debug — `/debug`
85
+
86
+ | Method | Path | Description |
87
+ |--------|------|-------------|
88
+ | POST | `/debug/tracers` | Trace existing clause (target: blockID/txID/clauseIndex) |
89
+ | POST | `/debug/tracers/call` | Trace a simulated call |
90
+ | POST | `/debug/storage-range` | Storage range at clause execution point |
91
+
92
+ Optional pprof endpoints at `/debug/pprof/*` when `--api-pprof` is set.
93
+
94
+ ### Subscriptions — `/subscriptions` (WebSocket)
95
+
96
+ | Path | Query Params | Payload |
97
+ |------|-------------|---------|
98
+ | `/subscriptions/block` | `pos` | New blocks |
99
+ | `/subscriptions/event` | `pos`, `addr`, `t0`–`t4` | Event logs |
100
+ | `/subscriptions/transfer` | `pos`, `txOrigin`, `sender`, `recipient` | Transfers |
101
+ | `/subscriptions/beat2` | `pos` | Beat2 heartbeat messages |
102
+ | `/subscriptions/txpool` | — | Pending transaction IDs |
103
+
104
+ `pos` (block ID) must be within backtrace limit (default 1000 blocks).
105
+
106
+ Deprecated: `/subscriptions/beat` (requires `--api-enable-deprecated`).
107
+
108
+ ### Documentation — `/doc`
109
+
110
+ | Path | Description |
111
+ |------|-------------|
112
+ | `/` | Redirects to Stoplight UI |
113
+ | `/doc/thor.yaml` | OpenAPI YAML spec |
114
+ | `/doc/*` | Static assets (Swagger UI, Stoplight UI) |
115
+
116
+ Embedded via `//go:embed`.
117
+
118
+ ## Admin API (Separate Server)
119
+
120
+ Runs on `--admin-addr` (default `localhost:2113`):
121
+
122
+ | Method | Path | Description |
123
+ |--------|------|-------------|
124
+ | GET | `/admin/health` | Health status (block lag tolerance, peer count) |
125
+ | GET/POST | `/admin/loglevel` | Get/set log level (debug/info/warn/error/trace/crit) |
126
+ | GET/POST | `/admin/apilogs` | Get/toggle API request logging |
127
+
128
+ ## Middleware Stack
129
+
130
+ Applied in order:
131
+
132
+ 1. **RequestBodyLimit** — 200 KB max body
133
+ 2. **APITimeout** — configurable, default 10s
134
+ 3. **RequestLogger** — logs slow queries and 5xx responses
135
+ 4. **Metrics** — counters and histograms (Prometheus)
136
+ 5. **PanicRecovery** — recovers panics, optional stack trace logging
137
+ 6. **XGenesisID** — validates/sets `x-genesis-id` header
138
+ 7. **XThorestVersion** — sets `x-thorest-ver` header
139
+ 8. **Compress** — gzip compression
140
+ 9. **CORS** — configurable allowed origins (`--api-cors`), allows `content-type` and `x-genesis-id` headers
141
+
142
+ ## Server Configuration
143
+
144
+ | Flag | Default | Description |
145
+ |------|---------|-------------|
146
+ | `--api-addr` | `localhost:8669` | API listen address |
147
+ | `--api-cors` | — | CORS allowed origins |
148
+ | `--api-timeout` | 10s | Request timeout |
149
+ | `--api-pprof` | false | Enable pprof endpoints |
150
+ | `--api-enable-txpool` | false | Enable txpool endpoints |
151
+ | `--api-enable-deprecated` | false | Enable deprecated endpoints |
152
+ | `--admin-addr` | `localhost:2113` | Admin server address |
153
+ | `--metrics-addr` | `localhost:2112` | Prometheus metrics address |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/architecture.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thor Node Architecture
2
+
3
+ Module path: `github.com/vechain/thor/v2`
4
+
5
+ ## Tech Stack
6
+
7
+ | Component | Technology |
8
+ |-----------|-----------|
9
+ | Language | Go (1.25+) |
10
+ | State DB | LevelDB via `muxdb` (multiplexed) |
11
+ | Log DB | SQLite (`logdb`) |
12
+ | EVM | Fork of go-ethereum, Shanghai hardfork compatible |
13
+ | Trie | Modified Merkle Patricia Trie with versioned nodes |
14
+ | P2P | devp2p (Ethereum-derived), RLPx |
15
+ | Hashing | Blake2b (not Keccak for most chain ops) |
16
+ | VRF | ECVRF-SECP256K1-SHA256-TAI |
17
+ | CLI | `urfave/cli/v3` |
18
+
19
+ ## Package Map
20
+
21
+ | Package | Purpose |
22
+ |---------|---------|
23
+ | `cmd/thor` | CLI entry point — `main.go` (network node), `solo` subcommand, `master-key`, `reprocess` |
24
+ | `thor` | Core types (`Address`, `Bytes32`), constants, fork config, governance param keys |
25
+ | `block` | Block header/body structures, signature handling, VRF alpha/beta fields |
26
+ | `tx` | Transaction types (legacy + typed after Galactica), multi-clause model, fee delegation |
27
+ | `state` | State trie access — account balances, storage, code; `Stater` creates state snapshots from root |
28
+ | `muxdb` | Multiplexed DB layer over LevelDB — main state storage with optional metrics |
29
+ | `logdb` | SQLite-based event/transfer log storage (skippable via `--skip-logs`) |
30
+ | `chain` | Chain repository — block summaries, chain forks, tx lookups, chain tag |
31
+ | `consensus` | Block validation — header checks, proposer validation (PoA or PoS), tx execution, state root verification |
32
+ | `bft` | BFT finality engine — vote tracking, epoch quality, justified/finalized checkpoints |
33
+ | `scheduler` | Block proposer scheduling — `PoASchedulerV1`, `PoASchedulerV2`, `PoSScheduler` |
34
+ | `vrf` | Verifiable Random Function — seed generation for proposer shuffling (post-VIP-214) |
35
+ | `packer` | Block construction — assembles blocks with transactions for proposers |
36
+ | `runtime` | EVM execution environment — runs transactions, handles built-in contract calls |
37
+ | `builtin` | Built-in contracts: Authority, Energy, Params, Prototype, Extension, Executor, Staker, Measure |
38
+ | `txpool` | Transaction pool management with per-account limits and lifetime expiry |
39
+ | `api` | RESTful API server (OpenAPI spec in `api/doc/thor.yaml`) |
40
+ | `p2p` / `p2psrv` | P2P networking layer |
41
+ | `comm` | P2P communication — block/tx propagation between peers |
42
+ | `genesis` | Genesis block generation for mainnet, testnet, devnet |
43
+ | `vm` | Modified EVM (forked from go-ethereum) |
44
+ | `tracers` | Transaction tracers — JS, native, and logger tracers (forked from geth) |
45
+ | `trie` | Versioned Merkle Patricia Trie implementation |
46
+ | `kv` | Key-value store abstraction |
47
+ | `xenv` | Execution environment for built-in contract native calls |
48
+ | `metrics` | Prometheus metrics collection |
49
+ | `cache` | LRU and priority caches |
50
+ | `stackedmap` | Copy-on-write map used in state management |
51
+
52
+ ## Data Flow: Block Sync & Validation
53
+
54
+ ```
55
+ P2P peers → comm (download blocks)
56
+ → consensus.Process()
57
+ → validateBlockHeader (timestamp, gas, score, VRF alpha/beta, baseFee)
58
+ → staker.SyncPOS() (check if PoS transition happened)
59
+ → validateAuthorityProposer OR validateStakingProposer
60
+ → scheduler picks correct Scheduler impl
61
+ → verify signer is scheduled for this timeslot
62
+ → verify score matches
63
+ → validateBlockBody (tx roots, chain tag, expiry, blocklist)
64
+ → verifyBlock (execute all txs, compare state root, receipts root)
65
+ → if PoS active: distribute rewards via Energy.DistributeRewards
66
+ → bft.CommitBlock (track votes, update quality, finalize checkpoints)
67
+ → chain.Repository saves block
68
+ → logdb records events/transfers (unless --skip-logs)
69
+ → pruner trims old state (unless --disable-pruner)
70
+ ```
71
+
72
+ ## Package Dependencies (Simplified)
73
+
74
+ ```
75
+ cmd/thor
76
+ ├── consensus (uses: chain, state, scheduler, builtin, runtime, block, tx)
77
+ ├── bft (uses: chain, state, builtin, block)
78
+ ├── packer (uses: chain, state, builtin, runtime, txpool)
79
+ ├── txpool (uses: chain, state, tx)
80
+ ├── api (uses: chain, state, logdb, txpool, bft)
81
+ ├── comm (uses: chain, txpool, p2p)
82
+ ├── logdb (standalone SQLite)
83
+ └── muxdb (standalone LevelDB)
84
+
85
+ builtin → state, thor, xenv, abi
86
+ ├── authority, energy, params, prototype (state-backed linked lists / storage)
87
+ └── staker (validation, delegation, aggregation, globalstats sub-packages)
88
+
89
+ consensus → scheduler → thor (for constants, Blake2b)
90
+ bft → chain, builtin.Staker (for PoS weight queries)
91
+ ```
92
+
93
+ ## Node Types
94
+
95
+ | Type | Flags | Storage | Notes |
96
+ |------|-------|---------|-------|
97
+ | **Full node** | `--network mainnet` | ~200 GB (Apr 2024), 1 TB SSD recommended | Logs + pruner enabled |
98
+ | **Full without logs** | `--skip-logs` | ~100 GB | Recommended for validators; `/logs` API disabled |
99
+ | **Archive node** | `--disable-pruner` | 400+ GB | Full state history preserved |
100
+ | **Validator** | `--skip-logs` + master key | ~100 GB, 500 GB NVMe SSD | Must be voted in via Authority contract, needs endorsement |
101
+ | **Solo** | `thor solo` | In-memory (or `--persist`) | Local dev/test; single node, no P2P; `--on-demand` for tx-triggered blocks |
102
+
103
+ ## Key Configuration
104
+
105
+ ### CLI Flags
106
+
107
+ | Flag | Default | Description |
108
+ |------|---------|-------------|
109
+ | `--network` | — | `mainnet`/`testnet` or path/URL to genesis file |
110
+ | `--api-addr` | `localhost:8669` | REST API listen address |
111
+ | `--p2p-port` | `11235` | P2P network port |
112
+ | `--max-peers` | `25` | Max P2P peers (0 disables P2P) |
113
+ | `--skip-logs` | false | Skip event/transfer log writes |
114
+ | `--disable-pruner` | false | Keep all state history (archive mode) |
115
+ | `--cache` | `4096` | MB of RAM for trie node cache |
116
+ | `--beneficiary` | — | Address for block rewards |
117
+ | `--target-gas-limit` | `0` (adaptive) | Target block gas limit |
118
+ | `--enable-metrics` | false | Prometheus metrics |
119
+ | `--metrics-addr` | `localhost:2112` | Metrics endpoint |
120
+ | `--enable-admin` | false | Admin server |
121
+ | `--admin-addr` | `localhost:2113` | Admin endpoint |
122
+ | `--min-effective-priority-fee` | `0` | Min priority fee for packing txs |
123
+
124
+ All flags support `THOR_` prefixed env vars (e.g., `THOR_NETWORK`, `THOR_API_ADDR`).
125
+
126
+ ### Ports
127
+
128
+ | Port | Protocol | Purpose |
129
+ |------|----------|---------|
130
+ | 8669 | TCP (HTTP) | REST API |
131
+ | 11235 | TCP + UDP | P2P network |
132
+ | 2112 | TCP (HTTP) | Prometheus metrics (opt-in) |
133
+ | 2113 | TCP (HTTP) | Admin server (opt-in) |
134
+
135
+ ### Fork Config
136
+
137
+ Fork activation is defined per-network by genesis block ID in `thor/fork_config.go`. Each fork activates at a specific block number.
138
+
139
+ | Fork | Mainnet Block | What Changed |
140
+ |------|--------------|-------------|
141
+ | `VIP191` | 3,337,300 | Fee delegation (tx feature flag) |
142
+ | `ETH_CONST` | 3,337,300 | Ethereum-compatible constants |
143
+ | `BLOCKLIST` | 4,817,300 | Origin/delegator address blocklist |
144
+ | `ETH_IST` | 9,254,300 | Ethereum Istanbul EVM changes |
145
+ | `VIP214` | 10,653,500 | PoA2 — VRF-based proposer shuffling, complex block signatures |
146
+ | `FINALITY` | 13,815,000 | BFT finality engine — justified/finalized checkpoints |
147
+ | `GALACTICA` | 22,084,200 | EIP-1559 base fee, typed transactions, staker contract |
148
+ | `HAYABUSA` | 23,414,400 | PoA-to-PoS transition period begins; weight-based BFT |
149
+
150
+ ### Block Constants
151
+
152
+ | Parameter | Value |
153
+ |-----------|-------|
154
+ | Block interval | 10 seconds |
155
+ | Initial gas limit | 10,000,000 |
156
+ | Min gas limit | 1,000,000 |
157
+ | Tx base gas | 5,000 |
158
+ | Clause gas | 16,000 |
159
+ | Max state history | 65,535 blocks |
160
+ | Epoch length | Used for BFT rounds |
161
+ | Max block proposers | 101 (initial) |
162
+ | Energy growth rate | ~0.000432 VTHO/VET/day |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/built-in-contracts.md ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Built-in Contracts
2
+
3
+ Built-in contracts are native to the VeChainThor blockchain. Unlike regular Solidity contracts, they:
4
+
5
+ - Have **deterministic addresses** derived from their name: `thor.BytesToAddress([]byte("ContractName"))`
6
+ - Are **not deployed via transactions** — their bytecode is loaded at genesis
7
+ - Have **native method implementations** in Go that bypass the EVM for core operations
8
+ - Solidity ABI is still used for encoding/decoding — callers interact via normal contract calls
9
+ - Some older contracts (compiled with Solidity 0.4.24) return unused gas to the caller
10
+
11
+ **Package**: `builtin/` — `builtin.go` defines all contract bindings, each `*_native.go` file registers native method handlers.
12
+
13
+ ## Contract Overview
14
+
15
+ | Contract | Address | Purpose |
16
+ |----------|---------|---------|
17
+ | **Authority** | `0x...Authority` | PoA authority node registry |
18
+ | **Energy** | `0x...Energy` | VTHO token (ERC20-like) |
19
+ | **Params** | `0x...Params` | On-chain governance parameters |
20
+ | **Prototype** | `0x...Prototype` | Account metadata: master, sponsors, credit plans |
21
+ | **Extension** | `0x...Extension` | Block/tx introspection from Solidity |
22
+ | **Executor** | `0x...Executor` | On-chain governance executor |
23
+ | **Staker** | `0x...Staker` | PoS staking, delegation, rewards (post-GALACTICA) |
24
+ | **Measure** | `0x...Measure` | Block measurement contract |
25
+
26
+ > Addresses are computed as `thor.BytesToAddress([]byte(name))`. For example, Authority's address = `BytesToAddress([]byte("Authority"))`.
27
+
28
+ ## Authority
29
+
30
+ **File**: `builtin/authority_native.go`, `builtin/authority/authority.go`
31
+
32
+ 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.
33
+
34
+ ### Native Methods
35
+
36
+ | Method | Description |
37
+ |--------|-------------|
38
+ | `native_executor` | Returns the executor address from Params |
39
+ | `native_add(nodeMaster, endorsor, identity)` | Register a new authority node |
40
+ | `native_revoke(nodeMaster)` | Remove an authority node |
41
+ | `native_get(nodeMaster)` | Get node info: listed, endorser, identity, active |
42
+ | `native_first` | First node in the linked list |
43
+ | `native_next(nodeMaster)` | Next node in the linked list |
44
+ | `native_isEndorsed(nodeMaster)` | Check if endorser meets the VET endorsement requirement |
45
+
46
+ After HAYABUSA, `native_isEndorsed` also considers queued VET in the Staker contract (transition period logic).
47
+
48
+ ## Energy (VTHO)
49
+
50
+ **File**: `builtin/energy_native.go`, `builtin/energy/energy.go`
51
+
52
+ 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.
53
+
54
+ ### Native Methods
55
+
56
+ | Method | Description |
57
+ |--------|-------------|
58
+ | `native_totalSupply` | Total VTHO supply |
59
+ | `native_totalBurned` | Total VTHO burned |
60
+ | `native_get(addr)` | VTHO balance of an address (includes accrued growth) |
61
+ | `native_add(addr, amount)` | Credit VTHO to an address |
62
+ | `native_sub(addr, amount)` | Debit VTHO from an address |
63
+ | `native_master(addr)` | Get the master address of an account |
64
+
65
+ Post-GALACTICA, the Energy contract also handles `DistributeRewards` — splitting block rewards between the proposer, validator beneficiary, and delegator reward pools.
66
+
67
+ ### VTHO Generation
68
+
69
+ VTHO is not minted per-block. Instead, each account's VTHO balance is calculated on-the-fly based on:
70
+ - Last recorded energy balance
71
+ - VET balance × growth rate × elapsed time since last update
72
+
73
+ Growth rate: `5,000,000,000 wei VTHO per VET per second` ≈ 0.000432 VTHO/VET/day.
74
+
75
+ ## Params
76
+
77
+ **File**: `builtin/params_native.go`, `builtin/params/params.go`
78
+
79
+ Generic key-value store for on-chain governance parameters. Only the Executor contract can write to it.
80
+
81
+ ### Native Methods
82
+
83
+ | Method | Description |
84
+ |--------|-------------|
85
+ | `native_executor` | Returns the executor address |
86
+ | `native_get(key)` | Read a parameter value |
87
+ | `native_set(key, value)` | Write a parameter value (executor only) |
88
+
89
+ ### Key Parameters
90
+
91
+ | Key | Purpose | Initial Value |
92
+ |-----|---------|---------------|
93
+ | `executor` | Governance executor address | Set at genesis |
94
+ | `reward-ratio` | Block reward ratio | 30% (3e17) |
95
+ | `validator-reward-percentage` | Validator share of rewards | 30% |
96
+ | `base-gas-price` | Legacy tx default gas price | 1e15 wei |
97
+ | `proposer-endorsement` | VET required to endorse a proposer | 25,000,000 VET |
98
+ | `max-block-proposers` | Max authority/validator count | 101 |
99
+ | `curve-factor` | VTHO issuance curve factor (post-PoS) | 76,800 |
100
+ | `delegator-contract-address` | Delegator contract address | — |
101
+ | `staker-switches` | Bit flags to pause staker/stargate | — |
102
+
103
+ ## Prototype
104
+
105
+ **File**: `builtin/prototype_native.go`, `builtin/prototype/prototype.go`
106
+
107
+ Provides per-account metadata: master address, credit plans, user lists, and sponsor mechanism. Central to VeChain's multi-party payment protocol (MPP).
108
+
109
+ ### Native Methods
110
+
111
+ | Method | Description |
112
+ |--------|-------------|
113
+ | `native_master(self)` | Get account's master address |
114
+ | `native_setMaster(self, newMaster)` | Set account's master |
115
+ | `native_balanceAtBlock(self, blockNum)` | Historical VET balance (within MaxStateHistory) |
116
+ | `native_energyAtBlock(self, blockNum)` | Historical VTHO balance |
117
+ | `native_hasCode(self)` | Check if account has contract code |
118
+ | `native_storageFor(self, key)` | Read account's storage slot |
119
+ | `native_creditPlan(self)` | Get credit plan (credit, recoveryRate) |
120
+ | `native_setCreditPlan(self, credit, rate)` | Set credit plan |
121
+ | `native_isUser(self, user)` | Check if address is a user of the contract |
122
+ | `native_addUser(self, user)` | Add user |
123
+ | `native_removeUser(self, user)` | Remove user |
124
+ | `native_sponsor(self, sponsor)` | Register as sponsor |
125
+ | `native_unsponsor(self, sponsor)` | Unregister as sponsor |
126
+ | `native_isSponsor(self, sponsor)` | Check sponsor status |
127
+ | `native_selectSponsor(self, sponsor)` | Select active sponsor |
128
+ | `native_currentSponsor(self)` | Get current sponsor |
129
+
130
+ ### Multi-Party Payment (MPP)
131
+
132
+ 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.
133
+
134
+ ## Extension
135
+
136
+ **File**: `builtin/extension_native.go`
137
+
138
+ Provides Solidity-accessible introspection into block and transaction context. Has three versions (Extension, ExtensionV2, ExtensionV3) — V3 is the active native ABI.
139
+
140
+ ### Native Methods
141
+
142
+ | Method | Description |
143
+ |--------|-------------|
144
+ | `native_blake2b256(data)` | Blake2b hash (VeChain's native hash) |
145
+ | `native_blockID(blockNum)` | Block ID by number |
146
+ | `native_blockTotalScore(blockNum)` | Total score at block |
147
+ | `native_blockTime(blockNum)` | Timestamp at block |
148
+ | `native_blockSigner(blockNum)` | Signer of a block |
149
+ | `native_totalSupply` | VET total supply |
150
+ | `native_txProvedWork` | PoW proved work of current tx |
151
+ | `native_txID` | Current transaction ID |
152
+ | `native_txBlockRef` | Current tx block reference |
153
+ | `native_txExpiration` | Current tx expiration |
154
+ | `native_txGasPayer` | Gas payer of current tx |
155
+ | `native_txClauseIndex` | Current clause index within multi-clause tx |
156
+ | `native_txClauseCount` | Total clause count of current tx |
157
+
158
+ ## Executor
159
+
160
+ **File**: `builtin/builtin.go` (binding only — `executor_test.go` exists)
161
+
162
+ 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()`.
163
+
164
+ ## Staker
165
+
166
+ **File**: `builtin/staker_native.go`, `builtin/staker/staker.go`
167
+
168
+ Introduced with GALACTICA. Manages PoS validator registration, staking, delegation, and rewards.
169
+
170
+ ### Architecture
171
+
172
+ The Staker contract delegates to sub-services:
173
+
174
+ | Sub-package | Purpose |
175
+ |-------------|---------|
176
+ | `staker/validation` | Validator registry — linked list of active/queued/exited validators |
177
+ | `staker/delegation` | Delegation records — delegators staking against validators |
178
+ | `staker/aggregation` | Per-validator aggregate stats (locked/pending VET + weight) |
179
+ | `staker/globalstats` | Global totals: locked, queued, withdrawable, cooldown |
180
+ | `staker/stakes` | Weighted stake calculation (stake × multiplier) |
181
+
182
+ ### Native Methods — Validation
183
+
184
+ | Method | Description |
185
+ |--------|-------------|
186
+ | `native_addValidation(validator, endorser, period, stake)` | Register a new validator (25M–600M VET) |
187
+ | `native_signalExit(validator, endorser)` | Signal intent to exit (calculates exit block) |
188
+ | `native_increaseStake(validator, endorser, amount)` | Increase active validator's stake |
189
+ | `native_decreaseStake(validator, endorser, amount)` | Decrease stake (must stay ≥ 25M VET) |
190
+ | `native_withdrawStake(validator, endorser)` | Withdraw after exit |
191
+ | `native_setBeneficiary(validator, endorser, beneficiary)` | Set reward recipient address |
192
+ | `native_getValidation(validator)` | Get validator info: endorser, locked/queued VET, weight, status, period, blocks |
193
+ | `native_getWithdrawable(validator)` | Get withdrawable amount |
194
+ | `native_firstActive` / `native_firstQueued` | Linked list traversal |
195
+ | `native_next(prev)` | Next validator in list |
196
+ | `native_getValidationsNum` | Count of active + queued validators |
197
+ | `native_getValidationTotals(validator)` | Total locked/queued/exiting stake + weight for a validator |
198
+
199
+ ### Native Methods — Delegation
200
+
201
+ | Method | Description |
202
+ |--------|-------------|
203
+ | `native_addDelegation(validator, stake, multiplier)` | Delegate VET to a validator |
204
+ | `native_signalDelegationExit(delegationID)` | Signal delegation exit |
205
+ | `native_withdrawDelegation(delegationID)` | Withdraw delegated stake |
206
+ | `native_getDelegation(delegationID)` | Get delegation info |
207
+ | `native_getDelegatorsRewards(validator, period)` | Accumulated delegator rewards |
208
+ | `native_getDelegatorContract` | Reads delegator contract address from Params |
209
+
210
+ ### Native Methods — Global
211
+
212
+ | Method | Description |
213
+ |--------|-------------|
214
+ | `native_totalStake` | Total locked VET and weight across all validators |
215
+ | `native_queuedStake` | Total queued VET |
216
+ | `native_issuance` | Current block reward issuance amount |
217
+ | `native_getControlSwitches` | Staker/stargate pause flags |
218
+
219
+ ### Staking Rules
220
+
221
+ | Rule | Value |
222
+ |------|-------|
223
+ | Min stake per validator | 25,000,000 VET |
224
+ | Max stake per validator | 600,000,000 VET (including delegations) |
225
+ | Staking periods | Low / Medium / High (governance-configurable) |
226
+ | Delegation multiplier | 1–N; affects weight calculation: `stake × multiplier` |
227
+ | PoS activation | ≥ 2/3 of `maxBlockProposers` queued → auto-activates at epoch boundary |
228
+ | Exit | Signal → wait for period end → exit block → withdraw |
229
+
230
+ ### Validator States
231
+
232
+ ```
233
+ StatusQueued → (transition when 2/3 threshold met) → StatusActive → (signalExit) → StatusExit
234
+ ```
235
+
236
+ - **Queued**: registered but not yet producing blocks
237
+ - **Active**: producing blocks, earning rewards, stake is locked
238
+ - **Exit**: waiting for/past exit block, stake can be withdrawn
239
+
240
+ ### Rewards
241
+
242
+ Post-GALACTICA, block rewards are distributed via `Energy.DistributeRewards()`:
243
+ - `validator-reward-percentage` (default 30%) goes to the block proposer's beneficiary
244
+ - Remaining goes to the delegator reward pool for that validator
245
+ - VTHO issuance is calculated using the `curve-factor` parameter
246
+
247
+ ### Transition Period (HAYABUSA)
248
+
249
+ During the HAYABUSA transition period:
250
+ - Authority nodes can register in the Staker contract (`AddValidation` requires existing authority listing)
251
+ - Queued VET counts toward endorsement checks in the Authority contract
252
+ - PoA remains active until ≥ 2/3 of maxBlockProposers have queued
253
+ - Once threshold is met, all queued validators activate and PoS takes over
254
+
255
+ ## How Native Calls Work
256
+
257
+ 1. When the EVM encounters a `CALL` to a built-in contract address, `FindNativeCall` in `builtin.go` matches the method selector
258
+ 2. If a native method is found, the Go implementation runs directly (no EVM bytecode execution)
259
+ 3. Native methods receive an `xenv.Environment` providing access to state, block context, gas metering, and event logging
260
+ 4. For older contracts (Authority, Energy, Params, Prototype, Extension), unused gas is returned to the caller
261
+ 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
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/consensus.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Consensus Mechanisms
2
+
3
+ Thor uses a hybrid consensus model that evolved through several forks:
4
+ **PoA v1** → **PoA v2** (VIP-214) → **BFT finality** (FINALITY fork) → **PoS** (HAYABUSA/GALACTICA).
5
+
6
+ ## Proof of Authority (PoA)
7
+
8
+ 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.
9
+
10
+ ### Endorsement Requirement
11
+
12
+ 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.
13
+
14
+ ### PoA v1 (Pre-VIP-214)
15
+
16
+ - **Packages**: `scheduler/poa_v1.go`, `consensus/poa_validator.go`
17
+ - Active authority nodes are collected from the `Authority` contract
18
+ - Proposer for each time slot determined by DPRP: `H(parentBlockNumber, blockTime)[:8] % len(actives)`
19
+ - `H` = Blake2b hash
20
+ - Each block time slot is `T` = 10 seconds apart
21
+ - If a scheduled proposer misses its slot, it gets deactivated; the producing proposer gets a score equal to the count of remaining active proposers
22
+ - No seed or VRF involved — deterministic from block number + time
23
+
24
+ ### PoA v2 (Post-VIP-214)
25
+
26
+ - **Packages**: `scheduler/poa_v2.go`
27
+ - Proposer list is **shuffled** using a VRF-derived seed
28
+ - Shuffle key: `Blake2b(seed, parentBlockNumber, proposerAddress)` — sorted to create a deterministic sequence
29
+ - Seed comes from the `Beta` output of a previous block's VRF proof (via `scheduler/seed.go`)
30
+ - Time slot assignment: proposer at index `(offset) % len(shuffled)` where offset is derived from elapsed slots
31
+ - Missed proposers are still deactivated; score = remaining active count
32
+
33
+ ### PoA → PoS: Key Differences
34
+
35
+ | Aspect | PoA v1 | PoA v2 | PoS |
36
+ |--------|--------|--------|-----|
37
+ | Proposer selection | DPRP hash | VRF-seeded shuffle | Weighted random sampling |
38
+ | Score model | Active count | Active count | Active weight / total weight × 10000 |
39
+ | Validator source | Authority contract | Authority contract | Staker contract (leader group) |
40
+ | Weight | Equal (1 per node) | Equal (1 per node) | Proportional to stake |
41
+
42
+ ## Proof of Stake (PoS) — HAYABUSA / GALACTICA
43
+
44
+ ### Transition to PoS
45
+
46
+ The transition is managed by `builtin/staker/transition.go`:
47
+
48
+ 1. After HAYABUSA fork, authority nodes can register in the Staker contract (requires existing authority listing during transition period)
49
+ 2. At each epoch boundary (every `EpochLength` blocks), `staker.SyncPOS()` checks if ≥ 2/3 of `maxBlockProposers` are queued in the Staker contract
50
+ 3. When threshold is met, queued validators are activated and PoS takes over proposer selection
51
+ 4. Once active, the Authority contract is no longer used for proposer selection
52
+
53
+ ### PoS Scheduler
54
+
55
+ - **Package**: `scheduler/pos.go`
56
+ - Uses **A-Res reservoir sampling** for weighted random proposer ordering:
57
+ - For each validator: `score = -ln(random) / weight`
58
+ - Sort by score ascending — lower score = higher priority
59
+ - `random` is from a ChaCha8 PRNG seeded with `Blake2b(vrfSeed, parentBlockNumber)`
60
+ - Higher stake → higher weight → statistically more likely to get earlier slots
61
+ - Time slot and missed-proposer logic identical to PoA v2
62
+
63
+ ### Validator Requirements
64
+
65
+ | Parameter | Value |
66
+ |-----------|-------|
67
+ | Min stake | 25,000,000 VET |
68
+ | Max stake | 600,000,000 VET |
69
+ | Staking periods | Low / Medium / High (governance-defined) |
70
+ | Endorser | Required (same address manages the validation) |
71
+ | Beneficiary | Optional; directs block rewards to a different address |
72
+
73
+ ### Validator Lifecycle
74
+
75
+ ```
76
+ AddValidation (queued)
77
+ → transition() activates when 2/3 threshold met
78
+ → active (producing blocks, earning rewards)
79
+ → SignalExit → ExitBlock calculated based on staking period
80
+ → exit status → WithdrawStake
81
+ ```
82
+
83
+ Validators can also: `IncreaseStake`, `DecreaseStake`, `SetBeneficiary`, `SetOnline`/offline.
84
+
85
+ ### Delegation
86
+
87
+ Delegators stake VET against an active or queued validator:
88
+ - `AddDelegation(validator, stake, multiplier)` — multiplier affects weight calculation
89
+ - `SignalDelegationExit` → waiting for period end → `WithdrawDelegation`
90
+ - Delegator rewards accumulate per-validator and per-staking-period
91
+
92
+ ## BFT Finality Engine
93
+
94
+ - **Package**: `bft/`
95
+ - Activated at the `FINALITY` fork
96
+ - Implements Casper-like justified/finalized checkpoint logic (described in VIP-220)
97
+ - **Epoch**: a fixed number of blocks (`EpochLength`)
98
+
99
+ ### Core Concepts
100
+
101
+ | Term | Meaning |
102
+ |------|---------|
103
+ | **Checkpoint** | First block of an epoch |
104
+ | **Quality** | Accumulated count of justified epochs |
105
+ | **Justified** | An epoch where >2/3 of validators (by count pre-HAYABUSA, by weight post-HAYABUSA) participated |
106
+ | **Committed** | An epoch where >2/3 voted COM (commit) |
107
+ | **Finalized** | A checkpoint whose quality is `current_quality - 1` after a committed epoch |
108
+ | **COM bit** | Block header flag — proposer votes to commit the current epoch's checkpoint |
109
+
110
+ ### Justification & Finality Flow
111
+
112
+ ```
113
+ Epoch N blocks produced
114
+ → at store point (last block of epoch): computeState()
115
+ → justifier collects votes from all blocks in the epoch
116
+ → if unique signers > 2/3 of maxBlockProposers → epoch is JUSTIFIED (quality++)
117
+ → if COM voters > 2/3 → epoch is COMMITTED
118
+ → if committed AND quality > 1 → checkpoint at quality-1 becomes FINALIZED
119
+ → finalized block ID persisted to DB
120
+ ```
121
+
122
+ ### Vote Safety (VIP-220)
123
+
124
+ `ShouldVote()` ensures a proposer never votes COM on conflicting checkpoints:
125
+ - Tracks past votes via `casts`
126
+ - Will not vote COM if a recent vote (within `quality ± 1`) conflicts with the current chain's justified checkpoint
127
+ - Prevents equivocation across forks
128
+
129
+ ### Pre-HAYABUSA vs Post-HAYABUSA BFT
130
+
131
+ - **Pre-HAYABUSA**: threshold = `maxBlockProposers * 2/3` (vote count)
132
+ - **Post-HAYABUSA**: threshold = `totalWeight * 2/3` (stake-weighted); each validator's vote carries its staking weight
133
+
134
+ ### Solo Mode
135
+
136
+ Solo uses a `soloMockedEngine` that simulates finality:
137
+ - Every epoch assumed committed
138
+ - `finalized = currentCheckpoint - 2 * EpochLength`
139
+ - `justified = currentCheckpoint - 1 * EpochLength`
140
+ - Enables pruner to work in solo mode
141
+
142
+ ## VRF (Verifiable Random Function)
143
+
144
+ - **Package**: `vrf/`
145
+ - Algorithm: ECVRF-SECP256K1-SHA256-TAI (suite string `0xfe`)
146
+ - Uses `github.com/vechain/go-ecvrf`
147
+ - `Prove(sk, alpha)` → `(beta, pi)` — beta is the random output, pi is the proof
148
+ - `Verify(pk, alpha, pi)` → `beta` — anyone can verify without the private key
149
+
150
+ ### Chained VRF in Blocks (Post-VIP-214)
151
+
152
+ - Block header contains `Alpha` (VRF input) and a VRF proof in the signature
153
+ - `Alpha` = parent block's `Beta` (VRF output), or parent's `StateRoot` for the initial value
154
+ - `Beta` is extracted from the block's complex signature
155
+ - The `Seeder` (`scheduler/seed.go`) uses Beta from a block one epoch behind as the seed for proposer shuffling
156
+
157
+ ## Fork History
158
+
159
+ | Fork | Block (Mainnet) | Key Changes |
160
+ |------|----------------|-------------|
161
+ | **VIP-191** | 3,337,300 | Fee delegation — transactions can designate a gas payer |
162
+ | **ETH_CONST** | 3,337,300 | Align gas constants with Ethereum |
163
+ | **BLOCKLIST** | 4,817,300 | Blocked addresses cannot originate or delegate transactions |
164
+ | **ETH_IST** | 9,254,300 | Ethereum Istanbul EVM opcodes |
165
+ | **VIP-214** | 10,653,500 | PoA v2: VRF-seeded proposer shuffling, complex signatures (65→162 bytes), chained VRF |
166
+ | **FINALITY** | 13,815,000 | BFT finality engine: justified/finalized checkpoints, COM voting, epoch-based quality tracking |
167
+ | **GALACTICA** | 22,084,200 | EIP-1559 base fee, typed transactions, Staker built-in contract, reward distribution changes |
168
+ | **HAYABUSA** | 23,414,400 | PoA-to-PoS transition period; stake-weighted BFT (weight replaces vote count); authority nodes can migrate to Staker contract |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/contributing.md ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to Thor
2
+
3
+ ## Prerequisites
4
+
5
+ - **Go 1.25+** (enforced by Makefile version check)
6
+ - `golangci-lint` — install from <https://golangci-lint.run/usage/install/>
7
+ - **Docker** — needed for Solidity compilation (`builtin/gen`) and license checks
8
+ - **GPG key** — all commits must be GPG-signed
9
+
10
+ ## Build System
11
+
12
+ | Target | Description |
13
+ |---|---|
14
+ | `make` / `make thor` | Build `bin/thor` (blockchain node) |
15
+ | `make disco` | Build `bin/disco` (discovery bootnode) |
16
+ | `make all` | Build both binaries |
17
+ | `make test` | Run unit tests with coverage |
18
+ | `make fuzz` | Fuzz test tx/block encoding (default 1 min per target) |
19
+ | `make test-coverage` | Tests with race detector + HTML coverage report |
20
+ | `make lint` | Run `golangci-lint` + `gopls/modernize` |
21
+ | `make lint-fix` | Auto-fix lint issues + regenerate builtins |
22
+ | `make generate` | Regenerate `builtin` package from Solidity sources |
23
+ | `make license-check` | Check license headers via Docker (Apache SkyWalking Eyes) |
24
+ | `make install-hooks` | Install pre-commit hook (private key detection) |
25
+ | `make clean` | Remove binaries and purge build/test caches |
26
+
27
+ Binaries are output to `bin/`.
28
+
29
+ Version strings are injected via `-ldflags` from `cmd/thor/VERSION` (currently `2.4.2`) and `cmd/disco/VERSION`.
30
+
31
+ ## Running the Node Locally
32
+
33
+ ```bash
34
+ make thor
35
+ bin/thor --network main # mainnet
36
+ bin/thor --network test # testnet
37
+ bin/thor solo # solo (dev) mode — instant blocks, all forks enabled at genesis
38
+ ```
39
+
40
+ Solo mode activates all forks at block 0 (`SoloFork` in `thor/fork_config.go`), making it ideal for local development.
41
+
42
+ ## Directory Organization
43
+
44
+ ```
45
+ cmd/
46
+ thor/ Main node binary (flags, solo mode, pruner, sync, p2p)
47
+ disco/ Bootnode discovery tool
48
+ api/ REST API layer (gorilla/mux)
49
+ accounts/ Account/contract endpoints
50
+ blocks/ Block query endpoints
51
+ transactions/ Tx submission/query
52
+ events/ Event log filtering
53
+ transfers/ Transfer log filtering
54
+ subscriptions/ WebSocket subscriptions
55
+ debug/ Debug/tracer endpoints
56
+ admin/ Admin endpoints
57
+ fees/ Fee delegation endpoints
58
+ node/ Node info endpoints
59
+ middleware/ HTTP middleware (metrics, logging)
60
+ restutil/ Shared REST utilities
61
+ doc/ OpenAPI spec
62
+ thor/ Core types (Address, Bytes32, ForkConfig)
63
+ tx/ Transaction model
64
+ block/ Block model
65
+ chain/ Chain repository (block storage, indexing)
66
+ state/ State trie access
67
+ runtime/ EVM execution runtime
68
+ vm/ EVM implementation (go-ethereum fork)
69
+ consensus/ Block validation / consensus rules
70
+ packer/ Block packing / proposal
71
+ scheduler/ Block scheduling
72
+ bft/ Byzantine fault tolerance (finality)
73
+ builtin/ Built-in smart contracts (native bindings)
74
+ gen/ Solidity sources + code generation
75
+ genesis/ Genesis block construction
76
+ logdb/ Event/transfer log database
77
+ muxdb/ Multiplexed database layer
78
+ trie/ Merkle Patricia trie
79
+ txpool/ Transaction pool
80
+ p2p/ Low-level P2P networking
81
+ p2psrv/ P2P server
82
+ comm/ P2P communication protocol
83
+ tracers/ EVM tracing (js, logger, native)
84
+ thorclient/ Go client library for thor API
85
+ metrics/ Prometheus metrics
86
+ test/ Test utilities
87
+ testchain/ In-memory chain for testing
88
+ testnode/ In-memory node for API testing
89
+ datagen/ Test data generators
90
+ bindcontract/ Contract binding helpers
91
+ eventcontract/ Test event contract
92
+ ```
93
+
94
+ ## Testing
95
+
96
+ Tests use standard `go test` and `github.com/stretchr/testify`.
97
+
98
+ ### Test utilities (`test/`)
99
+
100
+ | Package | Purpose |
101
+ |---|---|
102
+ | `testchain` | Spins up an in-memory chain with genesis, BFT engine, and block production helpers |
103
+ | `testnode` | Builds a full in-memory node with REST API for integration tests |
104
+ | `datagen` | Generates random addresses, hashes, bytes, and numbers for tests |
105
+ | `bindcontract` | Helpers for deploying and binding test contracts |
106
+ | `eventcontract` | Pre-built contract for event emission tests |
107
+
108
+ `testchain.Chain` provides `MintBlock()` / `MintTransactions()` to produce blocks programmatically without P2P.
109
+
110
+ ### Fuzz targets
111
+
112
+ Located in `tx/` and `block/` packages — test marshalling/unmarshalling roundtrips.
113
+
114
+ ## Code Style & Linting
115
+
116
+ ### Formatting
117
+
118
+ Enforced via `golangci-lint` formatters (`.golangci.yml`):
119
+
120
+ - `gofmt` (with simplify)
121
+ - `goimports` (local prefix: `github.com/vechain/thor`)
122
+ - `gofumpt`
123
+ - `golines` (max line length: 160)
124
+
125
+ ### Linters enabled
126
+
127
+ `bidichk`, `copyloopvar`, `durationcheck`, `gosec`, `govet`, `ineffassign`, `misspell`, `revive`, `staticcheck`, `unconvert`, `unused`, `whitespace`
128
+
129
+ Paths excluded from linting: `third_party`, `builtin`, `examples`, `p2p/*`.
130
+
131
+ ### Pre-commit hook
132
+
133
+ `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`.
134
+
135
+ ## CI Pipeline (Pull Requests)
136
+
137
+ PRs trigger these checks (`.github/workflows/on-pull-request.yaml`):
138
+
139
+ 1. **Unit tests** — `make test` with codecov upload
140
+ 2. **License check** — Apache SkyWalking Eyes header scan
141
+ 3. **Lint** — `golangci-lint` via `lint-go.yaml`
142
+ 4. **Go module check** — verifies `go.mod` / `go.sum` consistency
143
+ 5. **Workflow scan** — security scan of GitHub Actions workflows
144
+ 6. **Docker test suite** — integration tests via Docker
145
+ 7. **Rosetta tests** — Coinbase Rosetta API compliance
146
+
147
+ ## Adding a REST API Endpoint
148
+
149
+ Each API domain follows the same pattern in `api/`:
150
+
151
+ 1. **Create a package** under `api/<domain>/` (e.g., `api/fees/`)
152
+ 2. **Define the handler struct** with dependencies (repo, stater, etc.):
153
+
154
+ ```go
155
+ type Fees struct {
156
+ repo *chain.Repository
157
+ stater *state.Stater
158
+ }
159
+ func New(repo *chain.Repository, stater *state.Stater) *Fees { ... }
160
+ ```
161
+
162
+ 3. **Implement handler methods** returning `func(w http.ResponseWriter, req *http.Request) error`:
163
+
164
+ ```go
165
+ func (f *Fees) handleGetFee(w http.ResponseWriter, req *http.Request) error { ... }
166
+ ```
167
+
168
+ 4. **Add a `Mount` method** to register routes on a `mux.Router`:
169
+
170
+ ```go
171
+ func (f *Fees) Mount(root *mux.Router, pathPrefix string) {
172
+ sub := root.PathPrefix(pathPrefix).Subrouter()
173
+ sub.Path("/{id}").Methods(http.MethodGet).
174
+ Name("GET /fees/{id}").
175
+ HandlerFunc(restutil.WrapHandlerFunc(f.handleGetFee))
176
+ }
177
+ ```
178
+
179
+ 5. **Define request/response types** in `api/<domain>_types.go` (at the `api/` package level)
180
+ 6. **Wire it up** in the main API router by calling `Mount()`
181
+
182
+ Key conventions:
183
+
184
+ - Use `restutil.WrapHandlerFunc` to wrap handlers (handles error responses)
185
+ - Parse path params with `mux.Vars(req)`
186
+ - Parse query params / block revision via shared utilities in `api/restutil/`
187
+
188
+ ## Fork Configuration
189
+
190
+ Forks are defined in `thor/fork_config.go` as the `ForkConfig` struct:
191
+
192
+ ```go
193
+ type ForkConfig struct {
194
+ VIP191 uint32
195
+ ETH_CONST uint32
196
+ BLOCKLIST uint32
197
+ ETH_IST uint32
198
+ VIP214 uint32
199
+ FINALITY uint32
200
+ HAYABUSA uint32
201
+ GALACTICA uint32
202
+ }
203
+ ```
204
+
205
+ Each field is a **block number** at which the fork activates. `math.MaxUint32` means disabled.
206
+
207
+ To add a new fork:
208
+
209
+ 1. Add a new field to `ForkConfig`
210
+ 2. Set it to `math.MaxUint32` in `NoFork`
211
+ 3. Set it to `0` in `SoloFork` (enables immediately in dev mode)
212
+ 4. Add activation block numbers in the `forkConfigs` map for mainnet/testnet genesis IDs
213
+ 5. Update `String()` to include the new fork name
214
+ 6. Reference `forkConfig.YourFork` in consensus/runtime code to gate new behavior
215
+
216
+ Fork names follow VIP numbers (e.g., `VIP191`, `VIP214`) or codenames (e.g., `HAYABUSA`, `GALACTICA`).
217
+
218
+ ## Built-in Contracts
219
+
220
+ Built-in (native) contracts live in `builtin/`:
221
+
222
+ | Contract | File | Purpose |
223
+ |---|---|---|
224
+ | Authority | `authority_native.go` | Authority/validator management |
225
+ | Energy (VTHO) | `energy_native.go` | VTHO token operations |
226
+ | Params | `params_native.go` | On-chain governance parameters |
227
+ | Prototype | `prototype_native.go` | Account metadata/master |
228
+ | Extension | `extension_native.go` | Block/tx introspection helpers |
229
+ | Executor | (via Solidity) | On-chain governance execution |
230
+ | Staker | `staker_native.go` | PoS staking (Hayabusa+) |
231
+
232
+ ### Modifying built-in contracts
233
+
234
+ 1. Edit Solidity source in `builtin/gen/*.sol`
235
+ 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)
236
+ 3. Regenerate Go bindings: `make generate` (runs `go generate builtin/gen/gen.go`)
237
+ 4. Implement native call handlers in `builtin/*_native.go`
238
+ 5. Wire into `builtin/builtin.go` and `builtin/contract.go`
239
+
240
+ Compiled ABI/bytecode lives in `builtin/gen/compiled/` (embedded via `//go:embed`).
241
+
242
+ ## Replaced Dependencies
243
+
244
+ Two critical `replace` directives in `go.mod`:
245
+
246
+ | Original | Fork | Why |
247
+ |---|---|---|
248
+ | `github.com/ethereum/go-ethereum` | `github.com/vechain/go-ethereum` | Customized EVM, crypto, RLP — diverged significantly from upstream |
249
+ | `github.com/syndtr/goleveldb` | `github.com/vechain/goleveldb` | Custom patches for VeChain's storage layer |
250
+
251
+ When importing `go-ethereum` packages, the actual code comes from the VeChain fork. This affects `vm/`, `abi/`, `crypto/`, `rlp/`, `trie/` and related packages.
252
+
253
+ ## PR Requirements
254
+
255
+ 1. Fork repo → create feature branch (`feature/your-feature-name`)
256
+ 2. Keep branch up-to-date with `master`
257
+ 3. Run `make test` and `make lint` before pushing
258
+ 4. **All commits must be GPG-signed**
259
+ 5. PR targets `master` branch
260
+ 6. PR description must clearly explain changes and rationale
261
+ 7. Follow [Effective Go](https://golang.org/doc/effective_go) guidelines
262
+ 8. VIPs (protocol changes) require a separate proposal at [vechain/VIPs](https://github.com/vechain/VIPs) first
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-block-production.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Block Production Flow
2
+
3
+ How a new block is produced in VeChainThor, from scheduling through finality.
4
+
5
+ ## Overview
6
+
7
+ ```
8
+ scheduler/ → packer/ → runtime/ → consensus/ → bft/ → chain/
9
+ │ │ │ │ │ │
10
+ Schedule Assemble Execute Validate Vote Store
11
+ ```
12
+
13
+ ## Step 1: Scheduling — Who Proposes Next
14
+
15
+ **Package:** `scheduler/`, `packer/pos_scheduler.go`, `packer/poa_scheduler.go`
16
+
17
+ The node's `packerLoop` (in `cmd/thor/node/packer_loop.go`) continuously calls `Packer.Schedule()` to determine when this node should propose.
18
+
19
+ | Type | Scheduler | Selection Method |
20
+ |------|-----------|-----------------|
21
+ | PoA (pre-Galactica) | `PoASchedulerV1` / `PoASchedulerV2` | Round-robin from `Authority` candidates with endorsement balance check |
22
+ | PoS (post-Galactica) | `PoSScheduler` | Weighted random sampling (A-Res reservoir) from `Staker.LeaderGroup()` |
23
+
24
+ **Key types:**
25
+ - `scheduler.Scheduler` — interface: `Schedule(nowTime) → newBlockTime`, `IsTheTime()`, `Updates()`
26
+ - `scheduler.Proposer` — `{Address, Active, Weight}`
27
+ - `scheduler.Seeder` — generates deterministic VRF-based seeds per block
28
+
29
+ **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.
30
+
31
+ **Triggers next:** `Packer.Schedule()` returns a `*Flow` with the target block time.
32
+
33
+ ## Step 2: Packing — Assembling the Block
34
+
35
+ **Package:** `packer/`
36
+
37
+ `Packer.Schedule()` determines consensus mode (PoA vs PoS) by calling `Staker.SyncPOS()`, then delegates to `schedulePOS` or `schedulePOA`. Both return `(beneficiary, newBlockTime, score)`.
38
+
39
+ A `Flow` is created with a `runtime.Runtime` initialized with:
40
+
41
+ ```go
42
+ xenv.BlockContext{
43
+ Beneficiary, Signer, Number, Time,
44
+ GasLimit, TotalScore, BaseFee,
45
+ }
46
+ ```
47
+
48
+ **Transaction adoption** (`Flow.Adopt`):
49
+ 1. Check blocklist, chain tag, block ref, expiration
50
+ 2. Check gas capacity (`gasUsed + tx.Gas ≤ GasLimit`)
51
+ 3. Post-Galactica: validate `EffectiveGasPrice ≥ BaseFee` and priority fee
52
+ 4. Check tx not duplicate, dependency resolved
53
+ 5. Create state checkpoint → `runtime.ExecuteTransaction(tx)` → on error, revert
54
+ 6. Accumulate `gasUsed`, append to `txs` and `receipts`
55
+
56
+ The `packerLoop` calls `flow.Adopt(tx)` for each executable tx from the pool, stopping at `errGasLimitReached`.
57
+
58
+ **Key types:**
59
+ - `packer.Packer` — holds repo, stater, nodeMaster, beneficiary, forkConfig
60
+ - `packer.Flow` — accumulates txs/receipts, tracks gas, calls runtime
61
+
62
+ **Triggers next:** `Flow.Pack(privateKey, conflicts, shouldVote)` builds and signs the block.
63
+
64
+ ## Step 3: Runtime Execution
65
+
66
+ **Package:** `runtime/`
67
+
68
+ `Runtime.ExecuteTransaction` resolves the tx, buys gas (VTHO), then executes each clause sequentially.
69
+
70
+ **Per-clause execution:**
71
+ 1. `PrepareClause` creates a `statedb.StateDB` and EVM instance
72
+ 2. If `clause.To() == nil` → contract creation; else → `evm.Call`
73
+ 3. Collects `Output{Data, Events, Transfers, LeftOverGas, VMErr}`
74
+ 4. On VM error → revert all clauses to checkpoint, mark `receipt.Reverted = true`
75
+
76
+ **Gas payment:** `ResolvedTransaction.BuyGas` deducts VTHO from payer (delegator → sponsor → origin fallback).
77
+
78
+ **Reward calculation (post-Galactica):**
79
+ - `priorityFeePerGas = min(maxFeePerGas - baseFee, maxPriorityFeePerGas)`
80
+ - `receipt.Reward = priorityFeePerGas × gasUsed`
81
+ - Reward credited to `Beneficiary` via `Energy.Add`
82
+
83
+ **Key types:**
84
+ - `runtime.Runtime` — wraps EVM, chain, state, block context
85
+ - `runtime.ResolvedTransaction` — resolved origin, delegator, intrinsic gas, clauses
86
+ - `runtime.TransactionExecutor` — iterator over clauses with `HasNextClause/PrepareNext/Finalize`
87
+ - `tx.Receipt` — `{Type, Reverted, Outputs, GasUsed, GasPayer, Paid, Reward}`
88
+
89
+ ## Step 4: Consensus Validation
90
+
91
+ **Package:** `consensus/`
92
+
93
+ When receiving a block (not packing), `Consensus.Process()` validates it:
94
+
95
+ 1. **Header validation** (`validateBlockHeader`):
96
+ - Timestamp > parent, aligned to `BlockInterval`
97
+ - Not future (≤ now + BlockInterval)
98
+ - GasUsed ≤ GasLimit, valid gas limit delta
99
+ - TotalScore > parent
100
+ - Signature length (65 bytes pre-VIP214, complex sig post-VIP214)
101
+ - BaseFee matches `galactica.CalcBaseFee(parent)` post-Galactica
102
+
103
+ 2. **Proposer validation**:
104
+ - **PoA:** `validateAuthorityProposer` — checks signer is in Authority candidates, scheduled for this slot
105
+ - **PoS:** `validateStakingProposer` — checks signer is in `Staker.LeaderGroup()`, scheduled via `PoSScheduler`
106
+ - Both verify `TotalScore = parent.TotalScore + score`
107
+
108
+ 3. **Body validation** (`validateBlockBody`):
109
+ - `TxsRoot` matches merkle root of txs
110
+ - Each tx: valid origin, chain tag, block ref, expiration, features
111
+
112
+ 4. **Block verification** (`verifyBlock`):
113
+ - Re-execute all txs via `runtime.ExecuteTransaction`
114
+ - Verify `GasUsed`, `ReceiptsRoot`, `StateRoot` all match header
115
+ - Post-PoS: distribute rewards via `Energy.DistributeRewards`
116
+
117
+ **Key types:**
118
+ - `consensus.Consensus` — holds repo, stater, seeder, forkConfig, validatorsCache
119
+
120
+ ## Step 5: BFT Finality
121
+
122
+ **Package:** `bft/`
123
+
124
+ The `bft.Engine` implements VIP-220 finality (epoch-based voting).
125
+
126
+ **Concepts:**
127
+ - **Epoch:** `EpochLength` blocks (e.g., 100). Checkpoint = first block of epoch.
128
+ - **COM bit:** Block header flag indicating the proposer votes for current checkpoint.
129
+ - **Quality:** Count of epochs with sufficient votes. Stored at `storePoint` (last block of epoch).
130
+ - **Justified:** Checkpoint with quality ≥ threshold for current epoch.
131
+ - **Finalized:** When quality > 1, `findCheckpointByQuality(quality-1)` is finalized.
132
+
133
+ **Key operations:**
134
+ - `ShouldVote(parentID)` — packer checks before setting COM bit
135
+ - `CommitBlock(header, isPacking)` — saves quality at epoch end, updates finalized
136
+ - `Select(header)` — fork choice: prefer higher quality, then `BetterThan`
137
+ - `Accepts(parentID)` — rejects blocks not descending from finalized checkpoint
138
+
139
+ **Key types:**
140
+ - `bft.Committer` — interface for `Engine`
141
+ - `bft.Engine` — tracks casts (votes), finalized/justified checkpoints
142
+ - `bft.justifier` — per-epoch vote accumulator
143
+
144
+ ## Step 6: Chain Storage
145
+
146
+ **Package:** `chain/`
147
+
148
+ `Repository.AddBlock(block, receipts, conflicts, asBest)`:
149
+
150
+ 1. **Index block:** Update index trie (block number → block ID mapping)
151
+ 2. **Save block:**
152
+ - Header summary → `hdrStore`
153
+ - Tx blobs → `bodyStore`
154
+ - Receipt blobs → `bodyStore`
155
+ - Tx metadata (index, reverted) → `txIndexer`
156
+ - Chain head → `headStore`
157
+ 3. If `asBest`: update `bestBlockID` in `propStore`, broadcast via `tick.Signal`
158
+
159
+ **Key types:**
160
+ - `chain.Repository` — thread-safe block/tx/receipt storage over `muxdb.MuxDB`
161
+ - `chain.Chain` — linked chain view from genesis to a given head, backed by index trie
162
+ - `chain.BlockSummary` — `{Header, Txs []Bytes32, Size, Conflicts}`
163
+ - `chain.TxMeta` — `{BlockNum, BlockConflicts, Index, Reverted}`
164
+
165
+ ## End-to-End Sequence (Packing Path)
166
+
167
+ ```
168
+ 1. packerLoop waits for sync, then loops:
169
+ 2. Packer.Schedule(bestBlock, now) → Flow
170
+ 3. Wait until flow.When() - BlockInterval/2
171
+ 4. For each txPool.Executables(): flow.Adopt(tx)
172
+ 5. bft.ShouldVote() → shouldVote
173
+ 6. flow.Pack(privateKey, conflicts, shouldVote) → block, stage, receipts
174
+ 7. stage.Commit() → persist state trie
175
+ 8. repo.AddBlock(block, receipts) → persist to DB
176
+ 9. bft.CommitBlock(header, isPacking) → update finality
177
+ 10. comm.BroadcastBlock(block) → propagate to peers
178
+ ```
179
+
180
+ ## End-to-End Sequence (Receiving Path)
181
+
182
+ ```
183
+ 1. comm.Sync downloads blocks from peers → handleBlockStream
184
+ 2. node.processBlock(block):
185
+ 3. bft.Accepts(parentID) → reject if not on finalized branch
186
+ 4. consensus.Process(parent, block, now, conflicts) → stage, receipts
187
+ 5. bft.Select(header) → fork choice (becomeBest?)
188
+ 6. node.commitBlock: stage.Commit(), repo.AddBlock(), bft.CommitBlock()
189
+ 7. If becomeBest: processFork (re-add orphaned txs to pool)
190
+ ```
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-reward-distribution.md ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reward Distribution Flow
2
+
3
+ How block rewards are calculated and distributed to validators and delegators.
4
+
5
+ ## Overview
6
+
7
+ ```
8
+ runtime/ (per-tx reward) → energy/ (distribute) → staker/ (delegation split)
9
+ │ │ │
10
+ Calculate Credit VTHO Split validator/delegator
11
+ ```
12
+
13
+ ## Two Reward Eras
14
+
15
+ | Era | Condition | Mechanism |
16
+ |-----|-----------|-----------|
17
+ | Pre-Galactica | `blockNumber < forkConfig.GALACTICA` | `rewardRatio` × gas price per tx |
18
+ | Post-Galactica (PoS) | `blockNumber ≥ forkConfig.GALACTICA` | Priority fee per tx + block reward from staking curve |
19
+
20
+ ## Per-Transaction Reward (Both Eras)
21
+
22
+ **Package:** `runtime/` — in `PrepareTransaction().Finalize()`
23
+
24
+ ### Pre-Galactica (PoA)
25
+
26
+ ```go
27
+ rewardRatio := Params.Get(KeyRewardRatio) // governance parameter
28
+ overallGasPrice := gasPrice + baseGasPrice * provedWork / txGas
29
+ reward := gasUsed * overallGasPrice * rewardRatio / 1e18
30
+ ```
31
+
32
+ The reward is a **fraction** of gas cost, controlled by on-chain `RewardRatio` parameter. The remainder (gas cost minus reward) is burned.
33
+
34
+ ### Post-Galactica (PoS)
35
+
36
+ ```go
37
+ priorityFeePerGas := min(maxFeePerGas - baseFee, maxPriorityFeePerGas)
38
+ receipt.Reward = priorityFeePerGas * gasUsed
39
+ ```
40
+
41
+ Priority fee goes entirely to the block proposer. The `baseFee` portion is burned (never credited).
42
+
43
+ ### Crediting per-tx reward
44
+
45
+ In both eras, after computing `receipt.Reward`:
46
+
47
+ ```go
48
+ Energy.Native(state, blockTime).Add(beneficiary, receipt.Reward)
49
+ ```
50
+
51
+ This credits VTHO directly to the block's `Beneficiary` address.
52
+
53
+ ## Block-Level Reward Distribution (PoS Only)
54
+
55
+ **Package:** `builtin/energy/energy.go` — `DistributeRewards()`
56
+
57
+ Called at block finalization in two places:
58
+ - **Packing path:** `Flow.Pack()` in `packer/flow.go`
59
+ - **Validation path:** `verifyBlock()` in `consensus/validator.go`
60
+
61
+ Both call:
62
+
63
+ ```go
64
+ energy.DistributeRewards(beneficiary, signer, staker, blockNumber)
65
+ ```
66
+
67
+ ### Reward Calculation (`CalculateRewards`)
68
+
69
+ ```go
70
+ totalStaked, _ := staker.LockedStake() // in VET (not wei)
71
+ sqrtStake := sqrt(totalStaked) * 1e18 // convert to wei precision
72
+ curveFactor := Params.Get(KeyCurveFactor) // governance parameter
73
+ reward := curveFactor * sqrtStake / blocksPerYear
74
+ ```
75
+
76
+ The reward curve is sublinear (`reward ∝ √(totalStaked)`), incentivizing broad participation rather than stake concentration.
77
+
78
+ ### Validator vs Delegator Split
79
+
80
+ ```go
81
+ validatorRewardPerc := Params.Get(KeyValidatorRewardPercentage) // e.g., 30
82
+ hasDelegations := staker.HasDelegations(signer)
83
+
84
+ if hasDelegations && validatorRewardPerc < 100 {
85
+ proposerReward = reward * validatorRewardPerc / 100
86
+ delegationReward = reward - proposerReward
87
+
88
+ // Credit delegator reward to delegation contract address
89
+ delegatorAddr := Params.Get(KeyDelegatorContractAddress)
90
+ state.SetEnergy(delegatorAddr, existing + delegationReward)
91
+ staker.IncreaseDelegatorsReward(signer, delegationReward, blockNumber)
92
+ }
93
+
94
+ // Credit validator reward to beneficiary
95
+ state.SetEnergy(beneficiary, existing + proposerReward)
96
+ energy.addIssued(reward) // track total supply
97
+ ```
98
+
99
+ **Key points:**
100
+ - If the validator has **no delegations**, they receive 100% of the block reward
101
+ - If delegated, the split is governed by `KeyValidatorRewardPercentage` (on-chain parameter)
102
+ - Delegator rewards are held in a contract address and tracked per-validator by `staker.IncreaseDelegatorsReward`
103
+ - `addIssued(reward)` increases the tracked VTHO total supply (for `totalSupply()` queries)
104
+
105
+ ## VTHO (Energy) Generation
106
+
107
+ **Package:** `builtin/energy/`, `state/`
108
+
109
+ VTHO is generated in two ways:
110
+
111
+ ### 1. Growth from VET holdings (pre-Hayabusa)
112
+
113
+ Every VET holder earns VTHO proportional to their balance over time:
114
+
115
+ ```go
116
+ func (acc Account) CalcEnergy(blockTime, stopTime uint64) *big.Int {
117
+ // energy += balance * (min(blockTime, stopTime) - acc.BlockTime) * energyGrowthRate
118
+ }
119
+ ```
120
+
121
+ Rate: `5 × 10⁻⁸ VTHO per VET per second` (≈ 0.000432 VTHO/VET/day).
122
+
123
+ **Hayabusa fork** calls `Energy.StopEnergyGrowth()` which freezes growth at the fork block time. After this, VTHO only comes from block rewards.
124
+
125
+ ### 2. Block rewards (post-Galactica)
126
+
127
+ As described above — `DistributeRewards` mints new VTHO each block.
128
+
129
+ ## VTHO Burning
130
+
131
+ VTHO is burned in two places:
132
+
133
+ 1. **Gas payment:** `ResolvedTransaction.BuyGas` deducts `gas × effectiveGasPrice` VTHO from payer. After execution, unused gas is refunded. The net burn = `gasUsed × effectiveGasPrice - receipt.Reward`.
134
+
135
+ 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.
136
+
137
+ Burning is tracked via `Energy.totalAddSub` — `TotalBurned = TotalSub - TotalAdd`.
138
+
139
+ ## BaseFee Mechanism (EIP-1559 Adapted)
140
+
141
+ **Package:** `consensus/upgrade/galactica/`
142
+
143
+ ```go
144
+ func CalcBaseFee(parent, forkConfig) *big.Int {
145
+ parentGasTarget = parent.GasLimit * GasTargetPercentage / 100
146
+ if parentGasUsed > parentGasTarget:
147
+ baseFee increases (min delta = 1)
148
+ else:
149
+ baseFee decreases (floor = InitialBaseFee)
150
+ }
151
+ ```
152
+
153
+ Adjustment rate: `baseFeeChangeDenominator` (governance parameter, similar to Ethereum's 8).
154
+
155
+ ## Reward Flow Diagram
156
+
157
+ ```
158
+ ┌──────────────────────┐
159
+ │ Per-Tx Priority Fee │
160
+ │ (runtime/ Finalize) │
161
+ └──────────┬───────────┘
162
+ │
163
+ ┌──────────▼───────────┐
164
+ │ Block Staking Reward │
165
+ │ (energy/ Calculate) │
166
+ │ √(totalStaked)*curve │
167
+ └──────────┬───────────┘
168
+ │
169
+ ┌────────────────┴────────────────┐
170
+ │ │
171
+ ┌─────────▼─────────┐ ┌─────────▼─────────┐
172
+ │ Validator Share │ │ Delegator Share │
173
+ │ validatorRewardPerc│ │ (100 - validatorRP)│
174
+ │ → beneficiary VTHO│ │ → contract address │
175
+ └───────────────────┘ │ → per-validator │
176
+ │ reward tracking │
177
+ └───────────────────┘
178
+ ```
179
+
180
+ ## Key Parameters (On-Chain Governance)
181
+
182
+ | Parameter | Key | Purpose |
183
+ |-----------|-----|---------|
184
+ | `KeyRewardRatio` | Pre-Galactica reward fraction | Fraction of gas cost given as reward |
185
+ | `KeyCurveFactor` | Block reward curve multiplier | Controls block reward magnitude |
186
+ | `KeyValidatorRewardPercentage` | Validator share of block reward | Split between validator and delegators |
187
+ | `KeyLegacyTxBaseGasPrice` | Base gas price for legacy txs | Floor price for legacy transactions |
188
+ | `KeyDelegatorContractAddress` | Delegator reward holding address | Where delegator rewards accumulate |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-staking-delegation.md ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Staking and Delegation Flow
2
+
3
+ How validators stake, delegators participate, and the PoS transition works (Galactica upgrade).
4
+
5
+ ## Overview
6
+
7
+ ```
8
+ builtin/staker/ ← scheduler/ ← consensus/
9
+ │ │ │
10
+ Stake mgmt PoS scheduling Proposer validation
11
+ ```
12
+
13
+ ## Staker Contract Architecture
14
+
15
+ **Package:** `builtin/staker/`
16
+
17
+ The `Staker` struct composes four services:
18
+
19
+ | Service | Package | Responsibility |
20
+ |---------|---------|---------------|
21
+ | `validationService` | `staker/validation/` | Validator lifecycle (add, activate, exit, renew) |
22
+ | `delegationService` | `staker/delegation/` | Delegation CRUD and exit signaling |
23
+ | `aggregationService` | `staker/aggregation/` | Per-validator delegation totals |
24
+ | `globalStatsService` | `staker/globalstats/` | System-wide stake counters |
25
+
26
+ The contract is deployed at `builtin.Staker.Address` and uses native calls (Go code, not Solidity EVM).
27
+
28
+ ## Step 1: Becoming a Validator
29
+
30
+ ### Adding a Validation
31
+
32
+ `Staker.AddValidation(validator, endorser, period, stake)`
33
+
34
+ **Requirements:**
35
+ - Stake: `25M VET ≤ stake ≤ 600M VET` (`MinStakeVET` / `MaxStakeVET`)
36
+ - Validator address must not already exist
37
+ - Period must be one of: `LowStakingPeriod`, `MediumStakingPeriod`, `HighStakingPeriod`
38
+ - VET transferred to staker contract address
39
+
40
+ **State changes:**
41
+ 1. `validationService.Add()` — creates `validation.Validation` in queued list
42
+ 2. `globalStatsService.AddQueued(stake)` — increment global queued counter
43
+ 3. `ContractBalanceCheck()` — invariant: `locked + queued + withdrawable + cooldown = contract balance`
44
+
45
+ ### Validation States
46
+
47
+ ```
48
+ Queued → Active → [Exit signaled] → Exit
49
+ ```
50
+
51
+ | Status | Meaning |
52
+ |--------|---------|
53
+ | `StatusQueued` | Waiting for activation at next epoch boundary |
54
+ | `StatusActive` | In the leader group, eligible to produce blocks |
55
+ | `StatusExit` | Exited, stake withdrawable after cooldown |
56
+
57
+ ### Key Type: `validation.Validation`
58
+
59
+ ```go
60
+ type Validation struct {
61
+ Endorser thor.Address
62
+ LockedVET uint64 // currently locked stake
63
+ Weight uint64 // effective weight (may include multiplier)
64
+ QueuedVET uint64 // additional stake pending next period
65
+ PendingUnlockVET uint64 // stake pending unlock at period end
66
+ Status Status
67
+ Period uint32 // staking period in blocks
68
+ StartBlock uint32 // when activated
69
+ ExitBlock *uint32 // when exit takes effect (nil if not signaled)
70
+ OfflineBlock *uint32 // when marked offline (nil if online)
71
+ Beneficiary *thor.Address // reward recipient override
72
+ }
73
+ ```
74
+
75
+ ## Step 2: Activation — Queued to Active
76
+
77
+ **Package:** `builtin/staker/housekeep.go`
78
+
79
+ Activation happens during **epoch transitions** via `Staker.Housekeep(currentBlock)`, called by `Staker.SyncPOS()` at every block.
80
+
81
+ Housekeep runs when `currentBlock % EpochLength == 0`:
82
+
83
+ 1. **Eviction check** (every `EvictionCheckInterval`): validators offline for > `ValidatorEvictionThreshold` blocks get force-exited
84
+ 2. **Renewals** (`UpdateGroup`): active validators at period end get their weight recalculated, queued stake promoted to locked
85
+ 3. **Exits**: validators with `ExitBlock == currentBlock` are moved to exit status
86
+ 4. **Activations**: queued validators promoted to leader group up to `MaxBlockProposers`
87
+
88
+ ### Activation detail (`activateNextValidation`):
89
+
90
+ ```go
91
+ validator, validation := validationService.NextToActivate(maxLeaderGroupSize)
92
+ aggregationService.Renew(validator) // consolidate delegation totals
93
+ validationService.ActivateValidator(validator, ...) // set status=Active, startBlock
94
+ globalStatsService.ApplyRenewal(renewal) // move queued→locked in counters
95
+ ```
96
+
97
+ ## Step 3: Delegation
98
+
99
+ ### Adding a Delegation
100
+
101
+ `Staker.AddDelegation(validator, stake, multiplier, currentBlock) → delegationID`
102
+
103
+ **Requirements:**
104
+ - Validator must be `StatusQueued` or `StatusActive` (and not signaled exit)
105
+ - `stake > 0`, `multiplier > 0`
106
+ - Total TVL (validation + delegations) must not exceed `MaxStakeVET` (600M)
107
+
108
+ **State changes:**
109
+ 1. `delegationService.Add()` → assigns `delegationID`, stores delegation starting at next iteration
110
+ 2. `aggregationService.AddPendingVET()` → adds weighted stake to per-validator pending totals
111
+ 3. `globalStatsService.AddQueued(stake)` → increment system queued counter
112
+ 4. If validator is active: `validationService.AddToRenewalList()` → ensure renewal at next epoch
113
+
114
+ ### Key Type: `delegation.Delegation`
115
+
116
+ ```go
117
+ type Delegation struct {
118
+ Validation thor.Address // validator this delegates to
119
+ StartIteration uint32 // iteration when delegation activates
120
+ LastIteration *uint32 // iteration when delegation exits (nil = auto-renew)
121
+ Stake uint64 // staked VET amount
122
+ Multiplier uint8 // weight multiplier (longer lock = higher weight)
123
+ }
124
+ ```
125
+
126
+ ### Delegation Exit
127
+
128
+ `Staker.SignalDelegationExit(delegationID, currentBlock)`:
129
+ - Sets `LastIteration` to current iteration
130
+ - Updates aggregation to signal pending exit
131
+ - Delegation remains locked until iteration end, then becomes withdrawable
132
+
133
+ ### Delegation Withdrawal
134
+
135
+ `Staker.WithdrawDelegation(delegationID, currentBlock) → amount`:
136
+ - Only if not started yet, or ended (past LastIteration)
137
+ - Returns VET to the delegator
138
+ - Updates global stats (remove from queued or withdrawable)
139
+
140
+ ## Step 4: PoS Consensus Participation
141
+
142
+ ### Leader Group Formation
143
+
144
+ Active validators form the **leader group**, queried via `Staker.LeaderGroup()`:
145
+
146
+ ```go
147
+ type Leader struct {
148
+ Address thor.Address
149
+ Endorser thor.Address
150
+ Active bool // online status
151
+ Weight uint64 // stake weight for scheduling
152
+ Beneficiary *thor.Address // reward recipient
153
+ }
154
+ ```
155
+
156
+ ### PoS Scheduling
157
+
158
+ **Package:** `scheduler/pos.go`
159
+
160
+ `PoSScheduler` uses the leader group for weighted random block assignment:
161
+
162
+ 1. Seed from VRF chain: `Blake2b(VRF_beta, blockNumber)`
163
+ 2. Each validator gets priority: `-ln(random) / weight` (A-Res weighted reservoir sampling)
164
+ 3. Validators sorted by priority → deterministic slot order
165
+ 4. Schedule advances in `BlockInterval` steps
166
+
167
+ ### PoS Consensus Validation
168
+
169
+ **Package:** `consensus/pos_validator.go`
170
+
171
+ `validateStakingProposer(header, parent, staker)`:
172
+ 1. Get signer from header
173
+ 2. Get leader group (cached or from `staker.LeaderGroup()`)
174
+ 3. Build `PoSScheduler` with leader group and VRF seed
175
+ 4. Verify `sched.IsTheTime(header.Timestamp())` — signer is scheduled for this slot
176
+ 5. Compute `updates, score = sched.Updates(timestamp)` — mark skipped validators as inactive
177
+ 6. Verify `parent.TotalScore + score == header.TotalScore`
178
+
179
+ ### Online/Offline Tracking
180
+
181
+ `Staker.SetOnline(validator, blockNum, online)`:
182
+ - Called during scheduling — validators that miss their slot are marked `Active: false`
183
+ - Offline validators can be evicted after `ValidatorEvictionThreshold` blocks
184
+ - Coming back online (producing a block) resets the offline counter
185
+
186
+ ## Step 5: Reward Distribution for Stakers/Delegators
187
+
188
+ See `flow-reward-distribution.md` for full detail. Summary:
189
+
190
+ 1. Block reward calculated: `curveFactor × √(totalStaked) / blocksPerYear`
191
+ 2. If validator has delegations: split by `ValidatorRewardPercentage`
192
+ 3. Validator share → beneficiary VTHO balance
193
+ 4. Delegator share → delegation contract address, tracked per-validator via `IncreaseDelegatorsReward`
194
+
195
+ ## Step 6: Unstaking and Cooldown
196
+
197
+ ### Validator Exit
198
+
199
+ ```
200
+ SignalExit(validator, endorser, currentBlock)
201
+ → sets ExitBlock (at next period boundary)
202
+ → at ExitBlock epoch: Housekeep moves to StatusExit
203
+
204
+ WithdrawStake(validator, endorser, currentBlock)
205
+ → returns locked + queued + cooldown VET
206
+ → updates global stats
207
+ ```
208
+
209
+ ### Cooldown Period
210
+
211
+ When a validator exits, their stake may go through a cooldown period before being withdrawable. The `globalStatsService` tracks three counters that reflect the lifecycle:
212
+
213
+ | Counter | Meaning |
214
+ |---------|---------|
215
+ | `queued` | Stake waiting to become active |
216
+ | `locked` | Actively staked and earning rewards |
217
+ | `withdrawable` | Exited and available for withdrawal |
218
+ | `cooldown` | Exited but still in cooldown period |
219
+
220
+ ### Stake Increase/Decrease (Active Validators)
221
+
222
+ - `IncreaseStake`: adds to `QueuedVET` (takes effect next period)
223
+ - `DecreaseStake`: reduces `LockedVET - PendingUnlockVET` (next period)
224
+ - Both require endorser authorization and add validator to renewal list
225
+
226
+ ## PoA → PoS Transition
227
+
228
+ **Package:** `builtin/staker/`, `consensus/upgrade/galactica/`
229
+
230
+ The transition is managed by `Staker.SyncPOS()`, called at every block:
231
+
232
+ 1. **Hayabusa fork:** Staker contract deployed, energy growth stopped
233
+ 2. **Transition period:** Authorities can migrate to staker contract. Authority endorsement checked via `TransitionPeriodBalanceCheck` which accepts both PoA endorsement and staker contract balance
234
+ 3. **Galactica fork:** BaseFee activated, `DynamicFee` tx type enabled, Shanghai EVM opcodes
235
+ 4. **PoS activation:** When enough validators have staked, `SyncPOS` returns `Active: true` and scheduling switches from PoA to PoS
236
+
237
+ ### Contract Balance Invariant
238
+
239
+ `ContractBalanceCheck(pendingWithdraw)` is called after every state-changing operation:
240
+
241
+ ```
242
+ locked + queued + withdrawable + cooldown + pendingWithdraw == contract VET balance
243
+ == effectiveVET (slot 0)
244
+ ```
245
+
246
+ Any mismatch is a consensus-level error.
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-sync.md ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chain Synchronization Flow
2
+
3
+ How a node discovers peers, downloads blocks, validates them, and handles forks.
4
+
5
+ ## Overview
6
+
7
+ ```
8
+ p2p/p2psrv/ → comm/ → consensus/ → chain/ → bft/
9
+ │ │ │ │ │
10
+ Discover Download Validate Store Finalize
11
+ ```
12
+
13
+ ## Step 1: Peer Discovery and Connection
14
+
15
+ **Package:** `p2p/`, `p2psrv/`
16
+
17
+ The P2P layer uses a devp2p-compatible stack with Kademlia-based discovery (discv5).
18
+
19
+ **Discovery topic:** `thor1@<last8bytes_of_genesisID>` — ensures peers are on the same network.
20
+
21
+ **Handshake** (`Communicator.runPeer`):
22
+ 1. 5-second timeout for status exchange
23
+ 2. Verify `GenesisBlockID` matches
24
+ 3. Verify system clock diff ≤ `2 × BlockInterval`
25
+ 4. Exchange `{BestBlockID, TotalScore, SysTimestamp}`
26
+ 5. Add to `PeerSet`, track head block and total score
27
+
28
+ **Key types:**
29
+ - `comm.Communicator` — orchestrates sync, tx relay, block announcements
30
+ - `comm.Peer` — wraps `p2p.Peer` with block/tx knowledge tracking
31
+ - `comm.PeerSet` — thread-safe peer collection with filtering
32
+
33
+ ## Step 2: Initial Sync
34
+
35
+ **Package:** `comm/communicator.go`, `comm/sync.go`
36
+
37
+ `Communicator.Sync()` runs a timer-based sync loop:
38
+
39
+ ```
40
+ 1. Find peer with TotalScore ≥ our best block's TotalScore
41
+ 2. download(ctx, repo, peer, headNum, handler) → stream blocks
42
+ 3. Repeat until synced (best block time + BlockInterval ≥ now, or >2 sync rounds)
43
+ 4. Close syncedCh → triggers packer loop and tx sync
44
+ ```
45
+
46
+ ### Download Pipeline (Three-Stage)
47
+
48
+ ```
49
+ Stage 1: fetchRawBlockBatches → rawBatches channel (cap 10)
50
+ Stage 2: decodeAndWarmupBatches → warmedUp channel (cap 2048)
51
+ Stage 3: handler (processBlock) → commit to chain
52
+ ```
53
+
54
+ **Stage 1** — fetches raw RLP-encoded blocks from peer via `proto.GetBlocksFromNumber`:
55
+ - Requests blocks starting from `ancestor + 1`
56
+ - Batches of raw bytes sent to channel
57
+ - Stops when peer returns empty result
58
+
59
+ **Stage 2** — decodes and pre-warms caches in parallel:
60
+ - RLP decode each block
61
+ - Verify block number sequence
62
+ - Parallel cache warm-up: `header.ID()`, `header.Beta()`, `tx.ID()`, `tx.IntrinsicGas()`, `tx.Delegator()`
63
+ - Throttling: inserts nil blocks when buffer > 10% full to reduce memory pressure
64
+
65
+ **Stage 3** — `node.handleBlockStream` processes each block through `processBlock`
66
+
67
+ ### Common Ancestor Discovery
68
+
69
+ `findCommonAncestor(ctx, repo, peer, headNum)`:
70
+
71
+ 1. **Fast seek:** Exponential backward scan (1, 2, 4, 8, ... blocks back) using `proto.GetBlockIDByNumber`
72
+ 2. **Binary search:** Between fast-seek result and head, find exact fork point
73
+ 3. Returns the highest block number both nodes agree on
74
+
75
+ ## Step 3: Block Processing During Sync
76
+
77
+ **Package:** `cmd/thor/node/block_exec.go`
78
+
79
+ `Node.processBlock(block, stats)`:
80
+
81
+ 1. **Guard processing:** Lock + conflict detection
82
+ - If `blockNum > maxBlockNum + 1` → `errBlockTemporaryUnprocessable`
83
+ - Otherwise, count existing blocks at same height (`ScanConflicts`)
84
+
85
+ 2. **BFT acceptance:** `bft.Accepts(parentID)` — reject if parent not on finalized branch
86
+
87
+ 3. **Consensus processing:** `consensus.Process(parentSummary, block, now, conflicts)` → `stage, receipts`
88
+ - Full header, proposer, body, and execution validation (see block production flow)
89
+
90
+ 4. **Fork choice:**
91
+ - Post-FINALITY: `bft.Select(header)` — quality-based selection
92
+ - Pre-FINALITY: `header.BetterThan(prevBest)` — total score comparison
93
+
94
+ 5. **Commit:** `commitBlock(ctx)`:
95
+ - Write logs to `logdb` (if becoming best and logs enabled)
96
+ - `stage.Commit()` — persist state trie
97
+ - `repo.AddBlock(block, receipts, conflicts, becomeBest)`
98
+ - `bft.CommitBlock(header, isPacking=false)`
99
+ - If becoming best: `processFork` to re-add orphaned txs
100
+
101
+ ### Error Handling
102
+
103
+ | Error | Action |
104
+ |-------|--------|
105
+ | `errKnownBlock` | Ignore (already stored) |
106
+ | `errFutureBlock` | Queue (block timestamp too far ahead) |
107
+ | `errParentMissing` | Queue (parent not yet received) |
108
+ | `errBlockTemporaryUnprocessable` | Queue (block number too far ahead) |
109
+ | `errBFTRejected` | Discard (conflicts with finalized checkpoint) |
110
+ | Consensus critical error | Log error, discard block |
111
+
112
+ ## Step 4: Steady-State Block Propagation
113
+
114
+ **Package:** `comm/communicator.go`, `comm/announcement_loop.go`
115
+
116
+ Once synced, new blocks arrive via two mechanisms:
117
+
118
+ ### Direct Block Push
119
+
120
+ Peers call `proto.NotifyNewBlock(peer, block)` — sends full block to √N random peers:
121
+
122
+ ```go
123
+ p := int(math.Sqrt(float64(len(peers))))
124
+ toPropagate := peers[:p] // send full block
125
+ toAnnounce := peers[p:] // send just block ID
126
+ ```
127
+
128
+ ### Block ID Announcement
129
+
130
+ Remaining peers receive just the block ID via `proto.NotifyNewBlockID`. The announcement loop processes these:
131
+
132
+ 1. Receive announcement with `{blockID, senderPeer}`
133
+ 2. If block unknown: fetch from peer via `proto.GetBlockByID`
134
+ 3. Process via `processBlock`
135
+ 4. If accepted as trunk: broadcast to our peers
136
+
137
+ ### Transaction Propagation
138
+
139
+ **Package:** `comm/txs_loop.go`
140
+
141
+ - After sync completes: `syncTxs(peer)` — bulk fetch txs from connected peer
142
+ - Ongoing: `txFeed` subscription relays new executable txs to peers
143
+ - Peer tracking: `peer.MarkTransaction(hash)` prevents duplicate sends
144
+
145
+ ## Step 5: Fork Handling
146
+
147
+ ### Fork Detection
148
+
149
+ Forks are detected when `processBlock` finds the new block becomes best but the previous best was at the same height on a different branch.
150
+
151
+ ### Fork Resolution
152
+
153
+ `Node.processFork(newBlock, oldBestBlockID)`:
154
+
155
+ ```go
156
+ oldTrunk := repo.NewChain(oldBestBlockID)
157
+ newTrunk := repo.NewChain(newBlock.ParentID())
158
+ sideIDs := oldTrunk.Exclude(newTrunk) // blocks on old branch not on new
159
+
160
+ for _, id := range sideIDs {
161
+ block := repo.GetBlock(id)
162
+ for _, tx := range block.Transactions() {
163
+ txPool.Add(tx) // re-add orphaned txs to pool
164
+ }
165
+ }
166
+ ```
167
+
168
+ The `Chain.Exclude(other)` method walks backwards from the chain head, finding blocks present in one chain but not the other.
169
+
170
+ ### Log Rewriting on Fork
171
+
172
+ ```go
173
+ oldBranch := oldTrunk.Exclude(newTrunk)
174
+ if len(oldBranch) > 0 {
175
+ logDB.Writer.Truncate(forkPoint) // remove old branch logs
176
+ }
177
+ newBranch := newTrunk.Exclude(oldTrunk)
178
+ for _, id := range newBranch {
179
+ logDB.Writer.Write(block, receipts) // write new branch logs
180
+ }
181
+ ```
182
+
183
+ ### BFT Finality and Fork Prevention
184
+
185
+ Post-FINALITY fork, the BFT engine prevents deep reorgs:
186
+
187
+ - `bft.Accepts(parentID)` rejects blocks whose parent is not a descendant of the finalized checkpoint
188
+ - `bft.Select(header)` prefers higher quality (more epoch votes) over total score
189
+ - Once a checkpoint is finalized, all blocks not descending from it are permanently rejected
190
+
191
+ ## Node Startup Sequence
192
+
193
+ **Package:** `cmd/thor/node/node.go`
194
+
195
+ ```go
196
+ func (n *Node) Run(ctx context.Context) error {
197
+ maxBlockNum := repo.GetMaxBlockNum()
198
+ txStash := newTxStash(db, 1000)
199
+
200
+ // Four concurrent goroutines:
201
+ go n.comm.Sync(ctx, n.handleBlockStream) // sync + block processing
202
+ go n.houseKeeping(ctx) // periodic maintenance
203
+ go n.txStashLoop(ctx, txStash) // persist non-executable txs
204
+ go n.packerLoop(ctx) // block production (waits for sync)
205
+ }
206
+ ```
207
+
208
+ The `packerLoop` blocks on `comm.Synced()` channel before starting block production.
209
+
210
+ ## Protocol Messages
211
+
212
+ **Package:** `comm/proto/`
213
+
214
+ | Message | Direction | Purpose |
215
+ |---------|-----------|---------|
216
+ | `GetStatus` | Request | Exchange genesis ID, best block, total score |
217
+ | `GetBlocksFromNumber` | Request | Batch download blocks for sync |
218
+ | `GetBlockIDByNumber` | Request | Common ancestor discovery |
219
+ | `GetBlockByID` | Request | Fetch single block |
220
+ | `NotifyNewBlock` | Push | Propagate full block |
221
+ | `NotifyNewBlockID` | Push | Announce new block (lightweight) |
222
+ | `GetTxs` | Request | Bulk tx sync after initial sync |
223
+ | `NotifyNewTx` | Push | Relay new executable transaction |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/flow-transaction-lifecycle.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transaction Lifecycle Flow
2
+
3
+ End-to-end journey of a transaction from submission to on-chain finality.
4
+
5
+ ## Overview
6
+
7
+ ```
8
+ API/P2P → txpool/ → packer/ → runtime/ → chain/ → logdb/
9
+ │ │ │ │ │ │
10
+ Receive Validate Select Execute Store Index logs
11
+ ```
12
+
13
+ ## Step 1: Transaction Receipt
14
+
15
+ Transactions enter the node through two paths:
16
+
17
+ | Entry Point | Package | Method |
18
+ |-------------|---------|--------|
19
+ | REST API `POST /transactions` | `api/transactions/` | `TxPool.AddLocal(tx)` |
20
+ | P2P propagation | `comm/handle_rpc.go` | `TxPool.Add(tx)` or `TxPool.StrictlyAdd(tx)` |
21
+ | Sync from peer | `comm/sync.go` | `TxPool.StrictlyAdd(tx)` |
22
+
23
+ ## Step 2: Transaction Types
24
+
25
+ **Package:** `tx/`
26
+
27
+ Two transaction types (starting from Galactica fork):
28
+
29
+ | Field | `TypeLegacy` (0x00) | `TypeDynamicFee` (0x51) |
30
+ |-------|---------------------|------------------------|
31
+ | Gas pricing | `GasPriceCoef` (0–255) over `BaseGasPrice` | `MaxFeePerGas` + `MaxPriorityFeePerGas` |
32
+ | Encoding | RLP list | Type-prefix + RLP |
33
+ | Work proofs | `ProvedWork` for priority boost | Not applicable |
34
+
35
+ **Common fields** (both types):
36
+ - `ChainTag` — last byte of genesis ID
37
+ - `BlockRef` — first 8 bytes of a recent block hash (establishes tx validity window)
38
+ - `Expiration` — valid from `BlockRef.Number` to `BlockRef.Number + Expiration`
39
+ - `Clauses` — array of `{To, Value, Data}` (multi-clause model)
40
+ - `Gas` — max gas
41
+ - `DependsOn` — optional tx dependency
42
+ - `Nonce` — replay protection (not sequential like Ethereum)
43
+ - `Reserved` — feature flags (e.g., `DelegationFeature` for VIP-191)
44
+
45
+ **Key types:**
46
+ - `tx.Transaction` — immutable, caches signingHash/origin/id/intrinsicGas
47
+ - `tx.Clause` — `{To *Address, Value *big.Int, Data []byte}`
48
+ - `tx.BlockRef` — 8-byte block reference
49
+ - `tx.Features` — bit flags (delegation support)
50
+
51
+ **ID calculation:** `tx.ID = Blake2b(signingHash, origin)` — unique per sender.
52
+
53
+ ## Step 3: TxPool Validation and Storage
54
+
55
+ **Package:** `txpool/`
56
+
57
+ `TxPool.add()` performs staged validation:
58
+
59
+ ### Static validation (`validateTxBasics`)
60
+ 1. Signature low-S check (`EnforceSignatureLowS`)
61
+ 2. Chain tag matches `repo.ChainTag()`
62
+ 3. Size ≤ `MaxTxSize` (64 KB)
63
+
64
+ ### Blocklist check
65
+ - Origin and delegator checked against both hardcoded blocklist and fetched blocklist
66
+
67
+ ### Resolution
68
+ `ResolveTx(tx)` → `TxObject` with computed `origin`, `priorityGasPrice`
69
+
70
+ ### Executability check (when chain is synced)
71
+ `TxObject.Executable()` verifies against current state:
72
+ - Tx not already on chain
73
+ - Block ref in valid range, not expired
74
+ - Dependencies resolved (not reverted)
75
+ - Sufficient VTHO balance for gas cost
76
+ - Post-Galactica: effective gas price ≥ baseFee
77
+
78
+ ### Pool management
79
+ - Pool limit: `Options.Limit` (default ~10k)
80
+ - Per-account limit: `Options.LimitPerAccount`
81
+ - Non-executable cap: 20% of pool limit
82
+ - Priority eviction: sorted by `priorityGasPrice` descending
83
+
84
+ ### Housekeeping (every second)
85
+ The `wash()` routine:
86
+ 1. Removes expired, settled, blocked, energy-depleted txs
87
+ 2. Recalculates `priorityGasPrice` when baseFee changes
88
+ 3. Produces sorted `Executables()` list for the packer
89
+
90
+ **Key types:**
91
+ - `txpool.TxPool` — `{all *txObjectMap, executables atomic.Value}`
92
+ - `txpool.TxObject` — wraps `tx.Transaction` with `executable bool`, `priorityGasPrice`
93
+ - `txpool.TxEvent` — `{Tx, Executable *bool}` — published to subscribers (comm layer for P2P broadcast)
94
+
95
+ ## Step 4: Transaction Selection for Block
96
+
97
+ **Package:** `packer/`
98
+
99
+ In `proposeAndCommit` (node packer loop):
100
+
101
+ ```go
102
+ txs := n.txPool.Executables() // sorted by priority gas price desc
103
+ for _, tx := range txs {
104
+ err := flow.Adopt(tx)
105
+ if packer.IsGasLimitReached(err) { break }
106
+ if packer.IsTxNotAdoptableNow(err) { continue }
107
+ // bad tx → mark for removal
108
+ }
109
+ ```
110
+
111
+ `Flow.Adopt` performs final checks (see block production flow) and calls `runtime.ExecuteTransaction`.
112
+
113
+ Error categories:
114
+ - `badTxError` — permanent rejection (wrong chain tag, expired, blocked origin)
115
+ - `errTxNotAdoptableNow` — temporary (future block ref, gas too high for remaining space)
116
+ - `errGasLimitReached` — block full, stop adopting
117
+ - `errKnownTx` — already on chain
118
+
119
+ ## Step 5: Clause Execution
120
+
121
+ **Package:** `runtime/`
122
+
123
+ VeChain's multi-clause model executes multiple operations atomically in one tx.
124
+
125
+ ### Execution flow per transaction
126
+
127
+ ```
128
+ ResolveTransaction(tx) → ResolvedTransaction
129
+ └─ BuyGas(state, blockTime, baseFee) → deduct VTHO from payer
130
+ └─ For each clause:
131
+ └─ PrepareClause → EVM.Call or EVM.Create
132
+ └─ Output{Events, Transfers, LeftOverGas, VMErr}
133
+ └─ Finalize → Receipt
134
+ ```
135
+
136
+ ### Gas payer resolution order (BuyGas)
137
+ 1. **Delegator** (VIP-191) — if tx has delegation feature + delegator signature
138
+ 2. **Sponsor** — if all clauses share same `To` and user has credit via `Prototype.Bind`
139
+ 3. **Contract `To`** — if sponsor insufficient but user has credit
140
+ 4. **Origin** — fallback
141
+
142
+ ### Clause execution detail
143
+ - Each clause gets its own EVM instance via `PrepareClause`
144
+ - Contract creation: `clause.To == nil` → `EVM.Create`
145
+ - Native contract calls intercepted via `InterceptContractCall` (builtin contracts)
146
+ - On any clause VM error: **all clauses revert** to checkpoint
147
+
148
+ ### Receipt generation
149
+ ```go
150
+ Receipt{
151
+ Type: tx.Type(),
152
+ Reverted: reverted,
153
+ Outputs: []{Events, Transfers}, // nil if reverted
154
+ GasUsed: tx.Gas() - leftOverGas,
155
+ GasPayer: payer,
156
+ Paid: gasUsed * effectiveGasPrice,
157
+ Reward: priorityFeePerGas * gasUsed, // post-Galactica
158
+ }
159
+ ```
160
+
161
+ ## Step 6: Storage and Indexing
162
+
163
+ ### Block storage (`chain/`)
164
+ When the block is committed via `Repository.AddBlock`:
165
+ - Tx blobs → `bodyStore` keyed by `(blockNum, conflicts, index, txFlag)`
166
+ - Receipt blobs → `bodyStore` keyed by `(blockNum, conflicts, index, receiptFlag)`
167
+ - Tx metadata → `txIndexer` keyed by `txID + varint(blockNum) + varint(conflicts)`
168
+ - Filter key → `txIndexer` keyed by first 8 bytes of txID (bloom-like fast lookup)
169
+
170
+ ### Log indexing (`logdb/`)
171
+ `LogDB` (SQLite) indexes events and transfers for query:
172
+ - **Events table:** `blockNum, txIndex, clauseIndex, address, topic0–4, data`
173
+ - **Transfers table:** `blockNum, txIndex, clauseIndex, sender, recipient, amount`
174
+ - Written by `node.writeLogs()` → `logdb.Writer.Write(block, receipts)`
175
+ - On fork: `Writer.Truncate(forkPoint)` then re-write new branch
176
+
177
+ ## Step 7: Query
178
+
179
+ Transactions become queryable via:
180
+
181
+ | Endpoint | Source | Key |
182
+ |----------|--------|-----|
183
+ | `GET /transactions/{id}` | `chain.Chain.GetTransaction(id)` | txID → txMeta → tx blob |
184
+ | `GET /transactions/{id}/receipt` | `chain.Chain.GetTransactionReceipt(id)` | txID → txMeta → receipt blob |
185
+ | `POST /logs/event` | `logdb.LogDB.FilterEvents()` | SQLite query with address/topic filters |
186
+ | `POST /logs/transfer` | `logdb.LogDB.FilterTransfers()` | SQLite query with sender/recipient filters |
187
+
188
+ ## Error Paths Summary
189
+
190
+ | Stage | Error | Result |
191
+ |-------|-------|--------|
192
+ | TxPool add | Bad signature, wrong chain tag, too large | `badTxError` — rejected |
193
+ | TxPool add | Pool full, non-executable | `txRejectedError` — rejected |
194
+ | TxPool wash | Expired, settled, insufficient energy | Removed from pool |
195
+ | Packer adopt | Expired, duplicate, gas limit | Skip or stop packing |
196
+ | Runtime execute | Intrinsic gas > provided gas | Tx not included |
197
+ | Runtime clause | VM revert/error | Receipt with `Reverted: true`, all clauses rolled back |
198
+ | Consensus verify | Mismatched receipts root, state root | Block rejected |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/p2p.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # P2P Networking
2
+
3
+ Thor uses Ethereum-derived devp2p networking: **discv5** for peer discovery, **RLPx** for encrypted connections,
4
+ and a custom `thor/1` protocol for block and transaction propagation. Default P2P port: **11235**.
5
+
6
+ ## Discovery — discv5
7
+
8
+ Located in `p2p/discv5/`. Ethereum-style v5 topic discovery over UDP.
9
+
10
+ - Kademlia-like DHT with XOR distance metric
11
+ - Topic-based: nodes register/search by `thor1@<genesisID[24:]>`
12
+ - 257 buckets, 16 nodes per bucket, concurrency factor (alpha) = 3
13
+
14
+ ### UDP Packet Types
15
+
16
+ | Packet | Purpose |
17
+ |--------|---------|
18
+ | `ping` / `pong` | Liveness check |
19
+ | `findnode` / `neighbors` | Node lookup |
20
+ | `findnodeHash` | v5 lookup by hash |
21
+ | `topicRegister` / `topicQuery` / `topicNodes` | Topic discovery |
22
+
23
+ ### Key Constants
24
+
25
+ | Constant | Value |
26
+ |----------|-------|
27
+ | Protocol version | 4 |
28
+ | Response timeout | 500ms |
29
+ | Packet expiration | 20s |
30
+ | Max packet size | 1280 bytes |
31
+ | Max neighbors per response | ~12 |
32
+ | Max findnode failures | 5 |
33
+ | Seed count | 30 |
34
+ | Seed max age | 5 days |
35
+ | Bucket refresh interval | 1 min |
36
+ | Auto-refresh interval | 1 hour |
37
+
38
+ ## ENR (Ethereum Node Records)
39
+
40
+ Located in `p2p/enr/`. EIP-778 style records, max 300 bytes.
41
+
42
+ | Entry Key | Type | Purpose |
43
+ |-----------|------|---------|
44
+ | `id` | `"v4"` | Identity scheme |
45
+ | `secp256k1` | compressed pubkey | Node identity |
46
+ | `ip` | IPv4/IPv6 | Network address |
47
+ | `tcp` | uint16 | TCP port |
48
+ | `udp` | uint16 | UDP discovery port |
49
+
50
+ Signing uses `secp256k1-keccak` identity scheme (Keccak256 of RLP-encoded record).
51
+
52
+ ## NAT Traversal
53
+
54
+ Located in `p2p/nat/`. Interface for port mapping.
55
+
56
+ | Value | Mechanism |
57
+ |-------|-----------|
58
+ | `none` / `off` / `""` | No mapping |
59
+ | `any` / `auto` / `on` | Auto-detect (UPnP or NAT-PMP) |
60
+ | `upnp` | UPnP |
61
+ | `pmp` / `natpmp` | NAT-PMP |
62
+ | `extip:<IP>` | Fixed external IP |
63
+
64
+ Mapping timeout: 20 min, update interval: 15 min. Maps both TCP (P2P) and UDP (discovery).
65
+
66
+ ## P2P Server
67
+
68
+ Two layers:
69
+
70
+ ### p2psrv.Server (`p2psrv/`)
71
+
72
+ High-level wrapper that integrates discv5 with the devp2p server:
73
+
74
+ - Starts discv5 UDP listener
75
+ - NAT mapping for UDP port
76
+ - Registers genesis topic (`thor1@<genesisID[24:]>`)
77
+ - Runs discovery loop → feeds discovered nodes to dial loop
78
+ - Manages peer caches: `discoveredNodes` (RandCache, 128), `knownNodes` (PrioCache, 5)
79
+
80
+ ### p2p.Server (`p2p/server.go`)
81
+
82
+ Low-level devp2p server:
83
+
84
+ - RLPx encrypted TCP connections
85
+ - Protocol negotiation via capabilities
86
+ - Connection flags: `dynDialedConn`, `staticDialedConn`, `inboundConn`, `trustedConn`
87
+
88
+ ### Connection Management
89
+
90
+ | Setting | Value |
91
+ |---------|-------|
92
+ | `--max-peers` | 25 (default) |
93
+ | `--p2p-port` | 11235 |
94
+ | Max active dial tasks | 16 |
95
+ | Default max pending peers | 50 |
96
+ | Dial timeout | 15s |
97
+ | Frame read timeout | 30s |
98
+ | Frame write timeout | 20s |
99
+ | DialRatio | `sqrt(MaxPeers)` |
100
+
101
+ Inbound limit: `MaxPeers - maxDialedConns`. Trusted peers bypass limits.
102
+
103
+ Dial pacing: 500ms for first 20 dials, 2s after, 10s when >50% peers connected.
104
+
105
+ ## Comm Protocol — Block & Transaction Propagation
106
+
107
+ Located in `comm/`. Protocol: `thor/1`, max message size 10 MB.
108
+
109
+ ### Message Types
110
+
111
+ | Code | Message | Type | Purpose |
112
+ |------|---------|------|---------|
113
+ | 0 | `MsgGetStatus` | Call | Handshake / status exchange |
114
+ | 1 | `MsgNewBlockID` | Notify | Announce new block (ID only) |
115
+ | 2 | `MsgNewBlock` | Notify | Broadcast full block |
116
+ | 3 | `MsgNewTx` | Notify | Broadcast transaction |
117
+ | 4 | `MsgGetBlockByID` | Call | Request block by ID |
118
+ | 5 | `MsgGetBlockIDByNumber` | Call | Request block ID by number |
119
+ | 6 | `MsgGetBlocksFromNumber` | Call | Request batch of blocks (sync) |
120
+ | 7 | `MsgGetTxs` | Call | Sync transactions |
121
+
122
+ ### Block Propagation
123
+
124
+ - `BroadcastBlock()`: `sqrt(peers)` receive `MsgNewBlock` (full block), remaining peers get `MsgNewBlockID`
125
+ - Announced block IDs trigger fetch via `MsgGetBlockByID` in the announcement loop
126
+
127
+ ### Transaction Propagation
128
+
129
+ - `txsLoop` subscribes to the tx pool
130
+ - `MsgNewTx` sent to peers that haven't seen the transaction
131
+ - After sync completes: `syncTxs()` via `MsgGetTxs` for catch-up
132
+
133
+ ### Sync
134
+
135
+ `Sync()` selects the best peer (highest total score) and runs `download()` using `MsgGetBlocksFromNumber` to fetch block batches.
136
+
137
+ ## Bootstrap Nodes
138
+
139
+ ### disco Command (`cmd/disco/`)
140
+
141
+ Standalone bootstrap node — UDP-only discv5 listener, no TCP, no thor protocol.
142
+
143
+ | Flag | Default | Purpose |
144
+ |------|---------|---------|
145
+ | `--addr` | `:55555` | Listen address |
146
+ | `--keyfile` | auto | Private key file |
147
+ | `--keyhex` | — | Private key as hex |
148
+ | `--nat` | `none` | NAT mechanism |
149
+ | `--netrestrict` | — | CIDR whitelist |
150
+
151
+ ### Node Sources
152
+
153
+ 1. **Hardcoded fallback**: 11 bootstrap nodes in `cmd/thor/p2p/bootstrap.go` (port 55555)
154
+ 2. **Remote list**: `https://vechain.github.io/bootstraps/node.list` (HTTP enode URLs)
155
+ 3. **Peer cache**: `peers.cache` in instance dir — known nodes saved on shutdown
156
+
157
+ ## Default Ports
158
+
159
+ | Port | Protocol | Use |
160
+ |------|----------|-----|
161
+ | 11235 | TCP | P2P connections (RLPx) |
162
+ | 55555 | UDP | Bootstrap node discovery |
163
+
164
+ ## Component Wiring
165
+
166
+ ```
167
+ cmd/thor/main.go
168
+ → newP2PCommunicator()
169
+ → p2psrv.New(opts) // wraps p2p.Server, manages discv5
170
+ → comm.New(...) // block/tx propagation logic
171
+ → p2pCommunicator.Start()
172
+ → p2psrv.Start(comm.Protocols(), comm.DiscTopic())
173
+ → p2p.Server.Start() // TCP listener
174
+ → discv5.ListenUDP() // UDP discovery
175
+ → RegisterTopic("thor1@<genesisID>")
176
+ → discoverLoop() + dialLoop()
177
+ → comm.Start() // sync, broadcast loops
178
+ ```
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/solo.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Solo Mode
2
+
3
+ Solo mode runs a local single-node VeChain chain for development and testing.
4
+ No P2P networking, no real consensus — just a local sandbox with pre-funded accounts.
5
+
6
+ ## Starting Solo
7
+
8
+ ```bash
9
+ thor solo [flags]
10
+ ```
11
+
12
+ ### Solo-Specific Flags
13
+
14
+ | Flag | Default | Description |
15
+ |------|---------|-------------|
16
+ | `--on-demand` | false | Create blocks only when pending transactions exist |
17
+ | `--block-interval` | 10 | Block interval in seconds |
18
+ | `--persist` | false | Persist data to disk (otherwise in-memory) |
19
+ | `--gas-limit` | 40,000,000 | Block gas limit (0 = adaptive) |
20
+ | `--genesis` | — | Custom genesis file path/URL (default: builtin devnet) |
21
+ | `--txpool-limit` | 10,000 | Transaction pool size |
22
+
23
+ ### Common Examples
24
+
25
+ ```bash
26
+ thor solo # basic, in-memory, 10s blocks
27
+ thor solo --on-demand # blocks only when txs arrive
28
+ thor solo --persist --on-demand # persistent + on-demand
29
+ thor solo --api-addr 0.0.0.0:8669 # expose API externally
30
+ thor solo --gas-limit 0 --api-cors="*" # adaptive gas, open CORS
31
+ ```
32
+
33
+ ## Mining Modes
34
+
35
+ ### Auto-Mining (Default)
36
+
37
+ - Loop runs every second
38
+ - Produces a block when `time.Now().Unix() % blockInterval == 0`
39
+ - Creates empty blocks if no transactions
40
+
41
+ ### On-Demand (`--on-demand`)
42
+
43
+ - Uses `OnDemandTxPool` instead of the standard tx pool
44
+ - Block produced immediately when an executable transaction is submitted
45
+ - Empty blocks are skipped
46
+ - Can produce blocks with future timestamps if needed
47
+
48
+ ## Pre-Funded Accounts
49
+
50
+ 10 accounts, each with **1,000,000,000 VET** (1e27 wei) in both balance and energy.
51
+
52
+ Generated from fixed private keys in `genesis/devnet.go`:
53
+
54
+ | # | Private Key |
55
+ |---|-------------|
56
+ | 0 | `99f0500549792796c14fed62011a51081dc5b5e68fe8bd8a13b86be829c4fd36` |
57
+ | 1 | `7b067f53d350f1cf20ec13df416b7b73e88a1dc7331bc904b92108b1e76a08b1` |
58
+ | 2 | `f4a1a17039216f535d42ec23732c79943ffb45a089fbb78a14daad0dae93e991` |
59
+ | 3 | `35b5cc144faca7d7f220fca7ad3420090861d5231d80eb23e1013426847371c4` |
60
+ | 4 | `10c851d8d6c6ed9e6f625742063f292f4cf57c2dbeea8099fa3aca53ef90aef1` |
61
+ | 5 | `2dd2c5b5d65913214783a6bd5679d8c6ef29ca9f2e2eae98b4add061d0b85ea0` |
62
+ | 6 | `e1b72a1761ae189c10ec3783dd124b902ffd8c6b93cd9ff443d5490ce70047ff` |
63
+ | 7 | `35cbc5ac0c3a2de0eb4f230ced958fd6a6c19ed36b5d2b1803a9f11978f96072` |
64
+ | 8 | `b639c258292096306d2f60bc1a8da9bc434ad37f15cd44ee9a2526685f592220` |
65
+ | 9 | `9d68178cdc934178cca0a0051f40ed46be153cf23cb1805b59cc612c0ad2bbe0` |
66
+
67
+ Account #0 (`0xf077b491b355E64048cE21E3A6Fc4751eEeA77fa`) also serves as the executor and block signer (PoA validator).
68
+
69
+ ## Persistence
70
+
71
+ | Mode | Storage | Behavior |
72
+ |------|---------|----------|
73
+ | Default (no `--persist`) | In-memory | Data lost on restart |
74
+ | `--persist` | Disk | Written to `--data-dir`, survives restarts |
75
+
76
+ With `--persist`, instance directory follows the standard naming: `instance-<genesisID[24:]>-<version>`.
77
+
78
+ ## API Access
79
+
80
+ Same HTTP API as a full node, default `localhost:8669`. Differences in solo:
81
+
82
+ - **Debug API**: PoA checks skipped during trace replay (`skipPoA: true`)
83
+ - **Admin health**: always reports healthy (peer count check bypassed)
84
+ - **No P2P**: `solo.Communicator{}` is a no-op stub
85
+
86
+ All standard flags work: `--api-addr`, `--api-cors`, `--api-timeout`, `--api-pprof`, etc.
87
+
88
+ ## Genesis Configuration
89
+
90
+ Default solo genesis is the **devnet** config (`genesis/devnet.go`):
91
+
92
+ - Genesis ID: `0x00000000bb55405beed90df9fea5acdb1cb7caba61b0d7513395f42efd30e558`
93
+ - All forks enabled from block 0 (`SoloFork`)
94
+ - Initial gas limit: 10,000,000 (overridable via `--gas-limit`)
95
+
96
+ ```go
97
+ SoloFork = ForkConfig{
98
+ VIP191: 0, ETH_CONST: 0, BLOCKLIST: 0, ETH_IST: 0,
99
+ VIP214: 0, FINALITY: 0, GALACTICA: 0, HAYABUSA: 0,
100
+ }
101
+ ```
102
+
103
+ Custom genesis can be provided via `--genesis <path-or-url>`.
104
+
105
+ ## Solo vs Testnet/Mainnet
106
+
107
+ | Aspect | Solo | Testnet/Mainnet |
108
+ |--------|------|-----------------|
109
+ | P2P networking | None | Full discv5 + RLPx |
110
+ | Consensus | Mocked BFT engine | Real BFT with PoA/PoS |
111
+ | Genesis | Devnet (all forks at block 0) | Network-specific fork schedule |
112
+ | Block production | Local packer (auto or on-demand) | Committee-based |
113
+ | Master key | Not required | Required for block signing |
114
+ | Persistence | Optional (in-memory default) | Always on disk |
115
+ | Pre-funded accounts | 10 × 1B VET | None |
116
+
117
+ ## Use Cases
118
+
119
+ - **Smart contract development**: deploy and test contracts with instant feedback
120
+ - **dApp development**: full API available locally, no sync delay
121
+ - **Integration testing**: deterministic blocks, predictable behavior
122
+ - **CI pipelines**: lightweight, fast startup, no external dependencies
123
+ - **On-demand mode**: block only when you transact, ideal for scripted tests
124
+
125
+ ## Key Source Files
126
+
127
+ | File | Purpose |
128
+ |------|---------|
129
+ | `cmd/thor/solo/solo.go` | Solo entry point and main loop |
130
+ | `cmd/thor/solo/core.go` | Block packing logic |
131
+ | `cmd/thor/solo/txpool.go` | On-demand transaction pool |
132
+ | `cmd/thor/solo/types.go` | Solo communicator stub |
133
+ | `genesis/devnet.go` | Devnet genesis, DevAccounts, SoloConfig |
134
+ | `thor/fork_config.go` | SoloFork definition |
135
+ | `bft/engine.go` | soloMockedEngine |
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/skill/references/storage.md ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Storage Architecture
2
+
3
+ Thor uses a layered storage design: **MuxDB** (LevelDB) for blockchain state and chain data,
4
+ **LogDB** (SQLite) for event/transfer logs, and a Merkle-Patricia trie for state management.
5
+
6
+ ## MuxDB — Main Database
7
+
8
+ Central storage abstraction in `muxdb/`. Wraps LevelDB and manages trie nodes + named KV stores.
9
+
10
+ ### Key Spaces
11
+
12
+ | Space | Byte Prefix | Purpose |
13
+ |-------|-------------|---------|
14
+ | `trieHistSpace` | 0 | Historical trie nodes (versioned, prunable) |
15
+ | `trieDedupedSpace` | 1 | Deduplicated trie nodes (checkpointed, permanent) |
16
+ | `namedStoreSpace` | 2 | Named KV stores for chain data |
17
+
18
+ ### Named KV Stores
19
+
20
+ | Store | Contents |
21
+ |-------|----------|
22
+ | `chain.hdr` | Block headers |
23
+ | `chain.body` | Block bodies |
24
+ | `chain.props` | Chain properties |
25
+ | `chain.heads` | Chain head pointers |
26
+ | `chain.txi` | Transaction index |
27
+ | `state.code` | Contract bytecode |
28
+ | `muxdb.props` | DB config (partition factors) |
29
+ | `pruner.props` | Pruner checkpoint state |
30
+
31
+ ### Trie Names
32
+
33
+ | Name | Purpose |
34
+ |------|---------|
35
+ | `"a"` | Account trie (address → account + metadata) |
36
+ | `"i"` | Index trie (block index) |
37
+ | `"s"` + storageID | Per-contract storage tries |
38
+
39
+ ## LevelDB — Underlying Engine
40
+
41
+ Engine: `syndtr/goleveldb` via `engine.LevelEngine`.
42
+
43
+ | Setting | Default | Description |
44
+ |---------|---------|-------------|
45
+ | BlockCacheCapacity | `ReadCacheMB` (256 MB) | Read cache |
46
+ | WriteBuffer | `WriteBufferMB` (128 MB) | Write buffer |
47
+ | Filter | Bloom 10-bit | Block filter |
48
+ | BlockSize | 32 KB | Data block size |
49
+ | CompactionTableSize | 4 MB | SST file size |
50
+ | OverflowPrefix | `trieHistSpace` | Compaction hint (when pruning enabled) |
51
+
52
+ Configured via `--cache` flag (default 4096 MB total).
53
+
54
+ ## LogDB — Event and Transfer Logs (SQLite)
55
+
56
+ SQLite database (`mattn/go-sqlite3`) with WAL journal mode.
57
+
58
+ ### Schema
59
+
60
+ **ref table** — blob deduplication for blockID, txID, addresses, topics:
61
+
62
+ ```sql
63
+ CREATE TABLE ref (id INTEGER PRIMARY KEY, data BLOB NOT NULL UNIQUE);
64
+ ```
65
+
66
+ **event table:**
67
+
68
+ ```sql
69
+ CREATE TABLE event (
70
+ seq INTEGER PRIMARY KEY,
71
+ blockID, blockTime, txID, txOrigin, clauseIndex,
72
+ address, topic0, topic1, topic2, topic3, topic4,
73
+ data BLOB
74
+ );
75
+ ```
76
+
77
+ Indexes on address, topic combinations (6 indexes total, one optional via `--logdb-additional-indexes`).
78
+
79
+ **transfer table:**
80
+
81
+ ```sql
82
+ CREATE TABLE transfer (
83
+ seq INTEGER PRIMARY KEY,
84
+ blockID, blockTime, txID, txOrigin, clauseIndex,
85
+ sender, recipient, amount BLOB(32)
86
+ );
87
+ ```
88
+
89
+ Indexes on txOrigin, sender, recipient.
90
+
91
+ ### Query API
92
+
93
+ - `FilterEvents(ctx, *EventFilter)` — range (block from/to), criteria (address, topics), order, limit
94
+ - `FilterTransfers(ctx, *TransferFilter)` — same pattern
95
+
96
+ `seq` encodes block number + tx index + log index for ordering.
97
+
98
+ Journal size limit: 50 MB. Separate read-only and write connections.
99
+
100
+ ## Merkle-Patricia Trie
101
+
102
+ Located in `trie/`. Versioned Merkle-Patricia trie for state management.
103
+
104
+ ### Node Types
105
+
106
+ | Type | Description |
107
+ |------|-------------|
108
+ | `fullNode` | 17 children (16 hex nibbles + value) |
109
+ | `shortNode` | Compressed path key + single child |
110
+ | `refNode` | Hash + version (database reference) |
111
+ | `valueNode` | Leaf value + metadata |
112
+
113
+ ### Version
114
+
115
+ `Version{Major, Minor uint32}` — major is block number, minor is sub-index within block.
116
+
117
+ ### Read Path
118
+
119
+ cache → hist space → deduped space (with fallback handling for account/index roots).
120
+
121
+ ### Write Path
122
+
123
+ `Commit()` writes to hist space, optionally populates cache. `Checkpoint()` copies nodes from hist to deduped space for a version range.
124
+
125
+ Empty root: `thor.Blake2b(rlp.EmptyString)`.
126
+
127
+ ## State Management
128
+
129
+ Located in `state/`. Connects tries to the EVM execution layer.
130
+
131
+ ```
132
+ revert-able state → stacked map → journal → playback → updated trie
133
+ → trie cache → read-only trie
134
+ ```
135
+
136
+ **State** struct holds:
137
+ - Account trie (`"a"`)
138
+ - Per-address cached objects (account data, code, storage trie, storage map)
139
+ - `StackedMap` for revertable changes (EVM snapshots)
140
+
141
+ **Stage/Commit**: `Stage(newVersion)` computes state root, returns `Stage` with `commit()` that writes code and commits all tries.
142
+
143
+ ## Pruning
144
+
145
+ Located in `cmd/thor/pruner/`. Removes historical trie nodes to reclaim disk space.
146
+
147
+ ### How It Works
148
+
149
+ 1. Runs periodically: every 65536 blocks (or 8192 when nearly synced)
150
+ 2. **Checkpoint**: copies trie nodes from hist → deduped space for `[base, target)` range
151
+ 3. **Delete**: removes hist nodes in that range via `DeleteTrieHistoryNodes()`
152
+ 4. Preserves `MaxStateHistory` (65535 blocks) of recent history for EVM access
153
+
154
+ ### Configuration
155
+
156
+ | Flag | Effect |
157
+ |------|--------|
158
+ | `--disable-pruner` | Stops pruner, keeps all history (archive mode) |
159
+
160
+ When disabled: `TrieHistPartitionFactor` = 524288 (vs 256 for pruning), instance dir gets `-full` suffix.
161
+
162
+ ### Partition Factors
163
+
164
+ | Setting | Pruning | Archive |
165
+ |---------|---------|---------|
166
+ | `TrieHistPartitionFactor` | 256 | 524288 |
167
+ | `TrieDedupedPartitionFactor` | MaxUint32 | MaxUint32 |
168
+ | `TrieCachedNodeTTL` | 30 | 30 |
169
+
170
+ ## Node Types vs Storage
171
+
172
+ | Type | Flags | Disk Size | Notes |
173
+ |------|-------|-----------|-------|
174
+ | **Full** | (default) | ~200 GB | Pruned trie history + logs |
175
+ | **Full without logs** | `--skip-logs` | ~100 GB | No event/transfer logs, `/logs` API disabled |
176
+ | **Archive** | `--disable-pruner` | >400 GB | All trie history preserved |
177
+
178
+ Instance directory naming: `instance-<genesisID[24:]>-<version>[-full]`.
179
+
180
+ ## Cache Layer
181
+
182
+ | Cache | Implementation | Size | Purpose |
183
+ |-------|---------------|------|---------|
184
+ | Trie node cache | `directcache` | 1/4 queried + 3/4 committed | Hot trie nodes |
185
+ | Root cache | Map + TTL eviction | — | Trie roots |
186
+ | Chain summaries | ARC | 512 | Block summaries |
187
+ | Chain txs | ARC | 2048 | Transactions |
188
+ | Chain receipts | ARC | 2048 | Receipts |
189
+ | Code cache | ARC | 512 | Contract bytecode |
190
+ | Future blocks | `RandCache` | 32 | Blocks ahead of head |
191
+ | Base fee | Custom | — | Cached base fee calculations |
192
+ | LevelDB | Block cache + write buffer | Configurable | Engine-level I/O cache |
193
+
194
+ ## Component Wiring
195
+
196
+ ```
197
+ main.go
198
+ → openMainDB() → muxdb.Open(path, opts) → LevelDB engine
199
+ → openLogDB() → logdb.New(path) → SQLite
200
+ → chain.NewRepository(mainDB, genesis) → named KV stores for headers/bodies/txindex
201
+ → state.NewStater(mainDB) → account trie + storage tries
202
+ → pruner.New(mainDB, repo, bftEngine) // unless --disable-pruner
203
+ ```
benchmarks/skillbench-venus-e/tasks/52e614810e2bad9f_q1/task.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "52e614810e2bad9f",
4
+ "query_id": "52e614810e2bad9f_q1",
5
+ "environment": {
6
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
7
+ "network": "none"
8
+ },
9
+ "outputs": [],
10
+ "success_criteria": [
11
+ "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json."
12
+ ],
13
+ "evaluation": {
14
+ "kind": "python",
15
+ "type": "verified"
16
+ },
17
+ "workspace": {
18
+ "input_mappings": [],
19
+ "skill_packages": [
20
+ {
21
+ "content_hash": "6e03e0e08a473fdaf2863f69c3c6cdf65c07d2b5616413605762ad220c51eb05",
22
+ "name": "thor",
23
+ "package_path": "skill",
24
+ "install_name": "thor-bac1a51b"
25
+ }
26
+ ],
27
+ "default_skill_target": ".claude/skills",
28
+ "candidate_mode": "response"
29
+ },
30
+ "source_skill": {
31
+ "sha256": "6e03e0e08a473fdaf2863f69c3c6cdf65c07d2b5616413605762ad220c51eb05",
32
+ "files": {
33
+ "SKILL.md": "9ba94f15b3e339d679c1b327fb70518c7db5341d7d89bb755a079fa32e45b8a6",
34
+ "references/api.md": "606bf39075cb5d68d3818cbfdbc5343fdd73cb23039d0d7b4b53d2dfc965df87",
35
+ "references/architecture.md": "c2e7013dbcf530c3a5031c96c7402edcbd010c4f95a06881163dbfc6051a861a",
36
+ "references/built-in-contracts.md": "072772cb4eba8cfe4dc0dc43726df5f8e196589a68f78e27b44522068a7f1231",
37
+ "references/consensus.md": "cf9308b0efba984d0cfe397572a16f99e2ddcc8d7cae9571956f43193987871f",
38
+ "references/contributing.md": "19902dae3ce9390fdf99981c2c05c7e1ef6f63a0e0e14c3dcb94ea19fae2a9c5",
39
+ "references/flow-block-production.md": "9994ccd82fc056abaf6bbd14217e7f2a6af966ede9c0b7b1d42eb7be1ecd60d4",
40
+ "references/flow-reward-distribution.md": "82162db97b58b0c1558d32ab76bca8cd480808387cf9957f5c5f44869acbea3a",
41
+ "references/flow-staking-delegation.md": "5dbf9aa93c97bc2d257fe83ae3517a91a4281f3e061a60211eed97ecad2aa043",
42
+ "references/flow-sync.md": "f00921750fe3df7f9a42119b3eabf23237148c05f153f37fedf0c0a214e58e04",
43
+ "references/flow-transaction-lifecycle.md": "6d87684d24459bfdfdccec2f5f04b96976ce6a6c57c0d8e0385b23bd491ae983",
44
+ "references/p2p.md": "5692b798f7dd9917e146224d371cab33e65b983b579d1bb5790051fcc38dd0c7",
45
+ "references/solo.md": "5b4a0ae18ac3366babe96c49bdafaa28cad5f22edf8f57beaba58a95b801344b",
46
+ "references/storage.md": "ada58c7a339cc3cb5f99e3eace56d9ba877feeac4cb125e01dd252d546f95276"
47
+ }
48
+ },
49
+ "migration": {
50
+ "source_schema": "mybench-portable-task-v2",
51
+ "legacy_task_json": "provenance/legacy-package/task.json",
52
+ "historical_gain_protocol": "legacy; not Harbor certified",
53
+ "reference_available": true,
54
+ "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task",
55
+ "original_skill_content_hashes": [
56
+ "bac1a51be2671cbd77342bd8ae09d996ef03c3a8d62bbff3444600d966fc8029"
57
+ ]
58
+ }
59
+ }
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_contract.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expected_check_ids": [
3
+ "0"
4
+ ],
5
+ "criterion_weights": {
6
+ "0": 1
7
+ }
8
+ }
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_entry.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable result protocol; candidate failures and evaluator errors stay distinct."""
2
+ from pathlib import Path
3
+ import contextlib,io,json,runpy,sys
4
+ from auto_policy import install,finalize
5
+ HERE=Path(__file__).resolve().parent
6
+
7
+ def main():
8
+ captured=io.StringIO()
9
+ try:
10
+ install()
11
+ with contextlib.redirect_stdout(captured):
12
+ try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
13
+ except SystemExit as error:
14
+ if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
15
+ body=None
16
+ for line in reversed(captured.getvalue().splitlines()):
17
+ try:value=json.loads(line)
18
+ except(ValueError,TypeError):continue
19
+ if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
20
+ if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
21
+ if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
22
+ cfgfile=HERE/'auto_policy.json'
23
+ if cfgfile.is_file():
24
+ cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
25
+ if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
26
+ checks=body['checks']
27
+ if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
28
+ ids=[str(c['id'])for c in checks]
29
+ if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
30
+ contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
31
+ if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
32
+ weights=contract['criterion_weights']
33
+ body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
34
+ print(json.dumps(body,ensure_ascii=True));return 0
35
+ except Exception as error:
36
+ print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
37
+
38
+ if __name__=='__main__':raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trusted bounded-invocation policy; never infer whole-program properties."""
2
+ from pathlib import Path
3
+ import hashlib,json,os,subprocess,sys,tempfile,time,uuid
4
+
5
+ HERE=Path(__file__).resolve().parent
6
+ ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
7
+ DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
8
+ class PolicyInfrastructureError(RuntimeError): pass
9
+ _installed=False
10
+ _original_popen=subprocess.Popen
11
+ _original_run=subprocess.run
12
+
13
+ def _config():
14
+ p=HERE/'auto_policy.json'
15
+ if not p.is_file():return None
16
+ value=json.loads(p.read_text())
17
+ if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
18
+ return value
19
+
20
+ def _folder():
21
+ if ENV not in os.environ:
22
+ os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
23
+ p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
24
+
25
+ def _python_target(command,cwd):
26
+ if not isinstance(command,(list,tuple))or not command:return None
27
+ argv=[os.fspath(x)for x in command]
28
+ if 'python'not in Path(argv[0]).name.lower():return None
29
+ i=1;flags=[]
30
+ while i<len(argv)and argv[i].startswith('-'):
31
+ flag=argv[i]
32
+ if flag=='-m':
33
+ if i+1>=len(argv):return None
34
+ name=argv[i+1];p=Path(cwd)/name.replace('.','/')
35
+ if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
36
+ return argv[0],flags,'module',name,argv[i+2:]
37
+ if flag in ['-c','-']:return None
38
+ flags.append(flag);i+=1
39
+ if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
40
+ if i>=len(argv)or not argv[i].endswith('.py'):return None
41
+ path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
42
+ path=path.resolve()
43
+ if path==HERE or HERE in path.parents:
44
+ if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
45
+ for value in argv[i+1:]:
46
+ if not value.endswith('.py')or value.startswith('-'):continue
47
+ subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
48
+ subject=subject.resolve()
49
+ if HERE not in subject.parents:
50
+ return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
51
+ return None
52
+ return argv[0],flags,'script',str(path),argv[i+1:]
53
+
54
+ def install():
55
+ global _installed
56
+ if _installed:return
57
+ _installed=True
58
+ cfg=_config()
59
+ if cfg is None:return
60
+ _folder()
61
+ os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
62
+ class GuardedPopen(_original_popen):
63
+ def __init__(self,args,*pos,**kwargs):
64
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
65
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
66
+ receipt=None
67
+ if target:
68
+ executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
69
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
70
+ if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
71
+ args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
72
+ env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
73
+ if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
74
+ try:super().__init__(args,*pos,**kwargs)
75
+ except OSError as error:
76
+ if receipt:
77
+ receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
78
+ raise
79
+ subprocess.Popen=GuardedPopen
80
+ def bounded_run(*pos,**kwargs):
81
+ command=pos[0]if pos else kwargs.get('args')
82
+ cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
83
+ target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
84
+ if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
85
+ if target is not None and cfg.get('execution_budget_seconds')is not None:
86
+ budget=cfg['execution_budget_seconds']
87
+ if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
88
+ kwargs['timeout']=budget
89
+ remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
90
+ if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
91
+ try:
92
+ if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
93
+ result=_original_run(*pos,**kwargs)
94
+ if target is not None and result.returncode<0:
95
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
96
+ return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
97
+ return result
98
+ except subprocess.TimeoutExpired as error:
99
+ if target is None:raise
100
+ (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
101
+ textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
102
+ empty=''if textual else b''
103
+ def output(value):
104
+ if value is None:return empty
105
+ return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
106
+ return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
107
+ subprocess.run=bounded_run
108
+
109
+ def status(require_execution=True):
110
+ install();p=_folder();rows=[]
111
+ for receipt in sorted(p.glob('*.json')):
112
+ try:row=json.loads(receipt.read_text())
113
+ except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
114
+ if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
115
+ raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
116
+ rows.append(row)
117
+ if require_execution and not any(r.get('target_present')for r in rows):return False
118
+ return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
119
+
120
+ def finalize(body,owner_ids,require_execution=True):
121
+ observed=status(require_execution=require_execution)
122
+ wanted=set(map(str,owner_ids))
123
+ for row in body.get('checks',[]):
124
+ if str(row['id'])in wanted:
125
+ if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
126
+ row['passed']=row['passed']and observed
127
+ row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
128
+ body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
129
+ body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
130
+ return body
131
+
132
+ def run(*args,**kwargs):
133
+ install();return subprocess.run(*args,**kwargs)
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/auto_policy_guard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child-side observer for the exact public bounded-invocation policy."""
2
+ from pathlib import Path
3
+ import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
4
+
5
+ receipt,config_file,kind,target,*arguments=sys.argv[1:]
6
+ subject=arguments.pop(0)if kind=='probe'else target
7
+ subject_filename=os.path.abspath(subject)
8
+ receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
9
+ local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
10
+ if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
11
+ if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
12
+ candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
13
+ observer_filename=__file__
14
+ stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
15
+ stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
16
+ if not getattr(sys,'stdlib_module_names',None):
17
+ for p in stdlib_root.iterdir():
18
+ if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
19
+ state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
20
+ busy=False
21
+ def save():
22
+ global busy
23
+ was=busy;busy=True
24
+ try:
25
+ temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
26
+ finally:busy=was
27
+ def violation(code,detail):
28
+ state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
29
+ def local_module(name):
30
+ first=name.partition('.')[0]
31
+ roots=list(local_roots)
32
+ for value in sys.path:
33
+ try:p=Path(value or cwd).resolve()
34
+ except (OSError,TypeError,ValueError):continue
35
+ if any(p==r or r in p.parents for r in local_roots):roots.append(p)
36
+ return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
37
+ def subject_active():
38
+ if kind!='probe':return True
39
+ frame=sys._getframe(1)
40
+ while frame:
41
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
42
+ if isinstance(filename,str):
43
+ absolute=os.path.abspath(filename)
44
+ if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
45
+ frame=frame.f_back
46
+ return False
47
+ def audit(event,args):
48
+ relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
49
+ if busy or not relevant or not subject_active():return
50
+ if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
51
+ check_import(str(args[0]))
52
+ if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
53
+ if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
54
+ if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
55
+ def check_import(name):
56
+ if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
57
+ base=name.partition('.')[0]
58
+ if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
59
+ def import_requested_by_candidate():
60
+ frame=sys._getframe(1)
61
+ while frame:
62
+ filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
63
+ if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
64
+ absolute=os.path.abspath(filename)
65
+ return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
66
+ return False
67
+ original_import=builtins.__import__;original_import_module=importlib.import_module
68
+ def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
69
+ if not busy and subject_active()and import_requested_by_candidate():
70
+ absolute=name
71
+ if level:
72
+ package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
73
+ try:absolute=importlib.util.resolve_name('.'*level+name,package)
74
+ except(ImportError,ValueError):absolute=name
75
+ check_import(absolute)
76
+ return original_import(name,globals,locals,fromlist,level)
77
+ def bounded_import_module(name,package=None):
78
+ if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
79
+ return original_import_module(name,package)
80
+ save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
81
+ @atexit.register
82
+ def finish():state['state']='finished';save()
83
+ for p in reversed(local_roots):sys.path.insert(0,str(p))
84
+ sys.argv=[target,*arguments]
85
+ if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
86
+ else:runpy.run_path(target,run_name='__main__')
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ import sys,json
3
+ from pathlib import Path
4
+ root=Path(__file__).resolve().parent
5
+ sys.path.insert(0,str(root/'legacy_tests'))
6
+ from evaluate import evaluate
7
+ t=json.loads((root/'legacy-task.json').read_text())
8
+ from repair_equivalences import install
9
+ install(t)
10
+ mode=t['workspace']['candidate_mode']
11
+ r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
12
+ if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
13
+ if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
14
+ print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy-task.json ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "mybench-portable-task-v2",
3
+ "task_id": "555c52aee32b7374",
4
+ "query_id": "555c52aee32b7374_q1",
5
+ "prompt": {
6
+ "path": "instruction.md",
7
+ "sha256": "f068d2b4997a48c54cd62cb2c8f49c42facee794ef3b534694d25c7d25e0c637"
8
+ },
9
+ "workspace": {
10
+ "input_mappings": [],
11
+ "skill_packages": [
12
+ {
13
+ "content_hash": "39a2c604a3b990f4f7ac973f13dd3558f3e702b45de26cb7d06c72e7016484a5",
14
+ "name": "ops-inbox",
15
+ "package_path": "environment/skills/ops-inbox-39a2c604",
16
+ "install_name": "ops-inbox-39a2c604",
17
+ "archive_provenance": {
18
+ "archive_id": "logical-skill-2655896ad5588e54c75c96c5",
19
+ "archive_schema": "skill-release-v1",
20
+ "release_skill_id": "logical-skill-2655896ad5588e54c75c96c5",
21
+ "site": "skills-sh",
22
+ "local_path": "skills/26/logical-skill-2655896ad5588e54c75c96c5",
23
+ "skill_md_sha256": "5ac34ec3914c5768dfead9be58809de390d53a76f2d17064a8173e830b8e0a77",
24
+ "release_payload_sha256": "39a2c604a3b990f4f7ac973f13dd3558f3e702b45de26cb7d06c72e7016484a5",
25
+ "license": "MIT",
26
+ "license_status": "detected",
27
+ "canonical_source_id": "skills-sh:davepoon/buildwithclaude/ops-inbox"
28
+ },
29
+ "omitted_entries": []
30
+ }
31
+ ],
32
+ "default_skill_target": ".claude/skills",
33
+ "candidate_mode": "workspace"
34
+ },
35
+ "ground_truth_skills": [
36
+ "39a2c604a3b990f4f7ac973f13dd3558f3e702b45de26cb7d06c72e7016484a5"
37
+ ],
38
+ "evaluation": {
39
+ "type": "verified",
40
+ "ground_truth_answer": {
41
+ "files": [
42
+ {
43
+ "path": "output/wacli_preflight.sh",
44
+ "content": "#!/usr/bin/env bash\nset -euo pipefail\nwacli doctor --json\nwacli chats list --json\n"
45
+ }
46
+ ]
47
+ },
48
+ "verifier": {
49
+ "type": "workspace_objective",
50
+ "version": 15,
51
+ "output_mode": "workspace",
52
+ "reference_files": [
53
+ {
54
+ "path": "output/wacli_preflight.sh",
55
+ "format": "shell",
56
+ "content": "#!/usr/bin/env bash\nset -euo pipefail\nwacli doctor --json\nwacli chats list --json\n"
57
+ }
58
+ ],
59
+ "checks": [
60
+ {
61
+ "id": "workspace_file_set",
62
+ "type": "workspace_file_set",
63
+ "paths": [
64
+ "output/wacli_preflight.sh"
65
+ ],
66
+ "roots": [
67
+ "output"
68
+ ]
69
+ },
70
+ {
71
+ "id": "file_001",
72
+ "type": "file_exists",
73
+ "path": "output/wacli_preflight.sh"
74
+ },
75
+ {
76
+ "id": "shell_001",
77
+ "type": "shell_syntax",
78
+ "path": "output/wacli_preflight.sh"
79
+ },
80
+ {
81
+ "id": "shell_001_001",
82
+ "type": "shell_command",
83
+ "path": "output/wacli_preflight.sh",
84
+ "value": "wacli doctor --json"
85
+ },
86
+ {
87
+ "id": "shell_001_002",
88
+ "type": "shell_command",
89
+ "path": "output/wacli_preflight.sh",
90
+ "value": "wacli chats list --json"
91
+ },
92
+ {
93
+ "id": "shell_001_sequence",
94
+ "type": "shell_command_sequence",
95
+ "path": "output/wacli_preflight.sh",
96
+ "values": [
97
+ "wacli doctor --json",
98
+ "wacli chats list --json"
99
+ ]
100
+ },
101
+ {
102
+ "id": "shell_001_unconditional",
103
+ "type": "shell_unconditional_commands",
104
+ "path": "output/wacli_preflight.sh",
105
+ "values": [
106
+ "wacli doctor --json",
107
+ "wacli chats list --json"
108
+ ]
109
+ },
110
+ {
111
+ "id": "shell_001_failure_propagation",
112
+ "type": "shell_failure_propagation",
113
+ "path": "output/wacli_preflight.sh",
114
+ "values": [
115
+ "wacli doctor --json",
116
+ "wacli chats list --json"
117
+ ]
118
+ },
119
+ {
120
+ "id": "shell_straight_line_001",
121
+ "type": "shell_straight_line",
122
+ "path": "output/wacli_preflight.sh"
123
+ }
124
+ ],
125
+ "self_test_passed": true
126
+ },
127
+ "dependency_contract": {
128
+ "version": 2,
129
+ "mode": "core_answer",
130
+ "dependency_type": "project_command_convention",
131
+ "requirement_ids": [
132
+ "skill_a033",
133
+ "skill_a034"
134
+ ],
135
+ "forbid_meta_reference": true,
136
+ "forbid_answer_leakage": true
137
+ }
138
+ }
139
+ }
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/evaluate.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a candidate response for one portable MyBench task."""
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+
13
+
14
+ def _load_verify():
15
+ try:
16
+ from verifiers import verify
17
+ return verify
18
+ except ImportError:
19
+ project_src = Path(__file__).resolve().parents[1] / "src"
20
+ if project_src.is_dir():
21
+ sys.path.insert(0, str(project_src))
22
+ from verifiers import verify
23
+ return verify
24
+ raise
25
+
26
+
27
+ def _emit(result, output=None):
28
+ text = json.dumps(result, ensure_ascii=False)
29
+ print(text)
30
+ if output:
31
+ Path(output).write_text(text + "\n", encoding="utf-8")
32
+
33
+
34
+ def _judge_contract(judge):
35
+ if not isinstance(judge, dict):
36
+ return "Judge output must be a JSON object"
37
+ if type(judge.get("passed")) is not bool:
38
+ return "Judge field passed must be a JSON boolean"
39
+ for key in ("score", "max_score"):
40
+ value = judge.get(key, 100 if key == "max_score" else None)
41
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
42
+ return f"Judge field {key} must be a finite number"
43
+ if not math.isfinite(float(value)):
44
+ return f"Judge field {key} must be a finite number"
45
+ score = float(judge["score"])
46
+ max_score = float(judge.get("max_score", 100))
47
+ if max_score <= 0:
48
+ return "Judge field max_score must be greater than zero"
49
+ if score < 0 or score > max_score:
50
+ return "Judge score must be between zero and max_score"
51
+ return None
52
+
53
+
54
+ def evaluate(task_json, candidate_path, open_judge_command=None,
55
+ open_judge_timeout=None):
56
+ task_json = Path(task_json).resolve()
57
+ candidate_path = Path(candidate_path).resolve()
58
+ task = json.loads(task_json.read_text(encoding="utf-8"))
59
+ evaluation = task.get("evaluation") or {}
60
+ track = evaluation.get("type")
61
+ base = {
62
+ "schema_version": task.get("schema_version"),
63
+ "task_id": task.get("task_id"),
64
+ "query_id": task.get("query_id"),
65
+ "track": track,
66
+ }
67
+ if track == "verified":
68
+ workspace_mode = ((evaluation.get("verifier") or {}).get("type") ==
69
+ "workspace_objective")
70
+ if workspace_mode and not candidate_path.is_dir():
71
+ return {**base, "status": "candidate_contract_error", "passed": False,
72
+ "score": 0, "max_score": 1,
73
+ "details": "workspace evaluator requires a candidate directory"}, 2
74
+ if not workspace_mode and not candidate_path.is_file():
75
+ return {**base, "status": "candidate_contract_error", "passed": False,
76
+ "score": 0, "max_score": 1,
77
+ "details": "response evaluator requires a candidate file"}, 2
78
+ if workspace_mode:
79
+ candidate = str(candidate_path)
80
+ else:
81
+ try:
82
+ candidate = candidate_path.read_text(encoding="utf-8")
83
+ except UnicodeError:
84
+ return {**base, "status": "candidate_contract_error", "passed": False,
85
+ "score": 0, "max_score": 1,
86
+ "details": "candidate response must use valid UTF-8"}, 2
87
+ passed, detail = _load_verify()(
88
+ evaluation.get("verifier") or {},
89
+ evaluation.get("ground_truth_answer"),
90
+ candidate,
91
+ None,
92
+ )
93
+ return {**base, "status": "scored", "passed": bool(passed),
94
+ "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1
95
+ if track != "open":
96
+ return {**base, "status": "unsupported_track", "passed": False,
97
+ "score": None, "details": f"unsupported track: {track}"}, 2
98
+ if not candidate_path.is_file():
99
+ return {**base, "status": "candidate_contract_error", "passed": False,
100
+ "score": None, "details": "open judge requires a candidate response file"}, 2
101
+ candidate_file = candidate_path
102
+ command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND")
103
+ if not command:
104
+ return {**base, "status": "requires_external_judge", "passed": None,
105
+ "score": None, "details": (
106
+ "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads "
107
+ "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2
108
+ environment = os.environ.copy()
109
+ environment["MYBENCH_TASK_JSON"] = str(task_json)
110
+ environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file)
111
+ timeout = float(open_judge_timeout or os.environ.get(
112
+ "MYBENCH_OPEN_JUDGE_TIMEOUT", 600))
113
+ if not math.isfinite(timeout) or timeout <= 0:
114
+ return {**base, "status": "judge_contract_error", "passed": False,
115
+ "score": None, "details": "Judge timeout must be a positive number"}, 2
116
+ try:
117
+ completed = subprocess.run(
118
+ shlex.split(command), cwd=str(task_json.parent), env=environment,
119
+ text=True, capture_output=True, timeout=timeout)
120
+ except (OSError, subprocess.TimeoutExpired) as exc:
121
+ return {**base, "status": "judge_error", "passed": False,
122
+ "score": None, "details": str(exc)}, 2
123
+ if completed.returncode:
124
+ return {**base, "status": "judge_error", "passed": False, "score": None,
125
+ "details": completed.stderr.strip() or completed.stdout.strip()}, 2
126
+ try:
127
+ judge = json.loads(completed.stdout)
128
+ except json.JSONDecodeError as exc:
129
+ return {**base, "status": "judge_contract_error", "passed": False,
130
+ "score": None, "details": str(exc)}, 2
131
+ contract_error = _judge_contract(judge)
132
+ if contract_error:
133
+ return {**base, "status": "judge_contract_error", "passed": False,
134
+ "score": None, "details": contract_error}, 2
135
+ result = {**base, "status": "scored", "passed": judge.get("passed"),
136
+ "score": judge.get("score"), "max_score": judge.get("max_score", 100),
137
+ "details": judge.get("details", judge)}
138
+ return result, 0 if result["passed"] else 1
139
+
140
+
141
+ def main():
142
+ parser = argparse.ArgumentParser()
143
+ parser.add_argument("--task-json", required=True)
144
+ candidates = parser.add_mutually_exclusive_group(required=True)
145
+ candidates.add_argument("--candidate-path")
146
+ candidates.add_argument("--candidate-file") # v1 compatibility
147
+ parser.add_argument("--result-output")
148
+ parser.add_argument("--open-judge-command")
149
+ parser.add_argument("--open-judge-timeout", type=float)
150
+ args = parser.parse_args()
151
+ result, code = evaluate(args.task_json,
152
+ args.candidate_path or args.candidate_file,
153
+ args.open_judge_command, args.open_judge_timeout)
154
+ _emit(result, args.result_output)
155
+ raise SystemExit(code)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/objective_evaluators.py ADDED
@@ -0,0 +1,1308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composable objective evaluators for response and workspace tasks.
2
+
3
+ Task semantics are deliberately *not* enumerated here. A task may describe any
4
+ real user goal; verified membership depends on whether its deliverables compile
5
+ to one of these small, trusted evaluator primitives and pass counterfactual
6
+ execution. This keeps the objective surface closed and auditable without
7
+ turning the benchmark's task ontology into a closed template list.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import copy
13
+ import builtins
14
+ import json
15
+ import os
16
+ import re
17
+ import shlex
18
+ import subprocess
19
+ import tempfile
20
+ import tomllib
21
+ from pathlib import Path, PurePosixPath
22
+ try:
23
+ from .shell_invocations import shell_invocations
24
+ except ImportError:
25
+ from shell_invocations import shell_invocations
26
+
27
+
28
+ WORKSPACE_EVALUATOR = "workspace_objective"
29
+ WORKSPACE_EVALUATOR_VERSION = 15
30
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
31
+ ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
32
+ _DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
33
+
34
+
35
+ class ObjectiveEvaluatorError(ValueError):
36
+ pass
37
+
38
+
39
+ def safe_relative_path(value):
40
+ """Return a normalized portable relative path or fail closed."""
41
+ text = str(value or "").strip().replace("\\", "/")
42
+ path = PurePosixPath(text)
43
+ if (not text or text.startswith("/") or path.is_absolute() or
44
+ any(part in {"", ".", ".."} for part in path.parts)):
45
+ raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
46
+ if len(path.parts) > 8 or len(text) > 180:
47
+ raise ObjectiveEvaluatorError("workspace path is too deep or long")
48
+ return path.as_posix()
49
+
50
+
51
+ def _json_value(value):
52
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
53
+ return value
54
+ return json.loads(str(value))
55
+
56
+
57
+ def _canonical(value):
58
+ if isinstance(value, dict):
59
+ return {key: _canonical(value[key]) for key in sorted(value)}
60
+ if isinstance(value, list):
61
+ return [_canonical(item) for item in value]
62
+ return value
63
+
64
+
65
+ def _file_content(item):
66
+ fmt = str(item.get("format") or "").casefold()
67
+ content = item.get("content")
68
+ if fmt == "json":
69
+ parsed = _json_value(content)
70
+ return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
71
+ if not isinstance(content, str):
72
+ raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
73
+ return content.rstrip() + "\n"
74
+
75
+
76
+ def _ast_name(node):
77
+ if isinstance(node, ast.Name):
78
+ return node.id
79
+ if isinstance(node, ast.Attribute):
80
+ parent = _ast_name(node.value)
81
+ return f"{parent}.{node.attr}" if parent else node.attr
82
+ return ""
83
+
84
+
85
+ def _python_inventory(text):
86
+ tree = ast.parse(text)
87
+ imports, calls = set(), set()
88
+ for node in ast.walk(tree):
89
+ if isinstance(node, ast.Import):
90
+ imports.update(alias.name for alias in node.names)
91
+ elif isinstance(node, ast.ImportFrom):
92
+ module = node.module or ""
93
+ for alias in node.names:
94
+ imports.add(f"{module}.{alias.name}".strip("."))
95
+ elif isinstance(node, ast.Call):
96
+ name = _ast_name(node.func)
97
+ if name:
98
+ calls.add(name)
99
+ return imports, calls
100
+
101
+
102
+ def _literal_value(node, constants=None):
103
+ constants = constants or {}
104
+ if isinstance(node, ast.Constant) and isinstance(
105
+ node.value, (str, int, float, bool, type(None))):
106
+ return node.value
107
+ if isinstance(node, ast.Name) and node.id in constants:
108
+ return constants[node.id]
109
+ if isinstance(node, (ast.Tuple, ast.List)):
110
+ values = [_literal_value(item, constants) for item in node.elts]
111
+ if all(value is not _UNRESOLVED for value in values):
112
+ return tuple(values) if isinstance(node, ast.Tuple) else values
113
+ return _UNRESOLVED
114
+
115
+
116
+ _UNRESOLVED = object()
117
+
118
+
119
+ def _python_semantics(text):
120
+ tree = ast.parse(text)
121
+ _annotate_assignment_contexts(tree)
122
+ imports, calls = _python_inventory(text)
123
+ constants = {}
124
+ for node in tree.body:
125
+ name = None
126
+ value_node = None
127
+ if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
128
+ isinstance(node.targets[0], ast.Name)):
129
+ name, value_node = node.targets[0].id, node.value
130
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
131
+ name, value_node = node.target.id, node.value
132
+ if name and value_node is not None:
133
+ value = _literal_value(value_node, constants)
134
+ if value is not _UNRESOLVED:
135
+ constants[name] = value
136
+ elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
137
+ isinstance(node.targets[0], (ast.Tuple, ast.List)) and
138
+ isinstance(node.value, (ast.Tuple, ast.List)) and
139
+ len(node.targets[0].elts) == len(node.value.elts)):
140
+ # Treat ordinary constant unpacking as semantically equivalent to
141
+ # separate assignments. Generated implementation files commonly
142
+ # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
143
+ # test formatting rather than the required repository values.
144
+ for target, value_node in zip(node.targets[0].elts, node.value.elts):
145
+ if not isinstance(target, ast.Name):
146
+ continue
147
+ value = _literal_value(value_node, constants)
148
+ if value is not _UNRESOLVED:
149
+ constants[target.id] = value
150
+ call_nodes = []
151
+ for node in ast.walk(tree):
152
+ if isinstance(node, ast.Call):
153
+ call_nodes.append((_ast_name(node.func), node))
154
+ return imports, calls, constants, call_nodes
155
+
156
+
157
+ def _python_resolved_call_nodes(text):
158
+ """Resolve call targets through imports and simple constructor bindings.
159
+
160
+ The evaluator intentionally supports a small static subset: imports,
161
+ local definitions, direct aliases, and names assigned from calls. That is
162
+ enough to recognize semantic equivalents such as ``import datetime`` vs
163
+ ``from datetime import timedelta as td`` and instance-variable renames,
164
+ without pretending to perform general Python type inference.
165
+ """
166
+ tree = ast.parse(text)
167
+ _annotate_assignment_contexts(tree)
168
+ bindings = {}
169
+ nodes = sorted(ast.walk(tree), key=lambda node: (
170
+ int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
171
+
172
+ def resolve(node):
173
+ if isinstance(node, ast.Name):
174
+ return bindings.get(node.id, node.id)
175
+ if isinstance(node, ast.Attribute):
176
+ parent = resolve(node.value)
177
+ return f"{parent}.{node.attr}" if parent else node.attr
178
+ return ""
179
+
180
+ # A few fixed-point passes cover aliases declared after an imported name
181
+ # and ordinary ``client = Client()`` instance construction.
182
+ for _ in range(4):
183
+ changed = False
184
+ for node in nodes:
185
+ updates = {}
186
+ if isinstance(node, ast.Import):
187
+ for alias in node.names:
188
+ local = alias.asname or alias.name.split(".")[0]
189
+ updates[local] = alias.name if alias.asname else local
190
+ elif isinstance(node, ast.ImportFrom):
191
+ module = node.module or ""
192
+ for alias in node.names:
193
+ if alias.name == "*":
194
+ continue
195
+ updates[alias.asname or alias.name] = \
196
+ f"{module}.{alias.name}".strip(".")
197
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
198
+ ast.ClassDef)):
199
+ updates[node.name] = "__local__." + node.name
200
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
201
+ targets = (node.targets if isinstance(node, ast.Assign)
202
+ else [node.target])
203
+ value = node.value
204
+ if isinstance(value, ast.Call):
205
+ provenance = resolve(value.func)
206
+ elif isinstance(value, (ast.Name, ast.Attribute)):
207
+ provenance = resolve(value)
208
+ else:
209
+ provenance = ""
210
+ if provenance:
211
+ for target in targets:
212
+ if isinstance(target, ast.Name):
213
+ updates[target.id] = provenance
214
+ for name, value in updates.items():
215
+ if bindings.get(name) != value:
216
+ bindings[name] = value
217
+ changed = True
218
+ if not changed:
219
+ break
220
+ return [(_ast_name(node.func), resolve(node.func), node)
221
+ for node in ast.walk(tree) if isinstance(node, ast.Call)]
222
+
223
+
224
+ def _call_name_matches(observed, expected):
225
+ return observed == expected or observed.endswith("." + expected)
226
+
227
+
228
+ def _objective_call_targets(kind, check, resolved_calls, constants):
229
+ """Return canonical targets satisfying one already-validated call check."""
230
+ function = str(check.get("function") or check.get("value") or "")
231
+ targets = set()
232
+ for name, target, node in resolved_calls:
233
+ if not _call_name_matches(name, function):
234
+ continue
235
+ if kind == "python_call_literal" and not _node_contains_literal(
236
+ node, check.get("value"), constants):
237
+ continue
238
+ if kind == "python_call_keyword_literal" and not _call_keyword_matches(
239
+ node, str(check.get("keyword") or ""), check.get("value"),
240
+ constants):
241
+ continue
242
+ if kind == "python_call_signature" and not _call_signature_matches(
243
+ node, check.get("arguments") or [],
244
+ check.get("keywords") or {}, constants,
245
+ check.get("argument_expressions") or [],
246
+ check.get("keyword_expressions") or {},
247
+ check.get("assignment")):
248
+ continue
249
+ if target:
250
+ targets.add(target)
251
+ return targets
252
+
253
+
254
+ def python_unbound_call_roots(text):
255
+ """Return call-root names that have no static binding in the module.
256
+
257
+ Objective call checks must not accept a syntactically valid file that will
258
+ immediately raise ``NameError``. This deliberately proves only the
259
+ conservative prerequisite that a root is imported, assigned, declared,
260
+ passed as an argument, or provided by Python builtins; it does not claim to
261
+ execute or type-check the program.
262
+ """
263
+ tree = ast.parse(text)
264
+ bound = set(dir(builtins))
265
+ for node in ast.walk(tree):
266
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
267
+ bound.add(node.id)
268
+ elif isinstance(node, ast.arg):
269
+ bound.add(node.arg)
270
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
271
+ ast.ClassDef)):
272
+ bound.add(node.name)
273
+ elif isinstance(node, ast.Import):
274
+ for alias in node.names:
275
+ bound.add(alias.asname or alias.name.split(".")[0])
276
+ elif isinstance(node, ast.ImportFrom):
277
+ for alias in node.names:
278
+ bound.add(alias.asname or alias.name)
279
+ elif isinstance(node, ast.ExceptHandler) and node.name:
280
+ bound.add(node.name)
281
+ unbound = set()
282
+ for node in ast.walk(tree):
283
+ if not isinstance(node, ast.Call):
284
+ continue
285
+ root = node.func
286
+ while isinstance(root, ast.Attribute):
287
+ root = root.value
288
+ if isinstance(root, ast.Name) and root.id not in bound:
289
+ unbound.add(root.id)
290
+ return sorted(unbound)
291
+
292
+
293
+ def _node_contains_literal(node, expected, constants):
294
+ for child in ast.walk(node):
295
+ value = _literal_value(child, constants)
296
+ if value is _UNRESOLVED:
297
+ continue
298
+ if value == expected:
299
+ return True
300
+ if isinstance(value, (list, tuple)) and expected in value:
301
+ return True
302
+ return False
303
+
304
+
305
+ def _call_keyword_matches(node, keyword, expected, constants):
306
+ """Return whether a direct call keyword resolves to the expected scalar."""
307
+ return any(
308
+ item.arg == keyword and _literal_value(item.value, constants) == expected
309
+ for item in getattr(node, "keywords", [])
310
+ if item.arg is not None)
311
+
312
+
313
+ def _portable_literal(value):
314
+ if isinstance(value, tuple):
315
+ return [_portable_literal(item) for item in value]
316
+ if isinstance(value, list):
317
+ return [_portable_literal(item) for item in value]
318
+ return value
319
+
320
+
321
+ def _expression_text(node):
322
+ """Return a formatting-independent, non-executed Python expression."""
323
+ return ast.unparse(node).strip()
324
+
325
+
326
+ def _expression_fingerprint(value):
327
+ if not isinstance(value, str) or not value.strip() or len(value) > 500:
328
+ return None
329
+ try:
330
+ tree = ast.parse(value, mode="eval")
331
+ except SyntaxError:
332
+ return None
333
+ return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
334
+
335
+
336
+ def _expression_matches(node, expected):
337
+ fingerprint = _expression_fingerprint(expected)
338
+ return bool(fingerprint and ast.dump(
339
+ node, annotate_fields=True, include_attributes=False) == fingerprint)
340
+
341
+
342
+ def _annotate_assignment_contexts(tree):
343
+ """Attach one conservative simple-assignment context to nested calls."""
344
+ for statement in ast.walk(tree):
345
+ target, value = None, None
346
+ if (isinstance(statement, ast.Assign) and
347
+ len(statement.targets) == 1 and
348
+ isinstance(statement.targets[0], ast.Name)):
349
+ target, value = statement.targets[0].id, statement.value
350
+ elif (isinstance(statement, ast.AnnAssign) and
351
+ isinstance(statement.target, ast.Name) and
352
+ statement.value is not None):
353
+ target, value = statement.target.id, statement.value
354
+ if not target or value is None:
355
+ continue
356
+ context = {"target": target, "expression": _expression_text(value)}
357
+ for child in ast.walk(value):
358
+ if isinstance(child, ast.Call):
359
+ setattr(child, "_mybench_assignment", context)
360
+
361
+
362
+ def _call_signature(node, constants):
363
+ arguments = []
364
+ argument_expressions = []
365
+ for index, argument in enumerate(getattr(node, "args", [])):
366
+ value = _literal_value(argument, constants)
367
+ if value is not _UNRESOLVED:
368
+ arguments.append({"index": index,
369
+ "value": _portable_literal(value)})
370
+ else:
371
+ argument_expressions.append({
372
+ "index": index, "expression": _expression_text(argument)})
373
+ keywords = {}
374
+ keyword_expressions = {}
375
+ for keyword in getattr(node, "keywords", []):
376
+ if keyword.arg is None:
377
+ continue
378
+ value = _literal_value(keyword.value, constants)
379
+ if value is not _UNRESOLVED:
380
+ keywords[keyword.arg] = _portable_literal(value)
381
+ else:
382
+ keyword_expressions[keyword.arg] = _expression_text(keyword.value)
383
+ signature = {"arguments": arguments, "keywords": keywords,
384
+ "argument_expressions": argument_expressions,
385
+ "keyword_expressions": keyword_expressions}
386
+ assignment = getattr(node, "_mybench_assignment", None)
387
+ if isinstance(assignment, dict):
388
+ signature["assignment"] = dict(assignment)
389
+ return signature
390
+
391
+
392
+ def _call_signature_matches(node, arguments, keywords, constants,
393
+ argument_expressions=None,
394
+ keyword_expressions=None, assignment=None):
395
+ for expected in arguments or []:
396
+ index = expected.get("index")
397
+ if (not isinstance(index, int) or index < 0 or
398
+ index >= len(getattr(node, "args", []))):
399
+ return False
400
+ actual = _literal_value(node.args[index], constants)
401
+ if (actual is _UNRESOLVED or
402
+ _canonical(_portable_literal(actual)) !=
403
+ _canonical(expected.get("value"))):
404
+ return False
405
+ for keyword, expected in (keywords or {}).items():
406
+ if not _call_keyword_matches(node, keyword, expected, constants):
407
+ return False
408
+ for expected in argument_expressions or []:
409
+ index = expected.get("index")
410
+ if (not isinstance(index, int) or index < 0 or
411
+ index >= len(getattr(node, "args", [])) or
412
+ not _expression_matches(
413
+ node.args[index], expected.get("expression"))):
414
+ return False
415
+ node_keywords = {item.arg: item.value for item in
416
+ getattr(node, "keywords", []) if item.arg is not None}
417
+ for keyword, expected in (keyword_expressions or {}).items():
418
+ if (keyword not in node_keywords or
419
+ not _expression_matches(node_keywords[keyword], expected)):
420
+ return False
421
+ if assignment:
422
+ actual = getattr(node, "_mybench_assignment", None)
423
+ if (not isinstance(actual, dict) or
424
+ actual.get("target") != assignment.get("target") or
425
+ _expression_fingerprint(actual.get("expression")) !=
426
+ _expression_fingerprint(assignment.get("expression"))):
427
+ return False
428
+ return bool(arguments or keywords or argument_expressions or
429
+ keyword_expressions or assignment)
430
+
431
+
432
+ def python_call_literal_signatures(text, function, expected, keyword=None):
433
+ """Return full literal signatures for matching reference call sites."""
434
+ _, _, constants, call_nodes = _python_semantics(text)
435
+ out = []
436
+ for name, node in call_nodes:
437
+ if not (name == function or name.endswith("." + function)):
438
+ continue
439
+ matches = (_call_keyword_matches(node, keyword, expected, constants)
440
+ if keyword else
441
+ _node_contains_literal(node, expected, constants))
442
+ if matches:
443
+ out.append(_call_signature(node, constants))
444
+ return out
445
+
446
+
447
+ def python_signature_expression_coverage_issues(evaluator, requirements=None):
448
+ """Detect anchored call expressions omitted by a static verifier.
449
+
450
+ Literal-only call checks used to silently discard non-literal positional
451
+ and keyword expressions from the same package-owned call. That allowed a
452
+ candidate to retain one easy literal while replacing the actual callback,
453
+ input binding, or argument tuple. Only expressions present in the
454
+ selected requirement text are required here; unrelated reference-file
455
+ context remains outside the objective contract.
456
+ """
457
+ if not isinstance(evaluator, dict) or evaluator.get("type") != \
458
+ WORKSPACE_EVALUATOR:
459
+ return []
460
+ reference_files = {
461
+ str(item.get("path") or ""): str(item.get("content") or "")
462
+ for item in evaluator.get("reference_files") or []
463
+ if isinstance(item, dict)}
464
+ requirement_texts = [
465
+ re.sub(r"\s+", "", str(item.get("requirement") or ""))
466
+ for item in requirements or [] if isinstance(item, dict)]
467
+ issues = []
468
+ for check in evaluator.get("checks") or []:
469
+ if (not isinstance(check, dict) or
470
+ check.get("type") != "python_call_signature"):
471
+ continue
472
+ function = str(check.get("function") or "")
473
+ source = reference_files.get(str(check.get("path") or ""), "")
474
+ if not function or not source:
475
+ continue
476
+ try:
477
+ _, _, constants, call_nodes = _python_semantics(source)
478
+ except SyntaxError:
479
+ issues.append("Python signature reference content is invalid")
480
+ continue
481
+ matches = [node for name, node in call_nodes
482
+ if _call_name_matches(name, function) and
483
+ _call_signature_matches(
484
+ node, check.get("arguments") or [],
485
+ check.get("keywords") or {}, constants,
486
+ check.get("argument_expressions") or [],
487
+ check.get("keyword_expressions") or {},
488
+ check.get("assignment"))]
489
+ if len(matches) != 1:
490
+ issues.append(
491
+ "Python call signature does not identify one reference call")
492
+ continue
493
+ reference_signature = _call_signature(matches[0], constants)
494
+ function_tokens = {re.sub(r"\s+", "", function),
495
+ re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
496
+
497
+ def positional_is_anchored(expression):
498
+ compact = re.sub(r"\s+", "", str(expression or ""))
499
+ return any(compact and compact in text and any(
500
+ token and token in text for token in function_tokens)
501
+ for text in requirement_texts)
502
+
503
+ def keyword_is_anchored(name, expression):
504
+ compact = re.sub(r"\s+", "", str(expression or ""))
505
+ needle = f"{name}={compact}"
506
+ return any(compact and needle in text and any(
507
+ token and token in text for token in function_tokens)
508
+ for text in requirement_texts)
509
+
510
+ expected_arguments = {
511
+ item["index"]: item.get("expression")
512
+ for item in reference_signature.get("argument_expressions") or []
513
+ if positional_is_anchored(item.get("expression"))}
514
+ expected_keywords = {
515
+ name: expression for name, expression in
516
+ (reference_signature.get("keyword_expressions") or {}).items()
517
+ if keyword_is_anchored(name, expression)}
518
+ actual_arguments = {
519
+ item.get("index"): item.get("expression")
520
+ for item in check.get("argument_expressions") or []
521
+ if isinstance(item, dict)}
522
+ actual_keywords = check.get("keyword_expressions") or {}
523
+ expected_assignment = reference_signature.get("assignment")
524
+ if expected_assignment:
525
+ compact_assignment = re.sub(
526
+ r"\s+", "", f"{expected_assignment.get('target')}="
527
+ f"{expected_assignment.get('expression')}")
528
+ assignment_is_anchored = any(
529
+ compact_assignment and compact_assignment in text and any(
530
+ token and token in text for token in function_tokens)
531
+ for text in requirement_texts)
532
+ else:
533
+ assignment_is_anchored = False
534
+ actual_assignment = check.get("assignment")
535
+ missing_argument = any(
536
+ index not in actual_arguments or
537
+ _expression_fingerprint(actual_arguments[index]) !=
538
+ _expression_fingerprint(expression)
539
+ for index, expression in expected_arguments.items())
540
+ missing_keyword = any(
541
+ name not in actual_keywords or
542
+ _expression_fingerprint(actual_keywords[name]) !=
543
+ _expression_fingerprint(expression)
544
+ for name, expression in expected_keywords.items())
545
+ missing_assignment = bool(
546
+ assignment_is_anchored and (
547
+ not isinstance(actual_assignment, dict) or
548
+ actual_assignment.get("target") !=
549
+ expected_assignment.get("target") or
550
+ _expression_fingerprint(actual_assignment.get("expression")) !=
551
+ _expression_fingerprint(
552
+ expected_assignment.get("expression"))))
553
+ if missing_argument or missing_keyword or missing_assignment:
554
+ issues.append(
555
+ "Python call signature omits an anchored expression or assignment")
556
+ return issues
557
+
558
+
559
+ def _shell_lines(text):
560
+ """Return executable lines with conservative local scalar substitution.
561
+
562
+ Shell authors routinely name a fixed argument before using it (for example
563
+ ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
564
+ assignments; never evaluate shell expressions, commands, or defaults.
565
+ """
566
+ logical, pending = [], ""
567
+ for raw in str(text or "").splitlines():
568
+ line = " ".join(raw.strip().split())
569
+ if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
570
+ continue
571
+ pending = (pending + " " + line).strip() if pending else line
572
+ if pending.endswith("\\"):
573
+ pending = pending[:-1].rstrip()
574
+ continue
575
+ logical.append(pending)
576
+ pending = ""
577
+ if pending:
578
+ logical.append(pending)
579
+
580
+ constants, out = {}, []
581
+ assignment = re.compile(
582
+ r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
583
+ r"([A-Za-z0-9_./:+-]+))$")
584
+ variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
585
+ for line in logical:
586
+ match = assignment.fullmatch(line)
587
+ if match:
588
+ constants[match.group(1)] = next(
589
+ value for value in match.groups()[1:] if value is not None)
590
+ out.append(line)
591
+ continue
592
+
593
+ def replace(match):
594
+ name = match.group(1) or match.group(2)
595
+ return constants.get(name, match.group(0))
596
+
597
+ out.append(variable.sub(replace, line))
598
+ return out
599
+
600
+
601
+ def _shell_command_matches(expected, actual):
602
+ """Accept the frozen invocation plus documented optional arguments/path prefixes."""
603
+ try:
604
+ wanted = shlex.split(str(expected))
605
+ found = shlex.split(str(actual))
606
+ except ValueError:
607
+ return False
608
+ def normalize_git_log_limit(tokens):
609
+ if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
610
+ return tokens
611
+ normalized, index = [], 0
612
+ while index < len(tokens):
613
+ token = tokens[index]
614
+ short = re.fullmatch(r"-(\d+)", token)
615
+ long = re.fullmatch(r"--max-count=(\d+)", token)
616
+ if short or long:
617
+ normalized.append("--max-count=" + (short or long).group(1))
618
+ elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
619
+ re.fullmatch(r"\d+", tokens[index + 1])):
620
+ normalized.append("--max-count=" + tokens[index + 1])
621
+ index += 1
622
+ else:
623
+ normalized.append(token)
624
+ index += 1
625
+ return normalized
626
+
627
+ wanted = normalize_git_log_limit(wanted)
628
+ found = normalize_git_log_limit(found)
629
+ if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
630
+ return False
631
+ for index, token in enumerate(wanted[1:], 1):
632
+ observed = found[index]
633
+ if observed == token:
634
+ continue
635
+ # A solver may anchor a package-relative script at $REPO_ROOT while
636
+ # preserving the exact package path selected by the Skill.
637
+ if (index == 1 and "/" in token and
638
+ observed.rstrip("/").endswith(token.lstrip("./"))):
639
+ continue
640
+ return False
641
+ return True
642
+
643
+
644
+ def _shell_command_sequence_matches(expected, actual_lines):
645
+ """Require every frozen command in order while allowing extra lines."""
646
+ cursor = 0
647
+ for command in expected:
648
+ for index in range(cursor, len(actual_lines)):
649
+ if _shell_command_matches(command, actual_lines[index]):
650
+ cursor = index + 1
651
+ break
652
+ else:
653
+ return False
654
+ return True
655
+
656
+
657
+ def _shell_unconditional_lines(text):
658
+ """Return conservative top-level command lines from a shell artifact.
659
+
660
+ Checked commands hidden in a conditional branch or an uncalled function do
661
+ not establish that the requested script performs them. This is not a full
662
+ shell parser: unsupported control flow simply makes nested lines
663
+ ineligible, which is appropriate for the small straight-line command
664
+ artifacts compiled by this evaluator.
665
+ """
666
+ lines = _shell_lines(text)
667
+ depth = 0
668
+ out = []
669
+ opener = re.compile(
670
+ r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
671
+ r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
672
+ closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
673
+ for line in lines:
674
+ if closer.match(line):
675
+ depth = max(0, depth - 1)
676
+ continue
677
+ if depth == 0 and not opener.match(line):
678
+ out.append(line)
679
+ if opener.match(line):
680
+ depth += 1
681
+ return out
682
+
683
+
684
+ def _shell_is_straight_line(text):
685
+ """Return whether every executable logical line is top-level.
686
+
687
+ This deliberately reuses the conservative control-flow recognizer used by
688
+ unconditional command checks. Any recognized conditional, loop, case, or
689
+ function makes the whole-script straight-line contract fail closed.
690
+ """
691
+ lines = _shell_lines(text)
692
+ return lines == _shell_unconditional_lines(text)
693
+
694
+
695
+ def compile_workspace_evaluator(deliverables):
696
+ """Compile trusted checks from validated deliverable specifications."""
697
+ if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
698
+ raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
699
+ reference_files, checks, paths = [], [], set()
700
+ for index, raw in enumerate(deliverables, 1):
701
+ if not isinstance(raw, dict):
702
+ raise ObjectiveEvaluatorError("deliverable is not an object")
703
+ path = safe_relative_path(raw.get("path"))
704
+ if path in paths:
705
+ raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
706
+ paths.add(path)
707
+ fmt = str(raw.get("format") or "").strip().casefold()
708
+ if fmt not in ARTIFACT_FORMATS:
709
+ raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
710
+ content = _file_content({**raw, "format": fmt})
711
+ if len(content.encode("utf-8")) > 200_000:
712
+ raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
713
+ reference_files.append({"path": path, "format": fmt, "content": content})
714
+ checks.append({"id": f"file_{index:03d}", "type": "file_exists",
715
+ "path": path})
716
+ if fmt == "json":
717
+ checks.append({"id": f"json_{index:03d}", "type": "json_exact",
718
+ "path": path, "expected": _json_value(raw.get("content"))})
719
+ elif fmt == "toml":
720
+ try:
721
+ expected = tomllib.loads(content)
722
+ except (tomllib.TOMLDecodeError, ValueError) as exc:
723
+ raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
724
+ checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
725
+ "path": path, "expected": expected})
726
+ elif fmt == "python":
727
+ try:
728
+ _, _, constants, call_nodes = _python_semantics(content)
729
+ resolved_calls = _python_resolved_call_nodes(content)
730
+ except SyntaxError as exc:
731
+ raise ObjectiveEvaluatorError("reference Python is invalid") from exc
732
+ checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
733
+ "path": path})
734
+ checks.append({"id": f"python_{index:03d}_bindings",
735
+ "type": "python_bound_calls", "path": path})
736
+ raw_checks = raw.get("checks") or []
737
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
738
+ raise ObjectiveEvaluatorError(
739
+ "Python deliverable requires 1-12 objective import/call checks")
740
+ for check_index, check in enumerate(raw_checks, 1):
741
+ if not isinstance(check, dict):
742
+ raise ObjectiveEvaluatorError("Python check is not an object")
743
+ kind = str(check.get("type") or "").strip().casefold()
744
+ if kind in {"python_import", "python_call"}:
745
+ value = str(check.get("value") or "").strip()
746
+ if not _DOTTED.fullmatch(value):
747
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
748
+ compiled = {"type": kind, "path": path, "value": value}
749
+ elif kind == "python_constant":
750
+ name = str(check.get("name") or "").strip()
751
+ value = check.get("value")
752
+ if (not _DOTTED.fullmatch(name) or "." in name or
753
+ isinstance(value, (dict, list)) or value is None or
754
+ constants.get(name, _UNRESOLVED) != value):
755
+ raise ObjectiveEvaluatorError(
756
+ "Python constant check is invalid or fails reference content")
757
+ compiled = {"type": kind, "path": path, "name": name,
758
+ "value": value}
759
+ elif kind == "python_call_literal":
760
+ function = str(check.get("function") or "").strip()
761
+ value = check.get("value")
762
+ if (not _DOTTED.fullmatch(function) or
763
+ isinstance(value, (dict, list)) or value is None or
764
+ not any(
765
+ (name == function or name.endswith("." + function)) and
766
+ _node_contains_literal(node, value, constants)
767
+ for name, node in call_nodes)):
768
+ raise ObjectiveEvaluatorError(
769
+ "Python call-literal check is invalid or fails reference content")
770
+ compiled = {"type": kind, "path": path,
771
+ "function": function, "value": value}
772
+ elif kind == "python_call_keyword_literal":
773
+ function = str(check.get("function") or "").strip()
774
+ keyword = str(check.get("keyword") or "").strip()
775
+ value = check.get("value")
776
+ if (not _DOTTED.fullmatch(function) or
777
+ not _DOTTED.fullmatch(keyword) or "." in keyword or
778
+ isinstance(value, (dict, list)) or value is None or
779
+ not any(
780
+ (name == function or name.endswith("." + function)) and
781
+ _call_keyword_matches(node, keyword, value, constants)
782
+ for name, node in call_nodes)):
783
+ raise ObjectiveEvaluatorError(
784
+ "Python call-keyword check is invalid or fails reference content")
785
+ compiled = {"type": kind, "path": path,
786
+ "function": function, "keyword": keyword,
787
+ "value": value}
788
+ elif kind == "python_call_signature":
789
+ function = str(check.get("function") or "").strip()
790
+ arguments = check.get("arguments") or []
791
+ keywords = check.get("keywords") or {}
792
+ argument_expressions = check.get(
793
+ "argument_expressions") or []
794
+ keyword_expressions = check.get(
795
+ "keyword_expressions") or {}
796
+ assignment = check.get("assignment")
797
+ if (not _DOTTED.fullmatch(function) or
798
+ not isinstance(arguments, list) or
799
+ not isinstance(keywords, dict) or
800
+ not isinstance(argument_expressions, list) or
801
+ not isinstance(keyword_expressions, dict) or
802
+ not (arguments or keywords or
803
+ argument_expressions or keyword_expressions or
804
+ assignment) or
805
+ any(not isinstance(item, dict) or
806
+ not isinstance(item.get("index"), int) or
807
+ item.get("index") < 0 or
808
+ isinstance(item.get("value"), dict)
809
+ for item in arguments) or
810
+ len({item["index"] for item in arguments}) !=
811
+ len(arguments) or
812
+ any(not _DOTTED.fullmatch(str(name)) or
813
+ "." in str(name) or isinstance(value, dict)
814
+ for name, value in keywords.items()) or
815
+ any(not isinstance(item, dict) or
816
+ not isinstance(item.get("index"), int) or
817
+ item.get("index") < 0 or
818
+ not _expression_fingerprint(
819
+ item.get("expression"))
820
+ for item in argument_expressions) or
821
+ len({item["index"] for item in
822
+ argument_expressions}) !=
823
+ len(argument_expressions) or
824
+ ({item["index"] for item in arguments} &
825
+ {item["index"] for item in
826
+ argument_expressions}) or
827
+ any(not _DOTTED.fullmatch(str(name)) or
828
+ "." in str(name) or
829
+ not _expression_fingerprint(value)
830
+ for name, value in
831
+ keyword_expressions.items()) or
832
+ (set(keywords) & set(keyword_expressions)) or
833
+ (assignment is not None and (
834
+ not isinstance(assignment, dict) or
835
+ not _DOTTED.fullmatch(str(
836
+ assignment.get("target") or "")) or
837
+ "." in str(assignment.get("target") or "") or
838
+ not _expression_fingerprint(
839
+ assignment.get("expression")))) or
840
+ not any(
841
+ (name == function or
842
+ name.endswith("." + function)) and
843
+ _call_signature_matches(
844
+ node, arguments, keywords, constants,
845
+ argument_expressions,
846
+ keyword_expressions, assignment)
847
+ for name, node in call_nodes)):
848
+ raise ObjectiveEvaluatorError(
849
+ "Python call-signature check is invalid or fails reference content")
850
+ compiled = {"type": kind, "path": path,
851
+ "function": function,
852
+ "arguments": arguments,
853
+ "keywords": keywords,
854
+ "argument_expressions": argument_expressions,
855
+ "keyword_expressions": keyword_expressions,
856
+ "assignment": assignment}
857
+ else:
858
+ raise ObjectiveEvaluatorError("unsupported Python objective check")
859
+ if kind in {"python_call", "python_call_literal",
860
+ "python_call_keyword_literal",
861
+ "python_call_signature"}:
862
+ targets = _objective_call_targets(
863
+ kind, compiled, resolved_calls, constants)
864
+ if len(targets) != 1:
865
+ raise ObjectiveEvaluatorError(
866
+ "Python call check has no unique canonical target")
867
+ compiled["target"] = next(iter(targets))
868
+ checks.append({"id": f"python_{index:03d}_{check_index:03d}",
869
+ **compiled})
870
+ else:
871
+ raw_checks = raw.get("checks") or []
872
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
873
+ raise ObjectiveEvaluatorError(
874
+ "shell deliverable requires 1-12 objective command checks")
875
+ checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
876
+ "path": path})
877
+ reference_sequence = _shell_lines(content)
878
+ reference_lines = set(reference_sequence)
879
+ unconditional_lines = _shell_unconditional_lines(content)
880
+ command_checks = []
881
+ for check in raw_checks:
882
+ value = " ".join(str(check.get("value") or "").strip().split())
883
+ if (not isinstance(check, dict) or
884
+ str(check.get("type") or "").strip().casefold() != "shell_command" or
885
+ not value or value not in reference_lines):
886
+ raise ObjectiveEvaluatorError("unsupported shell objective check")
887
+ command_checks.append({"type": "shell_command", "path": path,
888
+ "value": value})
889
+ if len({item["value"] for item in command_checks}) != len(command_checks):
890
+ raise ObjectiveEvaluatorError("shell objective checks must be unique")
891
+ command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
892
+ if not all(any(_shell_command_matches(
893
+ item["value"], line) for line in unconditional_lines)
894
+ for item in command_checks):
895
+ raise ObjectiveEvaluatorError(
896
+ "checked shell commands must be top-level and unconditional")
897
+ for check_index, check in enumerate(command_checks, 1):
898
+ checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
899
+ **check})
900
+ if len(command_checks) >= 2:
901
+ checks.append({
902
+ "id": f"shell_{index:03d}_sequence",
903
+ "type": "shell_command_sequence", "path": path,
904
+ "values": [item["value"] for item in command_checks],
905
+ })
906
+ checks.append({
907
+ "id": f"shell_{index:03d}_unconditional",
908
+ "type": "shell_unconditional_commands", "path": path,
909
+ "values": [item["value"] for item in command_checks],
910
+ })
911
+ # Preserve the reference's fail-fast behavior when accepting normal
912
+ # command-substitution/guard wrappers. Never turn `|| true` into a
913
+ # passing preflight simply because it contains the correct argv.
914
+ reference_calls = shell_invocations(content)
915
+ protected = [item["value"] for item in command_checks if any(
916
+ call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
917
+ for call in reference_calls)]
918
+ if protected:
919
+ checks.append({"id": f"shell_{index:03d}_failure_propagation",
920
+ "type": "shell_failure_propagation", "path": path,
921
+ "values": protected})
922
+ # Candidate workspaces may also contain root-level public inputs and
923
+ # installed Skill packages. Deliverables use dedicated top-level output
924
+ # directories, so enforce an exact file set inside those namespaces while
925
+ # leaving the read-only environment outside them untouched.
926
+ output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
927
+ if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
928
+ checks.insert(0, {
929
+ "id": "workspace_file_set", "type": "workspace_file_set",
930
+ "paths": sorted(paths), "roots": output_roots,
931
+ })
932
+ return {
933
+ "type": WORKSPACE_EVALUATOR,
934
+ "version": WORKSPACE_EVALUATOR_VERSION,
935
+ "output_mode": "workspace",
936
+ "reference_files": reference_files,
937
+ "checks": checks,
938
+ }
939
+
940
+
941
+ def reference_bundle(evaluator):
942
+ if evaluator.get("type") != WORKSPACE_EVALUATOR:
943
+ raise ObjectiveEvaluatorError("not a workspace evaluator")
944
+ return {"files": [
945
+ {"path": item["path"], "content": item["content"]}
946
+ for item in evaluator.get("reference_files") or []
947
+ ]}
948
+
949
+
950
+ def hidden_workspace_values(evaluator):
951
+ """Return decisive package-owned values that public queries must not leak."""
952
+ values = []
953
+ for check in (evaluator or {}).get("checks") or []:
954
+ kind = check.get("type")
955
+ if kind in {"json_exact", "toml_exact"}:
956
+ values.extend(value for _, value in _flatten(check.get("expected")))
957
+ elif kind in {"python_import", "python_call", "shell_command",
958
+ "python_constant", "python_call_literal",
959
+ "python_call_keyword_literal"}:
960
+ values.append(check.get("value"))
961
+ elif kind == "python_call_signature":
962
+ values.extend(value for _, value in _flatten({
963
+ "arguments": [item.get("value") for item in
964
+ check.get("arguments") or []],
965
+ "keywords": check.get("keywords") or {},
966
+ "argument_expressions": [item.get("expression") for item in
967
+ check.get("argument_expressions") or []],
968
+ "keyword_expressions": check.get("keyword_expressions") or {},
969
+ "assignment": check.get("assignment"),
970
+ }))
971
+ return [value for value in values if value is not None]
972
+
973
+
974
+ def _flatten(value, path=()):
975
+ if isinstance(value, dict):
976
+ out = []
977
+ for key, item in value.items():
978
+ out.extend(_flatten(item, path + (str(key),)))
979
+ return out
980
+ if isinstance(value, list):
981
+ out = []
982
+ for index, item in enumerate(value):
983
+ out.extend(_flatten(item, path + (index,)))
984
+ return out
985
+ return [(path, value)]
986
+
987
+
988
+ def _bundle_rows(candidate):
989
+ if isinstance(candidate, str):
990
+ text = candidate.strip()
991
+ # Chat solvers often wrap the requested file bundle in a Markdown fence
992
+ # or append a duplicate FINAL_ANSWER object. Decode one complete JSON
993
+ # value at a time instead of requiring the entire response to be JSON;
994
+ # only an object carrying the explicit ``files`` transport field is
995
+ # eligible, so unrelated prose/objects are not silently accepted.
996
+ decoder = json.JSONDecoder()
997
+ candidate = None
998
+ for match in re.finditer(r"\{", text):
999
+ try:
1000
+ parsed, _ = decoder.raw_decode(text, match.start())
1001
+ except json.JSONDecodeError:
1002
+ continue
1003
+ if isinstance(parsed, dict) and "files" in parsed:
1004
+ candidate = parsed
1005
+ break
1006
+ if candidate is None:
1007
+ raise ObjectiveEvaluatorError(
1008
+ "workspace response contains no complete JSON file bundle")
1009
+ if not isinstance(candidate, dict):
1010
+ raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
1011
+ files = candidate.get("files")
1012
+ if isinstance(files, dict):
1013
+ files = [{"path": path, "content": content}
1014
+ for path, content in files.items()]
1015
+ if not isinstance(files, list) or len(files) > 30:
1016
+ raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
1017
+ return files
1018
+
1019
+
1020
+ def materialize_bundle(candidate, workspace):
1021
+ root = Path(workspace).resolve()
1022
+ root.mkdir(parents=True, exist_ok=True)
1023
+ seen = set()
1024
+ for item in _bundle_rows(candidate):
1025
+ if not isinstance(item, dict):
1026
+ raise ObjectiveEvaluatorError("candidate file entry is not an object")
1027
+ relative = safe_relative_path(item.get("path"))
1028
+ if relative in seen:
1029
+ raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
1030
+ seen.add(relative)
1031
+ content = item.get("content")
1032
+ if isinstance(content, (dict, list)):
1033
+ content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
1034
+ if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
1035
+ raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
1036
+ target = (root / relative).resolve()
1037
+ if root not in target.parents:
1038
+ raise ObjectiveEvaluatorError("candidate file escapes workspace")
1039
+ target.parent.mkdir(parents=True, exist_ok=True)
1040
+ target.write_text(content, encoding="utf-8")
1041
+ return root
1042
+
1043
+
1044
+ def evaluate_workspace(evaluator, workspace):
1045
+ if (not isinstance(evaluator, dict) or
1046
+ evaluator.get("type") != WORKSPACE_EVALUATOR or
1047
+ int(evaluator.get("version") or 0) not in
1048
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
1049
+ return False, {"error": "invalid workspace evaluator contract"}
1050
+ root = Path(workspace).resolve()
1051
+ results = []
1052
+ for check in evaluator.get("checks") or []:
1053
+ kind = check.get("type")
1054
+ relative, path = "", None
1055
+ if kind != "workspace_file_set":
1056
+ relative = safe_relative_path(check.get("path"))
1057
+ path = (root / relative).resolve()
1058
+ if root not in path.parents:
1059
+ return False, {"error": "evaluator path escapes workspace"}
1060
+ passed, detail = False, ""
1061
+ try:
1062
+ if kind == "workspace_file_set":
1063
+ expected = {safe_relative_path(value)
1064
+ for value in check.get("paths") or []}
1065
+ roots = [safe_relative_path(value)
1066
+ for value in check.get("roots") or []]
1067
+ actual = set()
1068
+ for relative_root in roots:
1069
+ scan_root = (root / relative_root).resolve()
1070
+ if root not in scan_root.parents:
1071
+ raise ObjectiveEvaluatorError(
1072
+ "workspace file-set root escapes workspace")
1073
+ if not scan_root.exists():
1074
+ continue
1075
+ for candidate in scan_root.rglob("*"):
1076
+ if candidate.is_file() or candidate.is_symlink():
1077
+ actual.add(candidate.relative_to(root).as_posix())
1078
+ passed = bool(expected) and actual == expected
1079
+ detail = ("exact deliverable file set" if passed else
1080
+ f"expected_files={sorted(expected)}; "
1081
+ f"actual_files={sorted(actual)}")
1082
+ elif kind == "file_exists":
1083
+ passed = path.is_file()
1084
+ detail = "present" if passed else "missing"
1085
+ elif kind == "json_exact":
1086
+ actual = json.loads(path.read_text(encoding="utf-8"))
1087
+ passed = _canonical(actual) == _canonical(check.get("expected"))
1088
+ detail = "semantic JSON match" if passed else "JSON value mismatch"
1089
+ elif kind == "toml_exact":
1090
+ actual = tomllib.loads(path.read_text(encoding="utf-8"))
1091
+ passed = _canonical(actual) == _canonical(check.get("expected"))
1092
+ detail = "semantic TOML match" if passed else "TOML value mismatch"
1093
+ elif kind in {"python_syntax", "python_bound_calls",
1094
+ "python_import", "python_call",
1095
+ "python_constant", "python_call_literal",
1096
+ "python_call_keyword_literal",
1097
+ "python_call_signature"}:
1098
+ source = path.read_text(encoding="utf-8")
1099
+ imports, calls, constants, call_nodes = _python_semantics(source)
1100
+ resolved_calls = _python_resolved_call_nodes(source)
1101
+ if kind == "python_syntax":
1102
+ passed, detail = True, "valid Python syntax"
1103
+ elif kind == "python_bound_calls":
1104
+ unbound = python_unbound_call_roots(
1105
+ path.read_text(encoding="utf-8"))
1106
+ passed = not unbound
1107
+ detail = ("all call roots are statically bound" if passed else
1108
+ "unbound call roots=" + repr(unbound))
1109
+ elif kind == "python_import":
1110
+ expected = str(check.get("value") or "")
1111
+ passed = expected in imports or any(
1112
+ value == expected or value.startswith(expected + ".")
1113
+ for value in imports)
1114
+ detail = f"imports={sorted(imports)}"
1115
+ elif kind == "python_call":
1116
+ expected = str(check.get("value") or "")
1117
+ target = str(check.get("target") or "")
1118
+ passed = (any(
1119
+ canonical == target
1120
+ for _, canonical, _ in resolved_calls)
1121
+ if target else expected in calls or any(
1122
+ value.endswith("." + expected)
1123
+ for value in calls))
1124
+ detail = f"calls={sorted(calls)}"
1125
+ elif kind == "python_constant":
1126
+ name, expected = str(check.get("name") or ""), check.get("value")
1127
+ actual = constants.get(name, _UNRESOLVED)
1128
+ passed = actual is not _UNRESOLVED and actual == expected
1129
+ detail = f"constant {name}={actual!r}"
1130
+ elif kind == "python_call_literal":
1131
+ function, expected = (str(check.get("function") or ""),
1132
+ check.get("value"))
1133
+ target = str(check.get("target") or "")
1134
+ source_calls = (resolved_calls if target else
1135
+ [(name, "", node) for name, node in call_nodes])
1136
+ passed = any(
1137
+ (bool(target) or _call_name_matches(name, function)) and
1138
+ (not target or canonical == target) and
1139
+ _node_contains_literal(node, expected, constants)
1140
+ for name, canonical, node in source_calls)
1141
+ detail = f"call={function} literal={expected!r}"
1142
+ elif kind == "python_call_keyword_literal":
1143
+ function = str(check.get("function") or "")
1144
+ keyword = str(check.get("keyword") or "")
1145
+ expected = check.get("value")
1146
+ target = str(check.get("target") or "")
1147
+ source_calls = (resolved_calls if target else
1148
+ [(name, "", node) for name, node in call_nodes])
1149
+ passed = any(
1150
+ (bool(target) or _call_name_matches(name, function)) and
1151
+ (not target or canonical == target) and
1152
+ _call_keyword_matches(node, keyword, expected, constants)
1153
+ for name, canonical, node in source_calls)
1154
+ detail = (f"call={function} keyword={keyword} "
1155
+ f"literal={expected!r}")
1156
+ else:
1157
+ function = str(check.get("function") or "")
1158
+ arguments = check.get("arguments") or []
1159
+ keywords = check.get("keywords") or {}
1160
+ argument_expressions = check.get(
1161
+ "argument_expressions") or []
1162
+ keyword_expressions = check.get(
1163
+ "keyword_expressions") or {}
1164
+ assignment = check.get("assignment")
1165
+ target = str(check.get("target") or "")
1166
+ source_calls = (resolved_calls if target else
1167
+ [(name, "", node) for name, node in call_nodes])
1168
+ passed = any(
1169
+ (bool(target) or _call_name_matches(name, function)) and
1170
+ (not target or canonical == target) and
1171
+ _call_signature_matches(
1172
+ node, arguments, keywords, constants,
1173
+ argument_expressions, keyword_expressions,
1174
+ assignment)
1175
+ for name, canonical, node in source_calls)
1176
+ detail = (f"call={function} arguments={arguments!r} "
1177
+ f"keywords={keywords!r} "
1178
+ f"argument_expressions={argument_expressions!r} "
1179
+ f"keyword_expressions={keyword_expressions!r} "
1180
+ f"assignment={assignment!r}")
1181
+ elif kind == "shell_syntax":
1182
+ completed = subprocess.run(
1183
+ ["bash", "-n", str(path)], capture_output=True, text=True,
1184
+ timeout=5, check=False)
1185
+ passed = completed.returncode == 0
1186
+ detail = ("valid shell syntax" if passed else
1187
+ (completed.stderr or "invalid shell syntax").strip())
1188
+ elif kind == "shell_command":
1189
+ source = path.read_text(encoding="utf-8")
1190
+ lines = ([call["command"] for call in shell_invocations(source)]
1191
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1192
+ expected = " ".join(str(check.get("value") or "").split())
1193
+ passed = any(_shell_command_matches(expected, line) for line in lines)
1194
+ detail = f"executable_lines={lines[:30]}"
1195
+ elif kind == "shell_command_sequence":
1196
+ source = path.read_text(encoding="utf-8")
1197
+ lines = ([call["command"] for call in shell_invocations(source)]
1198
+ if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
1199
+ expected = [" ".join(str(value).split())
1200
+ for value in check.get("values") or []]
1201
+ passed = (len(expected) >= 2 and
1202
+ _shell_command_sequence_matches(expected, lines))
1203
+ detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
1204
+ elif kind == "shell_unconditional_commands":
1205
+ source = path.read_text(encoding="utf-8")
1206
+ lines = ([call["command"] for call in shell_invocations(source)]
1207
+ if int(evaluator.get("version", 0)) >= 15
1208
+ else _shell_unconditional_lines(source))
1209
+ expected = [" ".join(str(value).split())
1210
+ for value in check.get("values") or []]
1211
+ passed = (bool(expected) and all(
1212
+ any(_shell_command_matches(command, line) for line in lines)
1213
+ for command in expected))
1214
+ detail = (f"expected_unconditional={expected}; "
1215
+ f"top_level_lines={lines[:30]}")
1216
+ elif kind == "shell_failure_propagation":
1217
+ calls = shell_invocations(path.read_text(encoding="utf-8"))
1218
+ expected = [" ".join(str(value).split())
1219
+ for value in check.get("values") or []]
1220
+ passed = bool(expected) and all(any(
1221
+ call["fail_fast"] and _shell_command_matches(command, call["command"])
1222
+ for call in calls) for command in expected)
1223
+ detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
1224
+ elif kind == "shell_straight_line":
1225
+ source = path.read_text(encoding="utf-8")
1226
+ passed = _shell_is_straight_line(source)
1227
+ detail = ("all executable lines are top-level" if passed else
1228
+ "shell contains conditional, loop, case, or function")
1229
+ else:
1230
+ detail = f"unsupported check: {kind}"
1231
+ except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
1232
+ json.JSONDecodeError,
1233
+ tomllib.TOMLDecodeError) as exc:
1234
+ detail = str(exc)
1235
+ results.append({"id": check.get("id"), "type": kind,
1236
+ "path": relative, "passed": bool(passed),
1237
+ "detail": detail[:1000]})
1238
+ return bool(results) and all(item["passed"] for item in results), {
1239
+ "type": WORKSPACE_EVALUATOR,
1240
+ "assertions_passed": sum(item["passed"] for item in results),
1241
+ "assertions_total": len(results),
1242
+ "assertions": results,
1243
+ }
1244
+
1245
+
1246
+ def evaluate_candidate(evaluator, candidate):
1247
+ if isinstance(candidate, os.PathLike):
1248
+ try:
1249
+ return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
1250
+ False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
1251
+ except (OSError, ValueError) as exc:
1252
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1253
+ if isinstance(candidate, str):
1254
+ # A chat file-bundle can be much longer than a filesystem path. Avoid
1255
+ # passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
1256
+ stripped = candidate.strip()
1257
+ if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
1258
+ and not stripped.startswith(("{", "[", "```"))):
1259
+ try:
1260
+ if Path(stripped).is_dir():
1261
+ return evaluate_workspace(evaluator, stripped)
1262
+ except (OSError, ValueError):
1263
+ # Python/platform versions differ on ENAMETOOLONG and invalid
1264
+ # path errors. It is still candidate text: parse it unchanged.
1265
+ pass
1266
+ try:
1267
+ with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
1268
+ materialize_bundle(candidate, temp)
1269
+ return evaluate_workspace(evaluator, temp)
1270
+ except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
1271
+ return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
1272
+
1273
+
1274
+ def self_test_workspace_evaluator(evaluator):
1275
+ correct = reference_bundle(evaluator)
1276
+ ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
1277
+ rows = list(correct.get("files") or [])
1278
+ perturbed = {"files": rows[1:] if len(rows) > 1 else []}
1279
+ ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
1280
+ mutations = []
1281
+ # Exact JSON fields must each matter, not merely the file's existence.
1282
+ for check in evaluator.get("checks") or []:
1283
+ if check.get("type") != "json_exact":
1284
+ continue
1285
+ for path, value in _flatten(check.get("expected")):
1286
+ candidate = copy.deepcopy(correct)
1287
+ file_row = next(row for row in candidate["files"]
1288
+ if row["path"] == check["path"])
1289
+ data = json.loads(file_row["content"])
1290
+ replacement = (not value if isinstance(value, bool) else
1291
+ value + 1 if isinstance(value, (int, float)) else
1292
+ str(value) + "__mutation__")
1293
+ if not path:
1294
+ data = replacement
1295
+ else:
1296
+ container = data
1297
+ for key in path[:-1]:
1298
+ container = container[key]
1299
+ container[path[-1]] = replacement
1300
+ file_row["content"] = json.dumps(data)
1301
+ passed, _ = evaluate_candidate(evaluator, candidate)
1302
+ mutations.append({"path": check["path"], "field": list(path),
1303
+ "rejected": not passed})
1304
+ return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
1305
+ "correct": correct_detail,
1306
+ "perturbed": wrong_detail,
1307
+ "scalar_mutations": mutations,
1308
+ }
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/shell_invocations.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A deliberately bounded, non-executing shell structure recognizer.
2
+
3
+ Supports simple commands, literal scalar assignments, one command substitution
4
+ on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
5
+ It does not interpret shell code or credit commands in branch bodies/functions.
6
+ Pipelines, command lists, substitutions within substitutions, and swallowed
7
+ failures are outside this grammar. bash -n remains a separate required check.
8
+ """
9
+ import re
10
+ import shlex
11
+
12
+
13
+ def _statements(text):
14
+ out, current = [], []
15
+ quote, escaped, comment, depth = None, False, False, 0
16
+ for ch in str(text):
17
+ if comment:
18
+ if ch == '\n':
19
+ comment = False
20
+ else:
21
+ continue
22
+ if escaped:
23
+ if ch != '\n':
24
+ current.extend(('\\', ch))
25
+ escaped = False
26
+ continue
27
+ if ch == '\\' and quote != "'":
28
+ escaped = True
29
+ continue
30
+ if quote:
31
+ current.append(ch)
32
+ if ch == quote:
33
+ quote = None
34
+ continue
35
+ if ch in "'\"":
36
+ quote = ch
37
+ current.append(ch)
38
+ elif ch == '#' and (not current or current[-1].isspace()):
39
+ comment = True
40
+ elif ch == '(':
41
+ depth += 1
42
+ current.append(ch)
43
+ elif ch == ')':
44
+ depth -= 1
45
+ if depth < 0:
46
+ return []
47
+ current.append(ch)
48
+ elif ch in '\n;' and depth == 0:
49
+ value = ''.join(current).strip()
50
+ if value:
51
+ out.append(value)
52
+ current = []
53
+ else:
54
+ current.append(ch)
55
+ if quote or escaped or depth:
56
+ return []
57
+ if ''.join(current).strip():
58
+ out.append(''.join(current).strip())
59
+ expanded = []
60
+ for statement in out:
61
+ inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
62
+ expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
63
+ return expanded
64
+
65
+
66
+ def _simple_argv(text):
67
+ if '$(' in text or '`' in text:
68
+ return None
69
+ try:
70
+ lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
71
+ lexer.whitespace_split = True
72
+ tokens = list(lexer)
73
+ except ValueError:
74
+ return None
75
+ argv, index = [], 0
76
+ redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
77
+ while index < len(tokens):
78
+ token = tokens[index]
79
+ if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
80
+ index += 1
81
+ token = tokens[index]
82
+ if token in redirects:
83
+ if index + 1 >= len(tokens):
84
+ return None
85
+ target = tokens[index + 1]
86
+ if (not target or any(c in target for c in '$`;&|<>()')
87
+ or target in ('{', '}')):
88
+ return None
89
+ index += 2
90
+ continue
91
+ if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
92
+ return None
93
+ argv.append(token)
94
+ index += 1
95
+ return argv or None
96
+
97
+
98
+ def _invocation(text):
99
+ substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
100
+ if substitution:
101
+ inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
102
+ argv = _simple_argv(inner)
103
+ return (argv, 'assignment_substitution') if argv else (None, None)
104
+ return _simple_argv(text), 'simple'
105
+
106
+
107
+ def _guard_end(statements, start):
108
+ depth = 1
109
+ for index in range(start + 1, len(statements)):
110
+ item = statements[index]
111
+ if re.match(r'^if\s', item):
112
+ depth += 1
113
+ elif item == 'fi':
114
+ depth -= 1
115
+ if depth == 0:
116
+ return index
117
+ return None
118
+
119
+
120
+
121
+ # R7: unwrap only execution wrappers whose effect is proved in this subset.
122
+ # In particular `command -v/-V` queries do not run their operand, and `builtin`
123
+ # cannot run an external tool. Keep these distinctions before inspecting state.
124
+ _BASH_BUILTINS = frozenset({
125
+ ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd',
126
+ 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',
127
+ 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
128
+ 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local',
129
+ 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray',
130
+ 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test',
131
+ 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias',
132
+ 'unset', 'wait',
133
+ })
134
+ _UNSUPPORTED_STATE = frozenset({
135
+ '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap',
136
+ 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local',
137
+ 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift',
138
+ '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts',
139
+ })
140
+
141
+
142
+ def _bash_dialect(text):
143
+ """No shebang uses the evaluator's Bash syntax contract; sh is not Bash."""
144
+ first = str(text).splitlines()[0] if str(text).splitlines() else ''
145
+ if not first.startswith('#!'):
146
+ return True
147
+ try:
148
+ words = shlex.split(first[2:])
149
+ except ValueError:
150
+ return False
151
+ if not words:
152
+ return False
153
+ executable = words[0].rsplit('/', 1)[-1]
154
+ if executable == 'env':
155
+ words = words[1:]
156
+ if words[:1] == ['-S']:
157
+ words = words[1:]
158
+ executable = words[0] if words else ''
159
+ return executable.rsplit('/', 1)[-1] == 'bash'
160
+
161
+
162
+ def _execution_argv(argv, bash=True):
163
+ """Normalize a finite chain; unsupported wrappers get no command credit."""
164
+ if not argv:
165
+ return None
166
+ argv = list(argv)
167
+ while argv and argv[0] in ('command', 'builtin'):
168
+ wrapper = argv[0]
169
+ if wrapper == 'builtin':
170
+ if not bash:
171
+ return None
172
+ argv = argv[1:]
173
+ if argv[:1] == ['--']:
174
+ argv = argv[1:]
175
+ if not argv or argv[0] not in _BASH_BUILTINS:
176
+ return None
177
+ continue
178
+ index, query, default_path = 1, False, False
179
+ while index < len(argv) and argv[index].startswith('-'):
180
+ option = argv[index]
181
+ index += 1
182
+ if option == '--':
183
+ break
184
+ if not re.fullmatch(r'-[pvV]+', option):
185
+ return None
186
+ query = query or 'v' in option or 'V' in option
187
+ default_path = default_path or 'p' in option
188
+ if query:
189
+ return argv # Query is an invocation of command, not its target.
190
+ if index == len(argv):
191
+ return None
192
+ argv = argv[index:]
193
+ # -p changes external PATH lookup. It is transparent for builtins only.
194
+ if default_path and argv[0] not in _BASH_BUILTINS:
195
+ return None
196
+ return argv or None
197
+
198
+
199
+ def _set_errexit(argv, current):
200
+ """Return the proven option state, or None for unsupported set options."""
201
+ if not argv or argv[0] != 'set':
202
+ return None
203
+ index = 1
204
+ while index < len(argv):
205
+ flag = argv[index]
206
+ if flag == '--' or not flag.startswith(('-', '+')):
207
+ break # Positional arguments cannot enable errexit.
208
+ if not re.fullmatch(r'[-+][eufxEo]+', flag):
209
+ return None # Includes noexec (-n), which suppresses later work.
210
+ if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1):
211
+ return None
212
+ if 'e' in flag[1:]:
213
+ current = flag[0] == '-'
214
+ if 'o' in flag[1:]:
215
+ if index + 1 >= len(argv):
216
+ return None
217
+ option = argv[index + 1]
218
+ if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
219
+ return None
220
+ if option == 'errexit':
221
+ current = flag[0] == '-'
222
+ index += 1
223
+ index += 1
224
+ return current
225
+
226
+
227
+ def shell_option_setting(text, bash=True):
228
+ """Recognize valid option setup for task-specific operation counters."""
229
+ argv = _execution_argv(_simple_argv(text), bash)
230
+ return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None)
231
+
232
+
233
+ def _exit_status(argv):
234
+ """A literal shell exit status; no-argument exit is handled by its caller."""
235
+ args = argv[1:]
236
+ if args[:1] == ['--']:
237
+ args = args[1:]
238
+ if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0])
239
+ or len(args[0]) > 20):
240
+ return None
241
+ value = int(args[0])
242
+ if not -(2**63) <= value <= 2**63 - 1:
243
+ return 2 # Bash exits for an out-of-range numeric argument.
244
+ return value % 256
245
+
246
+
247
+
248
+ def _nonzero_exit_body(statements, bash=True):
249
+ """Only literal logging followed by a final unconditional nonzero exit."""
250
+ if not statements:
251
+ return False
252
+ for index, statement in enumerate(statements):
253
+ argv = _execution_argv(_simple_argv(statement), bash)
254
+ if not argv:
255
+ return False
256
+ if argv[0] == 'exit':
257
+ status = _exit_status(argv)
258
+ return index == len(statements) - 1 and status is not None and status != 0
259
+ if argv[0] not in ('echo', 'printf'):
260
+ return False
261
+ return False
262
+
263
+
264
+ def shell_invocations(text):
265
+ """Return ordered, actually evaluated invocation nodes in the supported subset.
266
+
267
+ fail_fast is a structural proof: a simple command/assignment runs under
268
+ errexit, or a negated test exits nonzero on failure. This is not a complete
269
+ shell interpreter, and unsupported syntax earns no invocation credit.
270
+ """
271
+ statements = _statements(text)
272
+ bash = _bash_dialect(text)
273
+ # Function definitions or dynamic shell mutation can shadow the command or
274
+ # `exit` itself. They are outside this objective subset, even if uncalled.
275
+ 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)
276
+ or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
277
+ for s in statements):
278
+ return []
279
+ constants, result, index, errexit = {}, [], 0, False
280
+ assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
281
+ variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
282
+ while index < len(statements):
283
+ statement = statements[index]
284
+ literal = assignment.fullmatch(statement)
285
+ if literal:
286
+ constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
287
+ index += 1
288
+ continue
289
+ statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement)
290
+ if re.match(r'^if\s', statement):
291
+ end = _guard_end(statements, index)
292
+ if end is None:
293
+ return []
294
+ negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
295
+ if (negated and index + 1 < end
296
+ and statements[index + 1] == 'then'
297
+ and _nonzero_exit_body(statements[index + 2:end], bash)):
298
+ argv, kind = _invocation(negated.group(1).strip())
299
+ argv = _execution_argv(argv, bash)
300
+ if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')):
301
+ return []
302
+ if argv:
303
+ if argv[0] == 'false':
304
+ break
305
+ result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
306
+ 'fail_fast': True, 'statement_index': index, 'expanded_statement': statement})
307
+ else:
308
+ return []
309
+ else:
310
+ # Arbitrary conditions may terminate the script or shadow its
311
+ # commands. Do not infer a reachable suffix through them.
312
+ return []
313
+ # Bodies are never credited and may have assigned local variables.
314
+ constants.clear()
315
+ index = end + 1
316
+ continue
317
+ if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
318
+ # Unsupported compounds are not searched for command substrings.
319
+ return []
320
+ argv, kind = _invocation(statement)
321
+ argv = _execution_argv(argv, bash)
322
+ if not argv:
323
+ # An unparsed statement may change control flow or shell state.
324
+ # Skipping it would incorrectly credit an unreachable suffix.
325
+ return []
326
+ if argv[0] in _UNSUPPORTED_STATE:
327
+ return []
328
+ if argv[0] == 'hash':
329
+ # Clearing/querying/cache lookup preserves the command's selected
330
+ # executable. An explicit -p binding can replace a required tool.
331
+ operands, flags = [], ''
332
+ option_mode = True
333
+ for word in argv[1:]:
334
+ if option_mode and word == '--':
335
+ option_mode = False
336
+ elif option_mode and word.startswith('-'):
337
+ if not re.fullmatch(r'-[lrdt]+', word):
338
+ return []
339
+ flags += word[1:]
340
+ else:
341
+ option_mode = False
342
+ if '$' in word:
343
+ return []
344
+ operands.append(word)
345
+ if ('d' in flags or 't' in flags) and not operands:
346
+ return []
347
+ if argv[0] == 'set':
348
+ new_errexit = _set_errexit(argv, errexit)
349
+ if new_errexit is None:
350
+ return []
351
+ if kind == 'simple':
352
+ errexit = new_errexit
353
+ index += 1
354
+ continue
355
+ # An assignment substitution runs in a subshell: set cannot change
356
+ # the parent's flags. Keep it as an ordinary evaluated node.
357
+ if argv[0] == 'exit':
358
+ if kind == 'simple':
359
+ # Only a literal, zero/one-argument exit is proved terminal.
360
+ # An invalid multi-argument exit can return and is unsupported.
361
+ if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None:
362
+ break
363
+ return []
364
+ status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv)
365
+ if status is None:
366
+ return []
367
+ if status and errexit:
368
+ break
369
+ if argv[0] == 'false' and errexit:
370
+ break
371
+ if kind == 'assignment_substitution':
372
+ assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
373
+ if assigned:
374
+ constants.pop(assigned.group(1), None)
375
+ result.append({'command': shlex.join(argv), 'kind': kind,
376
+ 'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement})
377
+ index += 1
378
+ return result
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/test.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}}
4
+ if [[ -z "$candidate" ]]; then
5
+ echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2
6
+ exit 64
7
+ fi
8
+ python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate"
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/legacy_tests/verifiers.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier execution engine and fail-closed self-tests.
2
+
3
+ New verified tasks use atomic_json (complete shape plus scalar assertions).
4
+ Legacy verifier types remain readable so historical runs can still be audited.
5
+ 自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
6
+ """
7
+ import json
8
+ import logging
9
+ import os
10
+ import re
11
+
12
+ try:
13
+ from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
14
+ reference_bundle,
15
+ self_test_workspace_evaluator)
16
+ except ImportError: # portable task copies these modules beside each other
17
+ from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
18
+ reference_bundle,
19
+ self_test_workspace_evaluator)
20
+
21
+ log = logging.getLogger("pipeline")
22
+
23
+
24
+ def _norm(s):
25
+ return str(s).strip().lower()
26
+
27
+
28
+ def _json_value(value):
29
+ """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
30
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
31
+ return value
32
+ text = str(value).strip()
33
+ match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
34
+ if match:
35
+ text = match.group(1).strip()
36
+ text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
37
+ text = re.sub(r"\s*```$", "", text)
38
+ start_obj, start_arr = text.find("{"), text.find("[")
39
+ starts = [x for x in (start_obj, start_arr) if x >= 0]
40
+ if starts:
41
+ start = min(starts)
42
+ closing = "}" if text[start] == "{" else "]"
43
+ end = text.rfind(closing)
44
+ if end >= start:
45
+ text = text[start:end + 1]
46
+ return json.loads(text)
47
+
48
+
49
+ def _canonical_json(value):
50
+ if isinstance(value, dict):
51
+ return {key: _canonical_json(value[key]) for key in sorted(value)}
52
+ if isinstance(value, list):
53
+ values = [_canonical_json(item) for item in value]
54
+ return sorted(values, key=lambda item: json.dumps(
55
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
56
+ return value
57
+
58
+
59
+ def _atomic_prepare(value, list_order):
60
+ if isinstance(value, dict):
61
+ return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
62
+ if isinstance(value, list):
63
+ values = [_atomic_prepare(item, list_order) for item in value]
64
+ if list_order == "unordered":
65
+ values.sort(key=lambda item: json.dumps(
66
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
67
+ return values
68
+ return value
69
+
70
+
71
+ def _atomic_shape(value):
72
+ if isinstance(value, dict):
73
+ return {"type": "object", "keys": {
74
+ key: _atomic_shape(item) for key, item in value.items()}}
75
+ if isinstance(value, list):
76
+ return {"type": "array", "length": len(value),
77
+ "items": [_atomic_shape(item) for item in value]}
78
+ if isinstance(value, bool):
79
+ return {"type": "boolean"}
80
+ if value is None:
81
+ return {"type": "null"}
82
+ if isinstance(value, (int, float)):
83
+ return {"type": "number"}
84
+ return {"type": "string"}
85
+
86
+
87
+ def _atomic_leaves(value, path="$", tokens=()):
88
+ if isinstance(value, dict):
89
+ out = []
90
+ for key, item in value.items():
91
+ out.extend(_atomic_leaves(
92
+ item, path + "." + key, tokens + (key,)))
93
+ return out
94
+ if isinstance(value, list):
95
+ out = []
96
+ for index, item in enumerate(value):
97
+ out.extend(_atomic_leaves(
98
+ item, f"{path}[{index}]", tokens + (index,)))
99
+ return out
100
+ return [(path, tokens, value)]
101
+
102
+
103
+ def _normalize_path_equivalence_tokens(values):
104
+ """Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
105
+ normalized = []
106
+ for tokens in values or []:
107
+ if (not isinstance(tokens, (list, tuple)) or not tokens or
108
+ any(not isinstance(token, (str, int)) for token in tokens)):
109
+ raise ValueError("path equivalence tokens must be non-empty JSON paths")
110
+ item = list(tokens)
111
+ if item not in normalized:
112
+ normalized.append(item)
113
+ return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
114
+
115
+
116
+ def _path_value(value):
117
+ """Normalize only portable path spelling, not general answer text."""
118
+ if not isinstance(value, str):
119
+ return None
120
+ text = value.strip().replace("\\", "/")
121
+ if text != "/":
122
+ text = text.rstrip("/")
123
+ return text
124
+
125
+
126
+ def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
127
+ path_equivalence_tokens=None):
128
+ """Freeze a complete JSON shape plus one assertion for every scalar leaf."""
129
+ if list_order not in {"ordered", "unordered"}:
130
+ raise ValueError(f"unsupported atomic list_order: {list_order}")
131
+ tolerance = float(float_tolerance)
132
+ prepared = _atomic_prepare(_json_value(expected), list_order)
133
+ path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
134
+ assertions = []
135
+ for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
136
+ assertion = {"id": f"leaf_{index:03d}", "path": path,
137
+ "tokens": list(tokens), "operator": "eq", "expected": value}
138
+ if isinstance(value, float):
139
+ assertion.update({"operator": "abs_diff", "tolerance": tolerance})
140
+ elif list(tokens) in path_tokens:
141
+ if not isinstance(value, str):
142
+ raise ValueError("path equivalence can only target string leaves")
143
+ assertion["operator"] = "path_eq"
144
+ assertions.append(assertion)
145
+ compiled = {
146
+ "type": "atomic_json", "version": 2 if path_tokens else 1,
147
+ "list_order": list_order,
148
+ "float_tolerance": tolerance,
149
+ "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
150
+ "assertions": assertions,
151
+ }
152
+ if path_tokens:
153
+ compiled["path_equivalence_tokens"] = path_tokens
154
+ return compiled
155
+
156
+
157
+ def _shape_differences(expected, actual, path="$"):
158
+ if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
159
+ return [f"{path}: expected {expected.get('type')}, got "
160
+ f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
161
+ kind = expected.get("type")
162
+ if kind == "object":
163
+ expected_keys = set((expected.get("keys") or {}))
164
+ actual_keys = set((actual.get("keys") or {}))
165
+ differences = [f"{path}: missing key {key}" for key in sorted(
166
+ expected_keys - actual_keys)]
167
+ differences.extend(f"{path}: extra key {key}" for key in sorted(
168
+ actual_keys - expected_keys))
169
+ for key in sorted(expected_keys & actual_keys):
170
+ differences.extend(_shape_differences(
171
+ expected["keys"][key], actual["keys"][key], path + "." + key))
172
+ return differences
173
+ if kind == "array":
174
+ differences = []
175
+ if actual.get("length") != expected.get("length"):
176
+ differences.append(
177
+ f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
178
+ for index, (expected_item, actual_item) in enumerate(zip(
179
+ expected.get("items") or [], actual.get("items") or [])):
180
+ differences.extend(_shape_differences(
181
+ expected_item, actual_item, f"{path}[{index}]"))
182
+ return differences
183
+ return []
184
+
185
+
186
+ def _atomic_get(value, tokens):
187
+ current = value
188
+ for token in tokens:
189
+ current = current[token]
190
+ return current
191
+
192
+
193
+ def _int_values(value):
194
+ if isinstance(value, (list, tuple)):
195
+ out = []
196
+ for item in value:
197
+ out.extend(_int_values(item))
198
+ return out
199
+ if isinstance(value, int) and not isinstance(value, bool):
200
+ return [value]
201
+ return [int(number) for number in re.findall(r"\d+", str(value or ""))]
202
+
203
+
204
+ def _finding_type(value):
205
+ text = str(value or "").lower().replace("-", "_")
206
+ if "duplicate" in text:
207
+ return "duplicate_rows"
208
+ if ("none" in text or "null" in text) and "check" in text:
209
+ return "none_check"
210
+ if "missing" in text or "empty" in text or "null" in text:
211
+ return "missing"
212
+ if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
213
+ return "outlier"
214
+ if "invalid" in text and "config" in text:
215
+ return "invalid_config"
216
+ if "off" in text and "one" in text:
217
+ return "off_by_one"
218
+ return text.strip().replace(" ", "_")
219
+
220
+
221
+ def _normalized_findings(value, family):
222
+ obj = _json_value(value)
223
+ findings = obj.get("findings") if isinstance(obj, dict) else None
224
+ if not isinstance(findings, list):
225
+ raise ValueError("answer must contain a findings array")
226
+ normalized = set()
227
+ for finding in findings:
228
+ if not isinstance(finding, dict):
229
+ raise ValueError("each finding must be an object")
230
+ # The public contract uses type/function. Accept common semantically
231
+ # equivalent aliases as a robustness layer, while still comparing the
232
+ # normalized values and exact locations against generator-owned GT.
233
+ kind = _finding_type(finding.get("type", finding.get(
234
+ "defect_type", finding.get("defect"))))
235
+ if family == "csv":
236
+ if kind == "duplicate_rows":
237
+ rows = _int_values(finding.get("rows", finding.get("row")))
238
+ if len(rows) != 2:
239
+ raise ValueError("duplicate finding requires exactly two row numbers")
240
+ normalized.add((kind, *sorted(rows)))
241
+ elif kind in {"missing", "outlier"}:
242
+ rows = _int_values(finding.get("row"))
243
+ column = str(finding.get("column") or "").strip().lower()
244
+ if len(rows) != 1 or not column:
245
+ raise ValueError(f"{kind} requires one row and column")
246
+ normalized.add((kind, rows[0], column))
247
+ else:
248
+ raise ValueError(f"unsupported CSV finding type: {kind}")
249
+ elif family == "config":
250
+ if kind != "invalid_config":
251
+ raise ValueError(f"unsupported config finding type: {kind}")
252
+ normalized.add((kind, str(finding.get("path") or "").lower(),
253
+ json.dumps(finding.get("value"), sort_keys=True),
254
+ str(finding.get("expected") or "").lower()))
255
+ elif family == "code":
256
+ if kind not in {"off_by_one", "none_check"}:
257
+ raise ValueError(f"unsupported code finding type: {kind}")
258
+ function = finding.get("function", finding.get("function_name"))
259
+ function = str(function or "").strip().lower()
260
+ if not function:
261
+ raise ValueError(f"{kind} requires a function")
262
+ normalized.add((kind, function))
263
+ else:
264
+ raise ValueError(f"unsupported findings family: {family}")
265
+ return normalized
266
+
267
+
268
+ def _normalized_facts(value):
269
+ obj = _json_value(value)
270
+ facts = obj.get("facts") if isinstance(obj, dict) else None
271
+ if not isinstance(facts, list):
272
+ raise ValueError("answer must contain a facts array")
273
+ def textual(item):
274
+ # The document generator serializes scalar values as visible text. JSON
275
+ # has no way to infer whether the source token "30" was authored from an
276
+ # integer or a string, so facts_match compares that surface text. Nested
277
+ # values retain structural JSON comparison.
278
+ if isinstance(item, (dict, list)):
279
+ return json.dumps(item, sort_keys=True, ensure_ascii=False,
280
+ separators=(",", ":"))
281
+ if item is None:
282
+ return "None"
283
+ return str(item)
284
+ return {(str(fact.get("key") or ""), textual(fact.get("value")))
285
+ for fact in facts if isinstance(fact, dict)}
286
+
287
+
288
+ def verify(verifier, gt_answer, solver_output, material_paths=None):
289
+ """执行 verifier。返回 (passed, detail)。"""
290
+ vtype = verifier.get("type")
291
+ try:
292
+ if vtype == WORKSPACE_EVALUATOR:
293
+ return evaluate_candidate(verifier, solver_output)
294
+
295
+ if vtype == "json_exact":
296
+ pred = _canonical_json(_json_value(solver_output))
297
+ gold = _canonical_json(_json_value(gt_answer))
298
+ ok = pred == gold
299
+ return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
300
+
301
+ if vtype == "atomic_json":
302
+ pred = _atomic_prepare(_json_value(solver_output),
303
+ verifier.get("list_order", "ordered"))
304
+ compiled = compile_atomic_verifier(
305
+ gt_answer, verifier.get("list_order", "ordered"),
306
+ verifier.get("float_tolerance", 0.01),
307
+ verifier.get("path_equivalence_tokens"))
308
+ frozen = {key: verifier.get(key) for key in
309
+ ("type", "version", "list_order", "float_tolerance",
310
+ "completeness", "assertions", "path_equivalence_tokens")}
311
+ expected_frozen = {key: compiled.get(key) for key in frozen}
312
+ if frozen != expected_frozen:
313
+ return False, {"error": "atomic verifier does not match ground truth"}
314
+ shape_failures = _shape_differences(
315
+ verifier["completeness"]["shape"], _atomic_shape(pred))
316
+ assertion_results = []
317
+ for assertion in verifier.get("assertions") or []:
318
+ try:
319
+ actual = _atomic_get(pred, assertion["tokens"])
320
+ if assertion["operator"] == "abs_diff":
321
+ passed = abs(float(actual) - float(assertion["expected"])) <= float(
322
+ assertion.get("tolerance", 0.0))
323
+ elif assertion["operator"] == "path_eq":
324
+ passed = (_path_value(actual) is not None and
325
+ _path_value(actual) == _path_value(assertion["expected"]))
326
+ else:
327
+ passed = (actual is assertion["expected"] if
328
+ isinstance(assertion["expected"], bool) else
329
+ actual == assertion["expected"])
330
+ message = "" if passed else (
331
+ f"actual={actual!r} expected={assertion['expected']!r}")
332
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
333
+ actual, passed, message = None, False, f"lookup/compare failed: {exc}"
334
+ assertion_results.append({
335
+ "id": assertion["id"], "path": assertion["path"],
336
+ "operator": assertion["operator"], "expected": assertion["expected"],
337
+ "actual": actual, "passed": passed, "message": message})
338
+ passed_count = sum(item["passed"] for item in assertion_results)
339
+ ok = not shape_failures and passed_count == len(assertion_results)
340
+ return ok, {
341
+ "type": "atomic_json", "completeness_passed": not shape_failures,
342
+ "completeness_failures": shape_failures,
343
+ "assertions_passed": passed_count,
344
+ "assertions_total": len(assertion_results),
345
+ "assertion_pass_rate": (passed_count / len(assertion_results)
346
+ if assertion_results else 1.0),
347
+ "assertions": assertion_results,
348
+ }
349
+
350
+ if vtype == "findings_match":
351
+ family = verifier.get("family")
352
+ pred = _normalized_findings(solver_output, family)
353
+ gold = _normalized_findings(gt_answer, family)
354
+ ok = pred == gold
355
+ return ok, ("findings_match: pass" if ok else
356
+ f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
357
+
358
+ if vtype == "facts_match":
359
+ pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
360
+ ok = pred == gold
361
+ return ok, ("facts_match: pass" if ok else
362
+ f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
363
+
364
+ if vtype == "exact_match":
365
+ ok = _norm(solver_output) == _norm(gt_answer)
366
+ return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
367
+
368
+ if vtype == "numeric":
369
+ tol = verifier.get("tolerance") or 1e-6
370
+ pred = float(str(solver_output).strip().split()[0])
371
+ gold = float(gt_answer)
372
+ ok = abs(pred - gold) <= tol
373
+ return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
374
+
375
+ if vtype == "set_match":
376
+ pred = set(_as_list(solver_output))
377
+ gold = set(_as_list(gt_answer))
378
+ ok = pred == gold
379
+ return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
380
+
381
+ if vtype == "structured_match":
382
+ pred = _json_value(solver_output)
383
+ gold = _json_value(gt_answer)
384
+ if not isinstance(pred, dict) or not isinstance(gold, dict):
385
+ return False, "structured_match requires JSON objects"
386
+ missing = [f for f in verifier.get("required_fields", []) if f not in pred]
387
+ wrong = [f for f in verifier.get("required_fields", [])
388
+ if f in pred and f in gold and pred[f] != gold[f]]
389
+ ok = not missing and not wrong
390
+ return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
391
+
392
+ if vtype == "execution":
393
+ return False, "execution verifier is disabled in verified-first v2"
394
+
395
+ if vtype == "constraint":
396
+ fails = _check_constraints(verifier.get("criteria", []), solver_output)
397
+ return not fails, f"constraint: failed={fails[:5]}"
398
+
399
+ if vtype == "file_inspection":
400
+ fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
401
+ return not fails, f"file_inspection: failed={fails[:5]}"
402
+
403
+ return False, f"unknown verifier type: {vtype}"
404
+ except Exception as e:
405
+ return False, f"verifier error: {e}"
406
+
407
+
408
+ def _as_list(x):
409
+ if isinstance(x, list):
410
+ return [_norm(i) for i in x]
411
+ # 逗号/换行分隔的字符串
412
+ return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
413
+
414
+
415
+ def _check_constraints(criteria, solver_output):
416
+ """criteria: ["must contain X", "must be valid json", "length <= 500"]"""
417
+ fails = []
418
+ text = str(solver_output)
419
+ for c in criteria:
420
+ cl = c.lower()
421
+ if cl.startswith("must contain "):
422
+ needle = c[len("must contain "):]
423
+ if needle.lower() not in text.lower():
424
+ fails.append(c)
425
+ elif "valid json" in cl:
426
+ try:
427
+ json.loads(text)
428
+ except Exception:
429
+ fails.append(c)
430
+ elif cl.startswith("length <="):
431
+ limit = int(cl.split("<=")[1].strip())
432
+ if len(text) > limit:
433
+ fails.append(c)
434
+ else:
435
+ # Deterministic verifier DSL is closed-world: unknown checks fail.
436
+ fails.append(f"unsupported criterion: {c}")
437
+ return fails
438
+
439
+
440
+ def _inspect_files(expected, material_paths):
441
+ fails = []
442
+ paths = set(material_paths or [])
443
+ for e in expected:
444
+ fname = e.get("filename") if isinstance(e, dict) else str(e)
445
+ if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
446
+ fails.append(f"missing file: {fname}")
447
+ return fails
448
+
449
+
450
+ # ---------------- 自测 ----------------
451
+
452
+ def build_correct_solution(verifier, gt_answer, planted_info):
453
+ """由埋点/ground truth 直接构造正确解。"""
454
+ vtype = verifier.get("type")
455
+ if vtype == WORKSPACE_EVALUATOR:
456
+ return reference_bundle(verifier)
457
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
458
+ "set_match", "structured_match"):
459
+ return gt_answer
460
+ if vtype == "constraint":
461
+ parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
462
+ if c.lower().startswith("must contain ")]
463
+ return " ".join(parts) if parts else str(gt_answer)
464
+ # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
465
+ return None
466
+
467
+
468
+ def build_perturbed_solution(verifier, gt_answer, planted_info):
469
+ """破坏埋点构造扰动解。"""
470
+ vtype = verifier.get("type")
471
+ if vtype == WORKSPACE_EVALUATOR:
472
+ files = list(reference_bundle(verifier).get("files") or [])
473
+ return {"files": files[1:] if len(files) > 1 else []}
474
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
475
+ gold = _json_value(gt_answer)
476
+ if isinstance(gold, dict):
477
+ perturbed = dict(gold)
478
+ key = next(iter(perturbed), "__missing__")
479
+ if key in perturbed:
480
+ perturbed.pop(key)
481
+ else:
482
+ perturbed["__wrong__"] = True
483
+ return perturbed
484
+ if isinstance(gold, list):
485
+ return gold[:-1] if gold else ["__wrong__"]
486
+ return "__wrong__"
487
+ if vtype in ("exact_match", "numeric"):
488
+ return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
489
+ if vtype == "set_match":
490
+ gold = _as_list(gt_answer)
491
+ return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
492
+ if vtype == "structured_match":
493
+ fields = verifier.get("required_fields", [])
494
+ return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
495
+ if vtype == "constraint":
496
+ return "perturbed output lacking required content"
497
+ return None
498
+
499
+
500
+ def self_test(verifier, gt_answer, planted_info, material_paths):
501
+ """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
502
+
503
+ 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
504
+ 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
505
+ """
506
+ if verifier.get("type") == WORKSPACE_EVALUATOR:
507
+ return self_test_workspace_evaluator(verifier)
508
+ correct = build_correct_solution(verifier, gt_answer, planted_info)
509
+ perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
510
+ if correct is None or perturbed is None:
511
+ return False, (f"cannot self-test verifier type {verifier.get('type')} "
512
+ "(execution/file_inspection need real correct/perturbed solutions)")
513
+ ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
514
+ ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
515
+ passed = ok1 and not ok2
516
+ return passed, {"correct": d1, "perturbed": d2}
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/evaluator/repair_equivalences.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task-scoped semantic equivalences for the 112 legacy verifier repairs.
2
+
3
+ No solver, oracle label, historical score or answer hash influences comparison.
4
+ The original private rubric, completeness checks and binary aggregation remain.
5
+ """
6
+ from __future__ import annotations
7
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
8
+ import copy
9
+ import json
10
+ import re
11
+ import shlex
12
+ import shutil
13
+ import tempfile
14
+ from decimal import Decimal, InvalidOperation
15
+ from pathlib import Path
16
+
17
+
18
+ def argv(value):
19
+ if not isinstance(value, str):
20
+ return None
21
+ try:
22
+ result = shlex.split(value, posix=True)
23
+ except ValueError:
24
+ return None
25
+ # Only the Bash execution wrapper is transparent. command -v/-V are queries.
26
+ while len(result) > 1 and result[0] == 'command':
27
+ if result[1] == '--':
28
+ result = result[2:]
29
+ elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]):
30
+ break
31
+ else:
32
+ result = result[1:]
33
+ return result or None
34
+
35
+
36
+ def git_limit(tokens):
37
+ if not tokens or tokens[:2] != ['git', 'log']:
38
+ return tokens
39
+ out, index = [], 0
40
+ while index < len(tokens):
41
+ token = tokens[index]
42
+ compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token)
43
+ if compact:
44
+ out.append('--max-count=' + next(x for x in compact.groups() if x is not None))
45
+ elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit():
46
+ index += 1
47
+ out.append('--max-count=' + tokens[index])
48
+ else:
49
+ out.append(token)
50
+ index += 1
51
+ return out
52
+
53
+
54
+ def shell_equal(expected, actual, normalize_env=False):
55
+ wanted, found = argv(expected), argv(actual)
56
+ if normalize_env and wanted and found:
57
+ wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted]
58
+ found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found]
59
+ wanted, found = git_limit(wanted), git_limit(found)
60
+ if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]:
61
+ return False
62
+ for index, token in enumerate(wanted[1:], 1):
63
+ observed = found[index]
64
+ if observed == token:
65
+ continue
66
+ if (index == 1 and '/' in token and
67
+ observed.rstrip('/').endswith('/' + token.lstrip('./'))):
68
+ continue # Existing package-path anchoring; no changed basename/arguments.
69
+ return False
70
+ return True
71
+
72
+
73
+ def command_equal(expected, value):
74
+ # Response command questions ask for one invocation, with no extra commands.
75
+ return argv(expected) is not None and argv(expected) == argv(value)
76
+
77
+
78
+ def convex_equal(expected, value):
79
+ a, b = argv(expected), argv(value)
80
+ if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]:
81
+ return False
82
+ def no_duplicates(pairs):
83
+ result = {}
84
+ for k, v in pairs:
85
+ if k in result:
86
+ raise ValueError('duplicate JSON key')
87
+ result[k] = v
88
+ return result
89
+ try:
90
+ return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates)
91
+ except (ValueError, TypeError):
92
+ return False
93
+
94
+
95
+ def docker_network_equal(expected, value):
96
+ tokens = argv(value)
97
+ return tokens in (['--network', 'none'], ['--network=none'])
98
+
99
+
100
+ def zar_amount(value):
101
+ if not isinstance(value, str):
102
+ return None
103
+ m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I)
104
+ if not m:
105
+ return None
106
+ number = m.group(1)
107
+ if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number):
108
+ return None
109
+ try:
110
+ amount = Decimal(number.replace(',', ''))
111
+ except InvalidOperation:
112
+ return None
113
+ return amount * (Decimal(1000000) if m.group(2) else 1)
114
+
115
+
116
+ def zar_equal(expected, value):
117
+ return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value)
118
+
119
+
120
+ def rust_attribute_equal(expected, value):
121
+ return isinstance(value, str) and re.fullmatch(r'\s*#\s*\[\s*serde\s*\(\s*rename_all\s*=\s*"camelCase"\s*,?\s*\)\s*\]\s*', value) is not None
122
+
123
+
124
+ def header_equal(expected, value):
125
+ return isinstance(value, str) and value.casefold() == expected.casefold()
126
+
127
+
128
+ def zero_arg_js_equal(expected, value):
129
+ name = expected[:-2]
130
+ return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None
131
+
132
+
133
+ RESPONSE_RULES = {
134
+ '82e94ae96e04ff71_q1': {'q1': convex_equal},
135
+ 'df978907fa6f0eea_q1': {'q1': docker_network_equal},
136
+ 'dee0c878f5707477_q1': {'q1': command_equal},
137
+ 'c51259d0062454b2_q1': {'q1': command_equal},
138
+ 'd25a8956477141f2_q1': {'q2': zar_equal},
139
+ '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal},
140
+ 'a4926e403c8165e9_q1': {'q2': header_equal},
141
+ '2b3bd5786727f2fb_q1': {'q1': command_equal},
142
+ }
143
+
144
+
145
+ def dashboard_contract(evaluator, candidate, objective):
146
+ root = Path(candidate)
147
+ path = evaluator['reference_files'][0]['path']
148
+ try:
149
+ text = (root / path).read_text()
150
+ except (OSError, UnicodeError):
151
+ return False
152
+ lines = objective._shell_lines(text)
153
+ # Public contract explicitly says no other commands/flags. Single quotes
154
+ # would suppress environment expansion; only the correctly quoted form counts.
155
+ return (len(lines) == 2 and
156
+ re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and
157
+ re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None)
158
+
159
+
160
+ def install(task):
161
+ import objective_evaluators as objective
162
+ import verifiers
163
+ task_id = task['query_id']
164
+ original_verify = verifiers.verify
165
+ original_matcher = objective._shell_command_matches
166
+ objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1')
167
+
168
+ def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None):
169
+ if evaluator.get('type') == 'workspace_objective':
170
+ # A text occurrence after exit/return, in echo output or within a
171
+ # non-executed branch does not prove the requested command runs.
172
+ grouped = {}
173
+ for check in evaluator.get('checks', []):
174
+ if check.get('type') == 'shell_command':
175
+ grouped.setdefault(check['path'], []).append(check['value'])
176
+ for path, expected_commands in grouped.items():
177
+ try:
178
+ text = (Path(solver_output) / path).read_text()
179
+ invocations = objective.shell_invocations(text)
180
+ for expected_command in expected_commands:
181
+ tokens = argv(expected_command)
182
+ if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]):
183
+ continue # Required scalar assignment is checked by original rubric.
184
+ if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations):
185
+ return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command}
186
+ except (OSError, UnicodeError, ValueError):
187
+ return False, {'error': 'cannot inspect required shell artifact', 'path': path}
188
+ if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective):
189
+ return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'}
190
+ normalizations = []
191
+ if task_id in RESPONSE_RULES:
192
+ try:
193
+ predicted = verifiers._json_value(solver_output)
194
+ gold = gt_answer
195
+ if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict):
196
+ for key, comparator in RESPONSE_RULES[task_id].items():
197
+ value = predicted['answers'].get(key)
198
+ expected = gold['answers'][key]
199
+ if value != expected and comparator(expected, value):
200
+ predicted['answers'][key] = expected
201
+ normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected})
202
+ solver_output = json.dumps(predicted)
203
+ except (KeyError, ValueError, TypeError):
204
+ pass # Preserve original malformed-answer rejection.
205
+ if task_id == '59f410a185c510f3_q1':
206
+ path = evaluator['reference_files'][0]['path']
207
+ try:
208
+ file_path = Path(solver_output) / path
209
+ predicted = json.loads(file_path.read_text())
210
+ expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact')
211
+ if isinstance(predicted, dict):
212
+ for widget in ('chart', 'banner'):
213
+ row = predicted.get(widget)
214
+ if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')):
215
+ if row.get('hydrate') != expected[widget]['hydrate']:
216
+ normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']})
217
+ row['hydrate'] = expected[widget]['hydrate']
218
+ if normalizations:
219
+ with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary:
220
+ view = Path(temporary) / 'candidate'
221
+ shutil.copytree(solver_output, view, symlinks=True)
222
+ copied = view / path
223
+ resolved = copied.resolve()
224
+ if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink():
225
+ return False, {'error': 'candidate output parent symlink escapes temporary comparison view'}
226
+ if copied.is_symlink():
227
+ copied.unlink() # Do not write through a frozen source symlink.
228
+ copied.write_text(json.dumps(predicted))
229
+ passed, details = original_verify(evaluator, gt_answer, str(view), material_paths)
230
+ if isinstance(details, dict):
231
+ details['equivalence_normalizations'] = normalizations
232
+ return passed, details
233
+ except (KeyError, ValueError, TypeError, OSError, UnicodeError):
234
+ pass
235
+ passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths)
236
+ if normalizations and isinstance(details, dict):
237
+ details['equivalence_normalizations'] = normalizations
238
+ return passed, details
239
+
240
+ verifiers.verify = repaired_verify
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/grading/verified_config.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "555c52aee32b7374_q1",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af",
8
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
9
+ "legacy-task.json": "1ab5d1c0966e010dd8c55d70c5c024f4f4097343431b31cf06ba6d0240137977",
10
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
11
+ "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d",
12
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
13
+ "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
14
+ "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
15
+ "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
16
+ "legacy_tests/objective_evaluators.py": "87c49a2c75c4819f004e3f93ac799589f1da35cf858f8c2674da27525a5d9b6d",
17
+ "legacy_tests/shell_invocations.py": "707d70e83b224c39a727afbd10f4d76c38dc50a2346444757ddfe392c1f4e75e",
18
+ "legacy_tests/verifiers.py": "4d95b3ac680fa9d32f50039e435b31e044e05087f587b9f8e00c8118da6483f6"
19
+ },
20
+ "runtime_requirements": {
21
+ "candidate_mode": "workspace",
22
+ "candidate_snapshot_copy_to_ephemeral_app": true,
23
+ "container_private_entry": "/grader/check.py",
24
+ "environment": {
25
+ "CANDIDATE_DIR": "/candidate",
26
+ "CANDIDATE_ROOT": "/candidate",
27
+ "MYBENCH_ANSWER": "/answer.txt",
28
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
29
+ "MYBENCH_CANDIDATE": "/candidate",
30
+ "MYBENCH_EPHEMERAL_APP": "1",
31
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1",
32
+ "MYBENCH_RUN_METADATA": "/run_metadata.json",
33
+ "MYBENCH_SOURCE_TASK": "/source",
34
+ "SOURCE_TASK_DIR": "/source"
35
+ },
36
+ "expected_check_ids": [
37
+ "0"
38
+ ],
39
+ "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
40
+ "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
41
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
42
+ "image_included": false,
43
+ "legacy_adapter": true,
44
+ "mounts_readonly": [
45
+ "/candidate",
46
+ "/source",
47
+ "/grader",
48
+ "/answer.txt"
49
+ ],
50
+ "network": "none",
51
+ "original_declared_resources": {
52
+ "agent": {
53
+ "basis": "advisory_not_measured",
54
+ "cpus": 2,
55
+ "memory_mib": 4096,
56
+ "timeout_sec": 1200
57
+ },
58
+ "oracle": {
59
+ "timeout_sec": 120
60
+ },
61
+ "source_agent": {
62
+ "command_timeout_sec": null,
63
+ "max_steps": null
64
+ },
65
+ "verifier": {
66
+ "cpus": 1,
67
+ "memory_mib": 1024,
68
+ "pids": 64,
69
+ "timeout_sec": 900,
70
+ "tmpfs_mib": 128
71
+ }
72
+ },
73
+ "private_entry": "evaluator/check.py",
74
+ "private_tree_environment_tokens": [
75
+ "MYBENCH_CANDIDATE_FILE",
76
+ "MYBENCH_OPEN_JUDGE_COMMAND",
77
+ "MYBENCH_OPEN_JUDGE_TIMEOUT",
78
+ "MYBENCH_TASK_JSON"
79
+ ],
80
+ "trusted_trace_environment_aliases": [
81
+ "MYBENCH_TOOL_TRAJECTORY",
82
+ "MYBENCH_TRUSTED_TRACE",
83
+ "TOOL_TRAJECTORY",
84
+ "TOOL_TRAJECTORY_FILE"
85
+ ],
86
+ "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
87
+ "working_directory": "/candidate",
88
+ "writable_ephemeral_roots": [
89
+ "/app",
90
+ "/workspace",
91
+ "/tmp"
92
+ ],
93
+ "criterion_weights": {
94
+ "0": 1
95
+ },
96
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair."
97
+ },
98
+ "engine": "portable_verified_v1"
99
+ }
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/instruction.md ADDED
@@ -0,0 +1 @@
 
 
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.
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/CHANNELS.md ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Channel Configuration Guide
2
+
3
+ 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**.
4
+
5
+ ## WhatsApp (wacli)
6
+
7
+ **Status:** CLI-based (wacli), no MCP needed.
8
+
9
+ **Setup:**
10
+
11
+ ```bash
12
+ # Install latest version from source (brew version may be outdated)
13
+ git clone https://github.com/steipete/wacli.git /tmp/wacli-src
14
+ cd /tmp/wacli-src
15
+ go build -o wacli ./cmd/wacli/
16
+ cp wacli /usr/local/bin/
17
+
18
+ # Authenticate (scans QR code with phone)
19
+ wacli auth
20
+
21
+ # Verify
22
+ wacli doctor
23
+ # Expected: AUTHENTICATED true, CONNECTED false (until sync runs)
24
+
25
+ # Initial sync (takes a minute for 142+ conversations)
26
+ wacli sync
27
+ ```
28
+
29
+ **Troubleshooting:**
30
+
31
+ - `Client outdated (405)`: Rebuild from source above
32
+ - `store is locked`: Kill stale process: `kill $(pgrep wacli)`
33
+ - After version upgrade: `wacli auth logout && wacli auth`
34
+
35
+ **History limitations:**
36
+ wacli only captures messages **received while connected**. It cannot reliably backfill historical messages after the fact:
37
+
38
+ - `wacli history backfill --chat <jid>` requires ≥1 existing local message per chat and often times out on the WhatsApp on-demand sync response.
39
+ - Chats in the new `@lid` (Linked Device) format frequently return empty message queries because their history was never captured during an active sync session.
40
+ - 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.
41
+
42
+ **Env vars (optional):**
43
+
44
+ - `WACLI_STORE` — default `~/.wacli`
45
+
46
+ **Run sync persistently (recommended):**
47
+
48
+ ```bash
49
+ # In a dedicated terminal tab — keeps wacli connected so new messages are captured
50
+ wacli sync --follow
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Email (gog)
56
+
57
+ **Status:** CLI-based (gog), optional MCP fallback.
58
+
59
+ **Setup:**
60
+
61
+ ```bash
62
+ # Install gog (gogcli — public CLI from steipete/gogcli, used by the OpenClaw ecosystem)
63
+ case "$(uname -s)" in
64
+ Darwin*) brew install gogcli ;;
65
+ Linux*) brew install gogcli 2>/dev/null \
66
+ || (command -v yay >/dev/null 2>&1 && yay -S gogcli) \
67
+ || (git clone https://github.com/steipete/gogcli.git /tmp/gogcli && cd /tmp/gogcli && make) ;;
68
+ MINGW*|MSYS*|CYGWIN*) winget install -e --id steipete.gogcli ;;
69
+ *) echo "Unsupported OS — see https://gogcli.sh/ for install instructions" ;;
70
+ esac
71
+
72
+ # Authorize once per Google account (uses your OS keyring for refresh tokens)
73
+ gog auth credentials /path/to/client_secret.json
74
+ gog auth add you@example.com --services gmail,calendar,drive,contacts,docs,sheets
75
+ ```
76
+
77
+ **Env vars (optional):**
78
+
79
+ - `GMAIL_ACCOUNT` — Gmail account (auto-detected if unset)
80
+
81
+ ---
82
+
83
+ ## Slack
84
+
85
+ **Status:** ⚠️ Not configured. Requires Slack MCP server.
86
+
87
+ **Requirements:**
88
+
89
+ - Slack MCP server installed and configured in `~/.claude/settings.json` under `mcpServers`
90
+ - Bot token with `channels:history`, `im:history`, `chat:write`, `search:read` scopes
91
+
92
+ **Setup:**
93
+
94
+ 1. Install a Slack MCP server:
95
+ ```bash
96
+ # Option A: Official reference
97
+ npm install -g @modelcontextprotocol/server-slack
98
+ ```
99
+ 2. Add to `~/.claude/settings.json`:
100
+ ```json
101
+ {
102
+ "mcpServers": {
103
+ "slack": {
104
+ "command": "npx",
105
+ "args": ["-y", "@modelcontextprotocol/server-slack"],
106
+ "env": {
107
+ "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",
108
+ "SLACK_TEAM_ID": "${SLACK_TEAM_ID}"
109
+ }
110
+ }
111
+ }
112
+ }
113
+ ```
114
+ 3. Export env vars (from Doppler, 1Password, or direnv — never commit):
115
+ ```bash
116
+ export SLACK_BOT_TOKEN="xoxb-..."
117
+ export SLACK_TEAM_ID="T..."
118
+ export SLACK_MCP_ENABLED=true
119
+ ```
120
+ 4. Restart Claude Code to load the MCP server
121
+
122
+ **Env vars:**
123
+
124
+ - `SLACK_BOT_TOKEN` — Bot token (starts with `xoxb-`)
125
+ - `SLACK_TEAM_ID` — Workspace ID
126
+ - `SLACK_MCP_ENABLED` — Set `true` to enable in ops-unread
127
+
128
+ ---
129
+
130
+ ## Telegram
131
+
132
+ **Status:** ⚠️ Not configured. Requires USER-AUTH MCP server (NOT a bot).
133
+
134
+ **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.
135
+
136
+ **Requirements:**
137
+
138
+ - Telegram API ID and hash from https://my.telegram.org/apps
139
+ - User-auth MCP server (e.g., `mcp-telegram-user` or custom tdlib wrapper)
140
+
141
+ **Setup:**
142
+
143
+ 1. Get API credentials from https://my.telegram.org/apps (for personal app, not bot)
144
+ 2. Install a user-auth Telegram MCP server (tdlib-based):
145
+ ```bash
146
+ # Example: custom tdlib MCP wrapper
147
+ npm install -g mcp-telegram-user
148
+ ```
149
+ 3. Add to `~/.claude/settings.json`:
150
+ ```json
151
+ {
152
+ "mcpServers": {
153
+ "telegram": {
154
+ "command": "mcp-telegram-user",
155
+ "env": {
156
+ "TELEGRAM_API_ID": "${TELEGRAM_API_ID}",
157
+ "TELEGRAM_API_HASH": "${TELEGRAM_API_HASH}",
158
+ "TELEGRAM_PHONE": "${TELEGRAM_PHONE}",
159
+ "TELEGRAM_SESSION_PATH": "${HOME}/.telegram-mcp-session"
160
+ }
161
+ }
162
+ }
163
+ }
164
+ ```
165
+ 4. Authenticate on first run (prompts for SMS code)
166
+ 5. Export env vars and enable:
167
+ ```bash
168
+ export TELEGRAM_API_ID="..."
169
+ export TELEGRAM_API_HASH="..."
170
+ export TELEGRAM_PHONE="+1..."
171
+ export TELEGRAM_ENABLED=true
172
+ ```
173
+
174
+ **Env vars:**
175
+
176
+ - `TELEGRAM_API_ID` — from my.telegram.org/apps
177
+ - `TELEGRAM_API_HASH` — from my.telegram.org/apps
178
+ - `TELEGRAM_PHONE` — phone number for auth
179
+ - `TELEGRAM_ENABLED` — Set `true` to enable in ops-unread
180
+
181
+ **⚠️ 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.**
182
+
183
+ ---
184
+
185
+ ## Notion
186
+
187
+ **Status:** MCP-based (claude.ai integration or self-hosted MCP server).
188
+
189
+ Notion acts as a knowledge base and task management channel. The integration surfaces:
190
+ - **Comments needing reply** — mentions, questions, and comments on pages/databases you own
191
+ - **Recently updated pages** — changes in databases you track (e.g., project boards, CRM)
192
+ - **Assigned tasks** — items assigned to you across Notion databases
193
+
194
+ **Requirements:**
195
+
196
+ - Notion MCP server configured via one of:
197
+ - **Claude.ai integration** (recommended): Add Notion via claude.ai > Settings > Integrations
198
+ - **Self-hosted MCP**: Install `@notionhq/notion-mcp-server` or similar
199
+
200
+ **Setup (Claude.ai integration — recommended):**
201
+
202
+ 1. Go to claude.ai > Settings > Integrations > Notion
203
+ 2. Authorize access to your Notion workspace
204
+ 3. Set env var in `~/.claude/settings.json`:
205
+ ```json
206
+ {
207
+ "env": {
208
+ "NOTION_MCP_ENABLED": "true"
209
+ }
210
+ }
211
+ ```
212
+ 4. Restart Claude Code to load the integration
213
+
214
+ **Setup (Self-hosted MCP server):**
215
+
216
+ 1. Install the Notion MCP server:
217
+ ```bash
218
+ npm install -g @notionhq/notion-mcp-server
219
+ ```
220
+ 2. Create a Notion integration at https://www.notion.so/my-integrations
221
+ 3. Add to `~/.claude/settings.json`:
222
+ ```json
223
+ {
224
+ "mcpServers": {
225
+ "notion": {
226
+ "command": "npx",
227
+ "args": ["-y", "@notionhq/notion-mcp-server"],
228
+ "env": {
229
+ "NOTION_API_KEY": "${NOTION_API_KEY}"
230
+ }
231
+ }
232
+ }
233
+ }
234
+ ```
235
+ 4. Export env vars:
236
+ ```bash
237
+ export NOTION_API_KEY="ntn_..."
238
+ export NOTION_MCP_ENABLED=true
239
+ ```
240
+
241
+ **Env vars:**
242
+
243
+ - `NOTION_API_KEY` — Integration token (starts with `ntn_`, only for self-hosted MCP)
244
+ - `NOTION_MCP_ENABLED` — Set `true` to enable in ops-unread
245
+
246
+ **MCP tools used:**
247
+
248
+ | Tool | Purpose |
249
+ |------|---------|
250
+ | `notion-search` | Search across workspace and connected sources (Slack, Drive, etc.) |
251
+ | `notion-fetch` | Fetch full page/database content by URL or ID |
252
+ | `notion-get-comments` | Get comments on a specific page |
253
+ | `notion-create-comment` | Reply to a comment thread on a page |
254
+ | `notion-update-page` | Update page properties (status, assignee, etc.) |
255
+ | `notion-create-pages` | Create new pages in databases |
256
+
257
+ ---
258
+
259
+ ## Verification
260
+
261
+ After configuring any channel, verify with:
262
+
263
+ ```bash
264
+ ${CLAUDE_PLUGIN_ROOT}/bin/ops-unread
265
+ ```
266
+
267
+ Expected output shows each channel's `available: true/false` status.
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/skill/SKILL.md ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: ops-inbox
3
+ 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.
4
+ argument-hint: "[channel: whatsapp|email|slack|telegram|discord|notion|all]"
5
+ allowed-tools:
6
+ - Bash
7
+ - Read
8
+ - Grep
9
+ - Glob
10
+ - Skill
11
+ - Agent
12
+ - AskUserQuestion
13
+ - TeamCreate
14
+ - SendMessage
15
+ - TaskCreate
16
+ - TaskUpdate
17
+ - TaskList
18
+ - CronCreate
19
+ - CronList
20
+ - mcp__gog__gmail_search
21
+ - mcp__gog__gmail_read_thread
22
+ - mcp__gog__gmail_send
23
+ - mcp__gog__gmail_labels
24
+ # Slack: MCP tools added when configured
25
+ # Telegram: user-auth MCP tools added when configured
26
+ # Notion: MCP tools (claude.ai integration or self-hosted)
27
+ - mcp__claude_ai_Notion__notion-search
28
+ - mcp__claude_ai_Notion__notion-fetch
29
+ - mcp__claude_ai_Notion__notion-get-comments
30
+ - mcp__claude_ai_Notion__notion-create-comment
31
+ - mcp__claude_ai_Notion__notion-update-page
32
+ - mcp__claude_ai_Notion__notion-create-pages
33
+ effort: high
34
+ maxTurns: 60
35
+ ---
36
+
37
+ # OPS ► INBOX ZERO
38
+
39
+ ## Runtime Context
40
+
41
+ Before executing, load available context:
42
+
43
+ 1. **Preferences**: Read `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`
44
+ - `default_channels` — which channels to scan by default
45
+ - `secrets_manager` / `doppler` — how to resolve channel credentials if not in env
46
+
47
+ 2. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`
48
+ - Check `wacli-sync` status — if not running or auth needed, skip WhatsApp and surface the issue
49
+ - Also check `~/.wacli/.health` for live auth status before any wacli command
50
+
51
+ 3. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/` before drafting any reply:
52
+ - `contact_*.md` — load profile for the contact you're about to reply to
53
+ - `preferences.md` — apply user's communication style and language preferences
54
+ - `topics_active.md` — check for active threads or deadlines related to this contact
55
+ - `donts.md` — never violate these restrictions in drafts
56
+
57
+ ## CLI/API Reference
58
+
59
+ ### wacli (WhatsApp)
60
+
61
+ **Health file** — check `~/.wacli/.health` BEFORE any wacli command:
62
+ - `status=connected` → proceed normally
63
+ - `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR"
64
+ - `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair"
65
+ - File missing → fall back to `wacli doctor --json`
66
+
67
+ | Command | Usage | Output |
68
+ |---------|-------|--------|
69
+ | `wacli doctor --json` | Check auth/connected/lock/FTS | `{data: {authenticated, connected, lock_held, fts_enabled}}` |
70
+ | `wacli chats list --json` | All chats | `{data: [{JID, Name, Kind, LastMessageTS}]}` |
71
+ | `wacli messages list --chat "<JID>" --limit N --json` | Messages for chat | `{data: {messages: [{FromMe, Text, Timestamp, SenderName, ChatName}]}}` |
72
+ | `wacli messages search --query "<text>" --json` | FTS search | Same as above |
73
+ | `wacli contacts --search "<name>" --json` | Contact lookup | Contact objects |
74
+ | `wacli send --to "<JID>" --message "<msg>"` | Send text | Success/error |
75
+ | `wacli history backfill --chat="<JID>" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages | Backfill result |
76
+
77
+ ### gog CLI (Gmail/Calendar)
78
+
79
+ | Command | Usage | Output |
80
+ |---------|-------|--------|
81
+ | `gog gmail search "in:inbox" --max 50 -j --results-only --no-input` | Full inbox scan | JSON array of threads |
82
+ | `gog gmail thread get <threadId> -j` | Get full thread with all messages | Full message JSON |
83
+ | `gog gmail get <messageId> -j` | Get single message | Message JSON |
84
+ | `gog gmail archive <messageId> ... --no-input --force` | Archive messages (remove from inbox) | Archive result |
85
+ | `gog gmail archive --query "<gmail-query>" --max N --force` | Archive by query | Archive result |
86
+ | `gog gmail send --to "<email>" --subject "<subj>" --body "<body>"` | Send email | Send result |
87
+ | `gog gmail send --reply-to-message-id <msgId> --reply-all --body "text"` | Reply all | Send result |
88
+ | `gog gmail mark-read <messageId> ... --no-input` | Mark as read | Result |
89
+ | `gog gmail labels list -j` | List all labels | Labels JSON |
90
+
91
+ ---
92
+
93
+
94
+ ## Agent Teams support
95
+
96
+ If `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, use **Agent Teams** when processing "all channels" mode. This enables:
97
+ - 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)
98
+ - You can steer agents: "skip WhatsApp for now, focus on email first"
99
+ - Agents report completion per-channel so you can process replies as they come in
100
+
101
+ **Team setup** (only when flag is enabled, "all channels" mode):
102
+ ```
103
+ TeamCreate("inbox-channels")
104
+ Agent(team_name="inbox-channels", name="whatsapp-scanner", ...)
105
+ Agent(team_name="inbox-channels", name="email-scanner", ...)
106
+ Agent(team_name="inbox-channels", name="slack-scanner", ...)
107
+ Agent(team_name="inbox-channels", name="telegram-scanner", ...)
108
+ Agent(team_name="inbox-channels", name="notion-scanner", ...)
109
+ ```
110
+
111
+ Each agent scans its channel and reports back classified results. You then process NEEDS_REPLY items across all channels in priority order.
112
+
113
+ If the flag is NOT set, process channels sequentially or use fire-and-forget subagents.
114
+
115
+ ## Pre-gathered data
116
+
117
+ ```!
118
+ ${CLAUDE_PLUGIN_ROOT}/../../bin/ops-unread 2>/dev/null || echo '{}'
119
+ ```
120
+
121
+ ## Environment variables
122
+
123
+ All channel credentials come from env vars or CLI auth — no hardcoded secrets.
124
+
125
+ | Variable | Default | Purpose |
126
+ | ------------------- | ----------- | ---------------------------------------------------- |
127
+ | `GMAIL_ACCOUNT` | auto-detect | Gmail account for `gog` CLI |
128
+ | `SLACK_MCP_ENABLED` | `false` | Set `true` when Slack MCP server is configured |
129
+ | `TELEGRAM_ENABLED` | `false` | Set `true` when Telegram user-auth MCP is configured |
130
+ | `NOTION_MCP_ENABLED`| `false` | Set `true` when Notion MCP integration is configured |
131
+ | `WACLI_STORE` | `~/.wacli` | wacli store directory |
132
+
133
+ ## Core principle: FULL INBOX SCAN
134
+
135
+ Do NOT just check unread. Scan the FULL recent inbox for each channel and classify every conversation:
136
+
137
+ ## Core principle: FULL CONTEXT — NEVER ASSUME
138
+
139
+ **CRITICAL SAFETY RULE — NEVER SEND WITHOUT UNDERSTANDING:**
140
+ 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:
141
+ 1. What the conversation is about
142
+ 2. What each party said (distinguish user messages from contact messages)
143
+ 3. What the contact is actually asking/saying in their last message
144
+ 4. What a sensible reply would address
145
+
146
+ **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.
147
+
148
+ **Hard rule: if you cannot summarize the conversation arc in 2 sentences, you have not read enough messages. Go back and read more.**
149
+
150
+ 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.
151
+
152
+ **For every NEEDS REPLY item, gather this context automatically:**
153
+
154
+ 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.
155
+ 2. **Contact profile** — search across channels to build a card:
156
+ - `gog gmail search "from:<contact_email>" --max 10` — recent email history
157
+ - `wacli contacts --search "<name>" --json` — WhatsApp presence
158
+ - `wacli messages search --query "<name>" --json --limit 5` — recent WhatsApp mentions
159
+ - If Linear configured: search for issues assigned to or mentioning this contact
160
+ - Present: who they are, role/company, last N interactions, relationship context
161
+ 3. **Topic context** — identify the subject matter and search for related threads:
162
+ - `gog gmail search "subject:<keywords>" --max 5` — related email threads
163
+ - `wacli messages search --query "<topic keywords>" --json --limit 5` — related WA messages
164
+ - Summarize: what this topic is about, any deadlines, any pending decisions
165
+ 4. **ops-memories** (if available) — check `~/.claude/plugins/data/ops-ops-marketplace/memories/` for any stored context about this contact or topic
166
+
167
+ **When presenting a NEEDS REPLY item:**
168
+ ```
169
+ ━━━ [Contact Name] — [Subject] ━━━
170
+ Who: [role, company, relationship — from contact search]
171
+ History: [last 3 interactions across channels]
172
+ Thread: [2-3 sentence summary of full conversation arc]
173
+ Last msg: [full body of their last message]
174
+ Context: [related threads/decisions/deadlines found]
175
+
176
+ Draft reply: "[contextually aware draft based on all above]"
177
+
178
+ [Send] [Edit] [Read full thread] [Skip]
179
+ ```
180
+
181
+ **When drafting replies:**
182
+ - Use the full thread history to maintain conversation continuity
183
+ - Reference specific points from their message
184
+ - Match the contact's communication style (formal/casual, language)
185
+ - If ops-memories has preferences for this contact, apply them
186
+ - Never generate a generic reply — every draft must show you read the full thread
187
+
188
+ - **NEEDS REPLY** — other party sent last message, awaiting your response
189
+ - **WAITING** — you sent last message, waiting for them (no action needed)
190
+ - **HANDLED** — conversation concluded, can be archived
191
+ - **FYI** — newsletters, notifications, automated messages (bulk archive)
192
+
193
+ ## Channel availability + fallback
194
+
195
+ For each channel, detect availability at runtime:
196
+
197
+ 1. **Email**: Try `gog` CLI first. If `gog` unavailable, try `mcp__gog__gmail_*` MCP tools. If neither, report unavailable.
198
+ 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.
199
+ 3. **Slack**: Only via MCP tools (`mcp__claude_ai_Slack__*`). Check `SLACK_MCP_ENABLED` env var.
200
+ 4. **Telegram**: Only via user-auth MCP (tdlib/MTProto). Check `TELEGRAM_ENABLED` env var. Never use BotFather bots.
201
+ 5. **Discord**: Via `${CLAUDE_PLUGIN_ROOT}/bin/ops-discord read <CHANNEL_ID> --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`.
202
+ 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.
203
+
204
+ ## Your task
205
+
206
+ 1. **Parse pre-gathered data** for initial counts (unread is just a starting signal).
207
+
208
+ 2. **For each channel, run a FULL scan** (not just unread):
209
+ - **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.**
210
+ - **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 <JID> --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.
211
+ - **Slack**: Search via Slack MCP tools. Check who sent last message in each thread.
212
+ - **Telegram**: Use user-auth MCP (NOT bot API) to read recent conversations.
213
+
214
+ 3. **Display the full inbox:**
215
+
216
+ ```
217
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
218
+ OPS ► INBOX MANAGER
219
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
220
+
221
+ 📱 WhatsApp [N need reply] | [N waiting] | [N archive]
222
+ 📧 Email [N need reply] | [N waiting] | [N FYI]
223
+ 💬 Slack [N need reply] | [N waiting]
224
+ ✈️ Telegram [N need reply] | [N waiting]
225
+
226
+ ──────────────────────────────────────────────────────
227
+ ```
228
+
229
+ 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.
230
+
231
+ AskUserQuestion call 1:
232
+ ```
233
+ [All channels (fastest — one pass)]
234
+ [WhatsApp only]
235
+ [Email only]
236
+ [More...]
237
+ ```
238
+
239
+ AskUserQuestion call 2 (only if "More..."):
240
+ ```
241
+ [Slack only]
242
+ [Telegram only]
243
+ [Skip — already done]
244
+ ```
245
+
246
+ If only 3 channels are configured, "All channels" + 3 channel options = 4, fits in one call. Then process the selected channel(s).
247
+
248
+ ---
249
+
250
+ ## Processing each channel
251
+
252
+ ### WhatsApp (FULL SCAN + DEEP CONTEXT)
253
+
254
+ **Phase 1 — Classify:**
255
+ 1. Get all chats: `wacli chats list --json`
256
+ 2. Filter to chats with `LastMessageTS` in the last 7 days
257
+ 3. For each, fetch the FULL recent conversation: `wacli messages list --chat "<JID>" --limit 20 --json` — get 20 messages, NOT 5. You need the full conversation thread to understand context.
258
+ 4. Parse `data.messages[]` — fields: `FromMe`, `Text`, `Timestamp`, `ChatName`, `SenderName`
259
+ 5. For EVERY chat, understand the conversation:
260
+ - Read ALL messages in order. Know which are `FromMe: true` (user sent) vs `FromMe: false` (contact sent)
261
+ - Understand what the conversation is about, what was discussed, what's pending
262
+ - Identify the user's tone and style in their sent messages
263
+ 6. Classify each chat:
264
+ - **NEEDS REPLY**: Last message has `FromMe: false` (they sent last)
265
+ - **WAITING**: Last message has `FromMe: true` (you sent last)
266
+ - **ARCHIVE**: Old conversation, no recent activity, or concluded
267
+
268
+ **Phase 2 — Build context for NEEDS REPLY chats (run in parallel):**
269
+ For each NEEDS REPLY chat:
270
+ 1. **Full conversation summary** — read all 20 messages, summarize the arc: what was discussed, key decisions, open questions
271
+ 2. **Contact profile** — search for this person:
272
+ - `wacli messages search --query "<contact_name>" --json --limit 10` — mentions in other chats
273
+ - `gog gmail search -j --results-only --no-input --max 5 "from:<name> OR to:<name>"` — email history
274
+ - Check `~/.claude/plugins/data/ops-ops-marketplace/memories/contact_*.md` for stored profile
275
+ - Build: who they are, relationship, communication history across channels
276
+ 3. **Topic context** — extract keywords from the conversation and search:
277
+ - `wacli messages search --query "<topic keywords>" --json --limit 5` — related WA messages
278
+ - `gog gmail search -j --results-only --no-input --max 3 "<topic keywords>"` — related emails
279
+ 4. **User's messaging style** — from the `FromMe: true` messages in this chat, note: language (NL/EN), formality, emoji usage, typical response length
280
+
281
+ **Phase 3 — Present with full context:**
282
+
283
+ ```
284
+ 📱 WHATSAPP — NEEDS REPLY (with context)
285
+
286
+ ━━━ 1. [Contact Name] ━━━
287
+ Who: [role, company, relationship — from contact search]
288
+ History: [last 3 interactions across channels]
289
+ Conversation: [2-3 sentence summary of the full chat thread]
290
+ Their message: [full text of their last message(s)]
291
+ Your last msg: [what you said before they replied]
292
+ Context: [related threads/topics found]
293
+ Language: [NL/EN — match the user's previous messages in this chat]
294
+
295
+ Draft reply: "[context-aware draft matching user's style + language]"
296
+
297
+ [Send] [Edit] [Read full thread] [More...]
298
+
299
+ If "More...":
300
+ [Archive] [Skip]
301
+
302
+ 📱 WHATSAPP — WAITING (no action needed)
303
+ N. [Contact] — you said: "[your last message]" — [time ago]
304
+ Thread: [1-line summary of what you're waiting for]
305
+ ```
306
+
307
+ Use `AskUserQuestion` for each NEEDS REPLY chat.
308
+
309
+ **When drafting WhatsApp replies:**
310
+ - Match the user's language (if they wrote Dutch to this contact, draft in Dutch)
311
+ - Match the user's style (casual/formal, emoji usage, message length)
312
+ - Reference specific points from the contact's message
313
+ - If ops-memories has preferences for this contact, apply them
314
+ - Never generate a generic reply — every draft must show you understood the full conversation
315
+
316
+ Reply via: `wacli send --to "<JID>" --message "<msg>"`
317
+
318
+ **wacli CLI reference (v0.5.0):**
319
+
320
+ | Command | Usage | Notes |
321
+ |---------|-------|-------|
322
+ | `wacli doctor` | `wacli doctor --json` | Check auth/connected/lock/FTS status |
323
+ | `wacli auth` | `wacli auth` | QR pairing (interactive — shows QR in terminal) |
324
+ | `wacli sync` | `wacli sync --follow --refresh-contacts --refresh-groups` | Persistent sync (managed by launchd keepalive) |
325
+ | `wacli sync --once` | `wacli sync --once --idle-exit=10s` | One-shot sync, exits when idle |
326
+ | `wacli chats list` | `wacli chats list --json` | All chats with JID, Name, Kind, LastMessageTS |
327
+ | `wacli messages list` | `wacli messages list --chat "<JID>" --limit 5 --json` | Messages: ChatJID, FromMe, Text, Timestamp, SenderName |
328
+ | `wacli messages search` | `wacli messages search --query "<text>" --json` | FTS5 search across all messages |
329
+ | `wacli contacts` | `wacli contacts --search "<name>" --json` | Contact lookup by name |
330
+ | `wacli send` | `wacli send --to "<JID>" --message "<msg>"` | Send text message |
331
+ | `wacli history backfill` | `wacli history backfill --chat="<JID>" --count=50 --requests=2 --wait=30s --idle-exit=5s --json` | Fetch older messages from phone (needs store lock) |
332
+
333
+ **Health file contract (`~/.wacli/.health`):**
334
+
335
+ Before ANY wacli command, read `~/.wacli/.health`:
336
+ - `status=connected` → proceed normally
337
+ - `status=needs_auth` → prompt user: "Run `wacli auth` in terminal, scan QR"
338
+ - `status=needs_reauth` → prompt user: "WhatsApp session expired. Run `wacli auth` to re-pair"
339
+ - File missing → fall back to `wacli doctor --json`
340
+
341
+ **Requesting backfill for @lid chats with empty messages:**
342
+
343
+ The keepalive daemon holds the store lock, so you can't run backfill directly. Instead:
344
+ 1. Write JIDs to `~/.wacli/.backfill_jids` (one per line)
345
+ 2. Restart the daemon: `launchctl kickstart -k gui/$(id -u)/com.claude-ops.wacli-keepalive`
346
+ 3. The daemon runs backfill before starting persistent sync
347
+
348
+ **wacli troubleshooting:**
349
+
350
+ - `@lid` JIDs (linked device format) may return empty messages → request backfill via the daemon (see above)
351
+ - "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/`
352
+ - "store is locked" → the keepalive daemon holds the lock; to release: `launchctl bootout gui/$(id -u)/com.claude-ops.wacli-keepalive`
353
+ - Auth expired → daemon writes `needs_auth` to health file; prompt user for QR scan
354
+ - Key desync (0 messages synced) → daemon writes `needs_reauth`; user needs `wacli auth` re-pair
355
+
356
+ ### Email (FULL SCAN + DEEP CONTEXT)
357
+
358
+ **Phase 1 — Classify:**
359
+ 1. Search `in:inbox` (NOT `is:unread`) via `gog gmail search -a $GMAIL_ACCOUNT -j --results-only --no-input --max 30 "in:inbox"`
360
+ 2. For each thread, read the FULL thread via `gog gmail thread get -a $GMAIL_ACCOUNT <threadId> -j` — read ALL messages, not just the last one
361
+ 3. Check the last message's `From` header and `labelIds` (SENT, DRAFT)
362
+ 4. Classify:
363
+ - **NEEDS REPLY**: Last sender is NOT you AND no unsent draft exists → action needed
364
+ - **WAITING**: Last sender IS you (SENT label) → waiting for response
365
+ - **DRAFT**: Unsent draft exists → verify no reply already sent, then offer to send
366
+ - **FYI**: Newsletters, automated notifications, receipts → bulk archive
367
+
368
+ **Phase 2 — Build context for NEEDS REPLY items (run in parallel):**
369
+ For each NEEDS REPLY thread, gather:
370
+ 1. **Full thread summary** — read every message in the thread, summarize the conversation arc (who said what, key decisions, open questions)
371
+ 2. **Contact profile** — for the sender:
372
+ - `gog gmail search -j --results-only --no-input --max 10 "from:<sender_email>"` — their recent emails to you
373
+ - `wacli contacts --search "<sender_name>" --json` — WhatsApp contact
374
+ - `wacli messages search --query "<sender_name>" --json --limit 5` — recent WhatsApp mentions
375
+ - Build: name, role/company, relationship history, last N interactions
376
+ 3. **Topic search** — extract key terms from subject + body, then:
377
+ - `gog gmail search -j --results-only --no-input --max 5 "subject:<keywords>"` — related threads
378
+ - Identify: pending decisions, deadlines, action items from related threads
379
+
380
+ **Phase 3 — Present with full context:**
381
+
382
+ ```
383
+ 📧 EMAIL — NEEDS REPLY (with context)
384
+
385
+ ━━━ 1. [Sender] — [Subject] ━━━
386
+ Who: [sender's role, company — from contact search]
387
+ History: [last 3 email exchanges with this person]
388
+ Thread summary: [2-3 sentences covering the full conversation arc]
389
+ Their message: [full body of their last message — NOT truncated]
390
+ Related: [any related threads or pending decisions found]
391
+
392
+ Draft reply: "[context-aware draft using full thread + contact history]"
393
+
394
+ [Send draft] [Edit draft] [Read full thread] [More...]
395
+
396
+ If "More...":
397
+ [Archive] [Skip]
398
+
399
+ 📧 EMAIL — DRAFTS (unsent)
400
+ N. [Recipient] — [Subject] (draft ready to send)
401
+
402
+ 📧 EMAIL — FYI / ARCHIVE
403
+ N. [Sender] — [Subject] (newsletter/notification)
404
+
405
+ For each NEEDS REPLY:
406
+ a) Read full thread + draft reply
407
+ b) Archive (no reply needed)
408
+ c) Skip
409
+
410
+ For FYI section:
411
+ x) Archive all FYI at once
412
+ ```
413
+
414
+ Use `AskUserQuestion` for each NEEDS REPLY email with options `[Read + Reply]` / `[Archive]` / `[Skip]`.
415
+
416
+ When replying, draft the reply and use `AskUserQuestion` to confirm:
417
+ ```
418
+ Reply to [Sender] — [Subject]:
419
+ "[drafted reply]"
420
+
421
+ [Send] [Edit] [Skip]
422
+ ```
423
+
424
+ For FYI bulk archive, use `AskUserQuestion`:
425
+ ```
426
+ Archive N FYI/newsletter emails?
427
+ [list of subjects]
428
+
429
+ [Archive all N] [Review each] [Skip]
430
+ ```
431
+
432
+ Draft replies via `gog gmail send`. Archive via `gog gmail archive <messageId> ... --no-input --force`.
433
+
434
+ ### Slack
435
+
436
+ Use Slack MCP tools with `query: "in:*"` (NOT `is:unread` — scan full recent activity, not just unread) for mentions.
437
+ For each result, show channel, sender, preview. Read thread for context.
438
+
439
+ ```
440
+ a) Read thread
441
+ b) Reply
442
+ c) Mark read / skip
443
+ ```
444
+
445
+ ### Telegram (FULL SCAN — User Account, NOT Bot)
446
+
447
+ 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.
448
+
449
+ Use the Telegram user-auth MCP server if available.
450
+
451
+ 1. List recent dialogs/conversations (last 7 days)
452
+ 2. For each, check who sent the last message
453
+ 3. Classify: NEEDS REPLY / WAITING / HANDLED
454
+
455
+ ```
456
+ ✈️ TELEGRAM — NEEDS REPLY
457
+ 1. [Contact] — [preview] — [time ago]
458
+
459
+ a) Read thread + reply
460
+ b) Archive
461
+ c) Skip
462
+ ```
463
+
464
+ If no Telegram user-auth tool is available, report: "Telegram not configured — needs user-auth MCP server (tdlib/MTProto)".
465
+
466
+ ### Notion (MCP — comments, mentions, assigned tasks)
467
+
468
+ Notion serves as a knowledge base and task management channel. Unlike messaging channels, Notion "inbox" items are:
469
+ - **Comments on pages you own or are mentioned in**
470
+ - **Tasks assigned to you** in tracked databases
471
+ - **Recently updated pages** in databases you monitor
472
+
473
+ **Phase 1 — Discover and scan:**
474
+
475
+ 1. Search for recent activity using `mcp__claude_ai_Notion__notion-search`:
476
+ - Use broad queries like `query: ""` (empty string returns recent pages) or topic-specific terms
477
+ - Use `filter: {"property": "object", "value": "page"}` to limit to pages (not databases)
478
+ - Sort by `last_edited_time` descending to surface recent activity
479
+ - Note: Notion search is full-text over titles/content — it does NOT support mention-based queries or date range filters
480
+ 2. For each result, fetch full content: `mcp__claude_ai_Notion__notion-fetch` with the page URL/ID
481
+ 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
482
+
483
+ **Phase 2 — Classify:**
484
+
485
+ For each page with comments or mentions:
486
+ - **NEEDS REPLY**: Someone commented/mentioned you and you haven't responded
487
+ - **WAITING**: You commented last, waiting for others
488
+ - **FYI**: Page updated but no direct mention or action needed
489
+ - **TASK**: Item assigned to you in a database (check status property)
490
+
491
+ **Phase 3 — Present with context:**
492
+
493
+ ```
494
+ 📓 NOTION — NEEDS REPLY
495
+
496
+ ━━━ 1. [Page Title] — [Database Name] ━━━
497
+ Page: [page URL]
498
+ Comment by: [commenter name] — [time ago]
499
+ Comment: "[full comment text]"
500
+ Page context: [2-3 sentence summary of the page content]
501
+
502
+ Draft reply: "[context-aware reply to the comment]"
503
+
504
+ [Reply] [View page] [Skip] [More...]
505
+
506
+ If "More...":
507
+ [Mark resolved] [Archive]
508
+
509
+ 📓 NOTION — ASSIGNED TASKS
510
+
511
+ N. [Task title] — [database] — Status: [status] — Due: [date]
512
+ Context: [1-line summary]
513
+
514
+ 📓 NOTION — RECENTLY UPDATED (FYI)
515
+
516
+ N. [Page title] — updated by [person] — [time ago]
517
+ ```
518
+
519
+ Use `AskUserQuestion` for each NEEDS REPLY item.
520
+
521
+ **When replying to Notion comments:**
522
+ - Use `mcp__claude_ai_Notion__notion-create-comment` with the page ID and reply text
523
+ - Match the formality of the original comment
524
+ - Reference specific page content when relevant
525
+
526
+ **When updating tasks:**
527
+ - Use `mcp__claude_ai_Notion__notion-update-page` to change status, add notes
528
+ - Only update properties the user explicitly approves
529
+
530
+ **API fallback (when MCP is down):**
531
+ If Notion MCP tools fail or are unavailable but `NOTION_API_KEY` is set, fall back to direct API:
532
+ ```bash
533
+ curl -s -H "Authorization: Bearer $NOTION_API_KEY" -H "Notion-Version: 2022-06-28" \
534
+ -H "Content-Type: application/json" \
535
+ -X POST https://api.notion.com/v1/search \
536
+ -d '{"sort":{"direction":"descending","timestamp":"last_edited_time"},"page_size":10}'
537
+ ```
538
+
539
+ 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".
540
+
541
+ ### Discord (v1 — REST channel scan)
542
+
543
+ Discord v1 support is channel-scoped (webhook send + REST read). DM + gateway are deferred to a v2 issue.
544
+
545
+ 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...]`).
546
+ 2. For each channel ID:
547
+ ```bash
548
+ ${CLAUDE_PLUGIN_ROOT}/bin/ops-discord read "<CHANNEL_ID>" --limit 20 --json
549
+ ```
550
+ 3. Classify each channel's recent messages:
551
+ - **NEEDS REPLY**: Latest non-bot message mentions the operator (`<@user-id>`) or is a direct question.
552
+ - **FYI**: Bot-posted notifications (CI, alerts) — summarize counts and skip.
553
+ 4. For replies, reuse the `send` path documented in `skills/ops-comms/SKILL.md` → **Discord send**.
554
+
555
+ 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.
556
+
557
+ ```
558
+ 💬 DISCORD — activity (last 7d)
559
+ #channel-name [N messages] | [M need reply]
560
+ ```
561
+
562
+ ---
563
+
564
+ ## Completion
565
+
566
+ After all selected channels are processed, print:
567
+
568
+ ```
569
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
570
+ INBOX ZERO ✓ — [timestamp]
571
+ Processed: [N] messages | Replied: [N] | Archived: [N]
572
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
573
+ ```
574
+
575
+ If `$ARGUMENTS` specifies a channel (e.g. `whatsapp`), skip the menu and go directly to that channel.
576
+
577
+ ---
578
+
579
+ ## Native tool usage
580
+
581
+ ### Tasks — inbox progress
582
+
583
+ 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.
584
+
585
+ ### Cron — scheduled inbox checks
586
+
587
+ After processing, offer to schedule recurring inbox checks via `AskUserQuestion`:
588
+ ```
589
+ [Schedule inbox check every 2 hours] [Schedule morning + evening] [No schedule]
590
+ ```
591
+ Use `CronCreate` if selected. Show existing schedules with `CronList`.
benchmarks/skillbench-venus-e/tasks/555c52aee32b7374_q1/task.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "555c52aee32b7374",
4
+ "query_id": "555c52aee32b7374_q1",
5
+ "environment": {
6
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
7
+ "network": "none"
8
+ },
9
+ "outputs": [
10
+ "output/wacli_preflight.sh"
11
+ ],
12
+ "success_criteria": [
13
+ "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json."
14
+ ],
15
+ "evaluation": {
16
+ "kind": "python",
17
+ "type": "verified"
18
+ },
19
+ "workspace": {
20
+ "input_mappings": [],
21
+ "skill_packages": [
22
+ {
23
+ "content_hash": "910cae0331e5a0218ed7d67a15becd780febb55f9230a60a2e0f105cec47070d",
24
+ "name": "ops-inbox",
25
+ "package_path": "skill",
26
+ "install_name": "ops-inbox-39a2c604"
27
+ }
28
+ ],
29
+ "default_skill_target": ".claude/skills",
30
+ "candidate_mode": "workspace"
31
+ },
32
+ "source_skill": {
33
+ "sha256": "910cae0331e5a0218ed7d67a15becd780febb55f9230a60a2e0f105cec47070d",
34
+ "files": {
35
+ "CHANNELS.md": "75f3ac160460e8fa8a71ff1d3ccef1c652e42099149d3095e8637c5ec81e66ed",
36
+ "SKILL.md": "5ac34ec3914c5768dfead9be58809de390d53a76f2d17064a8173e830b8e0a77"
37
+ }
38
+ },
39
+ "migration": {
40
+ "source_schema": "mybench-portable-task-v2",
41
+ "legacy_task_json": "provenance/legacy-package/task.json",
42
+ "historical_gain_protocol": "legacy; not Harbor certified",
43
+ "reference_available": true,
44
+ "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task",
45
+ "original_skill_content_hashes": [
46
+ "39a2c604a3b990f4f7ac973f13dd3558f3e702b45de26cb7d06c72e7016484a5"
47
+ ]
48
+ }
49
+ }