StudentTang commited on
Commit
9d48c6d
·
verified ·
1 Parent(s): 5a9b3df

Upload Skill-Venus Data as released (part 10)

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/946da78883724707e43b358e/evaluator/auto_policy.py +133 -0
  2. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/auto_policy_guard.py +86 -0
  3. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/autograde_task_check.py +154 -0
  4. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/check.py +2 -0
  5. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/format_constraints.py +58 -0
  6. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/original_check.py +118 -0
  7. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/public_inputs.json +1 -0
  8. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/r10_support.py +107 -0
  9. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/PyYAML-LICENSE +20 -0
  10. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/__init__.py +390 -0
  11. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/composer.py +139 -0
  12. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/constructor.py +748 -0
  13. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/cyaml.py +101 -0
  14. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/dumper.py +62 -0
  15. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/emitter.py +1137 -0
  16. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/error.py +75 -0
  17. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/events.py +86 -0
  18. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/loader.py +63 -0
  19. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/nodes.py +49 -0
  20. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/parser.py +589 -0
  21. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/reader.py +185 -0
  22. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/representer.py +389 -0
  23. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/resolver.py +227 -0
  24. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/scanner.py +1435 -0
  25. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/serializer.py +111 -0
  26. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/tokens.py +104 -0
  27. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/grading/verified_config.json +107 -0
  28. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/inputs/article.html +33 -0
  29. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/instruction.md +13 -0
  30. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/SKILL.md +3 -0
  31. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/members/M000/SKILL.md +139 -0
  32. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/members/M001/SKILL.md +279 -0
  33. benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/task.json +132 -0
  34. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/auto_contract.json +8 -0
  35. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/auto_entry.py +38 -0
  36. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/auto_policy.py +133 -0
  37. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/auto_policy_guard.py +86 -0
  38. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/autograde_task_check.py +14 -0
  39. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/check.py +2 -0
  40. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy-task.json +131 -0
  41. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/evaluate.py +159 -0
  42. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/objective_evaluators.py +946 -0
  43. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/shell_invocations.py +455 -0
  44. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/test.sh +8 -0
  45. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/verifiers.py +554 -0
  46. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/repair_equivalences.py +249 -0
  47. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/grading/verified_config.json +100 -0
  48. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/instruction.md +1 -0
  49. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/skill/SKILL.md +362 -0
  50. benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/skill/references/api-escape-hatch.md +185 -0
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/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/946da78883724707e43b358e/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/946da78883724707e43b358e/evaluator/autograde_task_check.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ from format_constraints import rendered,emphasis_ok,tables_ok
3
+ import ast, contextlib, io, json, os, re, shutil, subprocess, sys, tempfile, hashlib
4
+ from pathlib import Path
5
+ ROOT=Path(__file__).resolve().parent
6
+ C=Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_DIR','/candidate'))).resolve()
7
+ sys.path.insert(0,str(ROOT/'vendor'))
8
+ def read(p):return Path(p).read_text(encoding='utf-8')
9
+ def load(p):return json.loads(read(p))
10
+ def public():return load(ROOT/'public_inputs.json')
11
+ def fresh(candidate=C,programs=True):
12
+ if os.environ.get('MYBENCH_EPHEMERAL_WORKSPACE')=='1':
13
+ t=Path('/workspace');t.mkdir(parents=True,exist_ok=True)
14
+ for child in t.iterdir():
15
+ if child.is_dir() and not child.is_symlink():shutil.rmtree(child)
16
+ else:child.unlink()
17
+ else:t=Path(tempfile.mkdtemp(prefix='repaired_',dir='/tmp'))
18
+ for name,text in public().items():
19
+ p=t/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text)
20
+ if programs:
21
+ from r10_support import copy_program
22
+ generated=tuple(str(p.relative_to(candidate)) for p in candidate.glob('????-??-??-*.md'))
23
+ copy_program(t,tuple(public())+generated)
24
+ return t
25
+ def run(t,name,args=()):return subprocess.run([sys.executable,name,*args],cwd=t,capture_output=True,text=True,timeout=60)
26
+ def stdlib(p):
27
+ return True
28
+ def legacy(source,candidate=C):
29
+ class Repath(ast.NodeTransformer):
30
+ def visit_Constant(self,node):
31
+ if isinstance(node.value,str) and node.value.startswith('/candidate'):return ast.copy_location(ast.Constant(str(candidate)+node.value[len('/candidate'):]),node)
32
+ return node
33
+ ns={'__name__':'__main__','__file__':str(ROOT/'check.py')};out=io.StringIO()
34
+ try:
35
+ tree=ast.fix_missing_locations(Repath().visit(ast.parse(source)))
36
+ with contextlib.redirect_stdout(out):
37
+ try:exec(compile(tree,str(ROOT/'original_check.py'),'exec'),ns)
38
+ except SystemExit:pass
39
+ value=json.loads(out.getvalue().strip());checks=value.get('checks',value) if isinstance(value,dict) else value
40
+ if not isinstance(checks,list) or len(checks)!=N:raise ValueError('legacy check count')
41
+ for i,c in enumerate(checks):c['id']=str(c.get('id',i));c['passed']=c.get('passed') is True
42
+ return checks,ns
43
+ except Exception as e:
44
+ raise
45
+ def require(checks,i,ok,reason,override=False):
46
+ for c in checks:
47
+ if c['id']==str(i):
48
+ c['passed']=bool(ok) if override else c['passed'] and bool(ok)
49
+ if not ok or override:c['reason']=reason
50
+ def finish(checks):
51
+ assert len(checks)==N and {c['id'] for c in checks}=={str(i) for i in range(N)}
52
+ print(json.dumps({'checks':checks},ensure_ascii=False))
53
+
54
+ def source_order_ok(sequence,body):
55
+ # Only an unordered-list run may permute; surrounding source/image order stays fixed.
56
+ normalized=' '.join(rendered(body).split());offset=0;index=0
57
+ while index<len(sequence):
58
+ kind,text=sequence[index]
59
+ if kind=='li':
60
+ run=[]
61
+ while index<len(sequence)and sequence[index][0]=='li':run.append(' '.join(sequence[index][1].split()));index+=1
62
+ ends=[];used=set()
63
+ for token in run:
64
+ where=normalized.find(token,offset)
65
+ while where>=0 and where in used:where=normalized.find(token,where+len(token))
66
+ if where<0:return False
67
+ used.add(where);ends.append(where+len(token))
68
+ offset=max(ends,default=offset);continue
69
+ token=' '.join(text.split());where=normalized.find(token,offset)
70
+ if where<0:return False
71
+ offset=where+len(token);index+=1
72
+ return True
73
+
74
+ N=7
75
+ ORIGINAL = 'from r10_support import install_copy,candidate_root\ninstall_copy((\'article.html\',)+tuple(str(p.relative_to(candidate_root()))for p in candidate_root().glob("*.md")))\nimport json,os,re,subprocess,shutil,tempfile\n\nARTICLE = \'\'\'<!-- 微信公众号文章导出片段 -->\n<div id="js_article">\n <h1 id="activity-name">Python 异步编程入门指南</h1>\n <div id="meta_content">作者:张三 公众号:技术小站</div>\n <div id="js_content">\n <p>异步编程是提高程序并发能力的重要手段。Python 中的 asyncio 模块提供了事件循环和协程支持。</p>\n <img data-src="https://mmbiz.qpic.cn/mmbiz_svg/aaa" data-type="svg">\n <img data-src="https://mmbiz.qpic.cn/sz_mmbiz_png/bbb/640?wx_fmt=png" data-index="2">\n <h2>基本概念</h2>\n <p>协程是一种可暂停恢复的函数。事件循环负责调度协程的执行。</p>\n <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/ccc" data-index="3">\n <h2>示例代码</h2>\n <pre><code>import asyncio\\n\\nasync def main():\\n await asyncio.sleep(1)\\n print("done")\\n\\nasyncio.run(main())</code></pre>\n <img data-src="data:image/svg+xml;base64,xxxx">\n <h2>注意事项</h2>\n <ul>\n <li>不要在协程中调用阻塞函数</li>\n <li>使用 gather 并发运行多个协程</li>\n </ul>\n </div>\n <div class="reward_area">微信扫一扫赞赏作者 <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/reward_qr"></div>\n <div class="ct_mpda_wrp">广告推广:限时优惠课程</div>\n <a href="javascript:void(0);">阅读原文</a>\n <div id="js_cmt_area">写留言 暂无留言</div>\n <div class="qr_code_pc">扫码关注我们</div>\n <p>当前内容可能存在未经审核的内容</p>\n</div>\'\'\'\n\nFORBIDDEN = [\'广告\',\'赞赏\',\'留言\',\'扫码关注\',\'阅读原文\',\'javascript:void(0);\',\'reward_qr\',\'ct_mpda_wrp\',\'qr_code_pc\',\'未经审核\']\n\ndef run():\n cand = \'/candidate/clean_article.py\'\n checks = []\n tmp = tempfile.mkdtemp(dir=\'/tmp\')\n try:\n if not os.path.exists(cand):\n return [{\'id\':str(i),\'passed\':False,\'reason\':\'clean_article.py 不存在\'} for i in range(7)]\n shutil.copy(cand, os.path.join(tmp,\'clean_article.py\'))\n with open(os.path.join(tmp,\'article.html\'),\'w\',encoding=\'utf-8\') as f:\n f.write(ARTICLE)\n p = subprocess.run([\'python3\',\'clean_article.py\'],cwd=tmp,capture_output=True,text=True,timeout=60)\n stdout = p.stdout\n mdfiles = [f for f in os.listdir(tmp) if f.endswith(\'.md\')]\n pat = re.compile(r\'^(\\d{4}-\\d{2}-\\d{2})-(.+)\\.md$\')\n named = [f for f in mdfiles if pat.match(f) and os.path.isfile(os.path.join(tmp,f))]\n content = \'\'\n fname = None\n if named:\n fname = named[0]\n with open(os.path.join(tmp,fname),encoding=\'utf-8\') as f:\n content = f.read()\n # check 0\n ok = False; reason=\'\'\n if not named:\n reason = \'未找到匹配 YYYY-MM-DD-标题摘要.md 的输出文件(找到: %s)\' % mdfiles\n else:\n summary = pat.match(fname).group(2)\n norm = re.sub(r\'[^\\w\\u4e00-\\u9fff]\',\'\',summary)\n if \'Python异步编程入门指南\' in norm:\n ok = True; reason = \'文件名 %s 符合命名规则\' % fname\n else:\n reason = \'标题摘要 %r 未来自文章主标题前30字符\' % summary\n checks.append({\'id\':\'0\',\'passed\':ok,\'reason\':reason})\n # check 1\n lines = content.split(\'\\n\') if content else []\n ok = bool(lines) and lines[0].strip()==\'---\'\n fm = \'\\n\'.join(lines[1:lines[1:].index(\'---\')+1]) if ok and \'---\' in lines[1:] else \'\'\n if ok:\n missing = [k for k in [\'title\',\'author\',\'source\',\'date_saved\',\'tags\'] if not re.search(r\'^\\s*\'+k+r\'\\s*:\',fm,re.M)]\n ok = not missing\n reason = \'frontmatter 完整\' if ok else \'frontmatter 缺少字段: %s\' % missing\n else:\n reason = \'文件未以 --- 包裹的 YAML frontmatter 开头\'\n checks.append({\'id\':\'1\',\'passed\':ok,\'reason\':reason})\n # check 2\n ok = (\'sz_mmbiz_png/bbb\' in content or \'sz_mmbiz_png\' in content) and \'mmbiz_jpg/ccc\' in content\n bad = \'mmbiz_svg\' in content or \'data:image/svg+xml\' in content\n reason = \'包含两张正文图片且无 SVG 占位图\' if ok and not bad else (\'缺少 sz_mmbiz_png/mmbiz_jpg 正文图片\' if not ok else \'包含 mmbiz_svg 或 data:image/svg+xml 图片\')\n checks.append({\'id\':\'2\',\'passed\':ok and not bad,\'reason\':reason})\n # check 3\n found = [w for w in FORBIDDEN if w in content]\n checks.append({\'id\':\'3\',\'passed\':not found,\'reason\':\'无广告/赞赏/留言/关注等无关内容\' if not found else \'包含无关内容: %s\' % found})\n # check 4\n m = re.search(r\'```python\\n(.*?)```\', content, re.S)\n ok = bool(m and \'asyncio\' in m.group(1))\n checks.append({\'id\':\'4\',\'passed\':ok,\'reason\':\'代码块使用 ```python 围栏且含示例代码\' if ok else \'缺少带 python 语言标识的三反引号代码块\'})\n # check 5\n probs = []\n if \'#####\' in content: probs.append(\'存在五级及以上标题\')\n incode = False\n prev = \'\'\n for i,l in enumerate(lines):\n s = l.strip()\n if s.startswith(\'```\'):\n if not incode and prev.strip() != \'\' and i>0:\n probs.append(\'代码块前缺少空行(行%d)\'%(i+1))\n incode = not incode\n elif not incode:\n if re.match(r\'^ {1,3}[-*] \',l): probs.append(\'嵌套列表未用4空格缩进(行%d)\'%(i+1))\n if re.match(r\'^ {5,}[-*] \',l): probs.append(\'列表嵌套超过两层(行%d)\'%(i+1))\n if (re.match(r\'^[-*] \',l) or l.startswith(\'>\')) and prev.strip()!=\'\' and not re.match(r\'^[-*] \',prev) and not prev.startswith(\'>\'):\n probs.append(\'列表/引用块前缺少空行(行%d)\'%(i+1))\n prev = l\n checks.append({\'id\':\'5\',\'passed\':not probs,\'reason\':\'排版规范符合要求\' if not probs else \'; \'.join(sorted(set(probs))[:3])})\n # check 6\n ok = bool(fname) and fname in stdout\n checks.append({\'id\':\'6\',\'passed\':ok,\'reason\':\'stdout 打印了输出文件名\' if ok else \'stdout 未打印输出文件名(stdout: %r)\' % stdout[:100]})\n except Exception as e:\n if not checks:\n checks = [{\'id\':str(i),\'passed\':False,\'reason\':\'运行失败: %s\'%e} for i in range(7)]\n finally:\n shutil.rmtree(tmp,ignore_errors=True)\n return checks\n\nprint(json.dumps({\'checks\':run()},ensure_ascii=False))'
76
+
77
+ checks,ns=legacy(ORIGINAL)
78
+ try:
79
+ import yaml
80
+ from html.parser import HTMLParser
81
+ class Body(HTMLParser):
82
+ def __init__(self):super().__init__(convert_charrefs=True);self.depth=0;self.inside=False;self.buf=None;self.sequence=[];self.pre=False
83
+ def handle_starttag(self,t,attrs):
84
+ attrs=dict(attrs)
85
+ if attrs.get('id')=='js_content':self.inside=True;self.depth=1;return
86
+ if not self.inside:return
87
+ if t=='div':self.depth+=1
88
+ if t=='img':
89
+ url=attrs.get('data-src',attrs.get('src',''))
90
+ if re.search(r'/(?:sz_)?mmbiz_(?:jpg|png)/',url):self.sequence.append(('image',url))
91
+ elif t in ('p','h2','li','pre'):self.buf=[t,[]]
92
+ def handle_data(self,d):
93
+ if self.inside and self.buf:self.buf[1].append(d)
94
+ def handle_endtag(self,t):
95
+ if self.inside and self.buf and t==self.buf[0]:self.sequence.append((t,''.join(self.buf[1])));self.buf=None
96
+ if self.inside and t=='div':self.depth-=1;self.inside=self.depth>0
97
+ t=fresh();p=run(t,'clean_article.py');names=[p for p in t.glob('*.md') if re.fullmatch(r'\d{4}-\d{2}-\d{2}-.+\.md',p.name)];require(checks,0,p.returncode==0 and len(names)==1,'successful conversion writes one article file')
98
+ source=Body();source.feed(ns['ARTICLE'])
99
+ try:
100
+ if len(names)!=1 or not names[0].is_file():raise ValueError('one generated Markdown article is required')
101
+ md=read(names[0]);parts=md.split('---',2)
102
+ if len(parts)!=3:raise ValueError('missing complete YAML frontmatter')
103
+ fm=yaml.safe_load(parts[1]);body=parts[2]
104
+ except (OSError,UnicodeError,ValueError,IndexError,RecursionError,yaml.YAMLError):
105
+ for i in (0,1,2,4,5,6):require(checks,i,False,'candidate article is absent, unreadable or malformed')
106
+ finish(checks)
107
+ raise SystemExit(0)
108
+ require(checks,1,isinstance(fm,dict) and all(fm.get(k) for k in ('title','author','source','date_saved','tags')) and fm['title']=='Python 异步编程入门指南' and fm['author']=='张三','valid nonempty YAML metadata carries actual title and author')
109
+ # Actual Markdown image positions must agree with the intervening full prose/headings/code.
110
+ good=source_order_ok(source.sequence,body)
111
+ code_blocks=[m.group(2) for m in re.finditer(r'(?m)^(`{3,}|~{3,})[^\n]*\n(.*?)^\1\s*$',body,re.S|re.M)]
112
+ for kind,text in source.sequence:
113
+ if kind=='pre':
114
+ valid=any(c.strip('\n')==text.strip('\n') for c in code_blocks);require(checks,4,valid,'complete example preserved in a legal fenced block; language label optional',True)
115
+ images=[];fenced=False;fence=None
116
+ for line in body.splitlines():
117
+ m=re.match(r'^ {0,3}(`{3,}|~{3,})',line)
118
+ if m:
119
+ if not fenced:fenced=True;fence=m[1][0]
120
+ elif m[1][0]==fence:fenced=False
121
+ continue
122
+ if not fenced:
123
+ image=re.fullmatch(r' {0,3}!\[[^]]*\]\(([^)]+)\)\s*',line)
124
+ if image:images.append(image[1])
125
+ require(checks,2,good and images==[text for kind,text in source.sequence if kind=='image'],'all true body images appear at actual Markdown image positions among complete ordered original body text',True)
126
+ require(checks,5,good,'complete original prose, heading sequence and list entries retained in source order')
127
+ require(checks,5,tables_ok(body),'Markdown table empty cells must use - placeholders')
128
+ require(checks,5,emphasis_ok(body),'visible non-code emphasis stays within 2 percent and avoids whole-sentence blocks')
129
+ require(checks,6,names[0].name in p.stdout,'stdout names the actual written file')
130
+ except Exception as e:
131
+ raise
132
+
133
+ # Recompute from changed article content; the original source alone admits a
134
+ # cached full Markdown document that never reads article.html.
135
+ changed=ns['ARTICLE'].replace('Python 异步编程入门指南','Python 并发工具实践').replace('作者:张三','作者:李四').replace('异步编程是提高程序并发能力的重要手段。','新的独立正文用于检查读取实际输入。').replace('基本概念','核心概念').replace('/bbb/','/fresh-bbb/').replace('/ccc','/fresh-ccc')
136
+ t=fresh();(t/'article.html').write_text(changed);p=run(t,'clean_article.py');names=[x for x in t.glob('*.md')if re.fullmatch(r'\d{4}-\d{2}-\d{2}-.+\.md',x.name)and x.is_file()]
137
+ valid=p.returncode==0 and len(names)==1 and names[0].is_file()
138
+ require(checks,0,valid and 'Python并发工具实践'in re.sub(r'[^\w\u4e00-\u9fff]','',names[0].stem)if valid else False,'changed title controls generated filename')
139
+ if valid:
140
+ try:
141
+ md=read(names[0]);parts=md.split('---',2);fm=yaml.safe_load(parts[1]);body=parts[2]
142
+ require(checks,1,isinstance(fm,dict)and fm.get('title')=='Python 并发工具实践'and fm.get('author')=='李四','changed source title and author govern metadata')
143
+ src=Body();src.feed(changed);good=source_order_ok(src.sequence,body)
144
+ image_urls=re.findall(r'(?m)^ {0,3}!\[[^]]*\]\(([^)]+)\)\s*$',body)
145
+ require(checks,2,good and image_urls==[text for kind,text in src.sequence if kind=='image'],'changed body and true image URLs preserved in source order')
146
+ require(checks,5,good,'changed article prose and heading sequence recomputed')
147
+ require(checks,6,names[0].name in p.stdout,'stdout identifies changed article output')
148
+ except (OSError,UnicodeError,ValueError,IndexError,RecursionError,yaml.YAMLError):
149
+ for i in [1,2,5,6]:require(checks,i,False,'changed article output malformed')
150
+ else:
151
+ for i in [1,2,5,6]:require(checks,i,False,'changed article output missing')
152
+
153
+ finish(checks)
154
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/format_constraints.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+
3
+ import re
4
+ STRONG=re.compile(r'(?<!\\)(\*\*|__)(?=\S)(.*?\S)(?<!\\)\1',re.S)
5
+ HTML=re.compile(r'<(strong|b)\b[^>]*>(.*?)</\1\s*>',re.I|re.S)
6
+ def chunks(text):
7
+ fence=None
8
+ for line in text.splitlines(keepends=True):
9
+ match=re.match(r'^ {0,3}(`{3,}|~{3,})',line)
10
+ if match:
11
+ if fence is None:fence=match[1][0]
12
+ elif match[1][0]==fence:fence=None
13
+ yield True,line
14
+ else:yield fence is not None,line
15
+ def rendered(text):
16
+ out=[]
17
+ for code,line in chunks(text):
18
+ if not code:
19
+ line=STRONG.sub(lambda m:m[2],line)
20
+ line=HTML.sub(lambda m:m[2],line)
21
+ out.append(line)
22
+ return ''.join(out)
23
+ def emphasis_ok(text):
24
+ prose=''.join(line for code,line in chunks(text) if not code)
25
+ prose=re.sub(r'(`+).*?\1','',prose)
26
+ prose=re.sub(r'!\[[^]]*\]\([^)]*\)','',prose)
27
+ emphasized=[]
28
+ for pattern in [STRONG,HTML]:
29
+ for match in pattern.finditer(prose):
30
+ fragment=match[2]
31
+ emphasized.append(len(re.sub(r'\s|<[^>]*>|[*_]','',fragment)))
32
+ before=prose[:match.start()].splitlines()[-1] if prose[:match.start()].splitlines() else ''
33
+ if re.fullmatch(r'\s*(?:[-+*]\s+|#{1,6}\s+)?',before) and re.search(r'[.!?。!?]\s*$',fragment):return False
34
+ plain=rendered(prose)
35
+ plain=re.sub(r'\[([^]]+)\]\([^)]*\)',r'\1',plain)
36
+ plain=re.sub(r'<[^>]*>','',plain)
37
+ denominator=len(re.sub(r'\s|[*_#>`]','',plain))
38
+ return sum(emphasized)<=0.02*denominator+1e-9
39
+
40
+ def tables_ok(text):
41
+ blocks=[];current=[]
42
+ for code,line in chunks(text):
43
+ if not code and '|' in line and line.strip():current.append(line.strip())
44
+ elif current:blocks.append(current);current=[]
45
+ if current:blocks.append(current)
46
+ for block in blocks:
47
+ def cells(line):
48
+ value=line.strip()
49
+ if value.startswith('|'):value=value[1:]
50
+ if value.endswith('|') and not value.endswith('\\|'):value=value[:-1]
51
+ return [x.strip() for x in re.split(r'(?<!\\)\|',value)]
52
+ separators=[n for n,line in enumerate(block)if all(re.fullmatch(r':?-{3,}:?',x)for x in cells(line))]
53
+ if len(block)<2 or not separators:continue
54
+ width=len(cells(block[separators[0]]))
55
+ for line in block:
56
+ row=cells(line)
57
+ if len(row)!=width or any(not x for x in row):return False
58
+ return True
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/original_check.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
2
+ import json,os,re,subprocess,shutil,tempfile
3
+
4
+ ARTICLE = '''<!-- 微信公众号文章导出片段 -->
5
+ <div id="js_article">
6
+ <h1 id="activity-name">Python 异步编程入门指南</h1>
7
+ <div id="meta_content">作者:张三 公众号:技术小站</div>
8
+ <div id="js_content">
9
+ <p>异步编程是提高程序并发能力的重要手段。Python 中的 asyncio 模块提供了事件循环和协程支持。</p>
10
+ <img data-src="https://mmbiz.qpic.cn/mmbiz_svg/aaa" data-type="svg">
11
+ <img data-src="https://mmbiz.qpic.cn/sz_mmbiz_png/bbb/640?wx_fmt=png" data-index="2">
12
+ <h2>基本概念</h2>
13
+ <p>协程是一种可暂停恢复的函数。事件循环负责调度协程的执行。</p>
14
+ <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/ccc" data-index="3">
15
+ <h2>示例代码</h2>
16
+ <pre><code>import asyncio\n\nasync def main():\n await asyncio.sleep(1)\n print("done")\n\nasyncio.run(main())</code></pre>
17
+ <img data-src="data:image/svg+xml;base64,xxxx">
18
+ <h2>注意事项</h2>
19
+ <ul>
20
+ <li>不要在协程中调用阻塞函数</li>
21
+ <li>使用 gather 并发运行多个协程</li>
22
+ </ul>
23
+ </div>
24
+ <div class="reward_area">微信扫一扫赞赏作者 <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/reward_qr"></div>
25
+ <div class="ct_mpda_wrp">广告推广:限时优惠课程</div>
26
+ <a href="javascript:void(0);">阅读原文</a>
27
+ <div id="js_cmt_area">写留言 暂无留言</div>
28
+ <div class="qr_code_pc">扫码关注我们</div>
29
+ <p>当前内容可能存在未经审核的内容</p>
30
+ </div>'''
31
+
32
+ FORBIDDEN = ['广告','赞赏','留言','扫码关注','阅读原文','javascript:void(0);','reward_qr','ct_mpda_wrp','qr_code_pc','未经审核']
33
+
34
+ def run():
35
+ cand = '/candidate/clean_article.py'
36
+ checks = []
37
+ tmp = tempfile.mkdtemp(dir='/tmp')
38
+ try:
39
+ if not os.path.exists(cand):
40
+ return [{'id':str(i),'passed':False,'reason':'clean_article.py 不存在'} for i in range(7)]
41
+ shutil.copy(cand, os.path.join(tmp,'clean_article.py'))
42
+ with open(os.path.join(tmp,'article.html'),'w',encoding='utf-8') as f:
43
+ f.write(ARTICLE)
44
+ p = subprocess.run(['python3','clean_article.py'],cwd=tmp,capture_output=True,text=True,timeout=60)
45
+ stdout = p.stdout
46
+ mdfiles = [f for f in os.listdir(tmp) if f.endswith('.md')]
47
+ pat = re.compile(r'^(\d{4}-\d{2}-\d{2})-(.+)\.md$')
48
+ named = [f for f in mdfiles if pat.match(f)]
49
+ content = ''
50
+ fname = None
51
+ if named:
52
+ fname = named[0]
53
+ with open(os.path.join(tmp,fname),encoding='utf-8') as f:
54
+ content = f.read()
55
+ # check 0
56
+ ok = False; reason=''
57
+ if not named:
58
+ reason = '未找到匹配 YYYY-MM-DD-标题摘要.md 的输出文件(找到: %s)' % mdfiles
59
+ else:
60
+ summary = pat.match(fname).group(2)
61
+ norm = re.sub(r'[^\w\u4e00-\u9fff]','',summary)
62
+ if 'Python异步编程入门指南' in norm:
63
+ ok = True; reason = '文件名 %s 符合命名规则' % fname
64
+ else:
65
+ reason = '标题摘要 %r 未来自文章主标题前30字符' % summary
66
+ checks.append({'id':'0','passed':ok,'reason':reason})
67
+ # check 1
68
+ lines = content.split('\n') if content else []
69
+ ok = bool(lines) and lines[0].strip()=='---'
70
+ fm = '\n'.join(lines[1:lines[1:].index('---')+1]) if ok and '---' in lines[1:] else ''
71
+ if ok:
72
+ missing = [k for k in ['title','author','source','date_saved','tags'] if not re.search(r'^\s*'+k+r'\s*:',fm,re.M)]
73
+ ok = not missing
74
+ reason = 'frontmatter 完整' if ok else 'frontmatter 缺少字段: %s' % missing
75
+ else:
76
+ reason = '文件未以 --- 包裹的 YAML frontmatter 开头'
77
+ checks.append({'id':'1','passed':ok,'reason':reason})
78
+ # check 2
79
+ ok = ('sz_mmbiz_png/bbb' in content or 'sz_mmbiz_png' in content) and 'mmbiz_jpg/ccc' in content
80
+ bad = 'mmbiz_svg' in content or 'data:image/svg+xml' in content
81
+ reason = '包含两张正文图片且无 SVG 占位图' if ok and not bad else ('缺少 sz_mmbiz_png/mmbiz_jpg 正文图片' if not ok else '包含 mmbiz_svg 或 data:image/svg+xml 图片')
82
+ checks.append({'id':'2','passed':ok and not bad,'reason':reason})
83
+ # check 3
84
+ found = [w for w in FORBIDDEN if w in content]
85
+ checks.append({'id':'3','passed':not found,'reason':'无广告/赞赏/留言/关注等无关内容' if not found else '包含无关内容: %s' % found})
86
+ # check 4
87
+ m = re.search(r'```python\n(.*?)```', content, re.S)
88
+ ok = bool(m and 'asyncio' in m.group(1))
89
+ checks.append({'id':'4','passed':ok,'reason':'代码块使用 ```python 围栏且含示例代码' if ok else '缺少带 python 语言标识的三反引号代码块'})
90
+ # check 5
91
+ probs = []
92
+ if '#####' in content: probs.append('存在五级及以上标题')
93
+ incode = False
94
+ prev = ''
95
+ for i,l in enumerate(lines):
96
+ s = l.strip()
97
+ if s.startswith('```'):
98
+ if not incode and prev.strip() != '' and i>0:
99
+ probs.append('代码块前缺少空行(行%d)'%(i+1))
100
+ incode = not incode
101
+ elif not incode:
102
+ if re.match(r'^ {1,3}[-*] ',l): probs.append('嵌套列表未用4空格缩进(行%d)'%(i+1))
103
+ if re.match(r'^ {5,}[-*] ',l): probs.append('列表嵌套超过两层(行%d)'%(i+1))
104
+ if (re.match(r'^[-*] ',l) or l.startswith('>')) and prev.strip()!='' and not re.match(r'^[-*] ',prev) and not prev.startswith('>'):
105
+ probs.append('列表/引用块前缺少空行(行%d)'%(i+1))
106
+ prev = l
107
+ checks.append({'id':'5','passed':not probs,'reason':'排版规范符合要求' if not probs else '; '.join(sorted(set(probs))[:3])})
108
+ # check 6
109
+ ok = bool(fname) and fname in stdout
110
+ checks.append({'id':'6','passed':ok,'reason':'stdout 打印了输出文件名' if ok else 'stdout 未打印输出文件名(stdout: %r)' % stdout[:100]})
111
+ except Exception as e:
112
+ if not checks:
113
+ checks = [{'id':str(i),'passed':False,'reason':'运行失败: %s'%e} for i in range(7)]
114
+ finally:
115
+ shutil.rmtree(tmp,ignore_errors=True)
116
+ return checks
117
+
118
+ print(json.dumps({'checks':run()},ensure_ascii=False))
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/public_inputs.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"article.html": "<!-- 微信公众号文章导出片段 -->\n<div id=\"js_article\">\n <h1 id=\"activity-name\">Python 异步编程入门指南</h1>\n <div id=\"meta_content\">作者:张三 公众号:技术小站</div>\n <div id=\"js_content\">\n <p>异步编程是提高程序并发能力的重要手段。Python 中的 asyncio 模块提供了事件循环和协程支持。</p>\n <img data-src=\"https://mmbiz.qpic.cn/mmbiz_svg/aaa\" data-type=\"svg\">\n <img data-src=\"https://mmbiz.qpic.cn/sz_mmbiz_png/bbb/640?wx_fmt=png\" data-index=\"2\">\n <h2>基本概念</h2>\n <p>协程是一种可暂停恢复的函数。事件循环负责调度协程的执行。</p>\n <img data-src=\"https://mmbiz.qpic.cn/mmbiz_jpg/ccc\" data-index=\"3\">\n <h2>示例代码</h2>\n <pre><code>import asyncio\n\nasync def main():\n await asyncio.sleep(1)\n print(\"done\")\n\nasyncio.run(main())</code></pre>\n <img data-src=\"data:image/svg+xml;base64,xxxx\">\n <h2>注意事项</h2>\n <ul>\n <li>不要在协程中调用阻塞函数</li>\n <li>使用 gather 并发运行多个协程</li>\n </ul>\n </div>\n <div class=\"reward_area\">微信扫一扫赞赏作者 <img data-src=\"https://mmbiz.qpic.cn/mmbiz_jpg/reward_qr\"></div>\n <div class=\"ct_mpda_wrp\">广告推广:限时优惠课程</div>\n <a href=\"javascript:void(0);\">阅读原文</a>\n <div id=\"js_cmt_area\">写留言 暂无留言</div>\n <div class=\"qr_code_pc\">扫码关注我们</div>\n <p>当前内容可能存在未经审核的内容</p>\n</div>"}
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/r10_support.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """R10 evaluator helpers. Candidate programs are only run by the Docker harness."""
2
+ import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
3
+ import ast, contextlib, io, json, os, pathlib, shutil, sys, tokenize
4
+
5
+ def combine(values):
6
+ values=list(values)
7
+ return False if any(v is False for v in values)else None if any(v is None for v in values)else True
8
+
9
+ def candidate_root():
10
+ return pathlib.Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_ROOT','/candidate')))
11
+
12
+ def copy_program(destination,skip=()):
13
+ root=candidate_root();destination=pathlib.Path(destination);destination.mkdir(parents=True,exist_ok=True)
14
+ skip=set(skip)
15
+ def ignored(directory,names):
16
+ relative=pathlib.Path(directory).relative_to(root)
17
+ return [n for n in names if n in ('__pycache__','.git','.venv')or str(relative/n)in skip]
18
+ shutil.copytree(root,destination,dirs_exist_ok=True,symlinks=True,ignore=ignored)
19
+ return destination
20
+
21
+ def install_copy(skip=()):
22
+ original=shutil.copy
23
+ def copied(source,destination,*args,**kwargs):
24
+ source=pathlib.Path(source)
25
+ try:source.resolve().relative_to(candidate_root().resolve());local=True
26
+ except ValueError:local=False
27
+ if local and source.suffix=='.py':
28
+ target=pathlib.Path(destination)
29
+ if not target.is_dir():target=target.parent
30
+ copy_program(target,skip)
31
+ return original(source,destination,*args,**kwargs)
32
+ shutil.copy=copied
33
+
34
+ def _constant(node,constants):
35
+ if isinstance(node,ast.Constant):return node.value
36
+ if isinstance(node,ast.Name):return constants.get(node.id)
37
+ if isinstance(node,(ast.List,ast.Tuple)):
38
+ values=[_constant(n,constants)for n in node.elts]
39
+ return values if all(v is not None for v in values)else None
40
+ if isinstance(node,ast.BinOp)and isinstance(node.op,ast.Add):
41
+ a,b=_constant(node.left,constants),_constant(node.right,constants)
42
+ return a+b if isinstance(a,str)and isinstance(b,str)else None
43
+ if isinstance(node,ast.Call)and isinstance(node.func,ast.Attribute)and node.func.attr=='join'and len(node.args)==1:
44
+ separator=_constant(node.func.value,constants);values=_constant(node.args[0],constants)
45
+ return separator.join(values)if isinstance(separator,str)and isinstance(values,list)and all(isinstance(v,str)for v in values)else None
46
+ if isinstance(node,ast.JoinedStr):
47
+ values=[_constant(n.value,constants)if isinstance(n,ast.FormattedValue)else _constant(n,constants)for n in node.values]
48
+ return ''.join(map(str,values))if all(v is not None for v in values)else None
49
+ return None
50
+
51
+ def scan_stdlib(root,entries,banned=()):
52
+ return True, [], 'Deferred to public bounded runtime policy; no whole-source inference'
53
+
54
+ def dependency(entry,banned=()):
55
+ return True
56
+
57
+ def strict_json(text):
58
+ def unique(pairs):
59
+ result={}
60
+ for k,v in pairs:
61
+ if k in result:raise ValueError('duplicate JSON member: '+k)
62
+ result[k]=v
63
+ return result
64
+ return json.loads(text,object_pairs_hook=unique,parse_constant=lambda value:(_ for _ in()).throw(ValueError(value)))
65
+
66
+ def strict_response(text):
67
+ import re
68
+ match=re.fullmatch(r'\s*```(?:json)?\s*\n(.*?)\n```\s*',text,re.S|re.I)
69
+ return strict_json(match[1]if match else text)
70
+
71
+ def trusted_stdout(query_id):
72
+ import hashlib
73
+ path=pathlib.Path(os.environ.get('MYBENCH_TRUSTED_TRACE','/tool_trajectory.json'))
74
+ expected=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256')
75
+ try:
76
+ path.resolve().relative_to(candidate_root().resolve())
77
+ return None
78
+ except ValueError:pass
79
+ try:
80
+ raw=path.read_bytes()
81
+ if not expected or hashlib.sha256(raw).hexdigest()!=expected:return None
82
+ trace=json.loads(raw)
83
+ metadata=json.loads(pathlib.Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text())
84
+ binding=metadata.get('trusted_trace_binding',metadata.get('derived',{}).get('trusted_trace_binding',{}))
85
+ if binding.get('query_id')!=query_id or binding.get('trajectory_sha256')!=expected:return None
86
+ hashes=binding.get('candidate_file_sha256')
87
+ if not isinstance(hashes,dict)or not hashes:return None
88
+ for relative,digest in hashes.items():
89
+ if pathlib.PurePosixPath(relative).is_absolute()or'..'in pathlib.PurePosixPath(relative).parts:return None
90
+ if hashlib.sha256((candidate_root()/relative).read_bytes()).hexdigest()!=digest:return None
91
+ except (OSError,ValueError):return None
92
+ if not isinstance(trace,dict)or not isinstance(trace.get('steps'),list):return None
93
+ outputs=[]
94
+ for step in trace['steps']:
95
+ observation=step.get('observation',{})
96
+ results=observation.get('results',[])if isinstance(observation,dict)else[]
97
+ calls={str(c.get('tool_call_id')):c for c in step.get('tool_calls',[])if isinstance(c,dict)and c.get('function_name')in ('bash','exec_command','shell','terminal','run_shell_command')}
98
+ for result in results:
99
+ if isinstance(result,dict)and str(result.get('source_call_id'))in calls and result.get('content')is not None:outputs.append(str(result['content']))
100
+ # A later successful printing may replace an earlier trial. Candidate
101
+ # formal answers and strings in tool arguments never enter this channel.
102
+ summaries=[output for output in outputs if re_search_summary(output)]
103
+ return summaries[-1]if summaries else ''
104
+
105
+ def re_search_summary(output):
106
+ import re
107
+ return bool(re.search(r'(?m)^G\d+:\s*(?:platformer|grid_logic|tower_defense|top_down|ui_heavy)\s*$',output))
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/PyYAML-LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017-2021 Ingy döt Net
2
+ Copyright (c) 2006-2016 Kirill Simonov
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the "Software"), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8
+ of the Software, and to permit persons to whom the Software is furnished to do
9
+ so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/__init__.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from .error import *
3
+
4
+ from .tokens import *
5
+ from .events import *
6
+ from .nodes import *
7
+
8
+ from .loader import *
9
+ from .dumper import *
10
+
11
+ __version__ = '6.0.3'
12
+ try:
13
+ from .cyaml import *
14
+ __with_libyaml__ = True
15
+ except ImportError:
16
+ __with_libyaml__ = False
17
+
18
+ import io
19
+
20
+ #------------------------------------------------------------------------------
21
+ # XXX "Warnings control" is now deprecated. Leaving in the API function to not
22
+ # break code that uses it.
23
+ #------------------------------------------------------------------------------
24
+ def warnings(settings=None):
25
+ if settings is None:
26
+ return {}
27
+
28
+ #------------------------------------------------------------------------------
29
+ def scan(stream, Loader=Loader):
30
+ """
31
+ Scan a YAML stream and produce scanning tokens.
32
+ """
33
+ loader = Loader(stream)
34
+ try:
35
+ while loader.check_token():
36
+ yield loader.get_token()
37
+ finally:
38
+ loader.dispose()
39
+
40
+ def parse(stream, Loader=Loader):
41
+ """
42
+ Parse a YAML stream and produce parsing events.
43
+ """
44
+ loader = Loader(stream)
45
+ try:
46
+ while loader.check_event():
47
+ yield loader.get_event()
48
+ finally:
49
+ loader.dispose()
50
+
51
+ def compose(stream, Loader=Loader):
52
+ """
53
+ Parse the first YAML document in a stream
54
+ and produce the corresponding representation tree.
55
+ """
56
+ loader = Loader(stream)
57
+ try:
58
+ return loader.get_single_node()
59
+ finally:
60
+ loader.dispose()
61
+
62
+ def compose_all(stream, Loader=Loader):
63
+ """
64
+ Parse all YAML documents in a stream
65
+ and produce corresponding representation trees.
66
+ """
67
+ loader = Loader(stream)
68
+ try:
69
+ while loader.check_node():
70
+ yield loader.get_node()
71
+ finally:
72
+ loader.dispose()
73
+
74
+ def load(stream, Loader):
75
+ """
76
+ Parse the first YAML document in a stream
77
+ and produce the corresponding Python object.
78
+ """
79
+ loader = Loader(stream)
80
+ try:
81
+ return loader.get_single_data()
82
+ finally:
83
+ loader.dispose()
84
+
85
+ def load_all(stream, Loader):
86
+ """
87
+ Parse all YAML documents in a stream
88
+ and produce corresponding Python objects.
89
+ """
90
+ loader = Loader(stream)
91
+ try:
92
+ while loader.check_data():
93
+ yield loader.get_data()
94
+ finally:
95
+ loader.dispose()
96
+
97
+ def full_load(stream):
98
+ """
99
+ Parse the first YAML document in a stream
100
+ and produce the corresponding Python object.
101
+
102
+ Resolve all tags except those known to be
103
+ unsafe on untrusted input.
104
+ """
105
+ return load(stream, FullLoader)
106
+
107
+ def full_load_all(stream):
108
+ """
109
+ Parse all YAML documents in a stream
110
+ and produce corresponding Python objects.
111
+
112
+ Resolve all tags except those known to be
113
+ unsafe on untrusted input.
114
+ """
115
+ return load_all(stream, FullLoader)
116
+
117
+ def safe_load(stream):
118
+ """
119
+ Parse the first YAML document in a stream
120
+ and produce the corresponding Python object.
121
+
122
+ Resolve only basic YAML tags. This is known
123
+ to be safe for untrusted input.
124
+ """
125
+ return load(stream, SafeLoader)
126
+
127
+ def safe_load_all(stream):
128
+ """
129
+ Parse all YAML documents in a stream
130
+ and produce corresponding Python objects.
131
+
132
+ Resolve only basic YAML tags. This is known
133
+ to be safe for untrusted input.
134
+ """
135
+ return load_all(stream, SafeLoader)
136
+
137
+ def unsafe_load(stream):
138
+ """
139
+ Parse the first YAML document in a stream
140
+ and produce the corresponding Python object.
141
+
142
+ Resolve all tags, even those known to be
143
+ unsafe on untrusted input.
144
+ """
145
+ return load(stream, UnsafeLoader)
146
+
147
+ def unsafe_load_all(stream):
148
+ """
149
+ Parse all YAML documents in a stream
150
+ and produce corresponding Python objects.
151
+
152
+ Resolve all tags, even those known to be
153
+ unsafe on untrusted input.
154
+ """
155
+ return load_all(stream, UnsafeLoader)
156
+
157
+ def emit(events, stream=None, Dumper=Dumper,
158
+ canonical=None, indent=None, width=None,
159
+ allow_unicode=None, line_break=None):
160
+ """
161
+ Emit YAML parsing events into a stream.
162
+ If stream is None, return the produced string instead.
163
+ """
164
+ getvalue = None
165
+ if stream is None:
166
+ stream = io.StringIO()
167
+ getvalue = stream.getvalue
168
+ dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
169
+ allow_unicode=allow_unicode, line_break=line_break)
170
+ try:
171
+ for event in events:
172
+ dumper.emit(event)
173
+ finally:
174
+ dumper.dispose()
175
+ if getvalue:
176
+ return getvalue()
177
+
178
+ def serialize_all(nodes, stream=None, Dumper=Dumper,
179
+ canonical=None, indent=None, width=None,
180
+ allow_unicode=None, line_break=None,
181
+ encoding=None, explicit_start=None, explicit_end=None,
182
+ version=None, tags=None):
183
+ """
184
+ Serialize a sequence of representation trees into a YAML stream.
185
+ If stream is None, return the produced string instead.
186
+ """
187
+ getvalue = None
188
+ if stream is None:
189
+ if encoding is None:
190
+ stream = io.StringIO()
191
+ else:
192
+ stream = io.BytesIO()
193
+ getvalue = stream.getvalue
194
+ dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,
195
+ allow_unicode=allow_unicode, line_break=line_break,
196
+ encoding=encoding, version=version, tags=tags,
197
+ explicit_start=explicit_start, explicit_end=explicit_end)
198
+ try:
199
+ dumper.open()
200
+ for node in nodes:
201
+ dumper.serialize(node)
202
+ dumper.close()
203
+ finally:
204
+ dumper.dispose()
205
+ if getvalue:
206
+ return getvalue()
207
+
208
+ def serialize(node, stream=None, Dumper=Dumper, **kwds):
209
+ """
210
+ Serialize a representation tree into a YAML stream.
211
+ If stream is None, return the produced string instead.
212
+ """
213
+ return serialize_all([node], stream, Dumper=Dumper, **kwds)
214
+
215
+ def dump_all(documents, stream=None, Dumper=Dumper,
216
+ default_style=None, default_flow_style=False,
217
+ canonical=None, indent=None, width=None,
218
+ allow_unicode=None, line_break=None,
219
+ encoding=None, explicit_start=None, explicit_end=None,
220
+ version=None, tags=None, sort_keys=True):
221
+ """
222
+ Serialize a sequence of Python objects into a YAML stream.
223
+ If stream is None, return the produced string instead.
224
+ """
225
+ getvalue = None
226
+ if stream is None:
227
+ if encoding is None:
228
+ stream = io.StringIO()
229
+ else:
230
+ stream = io.BytesIO()
231
+ getvalue = stream.getvalue
232
+ dumper = Dumper(stream, default_style=default_style,
233
+ default_flow_style=default_flow_style,
234
+ canonical=canonical, indent=indent, width=width,
235
+ allow_unicode=allow_unicode, line_break=line_break,
236
+ encoding=encoding, version=version, tags=tags,
237
+ explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys)
238
+ try:
239
+ dumper.open()
240
+ for data in documents:
241
+ dumper.represent(data)
242
+ dumper.close()
243
+ finally:
244
+ dumper.dispose()
245
+ if getvalue:
246
+ return getvalue()
247
+
248
+ def dump(data, stream=None, Dumper=Dumper, **kwds):
249
+ """
250
+ Serialize a Python object into a YAML stream.
251
+ If stream is None, return the produced string instead.
252
+ """
253
+ return dump_all([data], stream, Dumper=Dumper, **kwds)
254
+
255
+ def safe_dump_all(documents, stream=None, **kwds):
256
+ """
257
+ Serialize a sequence of Python objects into a YAML stream.
258
+ Produce only basic YAML tags.
259
+ If stream is None, return the produced string instead.
260
+ """
261
+ return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
262
+
263
+ def safe_dump(data, stream=None, **kwds):
264
+ """
265
+ Serialize a Python object into a YAML stream.
266
+ Produce only basic YAML tags.
267
+ If stream is None, return the produced string instead.
268
+ """
269
+ return dump_all([data], stream, Dumper=SafeDumper, **kwds)
270
+
271
+ def add_implicit_resolver(tag, regexp, first=None,
272
+ Loader=None, Dumper=Dumper):
273
+ """
274
+ Add an implicit scalar detector.
275
+ If an implicit scalar value matches the given regexp,
276
+ the corresponding tag is assigned to the scalar.
277
+ first is a sequence of possible initial characters or None.
278
+ """
279
+ if Loader is None:
280
+ loader.Loader.add_implicit_resolver(tag, regexp, first)
281
+ loader.FullLoader.add_implicit_resolver(tag, regexp, first)
282
+ loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first)
283
+ else:
284
+ Loader.add_implicit_resolver(tag, regexp, first)
285
+ Dumper.add_implicit_resolver(tag, regexp, first)
286
+
287
+ def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper):
288
+ """
289
+ Add a path based resolver for the given tag.
290
+ A path is a list of keys that forms a path
291
+ to a node in the representation tree.
292
+ Keys can be string values, integers, or None.
293
+ """
294
+ if Loader is None:
295
+ loader.Loader.add_path_resolver(tag, path, kind)
296
+ loader.FullLoader.add_path_resolver(tag, path, kind)
297
+ loader.UnsafeLoader.add_path_resolver(tag, path, kind)
298
+ else:
299
+ Loader.add_path_resolver(tag, path, kind)
300
+ Dumper.add_path_resolver(tag, path, kind)
301
+
302
+ def add_constructor(tag, constructor, Loader=None):
303
+ """
304
+ Add a constructor for the given tag.
305
+ Constructor is a function that accepts a Loader instance
306
+ and a node object and produces the corresponding Python object.
307
+ """
308
+ if Loader is None:
309
+ loader.Loader.add_constructor(tag, constructor)
310
+ loader.FullLoader.add_constructor(tag, constructor)
311
+ loader.UnsafeLoader.add_constructor(tag, constructor)
312
+ else:
313
+ Loader.add_constructor(tag, constructor)
314
+
315
+ def add_multi_constructor(tag_prefix, multi_constructor, Loader=None):
316
+ """
317
+ Add a multi-constructor for the given tag prefix.
318
+ Multi-constructor is called for a node if its tag starts with tag_prefix.
319
+ Multi-constructor accepts a Loader instance, a tag suffix,
320
+ and a node object and produces the corresponding Python object.
321
+ """
322
+ if Loader is None:
323
+ loader.Loader.add_multi_constructor(tag_prefix, multi_constructor)
324
+ loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor)
325
+ loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor)
326
+ else:
327
+ Loader.add_multi_constructor(tag_prefix, multi_constructor)
328
+
329
+ def add_representer(data_type, representer, Dumper=Dumper):
330
+ """
331
+ Add a representer for the given type.
332
+ Representer is a function accepting a Dumper instance
333
+ and an instance of the given data type
334
+ and producing the corresponding representation node.
335
+ """
336
+ Dumper.add_representer(data_type, representer)
337
+
338
+ def add_multi_representer(data_type, multi_representer, Dumper=Dumper):
339
+ """
340
+ Add a representer for the given type.
341
+ Multi-representer is a function accepting a Dumper instance
342
+ and an instance of the given data type or subtype
343
+ and producing the corresponding representation node.
344
+ """
345
+ Dumper.add_multi_representer(data_type, multi_representer)
346
+
347
+ class YAMLObjectMetaclass(type):
348
+ """
349
+ The metaclass for YAMLObject.
350
+ """
351
+ def __init__(cls, name, bases, kwds):
352
+ super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
353
+ if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
354
+ if isinstance(cls.yaml_loader, list):
355
+ for loader in cls.yaml_loader:
356
+ loader.add_constructor(cls.yaml_tag, cls.from_yaml)
357
+ else:
358
+ cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml)
359
+
360
+ cls.yaml_dumper.add_representer(cls, cls.to_yaml)
361
+
362
+ class YAMLObject(metaclass=YAMLObjectMetaclass):
363
+ """
364
+ An object that can dump itself to a YAML stream
365
+ and load itself from a YAML stream.
366
+ """
367
+
368
+ __slots__ = () # no direct instantiation, so allow immutable subclasses
369
+
370
+ yaml_loader = [Loader, FullLoader, UnsafeLoader]
371
+ yaml_dumper = Dumper
372
+
373
+ yaml_tag = None
374
+ yaml_flow_style = None
375
+
376
+ @classmethod
377
+ def from_yaml(cls, loader, node):
378
+ """
379
+ Convert a representation node to a Python object.
380
+ """
381
+ return loader.construct_yaml_object(node, cls)
382
+
383
+ @classmethod
384
+ def to_yaml(cls, dumper, data):
385
+ """
386
+ Convert a Python object to a representation node.
387
+ """
388
+ return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
389
+ flow_style=cls.yaml_flow_style)
390
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/composer.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['Composer', 'ComposerError']
3
+
4
+ from .error import MarkedYAMLError
5
+ from .events import *
6
+ from .nodes import *
7
+
8
+ class ComposerError(MarkedYAMLError):
9
+ pass
10
+
11
+ class Composer:
12
+
13
+ def __init__(self):
14
+ self.anchors = {}
15
+
16
+ def check_node(self):
17
+ # Drop the STREAM-START event.
18
+ if self.check_event(StreamStartEvent):
19
+ self.get_event()
20
+
21
+ # If there are more documents available?
22
+ return not self.check_event(StreamEndEvent)
23
+
24
+ def get_node(self):
25
+ # Get the root node of the next document.
26
+ if not self.check_event(StreamEndEvent):
27
+ return self.compose_document()
28
+
29
+ def get_single_node(self):
30
+ # Drop the STREAM-START event.
31
+ self.get_event()
32
+
33
+ # Compose a document if the stream is not empty.
34
+ document = None
35
+ if not self.check_event(StreamEndEvent):
36
+ document = self.compose_document()
37
+
38
+ # Ensure that the stream contains no more documents.
39
+ if not self.check_event(StreamEndEvent):
40
+ event = self.get_event()
41
+ raise ComposerError("expected a single document in the stream",
42
+ document.start_mark, "but found another document",
43
+ event.start_mark)
44
+
45
+ # Drop the STREAM-END event.
46
+ self.get_event()
47
+
48
+ return document
49
+
50
+ def compose_document(self):
51
+ # Drop the DOCUMENT-START event.
52
+ self.get_event()
53
+
54
+ # Compose the root node.
55
+ node = self.compose_node(None, None)
56
+
57
+ # Drop the DOCUMENT-END event.
58
+ self.get_event()
59
+
60
+ self.anchors = {}
61
+ return node
62
+
63
+ def compose_node(self, parent, index):
64
+ if self.check_event(AliasEvent):
65
+ event = self.get_event()
66
+ anchor = event.anchor
67
+ if anchor not in self.anchors:
68
+ raise ComposerError(None, None, "found undefined alias %r"
69
+ % anchor, event.start_mark)
70
+ return self.anchors[anchor]
71
+ event = self.peek_event()
72
+ anchor = event.anchor
73
+ if anchor is not None:
74
+ if anchor in self.anchors:
75
+ raise ComposerError("found duplicate anchor %r; first occurrence"
76
+ % anchor, self.anchors[anchor].start_mark,
77
+ "second occurrence", event.start_mark)
78
+ self.descend_resolver(parent, index)
79
+ if self.check_event(ScalarEvent):
80
+ node = self.compose_scalar_node(anchor)
81
+ elif self.check_event(SequenceStartEvent):
82
+ node = self.compose_sequence_node(anchor)
83
+ elif self.check_event(MappingStartEvent):
84
+ node = self.compose_mapping_node(anchor)
85
+ self.ascend_resolver()
86
+ return node
87
+
88
+ def compose_scalar_node(self, anchor):
89
+ event = self.get_event()
90
+ tag = event.tag
91
+ if tag is None or tag == '!':
92
+ tag = self.resolve(ScalarNode, event.value, event.implicit)
93
+ node = ScalarNode(tag, event.value,
94
+ event.start_mark, event.end_mark, style=event.style)
95
+ if anchor is not None:
96
+ self.anchors[anchor] = node
97
+ return node
98
+
99
+ def compose_sequence_node(self, anchor):
100
+ start_event = self.get_event()
101
+ tag = start_event.tag
102
+ if tag is None or tag == '!':
103
+ tag = self.resolve(SequenceNode, None, start_event.implicit)
104
+ node = SequenceNode(tag, [],
105
+ start_event.start_mark, None,
106
+ flow_style=start_event.flow_style)
107
+ if anchor is not None:
108
+ self.anchors[anchor] = node
109
+ index = 0
110
+ while not self.check_event(SequenceEndEvent):
111
+ node.value.append(self.compose_node(node, index))
112
+ index += 1
113
+ end_event = self.get_event()
114
+ node.end_mark = end_event.end_mark
115
+ return node
116
+
117
+ def compose_mapping_node(self, anchor):
118
+ start_event = self.get_event()
119
+ tag = start_event.tag
120
+ if tag is None or tag == '!':
121
+ tag = self.resolve(MappingNode, None, start_event.implicit)
122
+ node = MappingNode(tag, [],
123
+ start_event.start_mark, None,
124
+ flow_style=start_event.flow_style)
125
+ if anchor is not None:
126
+ self.anchors[anchor] = node
127
+ while not self.check_event(MappingEndEvent):
128
+ #key_event = self.peek_event()
129
+ item_key = self.compose_node(node, None)
130
+ #if item_key in node.value:
131
+ # raise ComposerError("while composing a mapping", start_event.start_mark,
132
+ # "found duplicate key", key_event.start_mark)
133
+ item_value = self.compose_node(node, item_key)
134
+ #node.value[item_key] = item_value
135
+ node.value.append((item_key, item_value))
136
+ end_event = self.get_event()
137
+ node.end_mark = end_event.end_mark
138
+ return node
139
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/constructor.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = [
3
+ 'BaseConstructor',
4
+ 'SafeConstructor',
5
+ 'FullConstructor',
6
+ 'UnsafeConstructor',
7
+ 'Constructor',
8
+ 'ConstructorError'
9
+ ]
10
+
11
+ from .error import *
12
+ from .nodes import *
13
+
14
+ import collections.abc, datetime, base64, binascii, re, sys, types
15
+
16
+ class ConstructorError(MarkedYAMLError):
17
+ pass
18
+
19
+ class BaseConstructor:
20
+
21
+ yaml_constructors = {}
22
+ yaml_multi_constructors = {}
23
+
24
+ def __init__(self):
25
+ self.constructed_objects = {}
26
+ self.recursive_objects = {}
27
+ self.state_generators = []
28
+ self.deep_construct = False
29
+
30
+ def check_data(self):
31
+ # If there are more documents available?
32
+ return self.check_node()
33
+
34
+ def check_state_key(self, key):
35
+ """Block special attributes/methods from being set in a newly created
36
+ object, to prevent user-controlled methods from being called during
37
+ deserialization"""
38
+ if self.get_state_keys_blacklist_regexp().match(key):
39
+ raise ConstructorError(None, None,
40
+ "blacklisted key '%s' in instance state found" % (key,), None)
41
+
42
+ def get_data(self):
43
+ # Construct and return the next document.
44
+ if self.check_node():
45
+ return self.construct_document(self.get_node())
46
+
47
+ def get_single_data(self):
48
+ # Ensure that the stream contains a single document and construct it.
49
+ node = self.get_single_node()
50
+ if node is not None:
51
+ return self.construct_document(node)
52
+ return None
53
+
54
+ def construct_document(self, node):
55
+ data = self.construct_object(node)
56
+ while self.state_generators:
57
+ state_generators = self.state_generators
58
+ self.state_generators = []
59
+ for generator in state_generators:
60
+ for dummy in generator:
61
+ pass
62
+ self.constructed_objects = {}
63
+ self.recursive_objects = {}
64
+ self.deep_construct = False
65
+ return data
66
+
67
+ def construct_object(self, node, deep=False):
68
+ if node in self.constructed_objects:
69
+ return self.constructed_objects[node]
70
+ if deep:
71
+ old_deep = self.deep_construct
72
+ self.deep_construct = True
73
+ if node in self.recursive_objects:
74
+ raise ConstructorError(None, None,
75
+ "found unconstructable recursive node", node.start_mark)
76
+ self.recursive_objects[node] = None
77
+ constructor = None
78
+ tag_suffix = None
79
+ if node.tag in self.yaml_constructors:
80
+ constructor = self.yaml_constructors[node.tag]
81
+ else:
82
+ for tag_prefix in self.yaml_multi_constructors:
83
+ if tag_prefix is not None and node.tag.startswith(tag_prefix):
84
+ tag_suffix = node.tag[len(tag_prefix):]
85
+ constructor = self.yaml_multi_constructors[tag_prefix]
86
+ break
87
+ else:
88
+ if None in self.yaml_multi_constructors:
89
+ tag_suffix = node.tag
90
+ constructor = self.yaml_multi_constructors[None]
91
+ elif None in self.yaml_constructors:
92
+ constructor = self.yaml_constructors[None]
93
+ elif isinstance(node, ScalarNode):
94
+ constructor = self.__class__.construct_scalar
95
+ elif isinstance(node, SequenceNode):
96
+ constructor = self.__class__.construct_sequence
97
+ elif isinstance(node, MappingNode):
98
+ constructor = self.__class__.construct_mapping
99
+ if tag_suffix is None:
100
+ data = constructor(self, node)
101
+ else:
102
+ data = constructor(self, tag_suffix, node)
103
+ if isinstance(data, types.GeneratorType):
104
+ generator = data
105
+ data = next(generator)
106
+ if self.deep_construct:
107
+ for dummy in generator:
108
+ pass
109
+ else:
110
+ self.state_generators.append(generator)
111
+ self.constructed_objects[node] = data
112
+ del self.recursive_objects[node]
113
+ if deep:
114
+ self.deep_construct = old_deep
115
+ return data
116
+
117
+ def construct_scalar(self, node):
118
+ if not isinstance(node, ScalarNode):
119
+ raise ConstructorError(None, None,
120
+ "expected a scalar node, but found %s" % node.id,
121
+ node.start_mark)
122
+ return node.value
123
+
124
+ def construct_sequence(self, node, deep=False):
125
+ if not isinstance(node, SequenceNode):
126
+ raise ConstructorError(None, None,
127
+ "expected a sequence node, but found %s" % node.id,
128
+ node.start_mark)
129
+ return [self.construct_object(child, deep=deep)
130
+ for child in node.value]
131
+
132
+ def construct_mapping(self, node, deep=False):
133
+ if not isinstance(node, MappingNode):
134
+ raise ConstructorError(None, None,
135
+ "expected a mapping node, but found %s" % node.id,
136
+ node.start_mark)
137
+ mapping = {}
138
+ for key_node, value_node in node.value:
139
+ key = self.construct_object(key_node, deep=deep)
140
+ if not isinstance(key, collections.abc.Hashable):
141
+ raise ConstructorError("while constructing a mapping", node.start_mark,
142
+ "found unhashable key", key_node.start_mark)
143
+ value = self.construct_object(value_node, deep=deep)
144
+ mapping[key] = value
145
+ return mapping
146
+
147
+ def construct_pairs(self, node, deep=False):
148
+ if not isinstance(node, MappingNode):
149
+ raise ConstructorError(None, None,
150
+ "expected a mapping node, but found %s" % node.id,
151
+ node.start_mark)
152
+ pairs = []
153
+ for key_node, value_node in node.value:
154
+ key = self.construct_object(key_node, deep=deep)
155
+ value = self.construct_object(value_node, deep=deep)
156
+ pairs.append((key, value))
157
+ return pairs
158
+
159
+ @classmethod
160
+ def add_constructor(cls, tag, constructor):
161
+ if not 'yaml_constructors' in cls.__dict__:
162
+ cls.yaml_constructors = cls.yaml_constructors.copy()
163
+ cls.yaml_constructors[tag] = constructor
164
+
165
+ @classmethod
166
+ def add_multi_constructor(cls, tag_prefix, multi_constructor):
167
+ if not 'yaml_multi_constructors' in cls.__dict__:
168
+ cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
169
+ cls.yaml_multi_constructors[tag_prefix] = multi_constructor
170
+
171
+ class SafeConstructor(BaseConstructor):
172
+
173
+ def construct_scalar(self, node):
174
+ if isinstance(node, MappingNode):
175
+ for key_node, value_node in node.value:
176
+ if key_node.tag == 'tag:yaml.org,2002:value':
177
+ return self.construct_scalar(value_node)
178
+ return super().construct_scalar(node)
179
+
180
+ def flatten_mapping(self, node):
181
+ merge = []
182
+ index = 0
183
+ while index < len(node.value):
184
+ key_node, value_node = node.value[index]
185
+ if key_node.tag == 'tag:yaml.org,2002:merge':
186
+ del node.value[index]
187
+ if isinstance(value_node, MappingNode):
188
+ self.flatten_mapping(value_node)
189
+ merge.extend(value_node.value)
190
+ elif isinstance(value_node, SequenceNode):
191
+ submerge = []
192
+ for subnode in value_node.value:
193
+ if not isinstance(subnode, MappingNode):
194
+ raise ConstructorError("while constructing a mapping",
195
+ node.start_mark,
196
+ "expected a mapping for merging, but found %s"
197
+ % subnode.id, subnode.start_mark)
198
+ self.flatten_mapping(subnode)
199
+ submerge.append(subnode.value)
200
+ submerge.reverse()
201
+ for value in submerge:
202
+ merge.extend(value)
203
+ else:
204
+ raise ConstructorError("while constructing a mapping", node.start_mark,
205
+ "expected a mapping or list of mappings for merging, but found %s"
206
+ % value_node.id, value_node.start_mark)
207
+ elif key_node.tag == 'tag:yaml.org,2002:value':
208
+ key_node.tag = 'tag:yaml.org,2002:str'
209
+ index += 1
210
+ else:
211
+ index += 1
212
+ if merge:
213
+ node.value = merge + node.value
214
+
215
+ def construct_mapping(self, node, deep=False):
216
+ if isinstance(node, MappingNode):
217
+ self.flatten_mapping(node)
218
+ return super().construct_mapping(node, deep=deep)
219
+
220
+ def construct_yaml_null(self, node):
221
+ self.construct_scalar(node)
222
+ return None
223
+
224
+ bool_values = {
225
+ 'yes': True,
226
+ 'no': False,
227
+ 'true': True,
228
+ 'false': False,
229
+ 'on': True,
230
+ 'off': False,
231
+ }
232
+
233
+ def construct_yaml_bool(self, node):
234
+ value = self.construct_scalar(node)
235
+ return self.bool_values[value.lower()]
236
+
237
+ def construct_yaml_int(self, node):
238
+ value = self.construct_scalar(node)
239
+ value = value.replace('_', '')
240
+ sign = +1
241
+ if value[0] == '-':
242
+ sign = -1
243
+ if value[0] in '+-':
244
+ value = value[1:]
245
+ if value == '0':
246
+ return 0
247
+ elif value.startswith('0b'):
248
+ return sign*int(value[2:], 2)
249
+ elif value.startswith('0x'):
250
+ return sign*int(value[2:], 16)
251
+ elif value[0] == '0':
252
+ return sign*int(value, 8)
253
+ elif ':' in value:
254
+ digits = [int(part) for part in value.split(':')]
255
+ digits.reverse()
256
+ base = 1
257
+ value = 0
258
+ for digit in digits:
259
+ value += digit*base
260
+ base *= 60
261
+ return sign*value
262
+ else:
263
+ return sign*int(value)
264
+
265
+ inf_value = 1e300
266
+ while inf_value != inf_value*inf_value:
267
+ inf_value *= inf_value
268
+ nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99).
269
+
270
+ def construct_yaml_float(self, node):
271
+ value = self.construct_scalar(node)
272
+ value = value.replace('_', '').lower()
273
+ sign = +1
274
+ if value[0] == '-':
275
+ sign = -1
276
+ if value[0] in '+-':
277
+ value = value[1:]
278
+ if value == '.inf':
279
+ return sign*self.inf_value
280
+ elif value == '.nan':
281
+ return self.nan_value
282
+ elif ':' in value:
283
+ digits = [float(part) for part in value.split(':')]
284
+ digits.reverse()
285
+ base = 1
286
+ value = 0.0
287
+ for digit in digits:
288
+ value += digit*base
289
+ base *= 60
290
+ return sign*value
291
+ else:
292
+ return sign*float(value)
293
+
294
+ def construct_yaml_binary(self, node):
295
+ try:
296
+ value = self.construct_scalar(node).encode('ascii')
297
+ except UnicodeEncodeError as exc:
298
+ raise ConstructorError(None, None,
299
+ "failed to convert base64 data into ascii: %s" % exc,
300
+ node.start_mark)
301
+ try:
302
+ if hasattr(base64, 'decodebytes'):
303
+ return base64.decodebytes(value)
304
+ else:
305
+ return base64.decodestring(value)
306
+ except binascii.Error as exc:
307
+ raise ConstructorError(None, None,
308
+ "failed to decode base64 data: %s" % exc, node.start_mark)
309
+
310
+ timestamp_regexp = re.compile(
311
+ r'''^(?P<year>[0-9][0-9][0-9][0-9])
312
+ -(?P<month>[0-9][0-9]?)
313
+ -(?P<day>[0-9][0-9]?)
314
+ (?:(?:[Tt]|[ \t]+)
315
+ (?P<hour>[0-9][0-9]?)
316
+ :(?P<minute>[0-9][0-9])
317
+ :(?P<second>[0-9][0-9])
318
+ (?:\.(?P<fraction>[0-9]*))?
319
+ (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
320
+ (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X)
321
+
322
+ def construct_yaml_timestamp(self, node):
323
+ value = self.construct_scalar(node)
324
+ match = self.timestamp_regexp.match(node.value)
325
+ values = match.groupdict()
326
+ year = int(values['year'])
327
+ month = int(values['month'])
328
+ day = int(values['day'])
329
+ if not values['hour']:
330
+ return datetime.date(year, month, day)
331
+ hour = int(values['hour'])
332
+ minute = int(values['minute'])
333
+ second = int(values['second'])
334
+ fraction = 0
335
+ tzinfo = None
336
+ if values['fraction']:
337
+ fraction = values['fraction'][:6]
338
+ while len(fraction) < 6:
339
+ fraction += '0'
340
+ fraction = int(fraction)
341
+ if values['tz_sign']:
342
+ tz_hour = int(values['tz_hour'])
343
+ tz_minute = int(values['tz_minute'] or 0)
344
+ delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
345
+ if values['tz_sign'] == '-':
346
+ delta = -delta
347
+ tzinfo = datetime.timezone(delta)
348
+ elif values['tz']:
349
+ tzinfo = datetime.timezone.utc
350
+ return datetime.datetime(year, month, day, hour, minute, second, fraction,
351
+ tzinfo=tzinfo)
352
+
353
+ def construct_yaml_omap(self, node):
354
+ # Note: we do not check for duplicate keys, because it's too
355
+ # CPU-expensive.
356
+ omap = []
357
+ yield omap
358
+ if not isinstance(node, SequenceNode):
359
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
360
+ "expected a sequence, but found %s" % node.id, node.start_mark)
361
+ for subnode in node.value:
362
+ if not isinstance(subnode, MappingNode):
363
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
364
+ "expected a mapping of length 1, but found %s" % subnode.id,
365
+ subnode.start_mark)
366
+ if len(subnode.value) != 1:
367
+ raise ConstructorError("while constructing an ordered map", node.start_mark,
368
+ "expected a single mapping item, but found %d items" % len(subnode.value),
369
+ subnode.start_mark)
370
+ key_node, value_node = subnode.value[0]
371
+ key = self.construct_object(key_node)
372
+ value = self.construct_object(value_node)
373
+ omap.append((key, value))
374
+
375
+ def construct_yaml_pairs(self, node):
376
+ # Note: the same code as `construct_yaml_omap`.
377
+ pairs = []
378
+ yield pairs
379
+ if not isinstance(node, SequenceNode):
380
+ raise ConstructorError("while constructing pairs", node.start_mark,
381
+ "expected a sequence, but found %s" % node.id, node.start_mark)
382
+ for subnode in node.value:
383
+ if not isinstance(subnode, MappingNode):
384
+ raise ConstructorError("while constructing pairs", node.start_mark,
385
+ "expected a mapping of length 1, but found %s" % subnode.id,
386
+ subnode.start_mark)
387
+ if len(subnode.value) != 1:
388
+ raise ConstructorError("while constructing pairs", node.start_mark,
389
+ "expected a single mapping item, but found %d items" % len(subnode.value),
390
+ subnode.start_mark)
391
+ key_node, value_node = subnode.value[0]
392
+ key = self.construct_object(key_node)
393
+ value = self.construct_object(value_node)
394
+ pairs.append((key, value))
395
+
396
+ def construct_yaml_set(self, node):
397
+ data = set()
398
+ yield data
399
+ value = self.construct_mapping(node)
400
+ data.update(value)
401
+
402
+ def construct_yaml_str(self, node):
403
+ return self.construct_scalar(node)
404
+
405
+ def construct_yaml_seq(self, node):
406
+ data = []
407
+ yield data
408
+ data.extend(self.construct_sequence(node))
409
+
410
+ def construct_yaml_map(self, node):
411
+ data = {}
412
+ yield data
413
+ value = self.construct_mapping(node)
414
+ data.update(value)
415
+
416
+ def construct_yaml_object(self, node, cls):
417
+ data = cls.__new__(cls)
418
+ yield data
419
+ if hasattr(data, '__setstate__'):
420
+ state = self.construct_mapping(node, deep=True)
421
+ data.__setstate__(state)
422
+ else:
423
+ state = self.construct_mapping(node)
424
+ data.__dict__.update(state)
425
+
426
+ def construct_undefined(self, node):
427
+ raise ConstructorError(None, None,
428
+ "could not determine a constructor for the tag %r" % node.tag,
429
+ node.start_mark)
430
+
431
+ SafeConstructor.add_constructor(
432
+ 'tag:yaml.org,2002:null',
433
+ SafeConstructor.construct_yaml_null)
434
+
435
+ SafeConstructor.add_constructor(
436
+ 'tag:yaml.org,2002:bool',
437
+ SafeConstructor.construct_yaml_bool)
438
+
439
+ SafeConstructor.add_constructor(
440
+ 'tag:yaml.org,2002:int',
441
+ SafeConstructor.construct_yaml_int)
442
+
443
+ SafeConstructor.add_constructor(
444
+ 'tag:yaml.org,2002:float',
445
+ SafeConstructor.construct_yaml_float)
446
+
447
+ SafeConstructor.add_constructor(
448
+ 'tag:yaml.org,2002:binary',
449
+ SafeConstructor.construct_yaml_binary)
450
+
451
+ SafeConstructor.add_constructor(
452
+ 'tag:yaml.org,2002:timestamp',
453
+ SafeConstructor.construct_yaml_timestamp)
454
+
455
+ SafeConstructor.add_constructor(
456
+ 'tag:yaml.org,2002:omap',
457
+ SafeConstructor.construct_yaml_omap)
458
+
459
+ SafeConstructor.add_constructor(
460
+ 'tag:yaml.org,2002:pairs',
461
+ SafeConstructor.construct_yaml_pairs)
462
+
463
+ SafeConstructor.add_constructor(
464
+ 'tag:yaml.org,2002:set',
465
+ SafeConstructor.construct_yaml_set)
466
+
467
+ SafeConstructor.add_constructor(
468
+ 'tag:yaml.org,2002:str',
469
+ SafeConstructor.construct_yaml_str)
470
+
471
+ SafeConstructor.add_constructor(
472
+ 'tag:yaml.org,2002:seq',
473
+ SafeConstructor.construct_yaml_seq)
474
+
475
+ SafeConstructor.add_constructor(
476
+ 'tag:yaml.org,2002:map',
477
+ SafeConstructor.construct_yaml_map)
478
+
479
+ SafeConstructor.add_constructor(None,
480
+ SafeConstructor.construct_undefined)
481
+
482
+ class FullConstructor(SafeConstructor):
483
+ # 'extend' is blacklisted because it is used by
484
+ # construct_python_object_apply to add `listitems` to a newly generate
485
+ # python instance
486
+ def get_state_keys_blacklist(self):
487
+ return ['^extend$', '^__.*__$']
488
+
489
+ def get_state_keys_blacklist_regexp(self):
490
+ if not hasattr(self, 'state_keys_blacklist_regexp'):
491
+ self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')')
492
+ return self.state_keys_blacklist_regexp
493
+
494
+ def construct_python_str(self, node):
495
+ return self.construct_scalar(node)
496
+
497
+ def construct_python_unicode(self, node):
498
+ return self.construct_scalar(node)
499
+
500
+ def construct_python_bytes(self, node):
501
+ try:
502
+ value = self.construct_scalar(node).encode('ascii')
503
+ except UnicodeEncodeError as exc:
504
+ raise ConstructorError(None, None,
505
+ "failed to convert base64 data into ascii: %s" % exc,
506
+ node.start_mark)
507
+ try:
508
+ if hasattr(base64, 'decodebytes'):
509
+ return base64.decodebytes(value)
510
+ else:
511
+ return base64.decodestring(value)
512
+ except binascii.Error as exc:
513
+ raise ConstructorError(None, None,
514
+ "failed to decode base64 data: %s" % exc, node.start_mark)
515
+
516
+ def construct_python_long(self, node):
517
+ return self.construct_yaml_int(node)
518
+
519
+ def construct_python_complex(self, node):
520
+ return complex(self.construct_scalar(node))
521
+
522
+ def construct_python_tuple(self, node):
523
+ return tuple(self.construct_sequence(node))
524
+
525
+ def find_python_module(self, name, mark, unsafe=False):
526
+ if not name:
527
+ raise ConstructorError("while constructing a Python module", mark,
528
+ "expected non-empty name appended to the tag", mark)
529
+ if unsafe:
530
+ try:
531
+ __import__(name)
532
+ except ImportError as exc:
533
+ raise ConstructorError("while constructing a Python module", mark,
534
+ "cannot find module %r (%s)" % (name, exc), mark)
535
+ if name not in sys.modules:
536
+ raise ConstructorError("while constructing a Python module", mark,
537
+ "module %r is not imported" % name, mark)
538
+ return sys.modules[name]
539
+
540
+ def find_python_name(self, name, mark, unsafe=False):
541
+ if not name:
542
+ raise ConstructorError("while constructing a Python object", mark,
543
+ "expected non-empty name appended to the tag", mark)
544
+ if '.' in name:
545
+ module_name, object_name = name.rsplit('.', 1)
546
+ else:
547
+ module_name = 'builtins'
548
+ object_name = name
549
+ if unsafe:
550
+ try:
551
+ __import__(module_name)
552
+ except ImportError as exc:
553
+ raise ConstructorError("while constructing a Python object", mark,
554
+ "cannot find module %r (%s)" % (module_name, exc), mark)
555
+ if module_name not in sys.modules:
556
+ raise ConstructorError("while constructing a Python object", mark,
557
+ "module %r is not imported" % module_name, mark)
558
+ module = sys.modules[module_name]
559
+ if not hasattr(module, object_name):
560
+ raise ConstructorError("while constructing a Python object", mark,
561
+ "cannot find %r in the module %r"
562
+ % (object_name, module.__name__), mark)
563
+ return getattr(module, object_name)
564
+
565
+ def construct_python_name(self, suffix, node):
566
+ value = self.construct_scalar(node)
567
+ if value:
568
+ raise ConstructorError("while constructing a Python name", node.start_mark,
569
+ "expected the empty value, but found %r" % value, node.start_mark)
570
+ return self.find_python_name(suffix, node.start_mark)
571
+
572
+ def construct_python_module(self, suffix, node):
573
+ value = self.construct_scalar(node)
574
+ if value:
575
+ raise ConstructorError("while constructing a Python module", node.start_mark,
576
+ "expected the empty value, but found %r" % value, node.start_mark)
577
+ return self.find_python_module(suffix, node.start_mark)
578
+
579
+ def make_python_instance(self, suffix, node,
580
+ args=None, kwds=None, newobj=False, unsafe=False):
581
+ if not args:
582
+ args = []
583
+ if not kwds:
584
+ kwds = {}
585
+ cls = self.find_python_name(suffix, node.start_mark)
586
+ if not (unsafe or isinstance(cls, type)):
587
+ raise ConstructorError("while constructing a Python instance", node.start_mark,
588
+ "expected a class, but found %r" % type(cls),
589
+ node.start_mark)
590
+ if newobj and isinstance(cls, type):
591
+ return cls.__new__(cls, *args, **kwds)
592
+ else:
593
+ return cls(*args, **kwds)
594
+
595
+ def set_python_instance_state(self, instance, state, unsafe=False):
596
+ if hasattr(instance, '__setstate__'):
597
+ instance.__setstate__(state)
598
+ else:
599
+ slotstate = {}
600
+ if isinstance(state, tuple) and len(state) == 2:
601
+ state, slotstate = state
602
+ if hasattr(instance, '__dict__'):
603
+ if not unsafe and state:
604
+ for key in state.keys():
605
+ self.check_state_key(key)
606
+ instance.__dict__.update(state)
607
+ elif state:
608
+ slotstate.update(state)
609
+ for key, value in slotstate.items():
610
+ if not unsafe:
611
+ self.check_state_key(key)
612
+ setattr(instance, key, value)
613
+
614
+ def construct_python_object(self, suffix, node):
615
+ # Format:
616
+ # !!python/object:module.name { ... state ... }
617
+ instance = self.make_python_instance(suffix, node, newobj=True)
618
+ yield instance
619
+ deep = hasattr(instance, '__setstate__')
620
+ state = self.construct_mapping(node, deep=deep)
621
+ self.set_python_instance_state(instance, state)
622
+
623
+ def construct_python_object_apply(self, suffix, node, newobj=False):
624
+ # Format:
625
+ # !!python/object/apply # (or !!python/object/new)
626
+ # args: [ ... arguments ... ]
627
+ # kwds: { ... keywords ... }
628
+ # state: ... state ...
629
+ # listitems: [ ... listitems ... ]
630
+ # dictitems: { ... dictitems ... }
631
+ # or short format:
632
+ # !!python/object/apply [ ... arguments ... ]
633
+ # The difference between !!python/object/apply and !!python/object/new
634
+ # is how an object is created, check make_python_instance for details.
635
+ if isinstance(node, SequenceNode):
636
+ args = self.construct_sequence(node, deep=True)
637
+ kwds = {}
638
+ state = {}
639
+ listitems = []
640
+ dictitems = {}
641
+ else:
642
+ value = self.construct_mapping(node, deep=True)
643
+ args = value.get('args', [])
644
+ kwds = value.get('kwds', {})
645
+ state = value.get('state', {})
646
+ listitems = value.get('listitems', [])
647
+ dictitems = value.get('dictitems', {})
648
+ instance = self.make_python_instance(suffix, node, args, kwds, newobj)
649
+ if state:
650
+ self.set_python_instance_state(instance, state)
651
+ if listitems:
652
+ instance.extend(listitems)
653
+ if dictitems:
654
+ for key in dictitems:
655
+ instance[key] = dictitems[key]
656
+ return instance
657
+
658
+ def construct_python_object_new(self, suffix, node):
659
+ return self.construct_python_object_apply(suffix, node, newobj=True)
660
+
661
+ FullConstructor.add_constructor(
662
+ 'tag:yaml.org,2002:python/none',
663
+ FullConstructor.construct_yaml_null)
664
+
665
+ FullConstructor.add_constructor(
666
+ 'tag:yaml.org,2002:python/bool',
667
+ FullConstructor.construct_yaml_bool)
668
+
669
+ FullConstructor.add_constructor(
670
+ 'tag:yaml.org,2002:python/str',
671
+ FullConstructor.construct_python_str)
672
+
673
+ FullConstructor.add_constructor(
674
+ 'tag:yaml.org,2002:python/unicode',
675
+ FullConstructor.construct_python_unicode)
676
+
677
+ FullConstructor.add_constructor(
678
+ 'tag:yaml.org,2002:python/bytes',
679
+ FullConstructor.construct_python_bytes)
680
+
681
+ FullConstructor.add_constructor(
682
+ 'tag:yaml.org,2002:python/int',
683
+ FullConstructor.construct_yaml_int)
684
+
685
+ FullConstructor.add_constructor(
686
+ 'tag:yaml.org,2002:python/long',
687
+ FullConstructor.construct_python_long)
688
+
689
+ FullConstructor.add_constructor(
690
+ 'tag:yaml.org,2002:python/float',
691
+ FullConstructor.construct_yaml_float)
692
+
693
+ FullConstructor.add_constructor(
694
+ 'tag:yaml.org,2002:python/complex',
695
+ FullConstructor.construct_python_complex)
696
+
697
+ FullConstructor.add_constructor(
698
+ 'tag:yaml.org,2002:python/list',
699
+ FullConstructor.construct_yaml_seq)
700
+
701
+ FullConstructor.add_constructor(
702
+ 'tag:yaml.org,2002:python/tuple',
703
+ FullConstructor.construct_python_tuple)
704
+
705
+ FullConstructor.add_constructor(
706
+ 'tag:yaml.org,2002:python/dict',
707
+ FullConstructor.construct_yaml_map)
708
+
709
+ FullConstructor.add_multi_constructor(
710
+ 'tag:yaml.org,2002:python/name:',
711
+ FullConstructor.construct_python_name)
712
+
713
+ class UnsafeConstructor(FullConstructor):
714
+
715
+ def find_python_module(self, name, mark):
716
+ return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True)
717
+
718
+ def find_python_name(self, name, mark):
719
+ return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True)
720
+
721
+ def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False):
722
+ return super(UnsafeConstructor, self).make_python_instance(
723
+ suffix, node, args, kwds, newobj, unsafe=True)
724
+
725
+ def set_python_instance_state(self, instance, state):
726
+ return super(UnsafeConstructor, self).set_python_instance_state(
727
+ instance, state, unsafe=True)
728
+
729
+ UnsafeConstructor.add_multi_constructor(
730
+ 'tag:yaml.org,2002:python/module:',
731
+ UnsafeConstructor.construct_python_module)
732
+
733
+ UnsafeConstructor.add_multi_constructor(
734
+ 'tag:yaml.org,2002:python/object:',
735
+ UnsafeConstructor.construct_python_object)
736
+
737
+ UnsafeConstructor.add_multi_constructor(
738
+ 'tag:yaml.org,2002:python/object/new:',
739
+ UnsafeConstructor.construct_python_object_new)
740
+
741
+ UnsafeConstructor.add_multi_constructor(
742
+ 'tag:yaml.org,2002:python/object/apply:',
743
+ UnsafeConstructor.construct_python_object_apply)
744
+
745
+ # Constructor is same as UnsafeConstructor. Need to leave this in place in case
746
+ # people have extended it directly.
747
+ class Constructor(UnsafeConstructor):
748
+ pass
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/cyaml.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = [
3
+ 'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader',
4
+ 'CBaseDumper', 'CSafeDumper', 'CDumper'
5
+ ]
6
+
7
+ from yaml._yaml import CParser, CEmitter
8
+
9
+ from .constructor import *
10
+
11
+ from .serializer import *
12
+ from .representer import *
13
+
14
+ from .resolver import *
15
+
16
+ class CBaseLoader(CParser, BaseConstructor, BaseResolver):
17
+
18
+ def __init__(self, stream):
19
+ CParser.__init__(self, stream)
20
+ BaseConstructor.__init__(self)
21
+ BaseResolver.__init__(self)
22
+
23
+ class CSafeLoader(CParser, SafeConstructor, Resolver):
24
+
25
+ def __init__(self, stream):
26
+ CParser.__init__(self, stream)
27
+ SafeConstructor.__init__(self)
28
+ Resolver.__init__(self)
29
+
30
+ class CFullLoader(CParser, FullConstructor, Resolver):
31
+
32
+ def __init__(self, stream):
33
+ CParser.__init__(self, stream)
34
+ FullConstructor.__init__(self)
35
+ Resolver.__init__(self)
36
+
37
+ class CUnsafeLoader(CParser, UnsafeConstructor, Resolver):
38
+
39
+ def __init__(self, stream):
40
+ CParser.__init__(self, stream)
41
+ UnsafeConstructor.__init__(self)
42
+ Resolver.__init__(self)
43
+
44
+ class CLoader(CParser, Constructor, Resolver):
45
+
46
+ def __init__(self, stream):
47
+ CParser.__init__(self, stream)
48
+ Constructor.__init__(self)
49
+ Resolver.__init__(self)
50
+
51
+ class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
52
+
53
+ def __init__(self, stream,
54
+ default_style=None, default_flow_style=False,
55
+ canonical=None, indent=None, width=None,
56
+ allow_unicode=None, line_break=None,
57
+ encoding=None, explicit_start=None, explicit_end=None,
58
+ version=None, tags=None, sort_keys=True):
59
+ CEmitter.__init__(self, stream, canonical=canonical,
60
+ indent=indent, width=width, encoding=encoding,
61
+ allow_unicode=allow_unicode, line_break=line_break,
62
+ explicit_start=explicit_start, explicit_end=explicit_end,
63
+ version=version, tags=tags)
64
+ Representer.__init__(self, default_style=default_style,
65
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
66
+ Resolver.__init__(self)
67
+
68
+ class CSafeDumper(CEmitter, SafeRepresenter, Resolver):
69
+
70
+ def __init__(self, stream,
71
+ default_style=None, default_flow_style=False,
72
+ canonical=None, indent=None, width=None,
73
+ allow_unicode=None, line_break=None,
74
+ encoding=None, explicit_start=None, explicit_end=None,
75
+ version=None, tags=None, sort_keys=True):
76
+ CEmitter.__init__(self, stream, canonical=canonical,
77
+ indent=indent, width=width, encoding=encoding,
78
+ allow_unicode=allow_unicode, line_break=line_break,
79
+ explicit_start=explicit_start, explicit_end=explicit_end,
80
+ version=version, tags=tags)
81
+ SafeRepresenter.__init__(self, default_style=default_style,
82
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
83
+ Resolver.__init__(self)
84
+
85
+ class CDumper(CEmitter, Serializer, Representer, Resolver):
86
+
87
+ def __init__(self, stream,
88
+ default_style=None, default_flow_style=False,
89
+ canonical=None, indent=None, width=None,
90
+ allow_unicode=None, line_break=None,
91
+ encoding=None, explicit_start=None, explicit_end=None,
92
+ version=None, tags=None, sort_keys=True):
93
+ CEmitter.__init__(self, stream, canonical=canonical,
94
+ indent=indent, width=width, encoding=encoding,
95
+ allow_unicode=allow_unicode, line_break=line_break,
96
+ explicit_start=explicit_start, explicit_end=explicit_end,
97
+ version=version, tags=tags)
98
+ Representer.__init__(self, default_style=default_style,
99
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
100
+ Resolver.__init__(self)
101
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/dumper.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['BaseDumper', 'SafeDumper', 'Dumper']
3
+
4
+ from .emitter import *
5
+ from .serializer import *
6
+ from .representer import *
7
+ from .resolver import *
8
+
9
+ class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
10
+
11
+ def __init__(self, stream,
12
+ default_style=None, default_flow_style=False,
13
+ canonical=None, indent=None, width=None,
14
+ allow_unicode=None, line_break=None,
15
+ encoding=None, explicit_start=None, explicit_end=None,
16
+ version=None, tags=None, sort_keys=True):
17
+ Emitter.__init__(self, stream, canonical=canonical,
18
+ indent=indent, width=width,
19
+ allow_unicode=allow_unicode, line_break=line_break)
20
+ Serializer.__init__(self, encoding=encoding,
21
+ explicit_start=explicit_start, explicit_end=explicit_end,
22
+ version=version, tags=tags)
23
+ Representer.__init__(self, default_style=default_style,
24
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
25
+ Resolver.__init__(self)
26
+
27
+ class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
28
+
29
+ def __init__(self, stream,
30
+ default_style=None, default_flow_style=False,
31
+ canonical=None, indent=None, width=None,
32
+ allow_unicode=None, line_break=None,
33
+ encoding=None, explicit_start=None, explicit_end=None,
34
+ version=None, tags=None, sort_keys=True):
35
+ Emitter.__init__(self, stream, canonical=canonical,
36
+ indent=indent, width=width,
37
+ allow_unicode=allow_unicode, line_break=line_break)
38
+ Serializer.__init__(self, encoding=encoding,
39
+ explicit_start=explicit_start, explicit_end=explicit_end,
40
+ version=version, tags=tags)
41
+ SafeRepresenter.__init__(self, default_style=default_style,
42
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
43
+ Resolver.__init__(self)
44
+
45
+ class Dumper(Emitter, Serializer, Representer, Resolver):
46
+
47
+ def __init__(self, stream,
48
+ default_style=None, default_flow_style=False,
49
+ canonical=None, indent=None, width=None,
50
+ allow_unicode=None, line_break=None,
51
+ encoding=None, explicit_start=None, explicit_end=None,
52
+ version=None, tags=None, sort_keys=True):
53
+ Emitter.__init__(self, stream, canonical=canonical,
54
+ indent=indent, width=width,
55
+ allow_unicode=allow_unicode, line_break=line_break)
56
+ Serializer.__init__(self, encoding=encoding,
57
+ explicit_start=explicit_start, explicit_end=explicit_end,
58
+ version=version, tags=tags)
59
+ Representer.__init__(self, default_style=default_style,
60
+ default_flow_style=default_flow_style, sort_keys=sort_keys)
61
+ Resolver.__init__(self)
62
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/emitter.py ADDED
@@ -0,0 +1,1137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Emitter expects events obeying the following grammar:
3
+ # stream ::= STREAM-START document* STREAM-END
4
+ # document ::= DOCUMENT-START node DOCUMENT-END
5
+ # node ::= SCALAR | sequence | mapping
6
+ # sequence ::= SEQUENCE-START node* SEQUENCE-END
7
+ # mapping ::= MAPPING-START (node node)* MAPPING-END
8
+
9
+ __all__ = ['Emitter', 'EmitterError']
10
+
11
+ from .error import YAMLError
12
+ from .events import *
13
+
14
+ class EmitterError(YAMLError):
15
+ pass
16
+
17
+ class ScalarAnalysis:
18
+ def __init__(self, scalar, empty, multiline,
19
+ allow_flow_plain, allow_block_plain,
20
+ allow_single_quoted, allow_double_quoted,
21
+ allow_block):
22
+ self.scalar = scalar
23
+ self.empty = empty
24
+ self.multiline = multiline
25
+ self.allow_flow_plain = allow_flow_plain
26
+ self.allow_block_plain = allow_block_plain
27
+ self.allow_single_quoted = allow_single_quoted
28
+ self.allow_double_quoted = allow_double_quoted
29
+ self.allow_block = allow_block
30
+
31
+ class Emitter:
32
+
33
+ DEFAULT_TAG_PREFIXES = {
34
+ '!' : '!',
35
+ 'tag:yaml.org,2002:' : '!!',
36
+ }
37
+
38
+ def __init__(self, stream, canonical=None, indent=None, width=None,
39
+ allow_unicode=None, line_break=None):
40
+
41
+ # The stream should have the methods `write` and possibly `flush`.
42
+ self.stream = stream
43
+
44
+ # Encoding can be overridden by STREAM-START.
45
+ self.encoding = None
46
+
47
+ # Emitter is a state machine with a stack of states to handle nested
48
+ # structures.
49
+ self.states = []
50
+ self.state = self.expect_stream_start
51
+
52
+ # Current event and the event queue.
53
+ self.events = []
54
+ self.event = None
55
+
56
+ # The current indentation level and the stack of previous indents.
57
+ self.indents = []
58
+ self.indent = None
59
+
60
+ # Flow level.
61
+ self.flow_level = 0
62
+
63
+ # Contexts.
64
+ self.root_context = False
65
+ self.sequence_context = False
66
+ self.mapping_context = False
67
+ self.simple_key_context = False
68
+
69
+ # Characteristics of the last emitted character:
70
+ # - current position.
71
+ # - is it a whitespace?
72
+ # - is it an indention character
73
+ # (indentation space, '-', '?', or ':')?
74
+ self.line = 0
75
+ self.column = 0
76
+ self.whitespace = True
77
+ self.indention = True
78
+
79
+ # Whether the document requires an explicit document indicator
80
+ self.open_ended = False
81
+
82
+ # Formatting details.
83
+ self.canonical = canonical
84
+ self.allow_unicode = allow_unicode
85
+ self.best_indent = 2
86
+ if indent and 1 < indent < 10:
87
+ self.best_indent = indent
88
+ self.best_width = 80
89
+ if width and width > self.best_indent*2:
90
+ self.best_width = width
91
+ self.best_line_break = '\n'
92
+ if line_break in ['\r', '\n', '\r\n']:
93
+ self.best_line_break = line_break
94
+
95
+ # Tag prefixes.
96
+ self.tag_prefixes = None
97
+
98
+ # Prepared anchor and tag.
99
+ self.prepared_anchor = None
100
+ self.prepared_tag = None
101
+
102
+ # Scalar analysis and style.
103
+ self.analysis = None
104
+ self.style = None
105
+
106
+ def dispose(self):
107
+ # Reset the state attributes (to clear self-references)
108
+ self.states = []
109
+ self.state = None
110
+
111
+ def emit(self, event):
112
+ self.events.append(event)
113
+ while not self.need_more_events():
114
+ self.event = self.events.pop(0)
115
+ self.state()
116
+ self.event = None
117
+
118
+ # In some cases, we wait for a few next events before emitting.
119
+
120
+ def need_more_events(self):
121
+ if not self.events:
122
+ return True
123
+ event = self.events[0]
124
+ if isinstance(event, DocumentStartEvent):
125
+ return self.need_events(1)
126
+ elif isinstance(event, SequenceStartEvent):
127
+ return self.need_events(2)
128
+ elif isinstance(event, MappingStartEvent):
129
+ return self.need_events(3)
130
+ else:
131
+ return False
132
+
133
+ def need_events(self, count):
134
+ level = 0
135
+ for event in self.events[1:]:
136
+ if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
137
+ level += 1
138
+ elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
139
+ level -= 1
140
+ elif isinstance(event, StreamEndEvent):
141
+ level = -1
142
+ if level < 0:
143
+ return False
144
+ return (len(self.events) < count+1)
145
+
146
+ def increase_indent(self, flow=False, indentless=False):
147
+ self.indents.append(self.indent)
148
+ if self.indent is None:
149
+ if flow:
150
+ self.indent = self.best_indent
151
+ else:
152
+ self.indent = 0
153
+ elif not indentless:
154
+ self.indent += self.best_indent
155
+
156
+ # States.
157
+
158
+ # Stream handlers.
159
+
160
+ def expect_stream_start(self):
161
+ if isinstance(self.event, StreamStartEvent):
162
+ if self.event.encoding and not hasattr(self.stream, 'encoding'):
163
+ self.encoding = self.event.encoding
164
+ self.write_stream_start()
165
+ self.state = self.expect_first_document_start
166
+ else:
167
+ raise EmitterError("expected StreamStartEvent, but got %s"
168
+ % self.event)
169
+
170
+ def expect_nothing(self):
171
+ raise EmitterError("expected nothing, but got %s" % self.event)
172
+
173
+ # Document handlers.
174
+
175
+ def expect_first_document_start(self):
176
+ return self.expect_document_start(first=True)
177
+
178
+ def expect_document_start(self, first=False):
179
+ if isinstance(self.event, DocumentStartEvent):
180
+ if (self.event.version or self.event.tags) and self.open_ended:
181
+ self.write_indicator('...', True)
182
+ self.write_indent()
183
+ if self.event.version:
184
+ version_text = self.prepare_version(self.event.version)
185
+ self.write_version_directive(version_text)
186
+ self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
187
+ if self.event.tags:
188
+ handles = sorted(self.event.tags.keys())
189
+ for handle in handles:
190
+ prefix = self.event.tags[handle]
191
+ self.tag_prefixes[prefix] = handle
192
+ handle_text = self.prepare_tag_handle(handle)
193
+ prefix_text = self.prepare_tag_prefix(prefix)
194
+ self.write_tag_directive(handle_text, prefix_text)
195
+ implicit = (first and not self.event.explicit and not self.canonical
196
+ and not self.event.version and not self.event.tags
197
+ and not self.check_empty_document())
198
+ if not implicit:
199
+ self.write_indent()
200
+ self.write_indicator('---', True)
201
+ if self.canonical:
202
+ self.write_indent()
203
+ self.state = self.expect_document_root
204
+ elif isinstance(self.event, StreamEndEvent):
205
+ if self.open_ended:
206
+ self.write_indicator('...', True)
207
+ self.write_indent()
208
+ self.write_stream_end()
209
+ self.state = self.expect_nothing
210
+ else:
211
+ raise EmitterError("expected DocumentStartEvent, but got %s"
212
+ % self.event)
213
+
214
+ def expect_document_end(self):
215
+ if isinstance(self.event, DocumentEndEvent):
216
+ self.write_indent()
217
+ if self.event.explicit:
218
+ self.write_indicator('...', True)
219
+ self.write_indent()
220
+ self.flush_stream()
221
+ self.state = self.expect_document_start
222
+ else:
223
+ raise EmitterError("expected DocumentEndEvent, but got %s"
224
+ % self.event)
225
+
226
+ def expect_document_root(self):
227
+ self.states.append(self.expect_document_end)
228
+ self.expect_node(root=True)
229
+
230
+ # Node handlers.
231
+
232
+ def expect_node(self, root=False, sequence=False, mapping=False,
233
+ simple_key=False):
234
+ self.root_context = root
235
+ self.sequence_context = sequence
236
+ self.mapping_context = mapping
237
+ self.simple_key_context = simple_key
238
+ if isinstance(self.event, AliasEvent):
239
+ self.expect_alias()
240
+ elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
241
+ self.process_anchor('&')
242
+ self.process_tag()
243
+ if isinstance(self.event, ScalarEvent):
244
+ self.expect_scalar()
245
+ elif isinstance(self.event, SequenceStartEvent):
246
+ if self.flow_level or self.canonical or self.event.flow_style \
247
+ or self.check_empty_sequence():
248
+ self.expect_flow_sequence()
249
+ else:
250
+ self.expect_block_sequence()
251
+ elif isinstance(self.event, MappingStartEvent):
252
+ if self.flow_level or self.canonical or self.event.flow_style \
253
+ or self.check_empty_mapping():
254
+ self.expect_flow_mapping()
255
+ else:
256
+ self.expect_block_mapping()
257
+ else:
258
+ raise EmitterError("expected NodeEvent, but got %s" % self.event)
259
+
260
+ def expect_alias(self):
261
+ if self.event.anchor is None:
262
+ raise EmitterError("anchor is not specified for alias")
263
+ self.process_anchor('*')
264
+ self.state = self.states.pop()
265
+
266
+ def expect_scalar(self):
267
+ self.increase_indent(flow=True)
268
+ self.process_scalar()
269
+ self.indent = self.indents.pop()
270
+ self.state = self.states.pop()
271
+
272
+ # Flow sequence handlers.
273
+
274
+ def expect_flow_sequence(self):
275
+ self.write_indicator('[', True, whitespace=True)
276
+ self.flow_level += 1
277
+ self.increase_indent(flow=True)
278
+ self.state = self.expect_first_flow_sequence_item
279
+
280
+ def expect_first_flow_sequence_item(self):
281
+ if isinstance(self.event, SequenceEndEvent):
282
+ self.indent = self.indents.pop()
283
+ self.flow_level -= 1
284
+ self.write_indicator(']', False)
285
+ self.state = self.states.pop()
286
+ else:
287
+ if self.canonical or self.column > self.best_width:
288
+ self.write_indent()
289
+ self.states.append(self.expect_flow_sequence_item)
290
+ self.expect_node(sequence=True)
291
+
292
+ def expect_flow_sequence_item(self):
293
+ if isinstance(self.event, SequenceEndEvent):
294
+ self.indent = self.indents.pop()
295
+ self.flow_level -= 1
296
+ if self.canonical:
297
+ self.write_indicator(',', False)
298
+ self.write_indent()
299
+ self.write_indicator(']', False)
300
+ self.state = self.states.pop()
301
+ else:
302
+ self.write_indicator(',', False)
303
+ if self.canonical or self.column > self.best_width:
304
+ self.write_indent()
305
+ self.states.append(self.expect_flow_sequence_item)
306
+ self.expect_node(sequence=True)
307
+
308
+ # Flow mapping handlers.
309
+
310
+ def expect_flow_mapping(self):
311
+ self.write_indicator('{', True, whitespace=True)
312
+ self.flow_level += 1
313
+ self.increase_indent(flow=True)
314
+ self.state = self.expect_first_flow_mapping_key
315
+
316
+ def expect_first_flow_mapping_key(self):
317
+ if isinstance(self.event, MappingEndEvent):
318
+ self.indent = self.indents.pop()
319
+ self.flow_level -= 1
320
+ self.write_indicator('}', False)
321
+ self.state = self.states.pop()
322
+ else:
323
+ if self.canonical or self.column > self.best_width:
324
+ self.write_indent()
325
+ if not self.canonical and self.check_simple_key():
326
+ self.states.append(self.expect_flow_mapping_simple_value)
327
+ self.expect_node(mapping=True, simple_key=True)
328
+ else:
329
+ self.write_indicator('?', True)
330
+ self.states.append(self.expect_flow_mapping_value)
331
+ self.expect_node(mapping=True)
332
+
333
+ def expect_flow_mapping_key(self):
334
+ if isinstance(self.event, MappingEndEvent):
335
+ self.indent = self.indents.pop()
336
+ self.flow_level -= 1
337
+ if self.canonical:
338
+ self.write_indicator(',', False)
339
+ self.write_indent()
340
+ self.write_indicator('}', False)
341
+ self.state = self.states.pop()
342
+ else:
343
+ self.write_indicator(',', False)
344
+ if self.canonical or self.column > self.best_width:
345
+ self.write_indent()
346
+ if not self.canonical and self.check_simple_key():
347
+ self.states.append(self.expect_flow_mapping_simple_value)
348
+ self.expect_node(mapping=True, simple_key=True)
349
+ else:
350
+ self.write_indicator('?', True)
351
+ self.states.append(self.expect_flow_mapping_value)
352
+ self.expect_node(mapping=True)
353
+
354
+ def expect_flow_mapping_simple_value(self):
355
+ self.write_indicator(':', False)
356
+ self.states.append(self.expect_flow_mapping_key)
357
+ self.expect_node(mapping=True)
358
+
359
+ def expect_flow_mapping_value(self):
360
+ if self.canonical or self.column > self.best_width:
361
+ self.write_indent()
362
+ self.write_indicator(':', True)
363
+ self.states.append(self.expect_flow_mapping_key)
364
+ self.expect_node(mapping=True)
365
+
366
+ # Block sequence handlers.
367
+
368
+ def expect_block_sequence(self):
369
+ indentless = (self.mapping_context and not self.indention)
370
+ self.increase_indent(flow=False, indentless=indentless)
371
+ self.state = self.expect_first_block_sequence_item
372
+
373
+ def expect_first_block_sequence_item(self):
374
+ return self.expect_block_sequence_item(first=True)
375
+
376
+ def expect_block_sequence_item(self, first=False):
377
+ if not first and isinstance(self.event, SequenceEndEvent):
378
+ self.indent = self.indents.pop()
379
+ self.state = self.states.pop()
380
+ else:
381
+ self.write_indent()
382
+ self.write_indicator('-', True, indention=True)
383
+ self.states.append(self.expect_block_sequence_item)
384
+ self.expect_node(sequence=True)
385
+
386
+ # Block mapping handlers.
387
+
388
+ def expect_block_mapping(self):
389
+ self.increase_indent(flow=False)
390
+ self.state = self.expect_first_block_mapping_key
391
+
392
+ def expect_first_block_mapping_key(self):
393
+ return self.expect_block_mapping_key(first=True)
394
+
395
+ def expect_block_mapping_key(self, first=False):
396
+ if not first and isinstance(self.event, MappingEndEvent):
397
+ self.indent = self.indents.pop()
398
+ self.state = self.states.pop()
399
+ else:
400
+ self.write_indent()
401
+ if self.check_simple_key():
402
+ self.states.append(self.expect_block_mapping_simple_value)
403
+ self.expect_node(mapping=True, simple_key=True)
404
+ else:
405
+ self.write_indicator('?', True, indention=True)
406
+ self.states.append(self.expect_block_mapping_value)
407
+ self.expect_node(mapping=True)
408
+
409
+ def expect_block_mapping_simple_value(self):
410
+ self.write_indicator(':', False)
411
+ self.states.append(self.expect_block_mapping_key)
412
+ self.expect_node(mapping=True)
413
+
414
+ def expect_block_mapping_value(self):
415
+ self.write_indent()
416
+ self.write_indicator(':', True, indention=True)
417
+ self.states.append(self.expect_block_mapping_key)
418
+ self.expect_node(mapping=True)
419
+
420
+ # Checkers.
421
+
422
+ def check_empty_sequence(self):
423
+ return (isinstance(self.event, SequenceStartEvent) and self.events
424
+ and isinstance(self.events[0], SequenceEndEvent))
425
+
426
+ def check_empty_mapping(self):
427
+ return (isinstance(self.event, MappingStartEvent) and self.events
428
+ and isinstance(self.events[0], MappingEndEvent))
429
+
430
+ def check_empty_document(self):
431
+ if not isinstance(self.event, DocumentStartEvent) or not self.events:
432
+ return False
433
+ event = self.events[0]
434
+ return (isinstance(event, ScalarEvent) and event.anchor is None
435
+ and event.tag is None and event.implicit and event.value == '')
436
+
437
+ def check_simple_key(self):
438
+ length = 0
439
+ if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
440
+ if self.prepared_anchor is None:
441
+ self.prepared_anchor = self.prepare_anchor(self.event.anchor)
442
+ length += len(self.prepared_anchor)
443
+ if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
444
+ and self.event.tag is not None:
445
+ if self.prepared_tag is None:
446
+ self.prepared_tag = self.prepare_tag(self.event.tag)
447
+ length += len(self.prepared_tag)
448
+ if isinstance(self.event, ScalarEvent):
449
+ if self.analysis is None:
450
+ self.analysis = self.analyze_scalar(self.event.value)
451
+ length += len(self.analysis.scalar)
452
+ return (length < 128 and (isinstance(self.event, AliasEvent)
453
+ or (isinstance(self.event, ScalarEvent)
454
+ and not self.analysis.empty and not self.analysis.multiline)
455
+ or self.check_empty_sequence() or self.check_empty_mapping()))
456
+
457
+ # Anchor, Tag, and Scalar processors.
458
+
459
+ def process_anchor(self, indicator):
460
+ if self.event.anchor is None:
461
+ self.prepared_anchor = None
462
+ return
463
+ if self.prepared_anchor is None:
464
+ self.prepared_anchor = self.prepare_anchor(self.event.anchor)
465
+ if self.prepared_anchor:
466
+ self.write_indicator(indicator+self.prepared_anchor, True)
467
+ self.prepared_anchor = None
468
+
469
+ def process_tag(self):
470
+ tag = self.event.tag
471
+ if isinstance(self.event, ScalarEvent):
472
+ if self.style is None:
473
+ self.style = self.choose_scalar_style()
474
+ if ((not self.canonical or tag is None) and
475
+ ((self.style == '' and self.event.implicit[0])
476
+ or (self.style != '' and self.event.implicit[1]))):
477
+ self.prepared_tag = None
478
+ return
479
+ if self.event.implicit[0] and tag is None:
480
+ tag = '!'
481
+ self.prepared_tag = None
482
+ else:
483
+ if (not self.canonical or tag is None) and self.event.implicit:
484
+ self.prepared_tag = None
485
+ return
486
+ if tag is None:
487
+ raise EmitterError("tag is not specified")
488
+ if self.prepared_tag is None:
489
+ self.prepared_tag = self.prepare_tag(tag)
490
+ if self.prepared_tag:
491
+ self.write_indicator(self.prepared_tag, True)
492
+ self.prepared_tag = None
493
+
494
+ def choose_scalar_style(self):
495
+ if self.analysis is None:
496
+ self.analysis = self.analyze_scalar(self.event.value)
497
+ if self.event.style == '"' or self.canonical:
498
+ return '"'
499
+ if not self.event.style and self.event.implicit[0]:
500
+ if (not (self.simple_key_context and
501
+ (self.analysis.empty or self.analysis.multiline))
502
+ and (self.flow_level and self.analysis.allow_flow_plain
503
+ or (not self.flow_level and self.analysis.allow_block_plain))):
504
+ return ''
505
+ if self.event.style and self.event.style in '|>':
506
+ if (not self.flow_level and not self.simple_key_context
507
+ and self.analysis.allow_block):
508
+ return self.event.style
509
+ if not self.event.style or self.event.style == '\'':
510
+ if (self.analysis.allow_single_quoted and
511
+ not (self.simple_key_context and self.analysis.multiline)):
512
+ return '\''
513
+ return '"'
514
+
515
+ def process_scalar(self):
516
+ if self.analysis is None:
517
+ self.analysis = self.analyze_scalar(self.event.value)
518
+ if self.style is None:
519
+ self.style = self.choose_scalar_style()
520
+ split = (not self.simple_key_context)
521
+ #if self.analysis.multiline and split \
522
+ # and (not self.style or self.style in '\'\"'):
523
+ # self.write_indent()
524
+ if self.style == '"':
525
+ self.write_double_quoted(self.analysis.scalar, split)
526
+ elif self.style == '\'':
527
+ self.write_single_quoted(self.analysis.scalar, split)
528
+ elif self.style == '>':
529
+ self.write_folded(self.analysis.scalar)
530
+ elif self.style == '|':
531
+ self.write_literal(self.analysis.scalar)
532
+ else:
533
+ self.write_plain(self.analysis.scalar, split)
534
+ self.analysis = None
535
+ self.style = None
536
+
537
+ # Analyzers.
538
+
539
+ def prepare_version(self, version):
540
+ major, minor = version
541
+ if major != 1:
542
+ raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
543
+ return '%d.%d' % (major, minor)
544
+
545
+ def prepare_tag_handle(self, handle):
546
+ if not handle:
547
+ raise EmitterError("tag handle must not be empty")
548
+ if handle[0] != '!' or handle[-1] != '!':
549
+ raise EmitterError("tag handle must start and end with '!': %r" % handle)
550
+ for ch in handle[1:-1]:
551
+ if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
552
+ or ch in '-_'):
553
+ raise EmitterError("invalid character %r in the tag handle: %r"
554
+ % (ch, handle))
555
+ return handle
556
+
557
+ def prepare_tag_prefix(self, prefix):
558
+ if not prefix:
559
+ raise EmitterError("tag prefix must not be empty")
560
+ chunks = []
561
+ start = end = 0
562
+ if prefix[0] == '!':
563
+ end = 1
564
+ while end < len(prefix):
565
+ ch = prefix[end]
566
+ if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
567
+ or ch in '-;/?!:@&=+$,_.~*\'()[]':
568
+ end += 1
569
+ else:
570
+ if start < end:
571
+ chunks.append(prefix[start:end])
572
+ start = end = end+1
573
+ data = ch.encode('utf-8')
574
+ for ch in data:
575
+ chunks.append('%%%02X' % ord(ch))
576
+ if start < end:
577
+ chunks.append(prefix[start:end])
578
+ return ''.join(chunks)
579
+
580
+ def prepare_tag(self, tag):
581
+ if not tag:
582
+ raise EmitterError("tag must not be empty")
583
+ if tag == '!':
584
+ return tag
585
+ handle = None
586
+ suffix = tag
587
+ prefixes = sorted(self.tag_prefixes.keys())
588
+ for prefix in prefixes:
589
+ if tag.startswith(prefix) \
590
+ and (prefix == '!' or len(prefix) < len(tag)):
591
+ handle = self.tag_prefixes[prefix]
592
+ suffix = tag[len(prefix):]
593
+ chunks = []
594
+ start = end = 0
595
+ while end < len(suffix):
596
+ ch = suffix[end]
597
+ if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
598
+ or ch in '-;/?:@&=+$,_.~*\'()[]' \
599
+ or (ch == '!' and handle != '!'):
600
+ end += 1
601
+ else:
602
+ if start < end:
603
+ chunks.append(suffix[start:end])
604
+ start = end = end+1
605
+ data = ch.encode('utf-8')
606
+ for ch in data:
607
+ chunks.append('%%%02X' % ch)
608
+ if start < end:
609
+ chunks.append(suffix[start:end])
610
+ suffix_text = ''.join(chunks)
611
+ if handle:
612
+ return '%s%s' % (handle, suffix_text)
613
+ else:
614
+ return '!<%s>' % suffix_text
615
+
616
+ def prepare_anchor(self, anchor):
617
+ if not anchor:
618
+ raise EmitterError("anchor must not be empty")
619
+ for ch in anchor:
620
+ if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
621
+ or ch in '-_'):
622
+ raise EmitterError("invalid character %r in the anchor: %r"
623
+ % (ch, anchor))
624
+ return anchor
625
+
626
+ def analyze_scalar(self, scalar):
627
+
628
+ # Empty scalar is a special case.
629
+ if not scalar:
630
+ return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
631
+ allow_flow_plain=False, allow_block_plain=True,
632
+ allow_single_quoted=True, allow_double_quoted=True,
633
+ allow_block=False)
634
+
635
+ # Indicators and special characters.
636
+ block_indicators = False
637
+ flow_indicators = False
638
+ line_breaks = False
639
+ special_characters = False
640
+
641
+ # Important whitespace combinations.
642
+ leading_space = False
643
+ leading_break = False
644
+ trailing_space = False
645
+ trailing_break = False
646
+ break_space = False
647
+ space_break = False
648
+
649
+ # Check document indicators.
650
+ if scalar.startswith('---') or scalar.startswith('...'):
651
+ block_indicators = True
652
+ flow_indicators = True
653
+
654
+ # First character or preceded by a whitespace.
655
+ preceded_by_whitespace = True
656
+
657
+ # Last character or followed by a whitespace.
658
+ followed_by_whitespace = (len(scalar) == 1 or
659
+ scalar[1] in '\0 \t\r\n\x85\u2028\u2029')
660
+
661
+ # The previous character is a space.
662
+ previous_space = False
663
+
664
+ # The previous character is a break.
665
+ previous_break = False
666
+
667
+ index = 0
668
+ while index < len(scalar):
669
+ ch = scalar[index]
670
+
671
+ # Check for indicators.
672
+ if index == 0:
673
+ # Leading indicators are special characters.
674
+ if ch in '#,[]{}&*!|>\'\"%@`':
675
+ flow_indicators = True
676
+ block_indicators = True
677
+ if ch in '?:':
678
+ flow_indicators = True
679
+ if followed_by_whitespace:
680
+ block_indicators = True
681
+ if ch == '-' and followed_by_whitespace:
682
+ flow_indicators = True
683
+ block_indicators = True
684
+ else:
685
+ # Some indicators cannot appear within a scalar as well.
686
+ if ch in ',?[]{}':
687
+ flow_indicators = True
688
+ if ch == ':':
689
+ flow_indicators = True
690
+ if followed_by_whitespace:
691
+ block_indicators = True
692
+ if ch == '#' and preceded_by_whitespace:
693
+ flow_indicators = True
694
+ block_indicators = True
695
+
696
+ # Check for line breaks, special, and unicode characters.
697
+ if ch in '\n\x85\u2028\u2029':
698
+ line_breaks = True
699
+ if not (ch == '\n' or '\x20' <= ch <= '\x7E'):
700
+ if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF'
701
+ or '\uE000' <= ch <= '\uFFFD'
702
+ or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF':
703
+ unicode_characters = True
704
+ if not self.allow_unicode:
705
+ special_characters = True
706
+ else:
707
+ special_characters = True
708
+
709
+ # Detect important whitespace combinations.
710
+ if ch == ' ':
711
+ if index == 0:
712
+ leading_space = True
713
+ if index == len(scalar)-1:
714
+ trailing_space = True
715
+ if previous_break:
716
+ break_space = True
717
+ previous_space = True
718
+ previous_break = False
719
+ elif ch in '\n\x85\u2028\u2029':
720
+ if index == 0:
721
+ leading_break = True
722
+ if index == len(scalar)-1:
723
+ trailing_break = True
724
+ if previous_space:
725
+ space_break = True
726
+ previous_space = False
727
+ previous_break = True
728
+ else:
729
+ previous_space = False
730
+ previous_break = False
731
+
732
+ # Prepare for the next character.
733
+ index += 1
734
+ preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029')
735
+ followed_by_whitespace = (index+1 >= len(scalar) or
736
+ scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029')
737
+
738
+ # Let's decide what styles are allowed.
739
+ allow_flow_plain = True
740
+ allow_block_plain = True
741
+ allow_single_quoted = True
742
+ allow_double_quoted = True
743
+ allow_block = True
744
+
745
+ # Leading and trailing whitespaces are bad for plain scalars.
746
+ if (leading_space or leading_break
747
+ or trailing_space or trailing_break):
748
+ allow_flow_plain = allow_block_plain = False
749
+
750
+ # We do not permit trailing spaces for block scalars.
751
+ if trailing_space:
752
+ allow_block = False
753
+
754
+ # Spaces at the beginning of a new line are only acceptable for block
755
+ # scalars.
756
+ if break_space:
757
+ allow_flow_plain = allow_block_plain = allow_single_quoted = False
758
+
759
+ # Spaces followed by breaks, as well as special character are only
760
+ # allowed for double quoted scalars.
761
+ if space_break or special_characters:
762
+ allow_flow_plain = allow_block_plain = \
763
+ allow_single_quoted = allow_block = False
764
+
765
+ # Although the plain scalar writer supports breaks, we never emit
766
+ # multiline plain scalars.
767
+ if line_breaks:
768
+ allow_flow_plain = allow_block_plain = False
769
+
770
+ # Flow indicators are forbidden for flow plain scalars.
771
+ if flow_indicators:
772
+ allow_flow_plain = False
773
+
774
+ # Block indicators are forbidden for block plain scalars.
775
+ if block_indicators:
776
+ allow_block_plain = False
777
+
778
+ return ScalarAnalysis(scalar=scalar,
779
+ empty=False, multiline=line_breaks,
780
+ allow_flow_plain=allow_flow_plain,
781
+ allow_block_plain=allow_block_plain,
782
+ allow_single_quoted=allow_single_quoted,
783
+ allow_double_quoted=allow_double_quoted,
784
+ allow_block=allow_block)
785
+
786
+ # Writers.
787
+
788
+ def flush_stream(self):
789
+ if hasattr(self.stream, 'flush'):
790
+ self.stream.flush()
791
+
792
+ def write_stream_start(self):
793
+ # Write BOM if needed.
794
+ if self.encoding and self.encoding.startswith('utf-16'):
795
+ self.stream.write('\uFEFF'.encode(self.encoding))
796
+
797
+ def write_stream_end(self):
798
+ self.flush_stream()
799
+
800
+ def write_indicator(self, indicator, need_whitespace,
801
+ whitespace=False, indention=False):
802
+ if self.whitespace or not need_whitespace:
803
+ data = indicator
804
+ else:
805
+ data = ' '+indicator
806
+ self.whitespace = whitespace
807
+ self.indention = self.indention and indention
808
+ self.column += len(data)
809
+ self.open_ended = False
810
+ if self.encoding:
811
+ data = data.encode(self.encoding)
812
+ self.stream.write(data)
813
+
814
+ def write_indent(self):
815
+ indent = self.indent or 0
816
+ if not self.indention or self.column > indent \
817
+ or (self.column == indent and not self.whitespace):
818
+ self.write_line_break()
819
+ if self.column < indent:
820
+ self.whitespace = True
821
+ data = ' '*(indent-self.column)
822
+ self.column = indent
823
+ if self.encoding:
824
+ data = data.encode(self.encoding)
825
+ self.stream.write(data)
826
+
827
+ def write_line_break(self, data=None):
828
+ if data is None:
829
+ data = self.best_line_break
830
+ self.whitespace = True
831
+ self.indention = True
832
+ self.line += 1
833
+ self.column = 0
834
+ if self.encoding:
835
+ data = data.encode(self.encoding)
836
+ self.stream.write(data)
837
+
838
+ def write_version_directive(self, version_text):
839
+ data = '%%YAML %s' % version_text
840
+ if self.encoding:
841
+ data = data.encode(self.encoding)
842
+ self.stream.write(data)
843
+ self.write_line_break()
844
+
845
+ def write_tag_directive(self, handle_text, prefix_text):
846
+ data = '%%TAG %s %s' % (handle_text, prefix_text)
847
+ if self.encoding:
848
+ data = data.encode(self.encoding)
849
+ self.stream.write(data)
850
+ self.write_line_break()
851
+
852
+ # Scalar streams.
853
+
854
+ def write_single_quoted(self, text, split=True):
855
+ self.write_indicator('\'', True)
856
+ spaces = False
857
+ breaks = False
858
+ start = end = 0
859
+ while end <= len(text):
860
+ ch = None
861
+ if end < len(text):
862
+ ch = text[end]
863
+ if spaces:
864
+ if ch is None or ch != ' ':
865
+ if start+1 == end and self.column > self.best_width and split \
866
+ and start != 0 and end != len(text):
867
+ self.write_indent()
868
+ else:
869
+ data = text[start:end]
870
+ self.column += len(data)
871
+ if self.encoding:
872
+ data = data.encode(self.encoding)
873
+ self.stream.write(data)
874
+ start = end
875
+ elif breaks:
876
+ if ch is None or ch not in '\n\x85\u2028\u2029':
877
+ if text[start] == '\n':
878
+ self.write_line_break()
879
+ for br in text[start:end]:
880
+ if br == '\n':
881
+ self.write_line_break()
882
+ else:
883
+ self.write_line_break(br)
884
+ self.write_indent()
885
+ start = end
886
+ else:
887
+ if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'':
888
+ if start < end:
889
+ data = text[start:end]
890
+ self.column += len(data)
891
+ if self.encoding:
892
+ data = data.encode(self.encoding)
893
+ self.stream.write(data)
894
+ start = end
895
+ if ch == '\'':
896
+ data = '\'\''
897
+ self.column += 2
898
+ if self.encoding:
899
+ data = data.encode(self.encoding)
900
+ self.stream.write(data)
901
+ start = end + 1
902
+ if ch is not None:
903
+ spaces = (ch == ' ')
904
+ breaks = (ch in '\n\x85\u2028\u2029')
905
+ end += 1
906
+ self.write_indicator('\'', False)
907
+
908
+ ESCAPE_REPLACEMENTS = {
909
+ '\0': '0',
910
+ '\x07': 'a',
911
+ '\x08': 'b',
912
+ '\x09': 't',
913
+ '\x0A': 'n',
914
+ '\x0B': 'v',
915
+ '\x0C': 'f',
916
+ '\x0D': 'r',
917
+ '\x1B': 'e',
918
+ '\"': '\"',
919
+ '\\': '\\',
920
+ '\x85': 'N',
921
+ '\xA0': '_',
922
+ '\u2028': 'L',
923
+ '\u2029': 'P',
924
+ }
925
+
926
+ def write_double_quoted(self, text, split=True):
927
+ self.write_indicator('"', True)
928
+ start = end = 0
929
+ while end <= len(text):
930
+ ch = None
931
+ if end < len(text):
932
+ ch = text[end]
933
+ if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \
934
+ or not ('\x20' <= ch <= '\x7E'
935
+ or (self.allow_unicode
936
+ and ('\xA0' <= ch <= '\uD7FF'
937
+ or '\uE000' <= ch <= '\uFFFD'))):
938
+ if start < end:
939
+ data = text[start:end]
940
+ self.column += len(data)
941
+ if self.encoding:
942
+ data = data.encode(self.encoding)
943
+ self.stream.write(data)
944
+ start = end
945
+ if ch is not None:
946
+ if ch in self.ESCAPE_REPLACEMENTS:
947
+ data = '\\'+self.ESCAPE_REPLACEMENTS[ch]
948
+ elif ch <= '\xFF':
949
+ data = '\\x%02X' % ord(ch)
950
+ elif ch <= '\uFFFF':
951
+ data = '\\u%04X' % ord(ch)
952
+ else:
953
+ data = '\\U%08X' % ord(ch)
954
+ self.column += len(data)
955
+ if self.encoding:
956
+ data = data.encode(self.encoding)
957
+ self.stream.write(data)
958
+ start = end+1
959
+ if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \
960
+ and self.column+(end-start) > self.best_width and split:
961
+ data = text[start:end]+'\\'
962
+ if start < end:
963
+ start = end
964
+ self.column += len(data)
965
+ if self.encoding:
966
+ data = data.encode(self.encoding)
967
+ self.stream.write(data)
968
+ self.write_indent()
969
+ self.whitespace = False
970
+ self.indention = False
971
+ if text[start] == ' ':
972
+ data = '\\'
973
+ self.column += len(data)
974
+ if self.encoding:
975
+ data = data.encode(self.encoding)
976
+ self.stream.write(data)
977
+ end += 1
978
+ self.write_indicator('"', False)
979
+
980
+ def determine_block_hints(self, text):
981
+ hints = ''
982
+ if text:
983
+ if text[0] in ' \n\x85\u2028\u2029':
984
+ hints += str(self.best_indent)
985
+ if text[-1] not in '\n\x85\u2028\u2029':
986
+ hints += '-'
987
+ elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029':
988
+ hints += '+'
989
+ return hints
990
+
991
+ def write_folded(self, text):
992
+ hints = self.determine_block_hints(text)
993
+ self.write_indicator('>'+hints, True)
994
+ if hints[-1:] == '+':
995
+ self.open_ended = True
996
+ self.write_line_break()
997
+ leading_space = True
998
+ spaces = False
999
+ breaks = True
1000
+ start = end = 0
1001
+ while end <= len(text):
1002
+ ch = None
1003
+ if end < len(text):
1004
+ ch = text[end]
1005
+ if breaks:
1006
+ if ch is None or ch not in '\n\x85\u2028\u2029':
1007
+ if not leading_space and ch is not None and ch != ' ' \
1008
+ and text[start] == '\n':
1009
+ self.write_line_break()
1010
+ leading_space = (ch == ' ')
1011
+ for br in text[start:end]:
1012
+ if br == '\n':
1013
+ self.write_line_break()
1014
+ else:
1015
+ self.write_line_break(br)
1016
+ if ch is not None:
1017
+ self.write_indent()
1018
+ start = end
1019
+ elif spaces:
1020
+ if ch != ' ':
1021
+ if start+1 == end and self.column > self.best_width:
1022
+ self.write_indent()
1023
+ else:
1024
+ data = text[start:end]
1025
+ self.column += len(data)
1026
+ if self.encoding:
1027
+ data = data.encode(self.encoding)
1028
+ self.stream.write(data)
1029
+ start = end
1030
+ else:
1031
+ if ch is None or ch in ' \n\x85\u2028\u2029':
1032
+ data = text[start:end]
1033
+ self.column += len(data)
1034
+ if self.encoding:
1035
+ data = data.encode(self.encoding)
1036
+ self.stream.write(data)
1037
+ if ch is None:
1038
+ self.write_line_break()
1039
+ start = end
1040
+ if ch is not None:
1041
+ breaks = (ch in '\n\x85\u2028\u2029')
1042
+ spaces = (ch == ' ')
1043
+ end += 1
1044
+
1045
+ def write_literal(self, text):
1046
+ hints = self.determine_block_hints(text)
1047
+ self.write_indicator('|'+hints, True)
1048
+ if hints[-1:] == '+':
1049
+ self.open_ended = True
1050
+ self.write_line_break()
1051
+ breaks = True
1052
+ start = end = 0
1053
+ while end <= len(text):
1054
+ ch = None
1055
+ if end < len(text):
1056
+ ch = text[end]
1057
+ if breaks:
1058
+ if ch is None or ch not in '\n\x85\u2028\u2029':
1059
+ for br in text[start:end]:
1060
+ if br == '\n':
1061
+ self.write_line_break()
1062
+ else:
1063
+ self.write_line_break(br)
1064
+ if ch is not None:
1065
+ self.write_indent()
1066
+ start = end
1067
+ else:
1068
+ if ch is None or ch in '\n\x85\u2028\u2029':
1069
+ data = text[start:end]
1070
+ if self.encoding:
1071
+ data = data.encode(self.encoding)
1072
+ self.stream.write(data)
1073
+ if ch is None:
1074
+ self.write_line_break()
1075
+ start = end
1076
+ if ch is not None:
1077
+ breaks = (ch in '\n\x85\u2028\u2029')
1078
+ end += 1
1079
+
1080
+ def write_plain(self, text, split=True):
1081
+ if self.root_context:
1082
+ self.open_ended = True
1083
+ if not text:
1084
+ return
1085
+ if not self.whitespace:
1086
+ data = ' '
1087
+ self.column += len(data)
1088
+ if self.encoding:
1089
+ data = data.encode(self.encoding)
1090
+ self.stream.write(data)
1091
+ self.whitespace = False
1092
+ self.indention = False
1093
+ spaces = False
1094
+ breaks = False
1095
+ start = end = 0
1096
+ while end <= len(text):
1097
+ ch = None
1098
+ if end < len(text):
1099
+ ch = text[end]
1100
+ if spaces:
1101
+ if ch != ' ':
1102
+ if start+1 == end and self.column > self.best_width and split:
1103
+ self.write_indent()
1104
+ self.whitespace = False
1105
+ self.indention = False
1106
+ else:
1107
+ data = text[start:end]
1108
+ self.column += len(data)
1109
+ if self.encoding:
1110
+ data = data.encode(self.encoding)
1111
+ self.stream.write(data)
1112
+ start = end
1113
+ elif breaks:
1114
+ if ch not in '\n\x85\u2028\u2029':
1115
+ if text[start] == '\n':
1116
+ self.write_line_break()
1117
+ for br in text[start:end]:
1118
+ if br == '\n':
1119
+ self.write_line_break()
1120
+ else:
1121
+ self.write_line_break(br)
1122
+ self.write_indent()
1123
+ self.whitespace = False
1124
+ self.indention = False
1125
+ start = end
1126
+ else:
1127
+ if ch is None or ch in ' \n\x85\u2028\u2029':
1128
+ data = text[start:end]
1129
+ self.column += len(data)
1130
+ if self.encoding:
1131
+ data = data.encode(self.encoding)
1132
+ self.stream.write(data)
1133
+ start = end
1134
+ if ch is not None:
1135
+ spaces = (ch == ' ')
1136
+ breaks = (ch in '\n\x85\u2028\u2029')
1137
+ end += 1
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/error.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']
3
+
4
+ class Mark:
5
+
6
+ def __init__(self, name, index, line, column, buffer, pointer):
7
+ self.name = name
8
+ self.index = index
9
+ self.line = line
10
+ self.column = column
11
+ self.buffer = buffer
12
+ self.pointer = pointer
13
+
14
+ def get_snippet(self, indent=4, max_length=75):
15
+ if self.buffer is None:
16
+ return None
17
+ head = ''
18
+ start = self.pointer
19
+ while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029':
20
+ start -= 1
21
+ if self.pointer-start > max_length/2-1:
22
+ head = ' ... '
23
+ start += 5
24
+ break
25
+ tail = ''
26
+ end = self.pointer
27
+ while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029':
28
+ end += 1
29
+ if end-self.pointer > max_length/2-1:
30
+ tail = ' ... '
31
+ end -= 5
32
+ break
33
+ snippet = self.buffer[start:end]
34
+ return ' '*indent + head + snippet + tail + '\n' \
35
+ + ' '*(indent+self.pointer-start+len(head)) + '^'
36
+
37
+ def __str__(self):
38
+ snippet = self.get_snippet()
39
+ where = " in \"%s\", line %d, column %d" \
40
+ % (self.name, self.line+1, self.column+1)
41
+ if snippet is not None:
42
+ where += ":\n"+snippet
43
+ return where
44
+
45
+ class YAMLError(Exception):
46
+ pass
47
+
48
+ class MarkedYAMLError(YAMLError):
49
+
50
+ def __init__(self, context=None, context_mark=None,
51
+ problem=None, problem_mark=None, note=None):
52
+ self.context = context
53
+ self.context_mark = context_mark
54
+ self.problem = problem
55
+ self.problem_mark = problem_mark
56
+ self.note = note
57
+
58
+ def __str__(self):
59
+ lines = []
60
+ if self.context is not None:
61
+ lines.append(self.context)
62
+ if self.context_mark is not None \
63
+ and (self.problem is None or self.problem_mark is None
64
+ or self.context_mark.name != self.problem_mark.name
65
+ or self.context_mark.line != self.problem_mark.line
66
+ or self.context_mark.column != self.problem_mark.column):
67
+ lines.append(str(self.context_mark))
68
+ if self.problem is not None:
69
+ lines.append(self.problem)
70
+ if self.problem_mark is not None:
71
+ lines.append(str(self.problem_mark))
72
+ if self.note is not None:
73
+ lines.append(self.note)
74
+ return '\n'.join(lines)
75
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/events.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Abstract classes.
3
+
4
+ class Event(object):
5
+ def __init__(self, start_mark=None, end_mark=None):
6
+ self.start_mark = start_mark
7
+ self.end_mark = end_mark
8
+ def __repr__(self):
9
+ attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
10
+ if hasattr(self, key)]
11
+ arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
12
+ for key in attributes])
13
+ return '%s(%s)' % (self.__class__.__name__, arguments)
14
+
15
+ class NodeEvent(Event):
16
+ def __init__(self, anchor, start_mark=None, end_mark=None):
17
+ self.anchor = anchor
18
+ self.start_mark = start_mark
19
+ self.end_mark = end_mark
20
+
21
+ class CollectionStartEvent(NodeEvent):
22
+ def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
23
+ flow_style=None):
24
+ self.anchor = anchor
25
+ self.tag = tag
26
+ self.implicit = implicit
27
+ self.start_mark = start_mark
28
+ self.end_mark = end_mark
29
+ self.flow_style = flow_style
30
+
31
+ class CollectionEndEvent(Event):
32
+ pass
33
+
34
+ # Implementations.
35
+
36
+ class StreamStartEvent(Event):
37
+ def __init__(self, start_mark=None, end_mark=None, encoding=None):
38
+ self.start_mark = start_mark
39
+ self.end_mark = end_mark
40
+ self.encoding = encoding
41
+
42
+ class StreamEndEvent(Event):
43
+ pass
44
+
45
+ class DocumentStartEvent(Event):
46
+ def __init__(self, start_mark=None, end_mark=None,
47
+ explicit=None, version=None, tags=None):
48
+ self.start_mark = start_mark
49
+ self.end_mark = end_mark
50
+ self.explicit = explicit
51
+ self.version = version
52
+ self.tags = tags
53
+
54
+ class DocumentEndEvent(Event):
55
+ def __init__(self, start_mark=None, end_mark=None,
56
+ explicit=None):
57
+ self.start_mark = start_mark
58
+ self.end_mark = end_mark
59
+ self.explicit = explicit
60
+
61
+ class AliasEvent(NodeEvent):
62
+ pass
63
+
64
+ class ScalarEvent(NodeEvent):
65
+ def __init__(self, anchor, tag, implicit, value,
66
+ start_mark=None, end_mark=None, style=None):
67
+ self.anchor = anchor
68
+ self.tag = tag
69
+ self.implicit = implicit
70
+ self.value = value
71
+ self.start_mark = start_mark
72
+ self.end_mark = end_mark
73
+ self.style = style
74
+
75
+ class SequenceStartEvent(CollectionStartEvent):
76
+ pass
77
+
78
+ class SequenceEndEvent(CollectionEndEvent):
79
+ pass
80
+
81
+ class MappingStartEvent(CollectionStartEvent):
82
+ pass
83
+
84
+ class MappingEndEvent(CollectionEndEvent):
85
+ pass
86
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/loader.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader']
3
+
4
+ from .reader import *
5
+ from .scanner import *
6
+ from .parser import *
7
+ from .composer import *
8
+ from .constructor import *
9
+ from .resolver import *
10
+
11
+ class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
12
+
13
+ def __init__(self, stream):
14
+ Reader.__init__(self, stream)
15
+ Scanner.__init__(self)
16
+ Parser.__init__(self)
17
+ Composer.__init__(self)
18
+ BaseConstructor.__init__(self)
19
+ BaseResolver.__init__(self)
20
+
21
+ class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
22
+
23
+ def __init__(self, stream):
24
+ Reader.__init__(self, stream)
25
+ Scanner.__init__(self)
26
+ Parser.__init__(self)
27
+ Composer.__init__(self)
28
+ FullConstructor.__init__(self)
29
+ Resolver.__init__(self)
30
+
31
+ class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
32
+
33
+ def __init__(self, stream):
34
+ Reader.__init__(self, stream)
35
+ Scanner.__init__(self)
36
+ Parser.__init__(self)
37
+ Composer.__init__(self)
38
+ SafeConstructor.__init__(self)
39
+ Resolver.__init__(self)
40
+
41
+ class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
42
+
43
+ def __init__(self, stream):
44
+ Reader.__init__(self, stream)
45
+ Scanner.__init__(self)
46
+ Parser.__init__(self)
47
+ Composer.__init__(self)
48
+ Constructor.__init__(self)
49
+ Resolver.__init__(self)
50
+
51
+ # UnsafeLoader is the same as Loader (which is and was always unsafe on
52
+ # untrusted input). Use of either Loader or UnsafeLoader should be rare, since
53
+ # FullLoad should be able to load almost all YAML safely. Loader is left intact
54
+ # to ensure backwards compatibility.
55
+ class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
56
+
57
+ def __init__(self, stream):
58
+ Reader.__init__(self, stream)
59
+ Scanner.__init__(self)
60
+ Parser.__init__(self)
61
+ Composer.__init__(self)
62
+ Constructor.__init__(self)
63
+ Resolver.__init__(self)
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/nodes.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class Node(object):
3
+ def __init__(self, tag, value, start_mark, end_mark):
4
+ self.tag = tag
5
+ self.value = value
6
+ self.start_mark = start_mark
7
+ self.end_mark = end_mark
8
+ def __repr__(self):
9
+ value = self.value
10
+ #if isinstance(value, list):
11
+ # if len(value) == 0:
12
+ # value = '<empty>'
13
+ # elif len(value) == 1:
14
+ # value = '<1 item>'
15
+ # else:
16
+ # value = '<%d items>' % len(value)
17
+ #else:
18
+ # if len(value) > 75:
19
+ # value = repr(value[:70]+u' ... ')
20
+ # else:
21
+ # value = repr(value)
22
+ value = repr(value)
23
+ return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value)
24
+
25
+ class ScalarNode(Node):
26
+ id = 'scalar'
27
+ def __init__(self, tag, value,
28
+ start_mark=None, end_mark=None, style=None):
29
+ self.tag = tag
30
+ self.value = value
31
+ self.start_mark = start_mark
32
+ self.end_mark = end_mark
33
+ self.style = style
34
+
35
+ class CollectionNode(Node):
36
+ def __init__(self, tag, value,
37
+ start_mark=None, end_mark=None, flow_style=None):
38
+ self.tag = tag
39
+ self.value = value
40
+ self.start_mark = start_mark
41
+ self.end_mark = end_mark
42
+ self.flow_style = flow_style
43
+
44
+ class SequenceNode(CollectionNode):
45
+ id = 'sequence'
46
+
47
+ class MappingNode(CollectionNode):
48
+ id = 'mapping'
49
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/parser.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # The following YAML grammar is LL(1) and is parsed by a recursive descent
3
+ # parser.
4
+ #
5
+ # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
6
+ # implicit_document ::= block_node DOCUMENT-END*
7
+ # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
8
+ # block_node_or_indentless_sequence ::=
9
+ # ALIAS
10
+ # | properties (block_content | indentless_block_sequence)?
11
+ # | block_content
12
+ # | indentless_block_sequence
13
+ # block_node ::= ALIAS
14
+ # | properties block_content?
15
+ # | block_content
16
+ # flow_node ::= ALIAS
17
+ # | properties flow_content?
18
+ # | flow_content
19
+ # properties ::= TAG ANCHOR? | ANCHOR TAG?
20
+ # block_content ::= block_collection | flow_collection | SCALAR
21
+ # flow_content ::= flow_collection | SCALAR
22
+ # block_collection ::= block_sequence | block_mapping
23
+ # flow_collection ::= flow_sequence | flow_mapping
24
+ # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
25
+ # indentless_sequence ::= (BLOCK-ENTRY block_node?)+
26
+ # block_mapping ::= BLOCK-MAPPING_START
27
+ # ((KEY block_node_or_indentless_sequence?)?
28
+ # (VALUE block_node_or_indentless_sequence?)?)*
29
+ # BLOCK-END
30
+ # flow_sequence ::= FLOW-SEQUENCE-START
31
+ # (flow_sequence_entry FLOW-ENTRY)*
32
+ # flow_sequence_entry?
33
+ # FLOW-SEQUENCE-END
34
+ # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
35
+ # flow_mapping ::= FLOW-MAPPING-START
36
+ # (flow_mapping_entry FLOW-ENTRY)*
37
+ # flow_mapping_entry?
38
+ # FLOW-MAPPING-END
39
+ # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
40
+ #
41
+ # FIRST sets:
42
+ #
43
+ # stream: { STREAM-START }
44
+ # explicit_document: { DIRECTIVE DOCUMENT-START }
45
+ # implicit_document: FIRST(block_node)
46
+ # block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START }
47
+ # flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START }
48
+ # block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
49
+ # flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR }
50
+ # block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START }
51
+ # flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
52
+ # block_sequence: { BLOCK-SEQUENCE-START }
53
+ # block_mapping: { BLOCK-MAPPING-START }
54
+ # block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY }
55
+ # indentless_sequence: { ENTRY }
56
+ # flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START }
57
+ # flow_sequence: { FLOW-SEQUENCE-START }
58
+ # flow_mapping: { FLOW-MAPPING-START }
59
+ # flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
60
+ # flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY }
61
+
62
+ __all__ = ['Parser', 'ParserError']
63
+
64
+ from .error import MarkedYAMLError
65
+ from .tokens import *
66
+ from .events import *
67
+ from .scanner import *
68
+
69
+ class ParserError(MarkedYAMLError):
70
+ pass
71
+
72
+ class Parser:
73
+ # Since writing a recursive-descendant parser is a straightforward task, we
74
+ # do not give many comments here.
75
+
76
+ DEFAULT_TAGS = {
77
+ '!': '!',
78
+ '!!': 'tag:yaml.org,2002:',
79
+ }
80
+
81
+ def __init__(self):
82
+ self.current_event = None
83
+ self.yaml_version = None
84
+ self.tag_handles = {}
85
+ self.states = []
86
+ self.marks = []
87
+ self.state = self.parse_stream_start
88
+
89
+ def dispose(self):
90
+ # Reset the state attributes (to clear self-references)
91
+ self.states = []
92
+ self.state = None
93
+
94
+ def check_event(self, *choices):
95
+ # Check the type of the next event.
96
+ if self.current_event is None:
97
+ if self.state:
98
+ self.current_event = self.state()
99
+ if self.current_event is not None:
100
+ if not choices:
101
+ return True
102
+ for choice in choices:
103
+ if isinstance(self.current_event, choice):
104
+ return True
105
+ return False
106
+
107
+ def peek_event(self):
108
+ # Get the next event.
109
+ if self.current_event is None:
110
+ if self.state:
111
+ self.current_event = self.state()
112
+ return self.current_event
113
+
114
+ def get_event(self):
115
+ # Get the next event and proceed further.
116
+ if self.current_event is None:
117
+ if self.state:
118
+ self.current_event = self.state()
119
+ value = self.current_event
120
+ self.current_event = None
121
+ return value
122
+
123
+ # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
124
+ # implicit_document ::= block_node DOCUMENT-END*
125
+ # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
126
+
127
+ def parse_stream_start(self):
128
+
129
+ # Parse the stream start.
130
+ token = self.get_token()
131
+ event = StreamStartEvent(token.start_mark, token.end_mark,
132
+ encoding=token.encoding)
133
+
134
+ # Prepare the next state.
135
+ self.state = self.parse_implicit_document_start
136
+
137
+ return event
138
+
139
+ def parse_implicit_document_start(self):
140
+
141
+ # Parse an implicit document.
142
+ if not self.check_token(DirectiveToken, DocumentStartToken,
143
+ StreamEndToken):
144
+ self.tag_handles = self.DEFAULT_TAGS
145
+ token = self.peek_token()
146
+ start_mark = end_mark = token.start_mark
147
+ event = DocumentStartEvent(start_mark, end_mark,
148
+ explicit=False)
149
+
150
+ # Prepare the next state.
151
+ self.states.append(self.parse_document_end)
152
+ self.state = self.parse_block_node
153
+
154
+ return event
155
+
156
+ else:
157
+ return self.parse_document_start()
158
+
159
+ def parse_document_start(self):
160
+
161
+ # Parse any extra document end indicators.
162
+ while self.check_token(DocumentEndToken):
163
+ self.get_token()
164
+
165
+ # Parse an explicit document.
166
+ if not self.check_token(StreamEndToken):
167
+ token = self.peek_token()
168
+ start_mark = token.start_mark
169
+ version, tags = self.process_directives()
170
+ if not self.check_token(DocumentStartToken):
171
+ raise ParserError(None, None,
172
+ "expected '<document start>', but found %r"
173
+ % self.peek_token().id,
174
+ self.peek_token().start_mark)
175
+ token = self.get_token()
176
+ end_mark = token.end_mark
177
+ event = DocumentStartEvent(start_mark, end_mark,
178
+ explicit=True, version=version, tags=tags)
179
+ self.states.append(self.parse_document_end)
180
+ self.state = self.parse_document_content
181
+ else:
182
+ # Parse the end of the stream.
183
+ token = self.get_token()
184
+ event = StreamEndEvent(token.start_mark, token.end_mark)
185
+ assert not self.states
186
+ assert not self.marks
187
+ self.state = None
188
+ return event
189
+
190
+ def parse_document_end(self):
191
+
192
+ # Parse the document end.
193
+ token = self.peek_token()
194
+ start_mark = end_mark = token.start_mark
195
+ explicit = False
196
+ if self.check_token(DocumentEndToken):
197
+ token = self.get_token()
198
+ end_mark = token.end_mark
199
+ explicit = True
200
+ event = DocumentEndEvent(start_mark, end_mark,
201
+ explicit=explicit)
202
+
203
+ # Prepare the next state.
204
+ self.state = self.parse_document_start
205
+
206
+ return event
207
+
208
+ def parse_document_content(self):
209
+ if self.check_token(DirectiveToken,
210
+ DocumentStartToken, DocumentEndToken, StreamEndToken):
211
+ event = self.process_empty_scalar(self.peek_token().start_mark)
212
+ self.state = self.states.pop()
213
+ return event
214
+ else:
215
+ return self.parse_block_node()
216
+
217
+ def process_directives(self):
218
+ self.yaml_version = None
219
+ self.tag_handles = {}
220
+ while self.check_token(DirectiveToken):
221
+ token = self.get_token()
222
+ if token.name == 'YAML':
223
+ if self.yaml_version is not None:
224
+ raise ParserError(None, None,
225
+ "found duplicate YAML directive", token.start_mark)
226
+ major, minor = token.value
227
+ if major != 1:
228
+ raise ParserError(None, None,
229
+ "found incompatible YAML document (version 1.* is required)",
230
+ token.start_mark)
231
+ self.yaml_version = token.value
232
+ elif token.name == 'TAG':
233
+ handle, prefix = token.value
234
+ if handle in self.tag_handles:
235
+ raise ParserError(None, None,
236
+ "duplicate tag handle %r" % handle,
237
+ token.start_mark)
238
+ self.tag_handles[handle] = prefix
239
+ if self.tag_handles:
240
+ value = self.yaml_version, self.tag_handles.copy()
241
+ else:
242
+ value = self.yaml_version, None
243
+ for key in self.DEFAULT_TAGS:
244
+ if key not in self.tag_handles:
245
+ self.tag_handles[key] = self.DEFAULT_TAGS[key]
246
+ return value
247
+
248
+ # block_node_or_indentless_sequence ::= ALIAS
249
+ # | properties (block_content | indentless_block_sequence)?
250
+ # | block_content
251
+ # | indentless_block_sequence
252
+ # block_node ::= ALIAS
253
+ # | properties block_content?
254
+ # | block_content
255
+ # flow_node ::= ALIAS
256
+ # | properties flow_content?
257
+ # | flow_content
258
+ # properties ::= TAG ANCHOR? | ANCHOR TAG?
259
+ # block_content ::= block_collection | flow_collection | SCALAR
260
+ # flow_content ::= flow_collection | SCALAR
261
+ # block_collection ::= block_sequence | block_mapping
262
+ # flow_collection ::= flow_sequence | flow_mapping
263
+
264
+ def parse_block_node(self):
265
+ return self.parse_node(block=True)
266
+
267
+ def parse_flow_node(self):
268
+ return self.parse_node()
269
+
270
+ def parse_block_node_or_indentless_sequence(self):
271
+ return self.parse_node(block=True, indentless_sequence=True)
272
+
273
+ def parse_node(self, block=False, indentless_sequence=False):
274
+ if self.check_token(AliasToken):
275
+ token = self.get_token()
276
+ event = AliasEvent(token.value, token.start_mark, token.end_mark)
277
+ self.state = self.states.pop()
278
+ else:
279
+ anchor = None
280
+ tag = None
281
+ start_mark = end_mark = tag_mark = None
282
+ if self.check_token(AnchorToken):
283
+ token = self.get_token()
284
+ start_mark = token.start_mark
285
+ end_mark = token.end_mark
286
+ anchor = token.value
287
+ if self.check_token(TagToken):
288
+ token = self.get_token()
289
+ tag_mark = token.start_mark
290
+ end_mark = token.end_mark
291
+ tag = token.value
292
+ elif self.check_token(TagToken):
293
+ token = self.get_token()
294
+ start_mark = tag_mark = token.start_mark
295
+ end_mark = token.end_mark
296
+ tag = token.value
297
+ if self.check_token(AnchorToken):
298
+ token = self.get_token()
299
+ end_mark = token.end_mark
300
+ anchor = token.value
301
+ if tag is not None:
302
+ handle, suffix = tag
303
+ if handle is not None:
304
+ if handle not in self.tag_handles:
305
+ raise ParserError("while parsing a node", start_mark,
306
+ "found undefined tag handle %r" % handle,
307
+ tag_mark)
308
+ tag = self.tag_handles[handle]+suffix
309
+ else:
310
+ tag = suffix
311
+ #if tag == '!':
312
+ # raise ParserError("while parsing a node", start_mark,
313
+ # "found non-specific tag '!'", tag_mark,
314
+ # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.")
315
+ if start_mark is None:
316
+ start_mark = end_mark = self.peek_token().start_mark
317
+ event = None
318
+ implicit = (tag is None or tag == '!')
319
+ if indentless_sequence and self.check_token(BlockEntryToken):
320
+ end_mark = self.peek_token().end_mark
321
+ event = SequenceStartEvent(anchor, tag, implicit,
322
+ start_mark, end_mark)
323
+ self.state = self.parse_indentless_sequence_entry
324
+ else:
325
+ if self.check_token(ScalarToken):
326
+ token = self.get_token()
327
+ end_mark = token.end_mark
328
+ if (token.plain and tag is None) or tag == '!':
329
+ implicit = (True, False)
330
+ elif tag is None:
331
+ implicit = (False, True)
332
+ else:
333
+ implicit = (False, False)
334
+ event = ScalarEvent(anchor, tag, implicit, token.value,
335
+ start_mark, end_mark, style=token.style)
336
+ self.state = self.states.pop()
337
+ elif self.check_token(FlowSequenceStartToken):
338
+ end_mark = self.peek_token().end_mark
339
+ event = SequenceStartEvent(anchor, tag, implicit,
340
+ start_mark, end_mark, flow_style=True)
341
+ self.state = self.parse_flow_sequence_first_entry
342
+ elif self.check_token(FlowMappingStartToken):
343
+ end_mark = self.peek_token().end_mark
344
+ event = MappingStartEvent(anchor, tag, implicit,
345
+ start_mark, end_mark, flow_style=True)
346
+ self.state = self.parse_flow_mapping_first_key
347
+ elif block and self.check_token(BlockSequenceStartToken):
348
+ end_mark = self.peek_token().start_mark
349
+ event = SequenceStartEvent(anchor, tag, implicit,
350
+ start_mark, end_mark, flow_style=False)
351
+ self.state = self.parse_block_sequence_first_entry
352
+ elif block and self.check_token(BlockMappingStartToken):
353
+ end_mark = self.peek_token().start_mark
354
+ event = MappingStartEvent(anchor, tag, implicit,
355
+ start_mark, end_mark, flow_style=False)
356
+ self.state = self.parse_block_mapping_first_key
357
+ elif anchor is not None or tag is not None:
358
+ # Empty scalars are allowed even if a tag or an anchor is
359
+ # specified.
360
+ event = ScalarEvent(anchor, tag, (implicit, False), '',
361
+ start_mark, end_mark)
362
+ self.state = self.states.pop()
363
+ else:
364
+ if block:
365
+ node = 'block'
366
+ else:
367
+ node = 'flow'
368
+ token = self.peek_token()
369
+ raise ParserError("while parsing a %s node" % node, start_mark,
370
+ "expected the node content, but found %r" % token.id,
371
+ token.start_mark)
372
+ return event
373
+
374
+ # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
375
+
376
+ def parse_block_sequence_first_entry(self):
377
+ token = self.get_token()
378
+ self.marks.append(token.start_mark)
379
+ return self.parse_block_sequence_entry()
380
+
381
+ def parse_block_sequence_entry(self):
382
+ if self.check_token(BlockEntryToken):
383
+ token = self.get_token()
384
+ if not self.check_token(BlockEntryToken, BlockEndToken):
385
+ self.states.append(self.parse_block_sequence_entry)
386
+ return self.parse_block_node()
387
+ else:
388
+ self.state = self.parse_block_sequence_entry
389
+ return self.process_empty_scalar(token.end_mark)
390
+ if not self.check_token(BlockEndToken):
391
+ token = self.peek_token()
392
+ raise ParserError("while parsing a block collection", self.marks[-1],
393
+ "expected <block end>, but found %r" % token.id, token.start_mark)
394
+ token = self.get_token()
395
+ event = SequenceEndEvent(token.start_mark, token.end_mark)
396
+ self.state = self.states.pop()
397
+ self.marks.pop()
398
+ return event
399
+
400
+ # indentless_sequence ::= (BLOCK-ENTRY block_node?)+
401
+
402
+ def parse_indentless_sequence_entry(self):
403
+ if self.check_token(BlockEntryToken):
404
+ token = self.get_token()
405
+ if not self.check_token(BlockEntryToken,
406
+ KeyToken, ValueToken, BlockEndToken):
407
+ self.states.append(self.parse_indentless_sequence_entry)
408
+ return self.parse_block_node()
409
+ else:
410
+ self.state = self.parse_indentless_sequence_entry
411
+ return self.process_empty_scalar(token.end_mark)
412
+ token = self.peek_token()
413
+ event = SequenceEndEvent(token.start_mark, token.start_mark)
414
+ self.state = self.states.pop()
415
+ return event
416
+
417
+ # block_mapping ::= BLOCK-MAPPING_START
418
+ # ((KEY block_node_or_indentless_sequence?)?
419
+ # (VALUE block_node_or_indentless_sequence?)?)*
420
+ # BLOCK-END
421
+
422
+ def parse_block_mapping_first_key(self):
423
+ token = self.get_token()
424
+ self.marks.append(token.start_mark)
425
+ return self.parse_block_mapping_key()
426
+
427
+ def parse_block_mapping_key(self):
428
+ if self.check_token(KeyToken):
429
+ token = self.get_token()
430
+ if not self.check_token(KeyToken, ValueToken, BlockEndToken):
431
+ self.states.append(self.parse_block_mapping_value)
432
+ return self.parse_block_node_or_indentless_sequence()
433
+ else:
434
+ self.state = self.parse_block_mapping_value
435
+ return self.process_empty_scalar(token.end_mark)
436
+ if not self.check_token(BlockEndToken):
437
+ token = self.peek_token()
438
+ raise ParserError("while parsing a block mapping", self.marks[-1],
439
+ "expected <block end>, but found %r" % token.id, token.start_mark)
440
+ token = self.get_token()
441
+ event = MappingEndEvent(token.start_mark, token.end_mark)
442
+ self.state = self.states.pop()
443
+ self.marks.pop()
444
+ return event
445
+
446
+ def parse_block_mapping_value(self):
447
+ if self.check_token(ValueToken):
448
+ token = self.get_token()
449
+ if not self.check_token(KeyToken, ValueToken, BlockEndToken):
450
+ self.states.append(self.parse_block_mapping_key)
451
+ return self.parse_block_node_or_indentless_sequence()
452
+ else:
453
+ self.state = self.parse_block_mapping_key
454
+ return self.process_empty_scalar(token.end_mark)
455
+ else:
456
+ self.state = self.parse_block_mapping_key
457
+ token = self.peek_token()
458
+ return self.process_empty_scalar(token.start_mark)
459
+
460
+ # flow_sequence ::= FLOW-SEQUENCE-START
461
+ # (flow_sequence_entry FLOW-ENTRY)*
462
+ # flow_sequence_entry?
463
+ # FLOW-SEQUENCE-END
464
+ # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
465
+ #
466
+ # Note that while production rules for both flow_sequence_entry and
467
+ # flow_mapping_entry are equal, their interpretations are different.
468
+ # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?`
469
+ # generate an inline mapping (set syntax).
470
+
471
+ def parse_flow_sequence_first_entry(self):
472
+ token = self.get_token()
473
+ self.marks.append(token.start_mark)
474
+ return self.parse_flow_sequence_entry(first=True)
475
+
476
+ def parse_flow_sequence_entry(self, first=False):
477
+ if not self.check_token(FlowSequenceEndToken):
478
+ if not first:
479
+ if self.check_token(FlowEntryToken):
480
+ self.get_token()
481
+ else:
482
+ token = self.peek_token()
483
+ raise ParserError("while parsing a flow sequence", self.marks[-1],
484
+ "expected ',' or ']', but got %r" % token.id, token.start_mark)
485
+
486
+ if self.check_token(KeyToken):
487
+ token = self.peek_token()
488
+ event = MappingStartEvent(None, None, True,
489
+ token.start_mark, token.end_mark,
490
+ flow_style=True)
491
+ self.state = self.parse_flow_sequence_entry_mapping_key
492
+ return event
493
+ elif not self.check_token(FlowSequenceEndToken):
494
+ self.states.append(self.parse_flow_sequence_entry)
495
+ return self.parse_flow_node()
496
+ token = self.get_token()
497
+ event = SequenceEndEvent(token.start_mark, token.end_mark)
498
+ self.state = self.states.pop()
499
+ self.marks.pop()
500
+ return event
501
+
502
+ def parse_flow_sequence_entry_mapping_key(self):
503
+ token = self.get_token()
504
+ if not self.check_token(ValueToken,
505
+ FlowEntryToken, FlowSequenceEndToken):
506
+ self.states.append(self.parse_flow_sequence_entry_mapping_value)
507
+ return self.parse_flow_node()
508
+ else:
509
+ self.state = self.parse_flow_sequence_entry_mapping_value
510
+ return self.process_empty_scalar(token.end_mark)
511
+
512
+ def parse_flow_sequence_entry_mapping_value(self):
513
+ if self.check_token(ValueToken):
514
+ token = self.get_token()
515
+ if not self.check_token(FlowEntryToken, FlowSequenceEndToken):
516
+ self.states.append(self.parse_flow_sequence_entry_mapping_end)
517
+ return self.parse_flow_node()
518
+ else:
519
+ self.state = self.parse_flow_sequence_entry_mapping_end
520
+ return self.process_empty_scalar(token.end_mark)
521
+ else:
522
+ self.state = self.parse_flow_sequence_entry_mapping_end
523
+ token = self.peek_token()
524
+ return self.process_empty_scalar(token.start_mark)
525
+
526
+ def parse_flow_sequence_entry_mapping_end(self):
527
+ self.state = self.parse_flow_sequence_entry
528
+ token = self.peek_token()
529
+ return MappingEndEvent(token.start_mark, token.start_mark)
530
+
531
+ # flow_mapping ::= FLOW-MAPPING-START
532
+ # (flow_mapping_entry FLOW-ENTRY)*
533
+ # flow_mapping_entry?
534
+ # FLOW-MAPPING-END
535
+ # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
536
+
537
+ def parse_flow_mapping_first_key(self):
538
+ token = self.get_token()
539
+ self.marks.append(token.start_mark)
540
+ return self.parse_flow_mapping_key(first=True)
541
+
542
+ def parse_flow_mapping_key(self, first=False):
543
+ if not self.check_token(FlowMappingEndToken):
544
+ if not first:
545
+ if self.check_token(FlowEntryToken):
546
+ self.get_token()
547
+ else:
548
+ token = self.peek_token()
549
+ raise ParserError("while parsing a flow mapping", self.marks[-1],
550
+ "expected ',' or '}', but got %r" % token.id, token.start_mark)
551
+ if self.check_token(KeyToken):
552
+ token = self.get_token()
553
+ if not self.check_token(ValueToken,
554
+ FlowEntryToken, FlowMappingEndToken):
555
+ self.states.append(self.parse_flow_mapping_value)
556
+ return self.parse_flow_node()
557
+ else:
558
+ self.state = self.parse_flow_mapping_value
559
+ return self.process_empty_scalar(token.end_mark)
560
+ elif not self.check_token(FlowMappingEndToken):
561
+ self.states.append(self.parse_flow_mapping_empty_value)
562
+ return self.parse_flow_node()
563
+ token = self.get_token()
564
+ event = MappingEndEvent(token.start_mark, token.end_mark)
565
+ self.state = self.states.pop()
566
+ self.marks.pop()
567
+ return event
568
+
569
+ def parse_flow_mapping_value(self):
570
+ if self.check_token(ValueToken):
571
+ token = self.get_token()
572
+ if not self.check_token(FlowEntryToken, FlowMappingEndToken):
573
+ self.states.append(self.parse_flow_mapping_key)
574
+ return self.parse_flow_node()
575
+ else:
576
+ self.state = self.parse_flow_mapping_key
577
+ return self.process_empty_scalar(token.end_mark)
578
+ else:
579
+ self.state = self.parse_flow_mapping_key
580
+ token = self.peek_token()
581
+ return self.process_empty_scalar(token.start_mark)
582
+
583
+ def parse_flow_mapping_empty_value(self):
584
+ self.state = self.parse_flow_mapping_key
585
+ return self.process_empty_scalar(self.peek_token().start_mark)
586
+
587
+ def process_empty_scalar(self, mark):
588
+ return ScalarEvent(None, None, (True, False), '', mark, mark)
589
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/reader.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module contains abstractions for the input stream. You don't have to
2
+ # looks further, there are no pretty code.
3
+ #
4
+ # We define two classes here.
5
+ #
6
+ # Mark(source, line, column)
7
+ # It's just a record and its only use is producing nice error messages.
8
+ # Parser does not use it for any other purposes.
9
+ #
10
+ # Reader(source, data)
11
+ # Reader determines the encoding of `data` and converts it to unicode.
12
+ # Reader provides the following methods and attributes:
13
+ # reader.peek(length=1) - return the next `length` characters
14
+ # reader.forward(length=1) - move the current position to `length` characters.
15
+ # reader.index - the number of the current character.
16
+ # reader.line, stream.column - the line and the column of the current character.
17
+
18
+ __all__ = ['Reader', 'ReaderError']
19
+
20
+ from .error import YAMLError, Mark
21
+
22
+ import codecs, re
23
+
24
+ class ReaderError(YAMLError):
25
+
26
+ def __init__(self, name, position, character, encoding, reason):
27
+ self.name = name
28
+ self.character = character
29
+ self.position = position
30
+ self.encoding = encoding
31
+ self.reason = reason
32
+
33
+ def __str__(self):
34
+ if isinstance(self.character, bytes):
35
+ return "'%s' codec can't decode byte #x%02x: %s\n" \
36
+ " in \"%s\", position %d" \
37
+ % (self.encoding, ord(self.character), self.reason,
38
+ self.name, self.position)
39
+ else:
40
+ return "unacceptable character #x%04x: %s\n" \
41
+ " in \"%s\", position %d" \
42
+ % (self.character, self.reason,
43
+ self.name, self.position)
44
+
45
+ class Reader(object):
46
+ # Reader:
47
+ # - determines the data encoding and converts it to a unicode string,
48
+ # - checks if characters are in allowed range,
49
+ # - adds '\0' to the end.
50
+
51
+ # Reader accepts
52
+ # - a `bytes` object,
53
+ # - a `str` object,
54
+ # - a file-like object with its `read` method returning `str`,
55
+ # - a file-like object with its `read` method returning `unicode`.
56
+
57
+ # Yeah, it's ugly and slow.
58
+
59
+ def __init__(self, stream):
60
+ self.name = None
61
+ self.stream = None
62
+ self.stream_pointer = 0
63
+ self.eof = True
64
+ self.buffer = ''
65
+ self.pointer = 0
66
+ self.raw_buffer = None
67
+ self.raw_decode = None
68
+ self.encoding = None
69
+ self.index = 0
70
+ self.line = 0
71
+ self.column = 0
72
+ if isinstance(stream, str):
73
+ self.name = "<unicode string>"
74
+ self.check_printable(stream)
75
+ self.buffer = stream+'\0'
76
+ elif isinstance(stream, bytes):
77
+ self.name = "<byte string>"
78
+ self.raw_buffer = stream
79
+ self.determine_encoding()
80
+ else:
81
+ self.stream = stream
82
+ self.name = getattr(stream, 'name', "<file>")
83
+ self.eof = False
84
+ self.raw_buffer = None
85
+ self.determine_encoding()
86
+
87
+ def peek(self, index=0):
88
+ try:
89
+ return self.buffer[self.pointer+index]
90
+ except IndexError:
91
+ self.update(index+1)
92
+ return self.buffer[self.pointer+index]
93
+
94
+ def prefix(self, length=1):
95
+ if self.pointer+length >= len(self.buffer):
96
+ self.update(length)
97
+ return self.buffer[self.pointer:self.pointer+length]
98
+
99
+ def forward(self, length=1):
100
+ if self.pointer+length+1 >= len(self.buffer):
101
+ self.update(length+1)
102
+ while length:
103
+ ch = self.buffer[self.pointer]
104
+ self.pointer += 1
105
+ self.index += 1
106
+ if ch in '\n\x85\u2028\u2029' \
107
+ or (ch == '\r' and self.buffer[self.pointer] != '\n'):
108
+ self.line += 1
109
+ self.column = 0
110
+ elif ch != '\uFEFF':
111
+ self.column += 1
112
+ length -= 1
113
+
114
+ def get_mark(self):
115
+ if self.stream is None:
116
+ return Mark(self.name, self.index, self.line, self.column,
117
+ self.buffer, self.pointer)
118
+ else:
119
+ return Mark(self.name, self.index, self.line, self.column,
120
+ None, None)
121
+
122
+ def determine_encoding(self):
123
+ while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2):
124
+ self.update_raw()
125
+ if isinstance(self.raw_buffer, bytes):
126
+ if self.raw_buffer.startswith(codecs.BOM_UTF16_LE):
127
+ self.raw_decode = codecs.utf_16_le_decode
128
+ self.encoding = 'utf-16-le'
129
+ elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE):
130
+ self.raw_decode = codecs.utf_16_be_decode
131
+ self.encoding = 'utf-16-be'
132
+ else:
133
+ self.raw_decode = codecs.utf_8_decode
134
+ self.encoding = 'utf-8'
135
+ self.update(1)
136
+
137
+ NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]')
138
+ def check_printable(self, data):
139
+ match = self.NON_PRINTABLE.search(data)
140
+ if match:
141
+ character = match.group()
142
+ position = self.index+(len(self.buffer)-self.pointer)+match.start()
143
+ raise ReaderError(self.name, position, ord(character),
144
+ 'unicode', "special characters are not allowed")
145
+
146
+ def update(self, length):
147
+ if self.raw_buffer is None:
148
+ return
149
+ self.buffer = self.buffer[self.pointer:]
150
+ self.pointer = 0
151
+ while len(self.buffer) < length:
152
+ if not self.eof:
153
+ self.update_raw()
154
+ if self.raw_decode is not None:
155
+ try:
156
+ data, converted = self.raw_decode(self.raw_buffer,
157
+ 'strict', self.eof)
158
+ except UnicodeDecodeError as exc:
159
+ character = self.raw_buffer[exc.start]
160
+ if self.stream is not None:
161
+ position = self.stream_pointer-len(self.raw_buffer)+exc.start
162
+ else:
163
+ position = exc.start
164
+ raise ReaderError(self.name, position, character,
165
+ exc.encoding, exc.reason)
166
+ else:
167
+ data = self.raw_buffer
168
+ converted = len(data)
169
+ self.check_printable(data)
170
+ self.buffer += data
171
+ self.raw_buffer = self.raw_buffer[converted:]
172
+ if self.eof:
173
+ self.buffer += '\0'
174
+ self.raw_buffer = None
175
+ break
176
+
177
+ def update_raw(self, size=4096):
178
+ data = self.stream.read(size)
179
+ if self.raw_buffer is None:
180
+ self.raw_buffer = data
181
+ else:
182
+ self.raw_buffer += data
183
+ self.stream_pointer += len(data)
184
+ if not data:
185
+ self.eof = True
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/representer.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
3
+ 'RepresenterError']
4
+
5
+ from .error import *
6
+ from .nodes import *
7
+
8
+ import datetime, copyreg, types, base64, collections
9
+
10
+ class RepresenterError(YAMLError):
11
+ pass
12
+
13
+ class BaseRepresenter:
14
+
15
+ yaml_representers = {}
16
+ yaml_multi_representers = {}
17
+
18
+ def __init__(self, default_style=None, default_flow_style=False, sort_keys=True):
19
+ self.default_style = default_style
20
+ self.sort_keys = sort_keys
21
+ self.default_flow_style = default_flow_style
22
+ self.represented_objects = {}
23
+ self.object_keeper = []
24
+ self.alias_key = None
25
+
26
+ def represent(self, data):
27
+ node = self.represent_data(data)
28
+ self.serialize(node)
29
+ self.represented_objects = {}
30
+ self.object_keeper = []
31
+ self.alias_key = None
32
+
33
+ def represent_data(self, data):
34
+ if self.ignore_aliases(data):
35
+ self.alias_key = None
36
+ else:
37
+ self.alias_key = id(data)
38
+ if self.alias_key is not None:
39
+ if self.alias_key in self.represented_objects:
40
+ node = self.represented_objects[self.alias_key]
41
+ #if node is None:
42
+ # raise RepresenterError("recursive objects are not allowed: %r" % data)
43
+ return node
44
+ #self.represented_objects[alias_key] = None
45
+ self.object_keeper.append(data)
46
+ data_types = type(data).__mro__
47
+ if data_types[0] in self.yaml_representers:
48
+ node = self.yaml_representers[data_types[0]](self, data)
49
+ else:
50
+ for data_type in data_types:
51
+ if data_type in self.yaml_multi_representers:
52
+ node = self.yaml_multi_representers[data_type](self, data)
53
+ break
54
+ else:
55
+ if None in self.yaml_multi_representers:
56
+ node = self.yaml_multi_representers[None](self, data)
57
+ elif None in self.yaml_representers:
58
+ node = self.yaml_representers[None](self, data)
59
+ else:
60
+ node = ScalarNode(None, str(data))
61
+ #if alias_key is not None:
62
+ # self.represented_objects[alias_key] = node
63
+ return node
64
+
65
+ @classmethod
66
+ def add_representer(cls, data_type, representer):
67
+ if not 'yaml_representers' in cls.__dict__:
68
+ cls.yaml_representers = cls.yaml_representers.copy()
69
+ cls.yaml_representers[data_type] = representer
70
+
71
+ @classmethod
72
+ def add_multi_representer(cls, data_type, representer):
73
+ if not 'yaml_multi_representers' in cls.__dict__:
74
+ cls.yaml_multi_representers = cls.yaml_multi_representers.copy()
75
+ cls.yaml_multi_representers[data_type] = representer
76
+
77
+ def represent_scalar(self, tag, value, style=None):
78
+ if style is None:
79
+ style = self.default_style
80
+ node = ScalarNode(tag, value, style=style)
81
+ if self.alias_key is not None:
82
+ self.represented_objects[self.alias_key] = node
83
+ return node
84
+
85
+ def represent_sequence(self, tag, sequence, flow_style=None):
86
+ value = []
87
+ node = SequenceNode(tag, value, flow_style=flow_style)
88
+ if self.alias_key is not None:
89
+ self.represented_objects[self.alias_key] = node
90
+ best_style = True
91
+ for item in sequence:
92
+ node_item = self.represent_data(item)
93
+ if not (isinstance(node_item, ScalarNode) and not node_item.style):
94
+ best_style = False
95
+ value.append(node_item)
96
+ if flow_style is None:
97
+ if self.default_flow_style is not None:
98
+ node.flow_style = self.default_flow_style
99
+ else:
100
+ node.flow_style = best_style
101
+ return node
102
+
103
+ def represent_mapping(self, tag, mapping, flow_style=None):
104
+ value = []
105
+ node = MappingNode(tag, value, flow_style=flow_style)
106
+ if self.alias_key is not None:
107
+ self.represented_objects[self.alias_key] = node
108
+ best_style = True
109
+ if hasattr(mapping, 'items'):
110
+ mapping = list(mapping.items())
111
+ if self.sort_keys:
112
+ try:
113
+ mapping = sorted(mapping)
114
+ except TypeError:
115
+ pass
116
+ for item_key, item_value in mapping:
117
+ node_key = self.represent_data(item_key)
118
+ node_value = self.represent_data(item_value)
119
+ if not (isinstance(node_key, ScalarNode) and not node_key.style):
120
+ best_style = False
121
+ if not (isinstance(node_value, ScalarNode) and not node_value.style):
122
+ best_style = False
123
+ value.append((node_key, node_value))
124
+ if flow_style is None:
125
+ if self.default_flow_style is not None:
126
+ node.flow_style = self.default_flow_style
127
+ else:
128
+ node.flow_style = best_style
129
+ return node
130
+
131
+ def ignore_aliases(self, data):
132
+ return False
133
+
134
+ class SafeRepresenter(BaseRepresenter):
135
+
136
+ def ignore_aliases(self, data):
137
+ if data is None:
138
+ return True
139
+ if isinstance(data, tuple) and data == ():
140
+ return True
141
+ if isinstance(data, (str, bytes, bool, int, float)):
142
+ return True
143
+
144
+ def represent_none(self, data):
145
+ return self.represent_scalar('tag:yaml.org,2002:null', 'null')
146
+
147
+ def represent_str(self, data):
148
+ return self.represent_scalar('tag:yaml.org,2002:str', data)
149
+
150
+ def represent_binary(self, data):
151
+ if hasattr(base64, 'encodebytes'):
152
+ data = base64.encodebytes(data).decode('ascii')
153
+ else:
154
+ data = base64.encodestring(data).decode('ascii')
155
+ return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|')
156
+
157
+ def represent_bool(self, data):
158
+ if data:
159
+ value = 'true'
160
+ else:
161
+ value = 'false'
162
+ return self.represent_scalar('tag:yaml.org,2002:bool', value)
163
+
164
+ def represent_int(self, data):
165
+ return self.represent_scalar('tag:yaml.org,2002:int', str(data))
166
+
167
+ inf_value = 1e300
168
+ while repr(inf_value) != repr(inf_value*inf_value):
169
+ inf_value *= inf_value
170
+
171
+ def represent_float(self, data):
172
+ if data != data or (data == 0.0 and data == 1.0):
173
+ value = '.nan'
174
+ elif data == self.inf_value:
175
+ value = '.inf'
176
+ elif data == -self.inf_value:
177
+ value = '-.inf'
178
+ else:
179
+ value = repr(data).lower()
180
+ # Note that in some cases `repr(data)` represents a float number
181
+ # without the decimal parts. For instance:
182
+ # >>> repr(1e17)
183
+ # '1e17'
184
+ # Unfortunately, this is not a valid float representation according
185
+ # to the definition of the `!!float` tag. We fix this by adding
186
+ # '.0' before the 'e' symbol.
187
+ if '.' not in value and 'e' in value:
188
+ value = value.replace('e', '.0e', 1)
189
+ return self.represent_scalar('tag:yaml.org,2002:float', value)
190
+
191
+ def represent_list(self, data):
192
+ #pairs = (len(data) > 0 and isinstance(data, list))
193
+ #if pairs:
194
+ # for item in data:
195
+ # if not isinstance(item, tuple) or len(item) != 2:
196
+ # pairs = False
197
+ # break
198
+ #if not pairs:
199
+ return self.represent_sequence('tag:yaml.org,2002:seq', data)
200
+ #value = []
201
+ #for item_key, item_value in data:
202
+ # value.append(self.represent_mapping(u'tag:yaml.org,2002:map',
203
+ # [(item_key, item_value)]))
204
+ #return SequenceNode(u'tag:yaml.org,2002:pairs', value)
205
+
206
+ def represent_dict(self, data):
207
+ return self.represent_mapping('tag:yaml.org,2002:map', data)
208
+
209
+ def represent_set(self, data):
210
+ value = {}
211
+ for key in data:
212
+ value[key] = None
213
+ return self.represent_mapping('tag:yaml.org,2002:set', value)
214
+
215
+ def represent_date(self, data):
216
+ value = data.isoformat()
217
+ return self.represent_scalar('tag:yaml.org,2002:timestamp', value)
218
+
219
+ def represent_datetime(self, data):
220
+ value = data.isoformat(' ')
221
+ return self.represent_scalar('tag:yaml.org,2002:timestamp', value)
222
+
223
+ def represent_yaml_object(self, tag, data, cls, flow_style=None):
224
+ if hasattr(data, '__getstate__'):
225
+ state = data.__getstate__()
226
+ else:
227
+ state = data.__dict__.copy()
228
+ return self.represent_mapping(tag, state, flow_style=flow_style)
229
+
230
+ def represent_undefined(self, data):
231
+ raise RepresenterError("cannot represent an object", data)
232
+
233
+ SafeRepresenter.add_representer(type(None),
234
+ SafeRepresenter.represent_none)
235
+
236
+ SafeRepresenter.add_representer(str,
237
+ SafeRepresenter.represent_str)
238
+
239
+ SafeRepresenter.add_representer(bytes,
240
+ SafeRepresenter.represent_binary)
241
+
242
+ SafeRepresenter.add_representer(bool,
243
+ SafeRepresenter.represent_bool)
244
+
245
+ SafeRepresenter.add_representer(int,
246
+ SafeRepresenter.represent_int)
247
+
248
+ SafeRepresenter.add_representer(float,
249
+ SafeRepresenter.represent_float)
250
+
251
+ SafeRepresenter.add_representer(list,
252
+ SafeRepresenter.represent_list)
253
+
254
+ SafeRepresenter.add_representer(tuple,
255
+ SafeRepresenter.represent_list)
256
+
257
+ SafeRepresenter.add_representer(dict,
258
+ SafeRepresenter.represent_dict)
259
+
260
+ SafeRepresenter.add_representer(set,
261
+ SafeRepresenter.represent_set)
262
+
263
+ SafeRepresenter.add_representer(datetime.date,
264
+ SafeRepresenter.represent_date)
265
+
266
+ SafeRepresenter.add_representer(datetime.datetime,
267
+ SafeRepresenter.represent_datetime)
268
+
269
+ SafeRepresenter.add_representer(None,
270
+ SafeRepresenter.represent_undefined)
271
+
272
+ class Representer(SafeRepresenter):
273
+
274
+ def represent_complex(self, data):
275
+ if data.imag == 0.0:
276
+ data = '%r' % data.real
277
+ elif data.real == 0.0:
278
+ data = '%rj' % data.imag
279
+ elif data.imag > 0:
280
+ data = '%r+%rj' % (data.real, data.imag)
281
+ else:
282
+ data = '%r%rj' % (data.real, data.imag)
283
+ return self.represent_scalar('tag:yaml.org,2002:python/complex', data)
284
+
285
+ def represent_tuple(self, data):
286
+ return self.represent_sequence('tag:yaml.org,2002:python/tuple', data)
287
+
288
+ def represent_name(self, data):
289
+ name = '%s.%s' % (data.__module__, data.__name__)
290
+ return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '')
291
+
292
+ def represent_module(self, data):
293
+ return self.represent_scalar(
294
+ 'tag:yaml.org,2002:python/module:'+data.__name__, '')
295
+
296
+ def represent_object(self, data):
297
+ # We use __reduce__ API to save the data. data.__reduce__ returns
298
+ # a tuple of length 2-5:
299
+ # (function, args, state, listitems, dictitems)
300
+
301
+ # For reconstructing, we calls function(*args), then set its state,
302
+ # listitems, and dictitems if they are not None.
303
+
304
+ # A special case is when function.__name__ == '__newobj__'. In this
305
+ # case we create the object with args[0].__new__(*args).
306
+
307
+ # Another special case is when __reduce__ returns a string - we don't
308
+ # support it.
309
+
310
+ # We produce a !!python/object, !!python/object/new or
311
+ # !!python/object/apply node.
312
+
313
+ cls = type(data)
314
+ if cls in copyreg.dispatch_table:
315
+ reduce = copyreg.dispatch_table[cls](data)
316
+ elif hasattr(data, '__reduce_ex__'):
317
+ reduce = data.__reduce_ex__(2)
318
+ elif hasattr(data, '__reduce__'):
319
+ reduce = data.__reduce__()
320
+ else:
321
+ raise RepresenterError("cannot represent an object", data)
322
+ reduce = (list(reduce)+[None]*5)[:5]
323
+ function, args, state, listitems, dictitems = reduce
324
+ args = list(args)
325
+ if state is None:
326
+ state = {}
327
+ if listitems is not None:
328
+ listitems = list(listitems)
329
+ if dictitems is not None:
330
+ dictitems = dict(dictitems)
331
+ if function.__name__ == '__newobj__':
332
+ function = args[0]
333
+ args = args[1:]
334
+ tag = 'tag:yaml.org,2002:python/object/new:'
335
+ newobj = True
336
+ else:
337
+ tag = 'tag:yaml.org,2002:python/object/apply:'
338
+ newobj = False
339
+ function_name = '%s.%s' % (function.__module__, function.__name__)
340
+ if not args and not listitems and not dictitems \
341
+ and isinstance(state, dict) and newobj:
342
+ return self.represent_mapping(
343
+ 'tag:yaml.org,2002:python/object:'+function_name, state)
344
+ if not listitems and not dictitems \
345
+ and isinstance(state, dict) and not state:
346
+ return self.represent_sequence(tag+function_name, args)
347
+ value = {}
348
+ if args:
349
+ value['args'] = args
350
+ if state or not isinstance(state, dict):
351
+ value['state'] = state
352
+ if listitems:
353
+ value['listitems'] = listitems
354
+ if dictitems:
355
+ value['dictitems'] = dictitems
356
+ return self.represent_mapping(tag+function_name, value)
357
+
358
+ def represent_ordered_dict(self, data):
359
+ # Provide uniform representation across different Python versions.
360
+ data_type = type(data)
361
+ tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \
362
+ % (data_type.__module__, data_type.__name__)
363
+ items = [[key, value] for key, value in data.items()]
364
+ return self.represent_sequence(tag, [items])
365
+
366
+ Representer.add_representer(complex,
367
+ Representer.represent_complex)
368
+
369
+ Representer.add_representer(tuple,
370
+ Representer.represent_tuple)
371
+
372
+ Representer.add_multi_representer(type,
373
+ Representer.represent_name)
374
+
375
+ Representer.add_representer(collections.OrderedDict,
376
+ Representer.represent_ordered_dict)
377
+
378
+ Representer.add_representer(types.FunctionType,
379
+ Representer.represent_name)
380
+
381
+ Representer.add_representer(types.BuiltinFunctionType,
382
+ Representer.represent_name)
383
+
384
+ Representer.add_representer(types.ModuleType,
385
+ Representer.represent_module)
386
+
387
+ Representer.add_multi_representer(object,
388
+ Representer.represent_object)
389
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/resolver.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['BaseResolver', 'Resolver']
3
+
4
+ from .error import *
5
+ from .nodes import *
6
+
7
+ import re
8
+
9
+ class ResolverError(YAMLError):
10
+ pass
11
+
12
+ class BaseResolver:
13
+
14
+ DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'
15
+ DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'
16
+ DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'
17
+
18
+ yaml_implicit_resolvers = {}
19
+ yaml_path_resolvers = {}
20
+
21
+ def __init__(self):
22
+ self.resolver_exact_paths = []
23
+ self.resolver_prefix_paths = []
24
+
25
+ @classmethod
26
+ def add_implicit_resolver(cls, tag, regexp, first):
27
+ if not 'yaml_implicit_resolvers' in cls.__dict__:
28
+ implicit_resolvers = {}
29
+ for key in cls.yaml_implicit_resolvers:
30
+ implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
31
+ cls.yaml_implicit_resolvers = implicit_resolvers
32
+ if first is None:
33
+ first = [None]
34
+ for ch in first:
35
+ cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp))
36
+
37
+ @classmethod
38
+ def add_path_resolver(cls, tag, path, kind=None):
39
+ # Note: `add_path_resolver` is experimental. The API could be changed.
40
+ # `new_path` is a pattern that is matched against the path from the
41
+ # root to the node that is being considered. `node_path` elements are
42
+ # tuples `(node_check, index_check)`. `node_check` is a node class:
43
+ # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None`
44
+ # matches any kind of a node. `index_check` could be `None`, a boolean
45
+ # value, a string value, or a number. `None` and `False` match against
46
+ # any _value_ of sequence and mapping nodes. `True` matches against
47
+ # any _key_ of a mapping node. A string `index_check` matches against
48
+ # a mapping value that corresponds to a scalar key which content is
49
+ # equal to the `index_check` value. An integer `index_check` matches
50
+ # against a sequence value with the index equal to `index_check`.
51
+ if not 'yaml_path_resolvers' in cls.__dict__:
52
+ cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy()
53
+ new_path = []
54
+ for element in path:
55
+ if isinstance(element, (list, tuple)):
56
+ if len(element) == 2:
57
+ node_check, index_check = element
58
+ elif len(element) == 1:
59
+ node_check = element[0]
60
+ index_check = True
61
+ else:
62
+ raise ResolverError("Invalid path element: %s" % element)
63
+ else:
64
+ node_check = None
65
+ index_check = element
66
+ if node_check is str:
67
+ node_check = ScalarNode
68
+ elif node_check is list:
69
+ node_check = SequenceNode
70
+ elif node_check is dict:
71
+ node_check = MappingNode
72
+ elif node_check not in [ScalarNode, SequenceNode, MappingNode] \
73
+ and not isinstance(node_check, str) \
74
+ and node_check is not None:
75
+ raise ResolverError("Invalid node checker: %s" % node_check)
76
+ if not isinstance(index_check, (str, int)) \
77
+ and index_check is not None:
78
+ raise ResolverError("Invalid index checker: %s" % index_check)
79
+ new_path.append((node_check, index_check))
80
+ if kind is str:
81
+ kind = ScalarNode
82
+ elif kind is list:
83
+ kind = SequenceNode
84
+ elif kind is dict:
85
+ kind = MappingNode
86
+ elif kind not in [ScalarNode, SequenceNode, MappingNode] \
87
+ and kind is not None:
88
+ raise ResolverError("Invalid node kind: %s" % kind)
89
+ cls.yaml_path_resolvers[tuple(new_path), kind] = tag
90
+
91
+ def descend_resolver(self, current_node, current_index):
92
+ if not self.yaml_path_resolvers:
93
+ return
94
+ exact_paths = {}
95
+ prefix_paths = []
96
+ if current_node:
97
+ depth = len(self.resolver_prefix_paths)
98
+ for path, kind in self.resolver_prefix_paths[-1]:
99
+ if self.check_resolver_prefix(depth, path, kind,
100
+ current_node, current_index):
101
+ if len(path) > depth:
102
+ prefix_paths.append((path, kind))
103
+ else:
104
+ exact_paths[kind] = self.yaml_path_resolvers[path, kind]
105
+ else:
106
+ for path, kind in self.yaml_path_resolvers:
107
+ if not path:
108
+ exact_paths[kind] = self.yaml_path_resolvers[path, kind]
109
+ else:
110
+ prefix_paths.append((path, kind))
111
+ self.resolver_exact_paths.append(exact_paths)
112
+ self.resolver_prefix_paths.append(prefix_paths)
113
+
114
+ def ascend_resolver(self):
115
+ if not self.yaml_path_resolvers:
116
+ return
117
+ self.resolver_exact_paths.pop()
118
+ self.resolver_prefix_paths.pop()
119
+
120
+ def check_resolver_prefix(self, depth, path, kind,
121
+ current_node, current_index):
122
+ node_check, index_check = path[depth-1]
123
+ if isinstance(node_check, str):
124
+ if current_node.tag != node_check:
125
+ return
126
+ elif node_check is not None:
127
+ if not isinstance(current_node, node_check):
128
+ return
129
+ if index_check is True and current_index is not None:
130
+ return
131
+ if (index_check is False or index_check is None) \
132
+ and current_index is None:
133
+ return
134
+ if isinstance(index_check, str):
135
+ if not (isinstance(current_index, ScalarNode)
136
+ and index_check == current_index.value):
137
+ return
138
+ elif isinstance(index_check, int) and not isinstance(index_check, bool):
139
+ if index_check != current_index:
140
+ return
141
+ return True
142
+
143
+ def resolve(self, kind, value, implicit):
144
+ if kind is ScalarNode and implicit[0]:
145
+ if value == '':
146
+ resolvers = self.yaml_implicit_resolvers.get('', [])
147
+ else:
148
+ resolvers = self.yaml_implicit_resolvers.get(value[0], [])
149
+ wildcard_resolvers = self.yaml_implicit_resolvers.get(None, [])
150
+ for tag, regexp in resolvers + wildcard_resolvers:
151
+ if regexp.match(value):
152
+ return tag
153
+ implicit = implicit[1]
154
+ if self.yaml_path_resolvers:
155
+ exact_paths = self.resolver_exact_paths[-1]
156
+ if kind in exact_paths:
157
+ return exact_paths[kind]
158
+ if None in exact_paths:
159
+ return exact_paths[None]
160
+ if kind is ScalarNode:
161
+ return self.DEFAULT_SCALAR_TAG
162
+ elif kind is SequenceNode:
163
+ return self.DEFAULT_SEQUENCE_TAG
164
+ elif kind is MappingNode:
165
+ return self.DEFAULT_MAPPING_TAG
166
+
167
+ class Resolver(BaseResolver):
168
+ pass
169
+
170
+ Resolver.add_implicit_resolver(
171
+ 'tag:yaml.org,2002:bool',
172
+ re.compile(r'''^(?:yes|Yes|YES|no|No|NO
173
+ |true|True|TRUE|false|False|FALSE
174
+ |on|On|ON|off|Off|OFF)$''', re.X),
175
+ list('yYnNtTfFoO'))
176
+
177
+ Resolver.add_implicit_resolver(
178
+ 'tag:yaml.org,2002:float',
179
+ re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
180
+ |\.[0-9][0-9_]*(?:[eE][-+][0-9]+)?
181
+ |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
182
+ |[-+]?\.(?:inf|Inf|INF)
183
+ |\.(?:nan|NaN|NAN))$''', re.X),
184
+ list('-+0123456789.'))
185
+
186
+ Resolver.add_implicit_resolver(
187
+ 'tag:yaml.org,2002:int',
188
+ re.compile(r'''^(?:[-+]?0b[0-1_]+
189
+ |[-+]?0[0-7_]+
190
+ |[-+]?(?:0|[1-9][0-9_]*)
191
+ |[-+]?0x[0-9a-fA-F_]+
192
+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X),
193
+ list('-+0123456789'))
194
+
195
+ Resolver.add_implicit_resolver(
196
+ 'tag:yaml.org,2002:merge',
197
+ re.compile(r'^(?:<<)$'),
198
+ ['<'])
199
+
200
+ Resolver.add_implicit_resolver(
201
+ 'tag:yaml.org,2002:null',
202
+ re.compile(r'''^(?: ~
203
+ |null|Null|NULL
204
+ | )$''', re.X),
205
+ ['~', 'n', 'N', ''])
206
+
207
+ Resolver.add_implicit_resolver(
208
+ 'tag:yaml.org,2002:timestamp',
209
+ re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
210
+ |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]?
211
+ (?:[Tt]|[ \t]+)[0-9][0-9]?
212
+ :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)?
213
+ (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X),
214
+ list('0123456789'))
215
+
216
+ Resolver.add_implicit_resolver(
217
+ 'tag:yaml.org,2002:value',
218
+ re.compile(r'^(?:=)$'),
219
+ ['='])
220
+
221
+ # The following resolver is only for documentation purposes. It cannot work
222
+ # because plain scalars cannot start with '!', '&', or '*'.
223
+ Resolver.add_implicit_resolver(
224
+ 'tag:yaml.org,2002:yaml',
225
+ re.compile(r'^(?:!|&|\*)$'),
226
+ list('!&*'))
227
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/scanner.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Scanner produces tokens of the following types:
3
+ # STREAM-START
4
+ # STREAM-END
5
+ # DIRECTIVE(name, value)
6
+ # DOCUMENT-START
7
+ # DOCUMENT-END
8
+ # BLOCK-SEQUENCE-START
9
+ # BLOCK-MAPPING-START
10
+ # BLOCK-END
11
+ # FLOW-SEQUENCE-START
12
+ # FLOW-MAPPING-START
13
+ # FLOW-SEQUENCE-END
14
+ # FLOW-MAPPING-END
15
+ # BLOCK-ENTRY
16
+ # FLOW-ENTRY
17
+ # KEY
18
+ # VALUE
19
+ # ALIAS(value)
20
+ # ANCHOR(value)
21
+ # TAG(value)
22
+ # SCALAR(value, plain, style)
23
+ #
24
+ # Read comments in the Scanner code for more details.
25
+ #
26
+
27
+ __all__ = ['Scanner', 'ScannerError']
28
+
29
+ from .error import MarkedYAMLError
30
+ from .tokens import *
31
+
32
+ class ScannerError(MarkedYAMLError):
33
+ pass
34
+
35
+ class SimpleKey:
36
+ # See below simple keys treatment.
37
+
38
+ def __init__(self, token_number, required, index, line, column, mark):
39
+ self.token_number = token_number
40
+ self.required = required
41
+ self.index = index
42
+ self.line = line
43
+ self.column = column
44
+ self.mark = mark
45
+
46
+ class Scanner:
47
+
48
+ def __init__(self):
49
+ """Initialize the scanner."""
50
+ # It is assumed that Scanner and Reader will have a common descendant.
51
+ # Reader do the dirty work of checking for BOM and converting the
52
+ # input data to Unicode. It also adds NUL to the end.
53
+ #
54
+ # Reader supports the following methods
55
+ # self.peek(i=0) # peek the next i-th character
56
+ # self.prefix(l=1) # peek the next l characters
57
+ # self.forward(l=1) # read the next l characters and move the pointer.
58
+
59
+ # Had we reached the end of the stream?
60
+ self.done = False
61
+
62
+ # The number of unclosed '{' and '['. `flow_level == 0` means block
63
+ # context.
64
+ self.flow_level = 0
65
+
66
+ # List of processed tokens that are not yet emitted.
67
+ self.tokens = []
68
+
69
+ # Add the STREAM-START token.
70
+ self.fetch_stream_start()
71
+
72
+ # Number of tokens that were emitted through the `get_token` method.
73
+ self.tokens_taken = 0
74
+
75
+ # The current indentation level.
76
+ self.indent = -1
77
+
78
+ # Past indentation levels.
79
+ self.indents = []
80
+
81
+ # Variables related to simple keys treatment.
82
+
83
+ # A simple key is a key that is not denoted by the '?' indicator.
84
+ # Example of simple keys:
85
+ # ---
86
+ # block simple key: value
87
+ # ? not a simple key:
88
+ # : { flow simple key: value }
89
+ # We emit the KEY token before all keys, so when we find a potential
90
+ # simple key, we try to locate the corresponding ':' indicator.
91
+ # Simple keys should be limited to a single line and 1024 characters.
92
+
93
+ # Can a simple key start at the current position? A simple key may
94
+ # start:
95
+ # - at the beginning of the line, not counting indentation spaces
96
+ # (in block context),
97
+ # - after '{', '[', ',' (in the flow context),
98
+ # - after '?', ':', '-' (in the block context).
99
+ # In the block context, this flag also signifies if a block collection
100
+ # may start at the current position.
101
+ self.allow_simple_key = True
102
+
103
+ # Keep track of possible simple keys. This is a dictionary. The key
104
+ # is `flow_level`; there can be no more that one possible simple key
105
+ # for each level. The value is a SimpleKey record:
106
+ # (token_number, required, index, line, column, mark)
107
+ # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow),
108
+ # '[', or '{' tokens.
109
+ self.possible_simple_keys = {}
110
+
111
+ # Public methods.
112
+
113
+ def check_token(self, *choices):
114
+ # Check if the next token is one of the given types.
115
+ while self.need_more_tokens():
116
+ self.fetch_more_tokens()
117
+ if self.tokens:
118
+ if not choices:
119
+ return True
120
+ for choice in choices:
121
+ if isinstance(self.tokens[0], choice):
122
+ return True
123
+ return False
124
+
125
+ def peek_token(self):
126
+ # Return the next token, but do not delete if from the queue.
127
+ # Return None if no more tokens.
128
+ while self.need_more_tokens():
129
+ self.fetch_more_tokens()
130
+ if self.tokens:
131
+ return self.tokens[0]
132
+ else:
133
+ return None
134
+
135
+ def get_token(self):
136
+ # Return the next token.
137
+ while self.need_more_tokens():
138
+ self.fetch_more_tokens()
139
+ if self.tokens:
140
+ self.tokens_taken += 1
141
+ return self.tokens.pop(0)
142
+
143
+ # Private methods.
144
+
145
+ def need_more_tokens(self):
146
+ if self.done:
147
+ return False
148
+ if not self.tokens:
149
+ return True
150
+ # The current token may be a potential simple key, so we
151
+ # need to look further.
152
+ self.stale_possible_simple_keys()
153
+ if self.next_possible_simple_key() == self.tokens_taken:
154
+ return True
155
+
156
+ def fetch_more_tokens(self):
157
+
158
+ # Eat whitespaces and comments until we reach the next token.
159
+ self.scan_to_next_token()
160
+
161
+ # Remove obsolete possible simple keys.
162
+ self.stale_possible_simple_keys()
163
+
164
+ # Compare the current indentation and column. It may add some tokens
165
+ # and decrease the current indentation level.
166
+ self.unwind_indent(self.column)
167
+
168
+ # Peek the next character.
169
+ ch = self.peek()
170
+
171
+ # Is it the end of stream?
172
+ if ch == '\0':
173
+ return self.fetch_stream_end()
174
+
175
+ # Is it a directive?
176
+ if ch == '%' and self.check_directive():
177
+ return self.fetch_directive()
178
+
179
+ # Is it the document start?
180
+ if ch == '-' and self.check_document_start():
181
+ return self.fetch_document_start()
182
+
183
+ # Is it the document end?
184
+ if ch == '.' and self.check_document_end():
185
+ return self.fetch_document_end()
186
+
187
+ # TODO: support for BOM within a stream.
188
+ #if ch == '\uFEFF':
189
+ # return self.fetch_bom() <-- issue BOMToken
190
+
191
+ # Note: the order of the following checks is NOT significant.
192
+
193
+ # Is it the flow sequence start indicator?
194
+ if ch == '[':
195
+ return self.fetch_flow_sequence_start()
196
+
197
+ # Is it the flow mapping start indicator?
198
+ if ch == '{':
199
+ return self.fetch_flow_mapping_start()
200
+
201
+ # Is it the flow sequence end indicator?
202
+ if ch == ']':
203
+ return self.fetch_flow_sequence_end()
204
+
205
+ # Is it the flow mapping end indicator?
206
+ if ch == '}':
207
+ return self.fetch_flow_mapping_end()
208
+
209
+ # Is it the flow entry indicator?
210
+ if ch == ',':
211
+ return self.fetch_flow_entry()
212
+
213
+ # Is it the block entry indicator?
214
+ if ch == '-' and self.check_block_entry():
215
+ return self.fetch_block_entry()
216
+
217
+ # Is it the key indicator?
218
+ if ch == '?' and self.check_key():
219
+ return self.fetch_key()
220
+
221
+ # Is it the value indicator?
222
+ if ch == ':' and self.check_value():
223
+ return self.fetch_value()
224
+
225
+ # Is it an alias?
226
+ if ch == '*':
227
+ return self.fetch_alias()
228
+
229
+ # Is it an anchor?
230
+ if ch == '&':
231
+ return self.fetch_anchor()
232
+
233
+ # Is it a tag?
234
+ if ch == '!':
235
+ return self.fetch_tag()
236
+
237
+ # Is it a literal scalar?
238
+ if ch == '|' and not self.flow_level:
239
+ return self.fetch_literal()
240
+
241
+ # Is it a folded scalar?
242
+ if ch == '>' and not self.flow_level:
243
+ return self.fetch_folded()
244
+
245
+ # Is it a single quoted scalar?
246
+ if ch == '\'':
247
+ return self.fetch_single()
248
+
249
+ # Is it a double quoted scalar?
250
+ if ch == '\"':
251
+ return self.fetch_double()
252
+
253
+ # It must be a plain scalar then.
254
+ if self.check_plain():
255
+ return self.fetch_plain()
256
+
257
+ # No? It's an error. Let's produce a nice error message.
258
+ raise ScannerError("while scanning for the next token", None,
259
+ "found character %r that cannot start any token" % ch,
260
+ self.get_mark())
261
+
262
+ # Simple keys treatment.
263
+
264
+ def next_possible_simple_key(self):
265
+ # Return the number of the nearest possible simple key. Actually we
266
+ # don't need to loop through the whole dictionary. We may replace it
267
+ # with the following code:
268
+ # if not self.possible_simple_keys:
269
+ # return None
270
+ # return self.possible_simple_keys[
271
+ # min(self.possible_simple_keys.keys())].token_number
272
+ min_token_number = None
273
+ for level in self.possible_simple_keys:
274
+ key = self.possible_simple_keys[level]
275
+ if min_token_number is None or key.token_number < min_token_number:
276
+ min_token_number = key.token_number
277
+ return min_token_number
278
+
279
+ def stale_possible_simple_keys(self):
280
+ # Remove entries that are no longer possible simple keys. According to
281
+ # the YAML specification, simple keys
282
+ # - should be limited to a single line,
283
+ # - should be no longer than 1024 characters.
284
+ # Disabling this procedure will allow simple keys of any length and
285
+ # height (may cause problems if indentation is broken though).
286
+ for level in list(self.possible_simple_keys):
287
+ key = self.possible_simple_keys[level]
288
+ if key.line != self.line \
289
+ or self.index-key.index > 1024:
290
+ if key.required:
291
+ raise ScannerError("while scanning a simple key", key.mark,
292
+ "could not find expected ':'", self.get_mark())
293
+ del self.possible_simple_keys[level]
294
+
295
+ def save_possible_simple_key(self):
296
+ # The next token may start a simple key. We check if it's possible
297
+ # and save its position. This function is called for
298
+ # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
299
+
300
+ # Check if a simple key is required at the current position.
301
+ required = not self.flow_level and self.indent == self.column
302
+
303
+ # The next token might be a simple key. Let's save it's number and
304
+ # position.
305
+ if self.allow_simple_key:
306
+ self.remove_possible_simple_key()
307
+ token_number = self.tokens_taken+len(self.tokens)
308
+ key = SimpleKey(token_number, required,
309
+ self.index, self.line, self.column, self.get_mark())
310
+ self.possible_simple_keys[self.flow_level] = key
311
+
312
+ def remove_possible_simple_key(self):
313
+ # Remove the saved possible key position at the current flow level.
314
+ if self.flow_level in self.possible_simple_keys:
315
+ key = self.possible_simple_keys[self.flow_level]
316
+
317
+ if key.required:
318
+ raise ScannerError("while scanning a simple key", key.mark,
319
+ "could not find expected ':'", self.get_mark())
320
+
321
+ del self.possible_simple_keys[self.flow_level]
322
+
323
+ # Indentation functions.
324
+
325
+ def unwind_indent(self, column):
326
+
327
+ ## In flow context, tokens should respect indentation.
328
+ ## Actually the condition should be `self.indent >= column` according to
329
+ ## the spec. But this condition will prohibit intuitively correct
330
+ ## constructions such as
331
+ ## key : {
332
+ ## }
333
+ #if self.flow_level and self.indent > column:
334
+ # raise ScannerError(None, None,
335
+ # "invalid indentation or unclosed '[' or '{'",
336
+ # self.get_mark())
337
+
338
+ # In the flow context, indentation is ignored. We make the scanner less
339
+ # restrictive then specification requires.
340
+ if self.flow_level:
341
+ return
342
+
343
+ # In block context, we may need to issue the BLOCK-END tokens.
344
+ while self.indent > column:
345
+ mark = self.get_mark()
346
+ self.indent = self.indents.pop()
347
+ self.tokens.append(BlockEndToken(mark, mark))
348
+
349
+ def add_indent(self, column):
350
+ # Check if we need to increase indentation.
351
+ if self.indent < column:
352
+ self.indents.append(self.indent)
353
+ self.indent = column
354
+ return True
355
+ return False
356
+
357
+ # Fetchers.
358
+
359
+ def fetch_stream_start(self):
360
+ # We always add STREAM-START as the first token and STREAM-END as the
361
+ # last token.
362
+
363
+ # Read the token.
364
+ mark = self.get_mark()
365
+
366
+ # Add STREAM-START.
367
+ self.tokens.append(StreamStartToken(mark, mark,
368
+ encoding=self.encoding))
369
+
370
+
371
+ def fetch_stream_end(self):
372
+
373
+ # Set the current indentation to -1.
374
+ self.unwind_indent(-1)
375
+
376
+ # Reset simple keys.
377
+ self.remove_possible_simple_key()
378
+ self.allow_simple_key = False
379
+ self.possible_simple_keys = {}
380
+
381
+ # Read the token.
382
+ mark = self.get_mark()
383
+
384
+ # Add STREAM-END.
385
+ self.tokens.append(StreamEndToken(mark, mark))
386
+
387
+ # The steam is finished.
388
+ self.done = True
389
+
390
+ def fetch_directive(self):
391
+
392
+ # Set the current indentation to -1.
393
+ self.unwind_indent(-1)
394
+
395
+ # Reset simple keys.
396
+ self.remove_possible_simple_key()
397
+ self.allow_simple_key = False
398
+
399
+ # Scan and add DIRECTIVE.
400
+ self.tokens.append(self.scan_directive())
401
+
402
+ def fetch_document_start(self):
403
+ self.fetch_document_indicator(DocumentStartToken)
404
+
405
+ def fetch_document_end(self):
406
+ self.fetch_document_indicator(DocumentEndToken)
407
+
408
+ def fetch_document_indicator(self, TokenClass):
409
+
410
+ # Set the current indentation to -1.
411
+ self.unwind_indent(-1)
412
+
413
+ # Reset simple keys. Note that there could not be a block collection
414
+ # after '---'.
415
+ self.remove_possible_simple_key()
416
+ self.allow_simple_key = False
417
+
418
+ # Add DOCUMENT-START or DOCUMENT-END.
419
+ start_mark = self.get_mark()
420
+ self.forward(3)
421
+ end_mark = self.get_mark()
422
+ self.tokens.append(TokenClass(start_mark, end_mark))
423
+
424
+ def fetch_flow_sequence_start(self):
425
+ self.fetch_flow_collection_start(FlowSequenceStartToken)
426
+
427
+ def fetch_flow_mapping_start(self):
428
+ self.fetch_flow_collection_start(FlowMappingStartToken)
429
+
430
+ def fetch_flow_collection_start(self, TokenClass):
431
+
432
+ # '[' and '{' may start a simple key.
433
+ self.save_possible_simple_key()
434
+
435
+ # Increase the flow level.
436
+ self.flow_level += 1
437
+
438
+ # Simple keys are allowed after '[' and '{'.
439
+ self.allow_simple_key = True
440
+
441
+ # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
442
+ start_mark = self.get_mark()
443
+ self.forward()
444
+ end_mark = self.get_mark()
445
+ self.tokens.append(TokenClass(start_mark, end_mark))
446
+
447
+ def fetch_flow_sequence_end(self):
448
+ self.fetch_flow_collection_end(FlowSequenceEndToken)
449
+
450
+ def fetch_flow_mapping_end(self):
451
+ self.fetch_flow_collection_end(FlowMappingEndToken)
452
+
453
+ def fetch_flow_collection_end(self, TokenClass):
454
+
455
+ # Reset possible simple key on the current level.
456
+ self.remove_possible_simple_key()
457
+
458
+ # Decrease the flow level.
459
+ self.flow_level -= 1
460
+
461
+ # No simple keys after ']' or '}'.
462
+ self.allow_simple_key = False
463
+
464
+ # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
465
+ start_mark = self.get_mark()
466
+ self.forward()
467
+ end_mark = self.get_mark()
468
+ self.tokens.append(TokenClass(start_mark, end_mark))
469
+
470
+ def fetch_flow_entry(self):
471
+
472
+ # Simple keys are allowed after ','.
473
+ self.allow_simple_key = True
474
+
475
+ # Reset possible simple key on the current level.
476
+ self.remove_possible_simple_key()
477
+
478
+ # Add FLOW-ENTRY.
479
+ start_mark = self.get_mark()
480
+ self.forward()
481
+ end_mark = self.get_mark()
482
+ self.tokens.append(FlowEntryToken(start_mark, end_mark))
483
+
484
+ def fetch_block_entry(self):
485
+
486
+ # Block context needs additional checks.
487
+ if not self.flow_level:
488
+
489
+ # Are we allowed to start a new entry?
490
+ if not self.allow_simple_key:
491
+ raise ScannerError(None, None,
492
+ "sequence entries are not allowed here",
493
+ self.get_mark())
494
+
495
+ # We may need to add BLOCK-SEQUENCE-START.
496
+ if self.add_indent(self.column):
497
+ mark = self.get_mark()
498
+ self.tokens.append(BlockSequenceStartToken(mark, mark))
499
+
500
+ # It's an error for the block entry to occur in the flow context,
501
+ # but we let the parser detect this.
502
+ else:
503
+ pass
504
+
505
+ # Simple keys are allowed after '-'.
506
+ self.allow_simple_key = True
507
+
508
+ # Reset possible simple key on the current level.
509
+ self.remove_possible_simple_key()
510
+
511
+ # Add BLOCK-ENTRY.
512
+ start_mark = self.get_mark()
513
+ self.forward()
514
+ end_mark = self.get_mark()
515
+ self.tokens.append(BlockEntryToken(start_mark, end_mark))
516
+
517
+ def fetch_key(self):
518
+
519
+ # Block context needs additional checks.
520
+ if not self.flow_level:
521
+
522
+ # Are we allowed to start a key (not necessary a simple)?
523
+ if not self.allow_simple_key:
524
+ raise ScannerError(None, None,
525
+ "mapping keys are not allowed here",
526
+ self.get_mark())
527
+
528
+ # We may need to add BLOCK-MAPPING-START.
529
+ if self.add_indent(self.column):
530
+ mark = self.get_mark()
531
+ self.tokens.append(BlockMappingStartToken(mark, mark))
532
+
533
+ # Simple keys are allowed after '?' in the block context.
534
+ self.allow_simple_key = not self.flow_level
535
+
536
+ # Reset possible simple key on the current level.
537
+ self.remove_possible_simple_key()
538
+
539
+ # Add KEY.
540
+ start_mark = self.get_mark()
541
+ self.forward()
542
+ end_mark = self.get_mark()
543
+ self.tokens.append(KeyToken(start_mark, end_mark))
544
+
545
+ def fetch_value(self):
546
+
547
+ # Do we determine a simple key?
548
+ if self.flow_level in self.possible_simple_keys:
549
+
550
+ # Add KEY.
551
+ key = self.possible_simple_keys[self.flow_level]
552
+ del self.possible_simple_keys[self.flow_level]
553
+ self.tokens.insert(key.token_number-self.tokens_taken,
554
+ KeyToken(key.mark, key.mark))
555
+
556
+ # If this key starts a new block mapping, we need to add
557
+ # BLOCK-MAPPING-START.
558
+ if not self.flow_level:
559
+ if self.add_indent(key.column):
560
+ self.tokens.insert(key.token_number-self.tokens_taken,
561
+ BlockMappingStartToken(key.mark, key.mark))
562
+
563
+ # There cannot be two simple keys one after another.
564
+ self.allow_simple_key = False
565
+
566
+ # It must be a part of a complex key.
567
+ else:
568
+
569
+ # Block context needs additional checks.
570
+ # (Do we really need them? They will be caught by the parser
571
+ # anyway.)
572
+ if not self.flow_level:
573
+
574
+ # We are allowed to start a complex value if and only if
575
+ # we can start a simple key.
576
+ if not self.allow_simple_key:
577
+ raise ScannerError(None, None,
578
+ "mapping values are not allowed here",
579
+ self.get_mark())
580
+
581
+ # If this value starts a new block mapping, we need to add
582
+ # BLOCK-MAPPING-START. It will be detected as an error later by
583
+ # the parser.
584
+ if not self.flow_level:
585
+ if self.add_indent(self.column):
586
+ mark = self.get_mark()
587
+ self.tokens.append(BlockMappingStartToken(mark, mark))
588
+
589
+ # Simple keys are allowed after ':' in the block context.
590
+ self.allow_simple_key = not self.flow_level
591
+
592
+ # Reset possible simple key on the current level.
593
+ self.remove_possible_simple_key()
594
+
595
+ # Add VALUE.
596
+ start_mark = self.get_mark()
597
+ self.forward()
598
+ end_mark = self.get_mark()
599
+ self.tokens.append(ValueToken(start_mark, end_mark))
600
+
601
+ def fetch_alias(self):
602
+
603
+ # ALIAS could be a simple key.
604
+ self.save_possible_simple_key()
605
+
606
+ # No simple keys after ALIAS.
607
+ self.allow_simple_key = False
608
+
609
+ # Scan and add ALIAS.
610
+ self.tokens.append(self.scan_anchor(AliasToken))
611
+
612
+ def fetch_anchor(self):
613
+
614
+ # ANCHOR could start a simple key.
615
+ self.save_possible_simple_key()
616
+
617
+ # No simple keys after ANCHOR.
618
+ self.allow_simple_key = False
619
+
620
+ # Scan and add ANCHOR.
621
+ self.tokens.append(self.scan_anchor(AnchorToken))
622
+
623
+ def fetch_tag(self):
624
+
625
+ # TAG could start a simple key.
626
+ self.save_possible_simple_key()
627
+
628
+ # No simple keys after TAG.
629
+ self.allow_simple_key = False
630
+
631
+ # Scan and add TAG.
632
+ self.tokens.append(self.scan_tag())
633
+
634
+ def fetch_literal(self):
635
+ self.fetch_block_scalar(style='|')
636
+
637
+ def fetch_folded(self):
638
+ self.fetch_block_scalar(style='>')
639
+
640
+ def fetch_block_scalar(self, style):
641
+
642
+ # A simple key may follow a block scalar.
643
+ self.allow_simple_key = True
644
+
645
+ # Reset possible simple key on the current level.
646
+ self.remove_possible_simple_key()
647
+
648
+ # Scan and add SCALAR.
649
+ self.tokens.append(self.scan_block_scalar(style))
650
+
651
+ def fetch_single(self):
652
+ self.fetch_flow_scalar(style='\'')
653
+
654
+ def fetch_double(self):
655
+ self.fetch_flow_scalar(style='"')
656
+
657
+ def fetch_flow_scalar(self, style):
658
+
659
+ # A flow scalar could be a simple key.
660
+ self.save_possible_simple_key()
661
+
662
+ # No simple keys after flow scalars.
663
+ self.allow_simple_key = False
664
+
665
+ # Scan and add SCALAR.
666
+ self.tokens.append(self.scan_flow_scalar(style))
667
+
668
+ def fetch_plain(self):
669
+
670
+ # A plain scalar could be a simple key.
671
+ self.save_possible_simple_key()
672
+
673
+ # No simple keys after plain scalars. But note that `scan_plain` will
674
+ # change this flag if the scan is finished at the beginning of the
675
+ # line.
676
+ self.allow_simple_key = False
677
+
678
+ # Scan and add SCALAR. May change `allow_simple_key`.
679
+ self.tokens.append(self.scan_plain())
680
+
681
+ # Checkers.
682
+
683
+ def check_directive(self):
684
+
685
+ # DIRECTIVE: ^ '%' ...
686
+ # The '%' indicator is already checked.
687
+ if self.column == 0:
688
+ return True
689
+
690
+ def check_document_start(self):
691
+
692
+ # DOCUMENT-START: ^ '---' (' '|'\n')
693
+ if self.column == 0:
694
+ if self.prefix(3) == '---' \
695
+ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
696
+ return True
697
+
698
+ def check_document_end(self):
699
+
700
+ # DOCUMENT-END: ^ '...' (' '|'\n')
701
+ if self.column == 0:
702
+ if self.prefix(3) == '...' \
703
+ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
704
+ return True
705
+
706
+ def check_block_entry(self):
707
+
708
+ # BLOCK-ENTRY: '-' (' '|'\n')
709
+ return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
710
+
711
+ def check_key(self):
712
+
713
+ # KEY(flow context): '?'
714
+ if self.flow_level:
715
+ return True
716
+
717
+ # KEY(block context): '?' (' '|'\n')
718
+ else:
719
+ return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
720
+
721
+ def check_value(self):
722
+
723
+ # VALUE(flow context): ':'
724
+ if self.flow_level:
725
+ return True
726
+
727
+ # VALUE(block context): ':' (' '|'\n')
728
+ else:
729
+ return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029'
730
+
731
+ def check_plain(self):
732
+
733
+ # A plain scalar may start with any non-space character except:
734
+ # '-', '?', ':', ',', '[', ']', '{', '}',
735
+ # '#', '&', '*', '!', '|', '>', '\'', '\"',
736
+ # '%', '@', '`'.
737
+ #
738
+ # It may also start with
739
+ # '-', '?', ':'
740
+ # if it is followed by a non-space character.
741
+ #
742
+ # Note that we limit the last rule to the block context (except the
743
+ # '-' character) because we want the flow context to be space
744
+ # independent.
745
+ ch = self.peek()
746
+ return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \
747
+ or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029'
748
+ and (ch == '-' or (not self.flow_level and ch in '?:')))
749
+
750
+ # Scanners.
751
+
752
+ def scan_to_next_token(self):
753
+ # We ignore spaces, line breaks and comments.
754
+ # If we find a line break in the block context, we set the flag
755
+ # `allow_simple_key` on.
756
+ # The byte order mark is stripped if it's the first character in the
757
+ # stream. We do not yet support BOM inside the stream as the
758
+ # specification requires. Any such mark will be considered as a part
759
+ # of the document.
760
+ #
761
+ # TODO: We need to make tab handling rules more sane. A good rule is
762
+ # Tabs cannot precede tokens
763
+ # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
764
+ # KEY(block), VALUE(block), BLOCK-ENTRY
765
+ # So the checking code is
766
+ # if <TAB>:
767
+ # self.allow_simple_keys = False
768
+ # We also need to add the check for `allow_simple_keys == True` to
769
+ # `unwind_indent` before issuing BLOCK-END.
770
+ # Scanners for block, flow, and plain scalars need to be modified.
771
+
772
+ if self.index == 0 and self.peek() == '\uFEFF':
773
+ self.forward()
774
+ found = False
775
+ while not found:
776
+ while self.peek() == ' ':
777
+ self.forward()
778
+ if self.peek() == '#':
779
+ while self.peek() not in '\0\r\n\x85\u2028\u2029':
780
+ self.forward()
781
+ if self.scan_line_break():
782
+ if not self.flow_level:
783
+ self.allow_simple_key = True
784
+ else:
785
+ found = True
786
+
787
+ def scan_directive(self):
788
+ # See the specification for details.
789
+ start_mark = self.get_mark()
790
+ self.forward()
791
+ name = self.scan_directive_name(start_mark)
792
+ value = None
793
+ if name == 'YAML':
794
+ value = self.scan_yaml_directive_value(start_mark)
795
+ end_mark = self.get_mark()
796
+ elif name == 'TAG':
797
+ value = self.scan_tag_directive_value(start_mark)
798
+ end_mark = self.get_mark()
799
+ else:
800
+ end_mark = self.get_mark()
801
+ while self.peek() not in '\0\r\n\x85\u2028\u2029':
802
+ self.forward()
803
+ self.scan_directive_ignored_line(start_mark)
804
+ return DirectiveToken(name, value, start_mark, end_mark)
805
+
806
+ def scan_directive_name(self, start_mark):
807
+ # See the specification for details.
808
+ length = 0
809
+ ch = self.peek(length)
810
+ while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
811
+ or ch in '-_':
812
+ length += 1
813
+ ch = self.peek(length)
814
+ if not length:
815
+ raise ScannerError("while scanning a directive", start_mark,
816
+ "expected alphabetic or numeric character, but found %r"
817
+ % ch, self.get_mark())
818
+ value = self.prefix(length)
819
+ self.forward(length)
820
+ ch = self.peek()
821
+ if ch not in '\0 \r\n\x85\u2028\u2029':
822
+ raise ScannerError("while scanning a directive", start_mark,
823
+ "expected alphabetic or numeric character, but found %r"
824
+ % ch, self.get_mark())
825
+ return value
826
+
827
+ def scan_yaml_directive_value(self, start_mark):
828
+ # See the specification for details.
829
+ while self.peek() == ' ':
830
+ self.forward()
831
+ major = self.scan_yaml_directive_number(start_mark)
832
+ if self.peek() != '.':
833
+ raise ScannerError("while scanning a directive", start_mark,
834
+ "expected a digit or '.', but found %r" % self.peek(),
835
+ self.get_mark())
836
+ self.forward()
837
+ minor = self.scan_yaml_directive_number(start_mark)
838
+ if self.peek() not in '\0 \r\n\x85\u2028\u2029':
839
+ raise ScannerError("while scanning a directive", start_mark,
840
+ "expected a digit or ' ', but found %r" % self.peek(),
841
+ self.get_mark())
842
+ return (major, minor)
843
+
844
+ def scan_yaml_directive_number(self, start_mark):
845
+ # See the specification for details.
846
+ ch = self.peek()
847
+ if not ('0' <= ch <= '9'):
848
+ raise ScannerError("while scanning a directive", start_mark,
849
+ "expected a digit, but found %r" % ch, self.get_mark())
850
+ length = 0
851
+ while '0' <= self.peek(length) <= '9':
852
+ length += 1
853
+ value = int(self.prefix(length))
854
+ self.forward(length)
855
+ return value
856
+
857
+ def scan_tag_directive_value(self, start_mark):
858
+ # See the specification for details.
859
+ while self.peek() == ' ':
860
+ self.forward()
861
+ handle = self.scan_tag_directive_handle(start_mark)
862
+ while self.peek() == ' ':
863
+ self.forward()
864
+ prefix = self.scan_tag_directive_prefix(start_mark)
865
+ return (handle, prefix)
866
+
867
+ def scan_tag_directive_handle(self, start_mark):
868
+ # See the specification for details.
869
+ value = self.scan_tag_handle('directive', start_mark)
870
+ ch = self.peek()
871
+ if ch != ' ':
872
+ raise ScannerError("while scanning a directive", start_mark,
873
+ "expected ' ', but found %r" % ch, self.get_mark())
874
+ return value
875
+
876
+ def scan_tag_directive_prefix(self, start_mark):
877
+ # See the specification for details.
878
+ value = self.scan_tag_uri('directive', start_mark)
879
+ ch = self.peek()
880
+ if ch not in '\0 \r\n\x85\u2028\u2029':
881
+ raise ScannerError("while scanning a directive", start_mark,
882
+ "expected ' ', but found %r" % ch, self.get_mark())
883
+ return value
884
+
885
+ def scan_directive_ignored_line(self, start_mark):
886
+ # See the specification for details.
887
+ while self.peek() == ' ':
888
+ self.forward()
889
+ if self.peek() == '#':
890
+ while self.peek() not in '\0\r\n\x85\u2028\u2029':
891
+ self.forward()
892
+ ch = self.peek()
893
+ if ch not in '\0\r\n\x85\u2028\u2029':
894
+ raise ScannerError("while scanning a directive", start_mark,
895
+ "expected a comment or a line break, but found %r"
896
+ % ch, self.get_mark())
897
+ self.scan_line_break()
898
+
899
+ def scan_anchor(self, TokenClass):
900
+ # The specification does not restrict characters for anchors and
901
+ # aliases. This may lead to problems, for instance, the document:
902
+ # [ *alias, value ]
903
+ # can be interpreted in two ways, as
904
+ # [ "value" ]
905
+ # and
906
+ # [ *alias , "value" ]
907
+ # Therefore we restrict aliases to numbers and ASCII letters.
908
+ start_mark = self.get_mark()
909
+ indicator = self.peek()
910
+ if indicator == '*':
911
+ name = 'alias'
912
+ else:
913
+ name = 'anchor'
914
+ self.forward()
915
+ length = 0
916
+ ch = self.peek(length)
917
+ while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
918
+ or ch in '-_':
919
+ length += 1
920
+ ch = self.peek(length)
921
+ if not length:
922
+ raise ScannerError("while scanning an %s" % name, start_mark,
923
+ "expected alphabetic or numeric character, but found %r"
924
+ % ch, self.get_mark())
925
+ value = self.prefix(length)
926
+ self.forward(length)
927
+ ch = self.peek()
928
+ if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`':
929
+ raise ScannerError("while scanning an %s" % name, start_mark,
930
+ "expected alphabetic or numeric character, but found %r"
931
+ % ch, self.get_mark())
932
+ end_mark = self.get_mark()
933
+ return TokenClass(value, start_mark, end_mark)
934
+
935
+ def scan_tag(self):
936
+ # See the specification for details.
937
+ start_mark = self.get_mark()
938
+ ch = self.peek(1)
939
+ if ch == '<':
940
+ handle = None
941
+ self.forward(2)
942
+ suffix = self.scan_tag_uri('tag', start_mark)
943
+ if self.peek() != '>':
944
+ raise ScannerError("while parsing a tag", start_mark,
945
+ "expected '>', but found %r" % self.peek(),
946
+ self.get_mark())
947
+ self.forward()
948
+ elif ch in '\0 \t\r\n\x85\u2028\u2029':
949
+ handle = None
950
+ suffix = '!'
951
+ self.forward()
952
+ else:
953
+ length = 1
954
+ use_handle = False
955
+ while ch not in '\0 \r\n\x85\u2028\u2029':
956
+ if ch == '!':
957
+ use_handle = True
958
+ break
959
+ length += 1
960
+ ch = self.peek(length)
961
+ handle = '!'
962
+ if use_handle:
963
+ handle = self.scan_tag_handle('tag', start_mark)
964
+ else:
965
+ handle = '!'
966
+ self.forward()
967
+ suffix = self.scan_tag_uri('tag', start_mark)
968
+ ch = self.peek()
969
+ if ch not in '\0 \r\n\x85\u2028\u2029':
970
+ raise ScannerError("while scanning a tag", start_mark,
971
+ "expected ' ', but found %r" % ch, self.get_mark())
972
+ value = (handle, suffix)
973
+ end_mark = self.get_mark()
974
+ return TagToken(value, start_mark, end_mark)
975
+
976
+ def scan_block_scalar(self, style):
977
+ # See the specification for details.
978
+
979
+ if style == '>':
980
+ folded = True
981
+ else:
982
+ folded = False
983
+
984
+ chunks = []
985
+ start_mark = self.get_mark()
986
+
987
+ # Scan the header.
988
+ self.forward()
989
+ chomping, increment = self.scan_block_scalar_indicators(start_mark)
990
+ self.scan_block_scalar_ignored_line(start_mark)
991
+
992
+ # Determine the indentation level and go to the first non-empty line.
993
+ min_indent = self.indent+1
994
+ if min_indent < 1:
995
+ min_indent = 1
996
+ if increment is None:
997
+ breaks, max_indent, end_mark = self.scan_block_scalar_indentation()
998
+ indent = max(min_indent, max_indent)
999
+ else:
1000
+ indent = min_indent+increment-1
1001
+ breaks, end_mark = self.scan_block_scalar_breaks(indent)
1002
+ line_break = ''
1003
+
1004
+ # Scan the inner part of the block scalar.
1005
+ while self.column == indent and self.peek() != '\0':
1006
+ chunks.extend(breaks)
1007
+ leading_non_space = self.peek() not in ' \t'
1008
+ length = 0
1009
+ while self.peek(length) not in '\0\r\n\x85\u2028\u2029':
1010
+ length += 1
1011
+ chunks.append(self.prefix(length))
1012
+ self.forward(length)
1013
+ line_break = self.scan_line_break()
1014
+ breaks, end_mark = self.scan_block_scalar_breaks(indent)
1015
+ if self.column == indent and self.peek() != '\0':
1016
+
1017
+ # Unfortunately, folding rules are ambiguous.
1018
+ #
1019
+ # This is the folding according to the specification:
1020
+
1021
+ if folded and line_break == '\n' \
1022
+ and leading_non_space and self.peek() not in ' \t':
1023
+ if not breaks:
1024
+ chunks.append(' ')
1025
+ else:
1026
+ chunks.append(line_break)
1027
+
1028
+ # This is Clark Evans's interpretation (also in the spec
1029
+ # examples):
1030
+ #
1031
+ #if folded and line_break == '\n':
1032
+ # if not breaks:
1033
+ # if self.peek() not in ' \t':
1034
+ # chunks.append(' ')
1035
+ # else:
1036
+ # chunks.append(line_break)
1037
+ #else:
1038
+ # chunks.append(line_break)
1039
+ else:
1040
+ break
1041
+
1042
+ # Chomp the tail.
1043
+ if chomping is not False:
1044
+ chunks.append(line_break)
1045
+ if chomping is True:
1046
+ chunks.extend(breaks)
1047
+
1048
+ # We are done.
1049
+ return ScalarToken(''.join(chunks), False, start_mark, end_mark,
1050
+ style)
1051
+
1052
+ def scan_block_scalar_indicators(self, start_mark):
1053
+ # See the specification for details.
1054
+ chomping = None
1055
+ increment = None
1056
+ ch = self.peek()
1057
+ if ch in '+-':
1058
+ if ch == '+':
1059
+ chomping = True
1060
+ else:
1061
+ chomping = False
1062
+ self.forward()
1063
+ ch = self.peek()
1064
+ if ch in '0123456789':
1065
+ increment = int(ch)
1066
+ if increment == 0:
1067
+ raise ScannerError("while scanning a block scalar", start_mark,
1068
+ "expected indentation indicator in the range 1-9, but found 0",
1069
+ self.get_mark())
1070
+ self.forward()
1071
+ elif ch in '0123456789':
1072
+ increment = int(ch)
1073
+ if increment == 0:
1074
+ raise ScannerError("while scanning a block scalar", start_mark,
1075
+ "expected indentation indicator in the range 1-9, but found 0",
1076
+ self.get_mark())
1077
+ self.forward()
1078
+ ch = self.peek()
1079
+ if ch in '+-':
1080
+ if ch == '+':
1081
+ chomping = True
1082
+ else:
1083
+ chomping = False
1084
+ self.forward()
1085
+ ch = self.peek()
1086
+ if ch not in '\0 \r\n\x85\u2028\u2029':
1087
+ raise ScannerError("while scanning a block scalar", start_mark,
1088
+ "expected chomping or indentation indicators, but found %r"
1089
+ % ch, self.get_mark())
1090
+ return chomping, increment
1091
+
1092
+ def scan_block_scalar_ignored_line(self, start_mark):
1093
+ # See the specification for details.
1094
+ while self.peek() == ' ':
1095
+ self.forward()
1096
+ if self.peek() == '#':
1097
+ while self.peek() not in '\0\r\n\x85\u2028\u2029':
1098
+ self.forward()
1099
+ ch = self.peek()
1100
+ if ch not in '\0\r\n\x85\u2028\u2029':
1101
+ raise ScannerError("while scanning a block scalar", start_mark,
1102
+ "expected a comment or a line break, but found %r" % ch,
1103
+ self.get_mark())
1104
+ self.scan_line_break()
1105
+
1106
+ def scan_block_scalar_indentation(self):
1107
+ # See the specification for details.
1108
+ chunks = []
1109
+ max_indent = 0
1110
+ end_mark = self.get_mark()
1111
+ while self.peek() in ' \r\n\x85\u2028\u2029':
1112
+ if self.peek() != ' ':
1113
+ chunks.append(self.scan_line_break())
1114
+ end_mark = self.get_mark()
1115
+ else:
1116
+ self.forward()
1117
+ if self.column > max_indent:
1118
+ max_indent = self.column
1119
+ return chunks, max_indent, end_mark
1120
+
1121
+ def scan_block_scalar_breaks(self, indent):
1122
+ # See the specification for details.
1123
+ chunks = []
1124
+ end_mark = self.get_mark()
1125
+ while self.column < indent and self.peek() == ' ':
1126
+ self.forward()
1127
+ while self.peek() in '\r\n\x85\u2028\u2029':
1128
+ chunks.append(self.scan_line_break())
1129
+ end_mark = self.get_mark()
1130
+ while self.column < indent and self.peek() == ' ':
1131
+ self.forward()
1132
+ return chunks, end_mark
1133
+
1134
+ def scan_flow_scalar(self, style):
1135
+ # See the specification for details.
1136
+ # Note that we loose indentation rules for quoted scalars. Quoted
1137
+ # scalars don't need to adhere indentation because " and ' clearly
1138
+ # mark the beginning and the end of them. Therefore we are less
1139
+ # restrictive then the specification requires. We only need to check
1140
+ # that document separators are not included in scalars.
1141
+ if style == '"':
1142
+ double = True
1143
+ else:
1144
+ double = False
1145
+ chunks = []
1146
+ start_mark = self.get_mark()
1147
+ quote = self.peek()
1148
+ self.forward()
1149
+ chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
1150
+ while self.peek() != quote:
1151
+ chunks.extend(self.scan_flow_scalar_spaces(double, start_mark))
1152
+ chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark))
1153
+ self.forward()
1154
+ end_mark = self.get_mark()
1155
+ return ScalarToken(''.join(chunks), False, start_mark, end_mark,
1156
+ style)
1157
+
1158
+ ESCAPE_REPLACEMENTS = {
1159
+ '0': '\0',
1160
+ 'a': '\x07',
1161
+ 'b': '\x08',
1162
+ 't': '\x09',
1163
+ '\t': '\x09',
1164
+ 'n': '\x0A',
1165
+ 'v': '\x0B',
1166
+ 'f': '\x0C',
1167
+ 'r': '\x0D',
1168
+ 'e': '\x1B',
1169
+ ' ': '\x20',
1170
+ '\"': '\"',
1171
+ '\\': '\\',
1172
+ '/': '/',
1173
+ 'N': '\x85',
1174
+ '_': '\xA0',
1175
+ 'L': '\u2028',
1176
+ 'P': '\u2029',
1177
+ }
1178
+
1179
+ ESCAPE_CODES = {
1180
+ 'x': 2,
1181
+ 'u': 4,
1182
+ 'U': 8,
1183
+ }
1184
+
1185
+ def scan_flow_scalar_non_spaces(self, double, start_mark):
1186
+ # See the specification for details.
1187
+ chunks = []
1188
+ while True:
1189
+ length = 0
1190
+ while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029':
1191
+ length += 1
1192
+ if length:
1193
+ chunks.append(self.prefix(length))
1194
+ self.forward(length)
1195
+ ch = self.peek()
1196
+ if not double and ch == '\'' and self.peek(1) == '\'':
1197
+ chunks.append('\'')
1198
+ self.forward(2)
1199
+ elif (double and ch == '\'') or (not double and ch in '\"\\'):
1200
+ chunks.append(ch)
1201
+ self.forward()
1202
+ elif double and ch == '\\':
1203
+ self.forward()
1204
+ ch = self.peek()
1205
+ if ch in self.ESCAPE_REPLACEMENTS:
1206
+ chunks.append(self.ESCAPE_REPLACEMENTS[ch])
1207
+ self.forward()
1208
+ elif ch in self.ESCAPE_CODES:
1209
+ length = self.ESCAPE_CODES[ch]
1210
+ self.forward()
1211
+ for k in range(length):
1212
+ if self.peek(k) not in '0123456789ABCDEFabcdef':
1213
+ raise ScannerError("while scanning a double-quoted scalar", start_mark,
1214
+ "expected escape sequence of %d hexadecimal numbers, but found %r" %
1215
+ (length, self.peek(k)), self.get_mark())
1216
+ code = int(self.prefix(length), 16)
1217
+ chunks.append(chr(code))
1218
+ self.forward(length)
1219
+ elif ch in '\r\n\x85\u2028\u2029':
1220
+ self.scan_line_break()
1221
+ chunks.extend(self.scan_flow_scalar_breaks(double, start_mark))
1222
+ else:
1223
+ raise ScannerError("while scanning a double-quoted scalar", start_mark,
1224
+ "found unknown escape character %r" % ch, self.get_mark())
1225
+ else:
1226
+ return chunks
1227
+
1228
+ def scan_flow_scalar_spaces(self, double, start_mark):
1229
+ # See the specification for details.
1230
+ chunks = []
1231
+ length = 0
1232
+ while self.peek(length) in ' \t':
1233
+ length += 1
1234
+ whitespaces = self.prefix(length)
1235
+ self.forward(length)
1236
+ ch = self.peek()
1237
+ if ch == '\0':
1238
+ raise ScannerError("while scanning a quoted scalar", start_mark,
1239
+ "found unexpected end of stream", self.get_mark())
1240
+ elif ch in '\r\n\x85\u2028\u2029':
1241
+ line_break = self.scan_line_break()
1242
+ breaks = self.scan_flow_scalar_breaks(double, start_mark)
1243
+ if line_break != '\n':
1244
+ chunks.append(line_break)
1245
+ elif not breaks:
1246
+ chunks.append(' ')
1247
+ chunks.extend(breaks)
1248
+ else:
1249
+ chunks.append(whitespaces)
1250
+ return chunks
1251
+
1252
+ def scan_flow_scalar_breaks(self, double, start_mark):
1253
+ # See the specification for details.
1254
+ chunks = []
1255
+ while True:
1256
+ # Instead of checking indentation, we check for document
1257
+ # separators.
1258
+ prefix = self.prefix(3)
1259
+ if (prefix == '---' or prefix == '...') \
1260
+ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
1261
+ raise ScannerError("while scanning a quoted scalar", start_mark,
1262
+ "found unexpected document separator", self.get_mark())
1263
+ while self.peek() in ' \t':
1264
+ self.forward()
1265
+ if self.peek() in '\r\n\x85\u2028\u2029':
1266
+ chunks.append(self.scan_line_break())
1267
+ else:
1268
+ return chunks
1269
+
1270
+ def scan_plain(self):
1271
+ # See the specification for details.
1272
+ # We add an additional restriction for the flow context:
1273
+ # plain scalars in the flow context cannot contain ',' or '?'.
1274
+ # We also keep track of the `allow_simple_key` flag here.
1275
+ # Indentation rules are loosed for the flow context.
1276
+ chunks = []
1277
+ start_mark = self.get_mark()
1278
+ end_mark = start_mark
1279
+ indent = self.indent+1
1280
+ # We allow zero indentation for scalars, but then we need to check for
1281
+ # document separators at the beginning of the line.
1282
+ #if indent == 0:
1283
+ # indent = 1
1284
+ spaces = []
1285
+ while True:
1286
+ length = 0
1287
+ if self.peek() == '#':
1288
+ break
1289
+ while True:
1290
+ ch = self.peek(length)
1291
+ if ch in '\0 \t\r\n\x85\u2028\u2029' \
1292
+ or (ch == ':' and
1293
+ self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029'
1294
+ + (u',[]{}' if self.flow_level else u''))\
1295
+ or (self.flow_level and ch in ',?[]{}'):
1296
+ break
1297
+ length += 1
1298
+ if length == 0:
1299
+ break
1300
+ self.allow_simple_key = False
1301
+ chunks.extend(spaces)
1302
+ chunks.append(self.prefix(length))
1303
+ self.forward(length)
1304
+ end_mark = self.get_mark()
1305
+ spaces = self.scan_plain_spaces(indent, start_mark)
1306
+ if not spaces or self.peek() == '#' \
1307
+ or (not self.flow_level and self.column < indent):
1308
+ break
1309
+ return ScalarToken(''.join(chunks), True, start_mark, end_mark)
1310
+
1311
+ def scan_plain_spaces(self, indent, start_mark):
1312
+ # See the specification for details.
1313
+ # The specification is really confusing about tabs in plain scalars.
1314
+ # We just forbid them completely. Do not use tabs in YAML!
1315
+ chunks = []
1316
+ length = 0
1317
+ while self.peek(length) in ' ':
1318
+ length += 1
1319
+ whitespaces = self.prefix(length)
1320
+ self.forward(length)
1321
+ ch = self.peek()
1322
+ if ch in '\r\n\x85\u2028\u2029':
1323
+ line_break = self.scan_line_break()
1324
+ self.allow_simple_key = True
1325
+ prefix = self.prefix(3)
1326
+ if (prefix == '---' or prefix == '...') \
1327
+ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
1328
+ return
1329
+ breaks = []
1330
+ while self.peek() in ' \r\n\x85\u2028\u2029':
1331
+ if self.peek() == ' ':
1332
+ self.forward()
1333
+ else:
1334
+ breaks.append(self.scan_line_break())
1335
+ prefix = self.prefix(3)
1336
+ if (prefix == '---' or prefix == '...') \
1337
+ and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029':
1338
+ return
1339
+ if line_break != '\n':
1340
+ chunks.append(line_break)
1341
+ elif not breaks:
1342
+ chunks.append(' ')
1343
+ chunks.extend(breaks)
1344
+ elif whitespaces:
1345
+ chunks.append(whitespaces)
1346
+ return chunks
1347
+
1348
+ def scan_tag_handle(self, name, start_mark):
1349
+ # See the specification for details.
1350
+ # For some strange reasons, the specification does not allow '_' in
1351
+ # tag handles. I have allowed it anyway.
1352
+ ch = self.peek()
1353
+ if ch != '!':
1354
+ raise ScannerError("while scanning a %s" % name, start_mark,
1355
+ "expected '!', but found %r" % ch, self.get_mark())
1356
+ length = 1
1357
+ ch = self.peek(length)
1358
+ if ch != ' ':
1359
+ while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
1360
+ or ch in '-_':
1361
+ length += 1
1362
+ ch = self.peek(length)
1363
+ if ch != '!':
1364
+ self.forward(length)
1365
+ raise ScannerError("while scanning a %s" % name, start_mark,
1366
+ "expected '!', but found %r" % ch, self.get_mark())
1367
+ length += 1
1368
+ value = self.prefix(length)
1369
+ self.forward(length)
1370
+ return value
1371
+
1372
+ def scan_tag_uri(self, name, start_mark):
1373
+ # See the specification for details.
1374
+ # Note: we do not check if URI is well-formed.
1375
+ chunks = []
1376
+ length = 0
1377
+ ch = self.peek(length)
1378
+ while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \
1379
+ or ch in '-;/?:@&=+$,_.!~*\'()[]%':
1380
+ if ch == '%':
1381
+ chunks.append(self.prefix(length))
1382
+ self.forward(length)
1383
+ length = 0
1384
+ chunks.append(self.scan_uri_escapes(name, start_mark))
1385
+ else:
1386
+ length += 1
1387
+ ch = self.peek(length)
1388
+ if length:
1389
+ chunks.append(self.prefix(length))
1390
+ self.forward(length)
1391
+ length = 0
1392
+ if not chunks:
1393
+ raise ScannerError("while parsing a %s" % name, start_mark,
1394
+ "expected URI, but found %r" % ch, self.get_mark())
1395
+ return ''.join(chunks)
1396
+
1397
+ def scan_uri_escapes(self, name, start_mark):
1398
+ # See the specification for details.
1399
+ codes = []
1400
+ mark = self.get_mark()
1401
+ while self.peek() == '%':
1402
+ self.forward()
1403
+ for k in range(2):
1404
+ if self.peek(k) not in '0123456789ABCDEFabcdef':
1405
+ raise ScannerError("while scanning a %s" % name, start_mark,
1406
+ "expected URI escape sequence of 2 hexadecimal numbers, but found %r"
1407
+ % self.peek(k), self.get_mark())
1408
+ codes.append(int(self.prefix(2), 16))
1409
+ self.forward(2)
1410
+ try:
1411
+ value = bytes(codes).decode('utf-8')
1412
+ except UnicodeDecodeError as exc:
1413
+ raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark)
1414
+ return value
1415
+
1416
+ def scan_line_break(self):
1417
+ # Transforms:
1418
+ # '\r\n' : '\n'
1419
+ # '\r' : '\n'
1420
+ # '\n' : '\n'
1421
+ # '\x85' : '\n'
1422
+ # '\u2028' : '\u2028'
1423
+ # '\u2029 : '\u2029'
1424
+ # default : ''
1425
+ ch = self.peek()
1426
+ if ch in '\r\n\x85':
1427
+ if self.prefix(2) == '\r\n':
1428
+ self.forward(2)
1429
+ else:
1430
+ self.forward()
1431
+ return '\n'
1432
+ elif ch in '\u2028\u2029':
1433
+ self.forward()
1434
+ return ch
1435
+ return ''
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/serializer.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ __all__ = ['Serializer', 'SerializerError']
3
+
4
+ from .error import YAMLError
5
+ from .events import *
6
+ from .nodes import *
7
+
8
+ class SerializerError(YAMLError):
9
+ pass
10
+
11
+ class Serializer:
12
+
13
+ ANCHOR_TEMPLATE = 'id%03d'
14
+
15
+ def __init__(self, encoding=None,
16
+ explicit_start=None, explicit_end=None, version=None, tags=None):
17
+ self.use_encoding = encoding
18
+ self.use_explicit_start = explicit_start
19
+ self.use_explicit_end = explicit_end
20
+ self.use_version = version
21
+ self.use_tags = tags
22
+ self.serialized_nodes = {}
23
+ self.anchors = {}
24
+ self.last_anchor_id = 0
25
+ self.closed = None
26
+
27
+ def open(self):
28
+ if self.closed is None:
29
+ self.emit(StreamStartEvent(encoding=self.use_encoding))
30
+ self.closed = False
31
+ elif self.closed:
32
+ raise SerializerError("serializer is closed")
33
+ else:
34
+ raise SerializerError("serializer is already opened")
35
+
36
+ def close(self):
37
+ if self.closed is None:
38
+ raise SerializerError("serializer is not opened")
39
+ elif not self.closed:
40
+ self.emit(StreamEndEvent())
41
+ self.closed = True
42
+
43
+ #def __del__(self):
44
+ # self.close()
45
+
46
+ def serialize(self, node):
47
+ if self.closed is None:
48
+ raise SerializerError("serializer is not opened")
49
+ elif self.closed:
50
+ raise SerializerError("serializer is closed")
51
+ self.emit(DocumentStartEvent(explicit=self.use_explicit_start,
52
+ version=self.use_version, tags=self.use_tags))
53
+ self.anchor_node(node)
54
+ self.serialize_node(node, None, None)
55
+ self.emit(DocumentEndEvent(explicit=self.use_explicit_end))
56
+ self.serialized_nodes = {}
57
+ self.anchors = {}
58
+ self.last_anchor_id = 0
59
+
60
+ def anchor_node(self, node):
61
+ if node in self.anchors:
62
+ if self.anchors[node] is None:
63
+ self.anchors[node] = self.generate_anchor(node)
64
+ else:
65
+ self.anchors[node] = None
66
+ if isinstance(node, SequenceNode):
67
+ for item in node.value:
68
+ self.anchor_node(item)
69
+ elif isinstance(node, MappingNode):
70
+ for key, value in node.value:
71
+ self.anchor_node(key)
72
+ self.anchor_node(value)
73
+
74
+ def generate_anchor(self, node):
75
+ self.last_anchor_id += 1
76
+ return self.ANCHOR_TEMPLATE % self.last_anchor_id
77
+
78
+ def serialize_node(self, node, parent, index):
79
+ alias = self.anchors[node]
80
+ if node in self.serialized_nodes:
81
+ self.emit(AliasEvent(alias))
82
+ else:
83
+ self.serialized_nodes[node] = True
84
+ self.descend_resolver(parent, index)
85
+ if isinstance(node, ScalarNode):
86
+ detected_tag = self.resolve(ScalarNode, node.value, (True, False))
87
+ default_tag = self.resolve(ScalarNode, node.value, (False, True))
88
+ implicit = (node.tag == detected_tag), (node.tag == default_tag)
89
+ self.emit(ScalarEvent(alias, node.tag, implicit, node.value,
90
+ style=node.style))
91
+ elif isinstance(node, SequenceNode):
92
+ implicit = (node.tag
93
+ == self.resolve(SequenceNode, node.value, True))
94
+ self.emit(SequenceStartEvent(alias, node.tag, implicit,
95
+ flow_style=node.flow_style))
96
+ index = 0
97
+ for item in node.value:
98
+ self.serialize_node(item, node, index)
99
+ index += 1
100
+ self.emit(SequenceEndEvent())
101
+ elif isinstance(node, MappingNode):
102
+ implicit = (node.tag
103
+ == self.resolve(MappingNode, node.value, True))
104
+ self.emit(MappingStartEvent(alias, node.tag, implicit,
105
+ flow_style=node.flow_style))
106
+ for key, value in node.value:
107
+ self.serialize_node(key, node, None)
108
+ self.serialize_node(value, node, key)
109
+ self.emit(MappingEndEvent())
110
+ self.ascend_resolver()
111
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/evaluator/vendor/yaml/tokens.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class Token(object):
3
+ def __init__(self, start_mark, end_mark):
4
+ self.start_mark = start_mark
5
+ self.end_mark = end_mark
6
+ def __repr__(self):
7
+ attributes = [key for key in self.__dict__
8
+ if not key.endswith('_mark')]
9
+ attributes.sort()
10
+ arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
11
+ for key in attributes])
12
+ return '%s(%s)' % (self.__class__.__name__, arguments)
13
+
14
+ #class BOMToken(Token):
15
+ # id = '<byte order mark>'
16
+
17
+ class DirectiveToken(Token):
18
+ id = '<directive>'
19
+ def __init__(self, name, value, start_mark, end_mark):
20
+ self.name = name
21
+ self.value = value
22
+ self.start_mark = start_mark
23
+ self.end_mark = end_mark
24
+
25
+ class DocumentStartToken(Token):
26
+ id = '<document start>'
27
+
28
+ class DocumentEndToken(Token):
29
+ id = '<document end>'
30
+
31
+ class StreamStartToken(Token):
32
+ id = '<stream start>'
33
+ def __init__(self, start_mark=None, end_mark=None,
34
+ encoding=None):
35
+ self.start_mark = start_mark
36
+ self.end_mark = end_mark
37
+ self.encoding = encoding
38
+
39
+ class StreamEndToken(Token):
40
+ id = '<stream end>'
41
+
42
+ class BlockSequenceStartToken(Token):
43
+ id = '<block sequence start>'
44
+
45
+ class BlockMappingStartToken(Token):
46
+ id = '<block mapping start>'
47
+
48
+ class BlockEndToken(Token):
49
+ id = '<block end>'
50
+
51
+ class FlowSequenceStartToken(Token):
52
+ id = '['
53
+
54
+ class FlowMappingStartToken(Token):
55
+ id = '{'
56
+
57
+ class FlowSequenceEndToken(Token):
58
+ id = ']'
59
+
60
+ class FlowMappingEndToken(Token):
61
+ id = '}'
62
+
63
+ class KeyToken(Token):
64
+ id = '?'
65
+
66
+ class ValueToken(Token):
67
+ id = ':'
68
+
69
+ class BlockEntryToken(Token):
70
+ id = '-'
71
+
72
+ class FlowEntryToken(Token):
73
+ id = ','
74
+
75
+ class AliasToken(Token):
76
+ id = '<alias>'
77
+ def __init__(self, value, start_mark, end_mark):
78
+ self.value = value
79
+ self.start_mark = start_mark
80
+ self.end_mark = end_mark
81
+
82
+ class AnchorToken(Token):
83
+ id = '<anchor>'
84
+ def __init__(self, value, start_mark, end_mark):
85
+ self.value = value
86
+ self.start_mark = start_mark
87
+ self.end_mark = end_mark
88
+
89
+ class TagToken(Token):
90
+ id = '<tag>'
91
+ def __init__(self, value, start_mark, end_mark):
92
+ self.value = value
93
+ self.start_mark = start_mark
94
+ self.end_mark = end_mark
95
+
96
+ class ScalarToken(Token):
97
+ id = '<scalar>'
98
+ def __init__(self, value, plain, start_mark, end_mark, style=None):
99
+ self.value = value
100
+ self.plain = plain
101
+ self.start_mark = start_mark
102
+ self.end_mark = end_mark
103
+ self.style = style
104
+
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/grading/verified_config.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "audited-verified-grader-v1",
3
+ "query_id": "946da78883724707e43b358e",
4
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
5
+ "grader_file_sha256": {
6
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
7
+ "public_inputs.json": "2a1408af8388d2faa0412ab95e2916d21e0162fb59db35274844bd7b69476e68",
8
+ "original_check.py": "6075f1680350a728eb7059e9f860f99e666ab71358a3bd89935357f00d358cd2",
9
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
10
+ "auto_policy.json": "0dcc536fc56e18fae99fb0ee6552586c7e90cf97e65ae04da5f1e7be038d710b",
11
+ "r10_support.py": "40d42ef87dc72d111ac18afe6e413f07e8acbf342aac9d089b51e2c0a3dcefa6",
12
+ "format_constraints.py": "8e3a2deb1f9b8b286b6861adfe8f798f9748d4993af133ba3a71aa86af6c2947",
13
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
14
+ "autograde_task_check.py": "80fd282067ebd90c5b7759de586691cf4f3a069fe21b46169664a78ae196e1cb",
15
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
16
+ "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e",
17
+ "vendor/PyYAML-LICENSE": "8d3928f9dc4490fd635707cb88eb26bd764102a7282954307d3e5167a577e8a4",
18
+ "vendor/yaml/nodes.py": "80f28d8fca4a09d87677882bde021820d9cf39a3b11a12405226211919cf13ce",
19
+ "vendor/yaml/reader.py": "d1d9b38ab3a20c6e17a38d519ee412ecaf6b918df18c78956ac7c330d4ea08dc",
20
+ "vendor/yaml/resolver.py": "f4bf9561f9b89961f1503d558385fbae30d12bfed565de9bf76c33abb63620a6",
21
+ "vendor/yaml/__init__.py": "b19dfcc333d6a75dfd73073901164507252f271b41d3b5f7d85510033a0547a7",
22
+ "vendor/yaml/emitter.py": "8e086d694ede170837d5b1b407b45979aff6f40762f422a65eafd08e04290a44",
23
+ "vendor/yaml/tokens.py": "953408cd2570f0c83dc2fe39f7e4e388e41eeb05738aa69196a5f6ffcf6ba79e",
24
+ "vendor/yaml/parser.py": "8a55a9e6fbe0a07146cef3990c8b45a068c3e83e369e1959ad9ca30306b4a09a",
25
+ "vendor/yaml/composer.py": "fcaa37d16afa783594794a5ab94193dcb720f503c19ce3d59539c8311189f453",
26
+ "vendor/yaml/scanner.py": "60433788b652690c17710460da5d91e0c753d3318fd85f5e1e42862a71f25906",
27
+ "vendor/yaml/dumper.py": "3cb72d66563064ba7b5e679477046ebf89d8399d940670c8532f3e94a7cb17ea",
28
+ "vendor/yaml/serializer.py": "0a1b85826854d35863e31808f0668abfabdf33606e8f06bd8bb7761401e3edc0",
29
+ "vendor/yaml/events.py": "e74fd392c810884e2ea7e94aa3f57e9c1cbeb402319083d0c58e6a0e1282787c",
30
+ "vendor/yaml/representer.py": "22e58ff9c016f6c1ca1274b4802a926bcf78935060e1c813c5a0f021c6d143e6",
31
+ "vendor/yaml/loader.py": "5156becc8aa6905482218abf3e04869b835226db4763645fff3438fdbd5f1cdd",
32
+ "vendor/yaml/cyaml.py": "e99ac01bd7c062f7557b614aff0d21997a06ed962ca185306a91bc0a20bbd87d",
33
+ "vendor/yaml/constructor.py": "90d8247da78b524c10618fd0e857f54f3d97570fe91b5c5513d024ef3faf88b0",
34
+ "vendor/yaml/error.py": "021f73fada072546c4f63f8cf18a7181244ce4280b09cc15cc980b2d1176171a"
35
+ },
36
+ "runtime_requirements": {
37
+ "family": "verified2_repaired_workspace",
38
+ "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
39
+ "network": "none",
40
+ "read_only_mounts": [
41
+ "task:/source",
42
+ "task:/task",
43
+ "evaluator:/grader",
44
+ "candidate:/candidate",
45
+ "answer:/answer.txt"
46
+ ],
47
+ "writable_tmpfs": [
48
+ "/app",
49
+ "/workspace",
50
+ "/tmp"
51
+ ],
52
+ "copy_completed_candidate_children_to_app_before_grader": true,
53
+ "entrypoint": [
54
+ "python3",
55
+ "/grader/check.py"
56
+ ],
57
+ "working_directory": "/candidate",
58
+ "environment": {
59
+ "MYBENCH_CANDIDATE": "/candidate",
60
+ "MYBENCH_CANDIDATE_PATH": "/candidate",
61
+ "CANDIDATE_DIR": "/candidate",
62
+ "CANDIDATE_ROOT": "/candidate",
63
+ "MYBENCH_SOURCE_TASK": "/source",
64
+ "SOURCE_TASK_DIR": "/source",
65
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
66
+ "MYBENCH_EPHEMERAL_APP": "1",
67
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1"
68
+ },
69
+ "environment_names_detected": [
70
+ "CANDIDATE_DIR",
71
+ "MYBENCH_CANDIDATE",
72
+ "MYBENCH_EPHEMERAL_WORKSPACE"
73
+ ],
74
+ "expected_check_ids": [
75
+ "0",
76
+ "1",
77
+ "2",
78
+ "3",
79
+ "4",
80
+ "5",
81
+ "6"
82
+ ],
83
+ "criterion_count": 7,
84
+ "criterion_weights": {
85
+ "0": 1,
86
+ "1": 1,
87
+ "2": 1,
88
+ "3": 1,
89
+ "4": 1,
90
+ "5": 1,
91
+ "6": 1
92
+ },
93
+ "actual_original_success_criteria_count": 7,
94
+ "original_task_metadata_must_not_define_override_criterion_count": false,
95
+ "requires_external_actual_native_trace": false,
96
+ "requires_external_trusted_snapshot_binding": false,
97
+ "fresh_native_binding_must_not_require_historical_run_id": true,
98
+ "checker_can_execute_candidate_subprocesses": true,
99
+ "host_execution_forbidden": true,
100
+ "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.",
101
+ "docker_image_payload_in_source_tree": false,
102
+ "runtime_missing": [],
103
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
104
+ "grader_timeout_seconds": 600
105
+ },
106
+ "engine": "portable_verified_v1"
107
+ }
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/inputs/article.html ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- 微信公众号文章导出片段 -->
2
+ <div id="js_article">
3
+ <h1 id="activity-name">Python 异步编程入门指南</h1>
4
+ <div id="meta_content">作者:张三 公众号:技术小站</div>
5
+ <div id="js_content">
6
+ <p>异步编程是提高程序并发能力的重要手段。Python 中的 asyncio 模块提供了事件循环和协程支持。</p>
7
+ <img data-src="https://mmbiz.qpic.cn/mmbiz_svg/aaa" data-type="svg">
8
+ <img data-src="https://mmbiz.qpic.cn/sz_mmbiz_png/bbb/640?wx_fmt=png" data-index="2">
9
+ <h2>基本概念</h2>
10
+ <p>协程是一种可暂停恢复的函数。事件循环负责调度协程的执行。</p>
11
+ <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/ccc" data-index="3">
12
+ <h2>示例代码</h2>
13
+ <pre><code>import asyncio
14
+
15
+ async def main():
16
+ await asyncio.sleep(1)
17
+ print("done")
18
+
19
+ asyncio.run(main())</code></pre>
20
+ <img data-src="data:image/svg+xml;base64,xxxx">
21
+ <h2>注意事项</h2>
22
+ <ul>
23
+ <li>不要在协程中调用阻塞函数</li>
24
+ <li>使用 gather 并发运行多个协程</li>
25
+ </ul>
26
+ </div>
27
+ <div class="reward_area">微信扫一扫赞赏作者 <img data-src="https://mmbiz.qpic.cn/mmbiz_jpg/reward_qr"></div>
28
+ <div class="ct_mpda_wrp">广告推广:限时优惠课程</div>
29
+ <a href="javascript:void(0);">阅读原文</a>
30
+ <div id="js_cmt_area">写留言 暂无留言</div>
31
+ <div class="qr_code_pc">扫码关注我们</div>
32
+ <p>当前内容可能存在未经审核的内容</p>
33
+ </div>
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 你收到一份从微信公众号文章导出的原始 HTML 片段(含正文、图片标签、广告与互动元素)。请编写一个 Python 脚本 clean_article.py,将其转换为一份干净、规范的 Markdown 笔记文件,要求:
2
+ 1. 按冻结 wechat-article-to-markdown Skill「提取图片并确定位置」的源码顺序及图片类型表提取、过滤正文图片,并按出现位置插入 Markdown;不能按 imgIndex 重排。
3
+ 2. 对本题的广告推广、赞赏、留言区、关注引导、无效链接和空图片类别,按该 Skill「清理无关内容」处理。本任务只转换已提供的离线 article.html,不抓取网络HTML/Markdown或下载图片。
4
+ 3. 按该 Skill「添加元信息」模板,在文件最开头生成 YAML frontmatter。
5
+ 4. 对本任务评分的笔记排版子集,使用冻结 markdown-notes-organizer Skill 的标题层级、同级条目/列表嵌套、列表/代码块/引用块前空白、关键词加粗占比、空表格单元格规则。不引入该文档其它未要求的数学/Callout/图表生成义务。
6
+ 5. 按冻结 wechat-article-to-markdown Skill「保存文件」中的命名规则,保存到当前目录。
7
+ 脚本需可直接用 python3 clean_article.py 运行,读取输入文件 article.html,输出转换后的 .md 文件,并在 stdout 打印输出文件名。
8
+ Bounded automatic resource contract: No standard-library import restriction is added; the available package environment may be used. Do not perform network operations during graded invocations. Do not load or call foreign native libraries through FFI during graded invocations. Child processes are not forbidden solely because they exist; all original output and interface requirements still apply. A launcher or instrumentation failure is an infrastructure error, not a wrong-answer score.
9
+
10
+ Execution budget: every grader-launched candidate Python invocation must complete within 60 seconds. A timeout after candidate startup fails this bounded-completion requirement; a trusted observer or launcher failure is an infrastructure error.
11
+
12
+
13
+ Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score.
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/SKILL.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Multi-skill source bundle
2
+
3
+ Private source bundle wrapper. The original skills are in members/.
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/members/M000/SKILL.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: markdown-notes-organizer
3
+ description: 将用户提供的文本内容整理为规范的 Markdown 笔记。当用户说"整理成笔记"、"帮我写成 md"、"整理一下这段内容"、"转成 Markdown"或类似表述时触发。
4
+ ---
5
+
6
+ # Markdown 笔记整理
7
+
8
+ ## 输出规则
9
+
10
+ 触发此 skill 后,**直接输出完整的 Markdown 笔记正文,不得在笔记前后附加任何多余内容**,包括但不限于:
11
+
12
+ - 开场白、确认语、客套话(如"好的,以下是整理结果:")
13
+ - 结尾说明、总结性评语(如"以上是整理好的笔记,如需调整请告知")
14
+
15
+ 用户需要能直接点击复制按钮,拿到一份干净、完整、可直接使用的 Markdown 笔记。
16
+
17
+ ## 标题层级规范
18
+
19
+ ### (1)主动识别层级结构
20
+
21
+ 拿到用户的文本后,先分析其内在的逻辑层次:
22
+
23
+ - 判断哪些内容是"大主题"、哪些是"子话题"、哪些是"细节展开"
24
+ - 同一层级的内容使用相同级别的标题,不随意升降级
25
+ - **标题只用于划分独立的内容板块**,不用于列举同类条目——同类条目应改用列表
26
+
27
+ ### (2)标题与列表的搭配原则
28
+
29
+ 整篇笔记最多使用四级标题,**禁止出现五级及以上标题**(`#####`)。
30
+
31
+ | 级别 | 符号 | 格式示例 |
32
+ | ------ | ---------- | ---------------------------------- |
33
+ | `#` | 文件大标题 | `# 笔记主题`(全篇唯一,可以没有) |
34
+ | `##` | 一级章节 | `## 1、章节名` |
35
+ | `###` | 二级小节 | `### (1)小节名` |
36
+ | `####` | 三级细分 | `#### ①细分名` |
37
+
38
+ 当内容层次不需要再往下细分,或者只是同级并列的条目时,用列表代替继续加深标题层级:
39
+
40
+ - **无序列表** `-`:并列的要点、特征、注意事项等,顺序无关紧要
41
+ - **有序列表** `1.`:有先后顺序的步骤、流程、排名等
42
+
43
+ 列表可以嵌套,但嵌套不超过两层,嵌套使用 **4 个空格**缩进:
44
+
45
+ ```
46
+ - 一级条目
47
+ - 二级条目(4 个空格缩进)
48
+ ```
49
+
50
+ **判断使用标题还是列表的原则**:若一组内容每项都能独立展开成一段或多段文字,用标题;若每项只是一句话或一个短语,用列表。
51
+
52
+ ## 公式规范
53
+
54
+ **只使用 `$` 符号格式,禁止混用其他任何表示方式。**
55
+
56
+ - 行内公式:`$公式$`
57
+ - 单行独立公式:`$$公式$$`
58
+
59
+ 禁止事项:
60
+
61
+ - 禁止使用 ` ```latex ``` ` 代码块包裹公式
62
+ - 禁止使用 `\(` `\)` 或 `\[` `\]` 格式
63
+
64
+ ## 表格规范
65
+
66
+ 所有表格转换为标准 Markdown 表格格式:
67
+
68
+ - 空格子用 `-` 占位,不能留空
69
+ - 对齐符号写在分隔行:`:---` 左对齐,`:---:` 居中,`---:` 右对齐
70
+ - 单元格内含有 `|` 时,用反斜杠转义:`\|`
71
+ - 表格前不留空行(部分解析器遇到空行会报错)
72
+
73
+ ## 流程图规范
74
+
75
+ 流程图统一使用 Mermaid 代码块表示:
76
+
77
+ ````
78
+ ```mermaid
79
+ flowchart TD
80
+ A[开始] --> B[步骤]
81
+ ```
82
+ ````
83
+
84
+ ## Callout 规范
85
+
86
+ 使用引用块 + `[!类型]` 语法创建提示框。五种类型及对应颜色:`NOTE` 🔵蓝、`TIP` 🟢绿、`IMPORTANT` 🔵蓝、`WARNING` 🟡黄、`CAUTION` 🟡黄。
87
+
88
+ - 自定义标题:`> [!TIP] 标题内容`
89
+ - 可折叠:类型后加 `-` 折叠 / `+` 展开
90
+ - 嵌套:通过引用块嵌套实现,如 `> > [!NOTE] 内容`
91
+ - 一个文档中 callout 数量适中,避免视觉疲劳,不连续堆叠
92
+ - 保持简洁,callout 内容不宜过长
93
+
94
+ ## 语言风格
95
+
96
+ - 通俗易懂,但不失严谨
97
+ - 润色表达,不大改原文意思,保留原有的比喻和说法
98
+ - 若原文带有口语化、对话式或第二人称表达,统一改写为陈述性文字,使笔记读起来像知识文档
99
+ - **禁止遗漏任何有效信息**
100
+
101
+ ## Markdown 格式注意点
102
+
103
+ ### 加粗
104
+
105
+ 加粗(`**文字**`)只用于极少数真正关键的词语,全篇占比不超过 2%:
106
+
107
+ - 只加粗核心关键词,禁止对整句长句加粗(等同于没加粗,失去意义)
108
+ - 同一段落内加粗不超过 1~2 处
109
+
110
+ ### 空白与换行
111
+
112
+ - 列表、代码块、引用块前必须有一个空行,否则会被解析为上一段的延续
113
+ - 嵌套列表使用 **4 个空格**缩进(不是 2 个),2 个空格在严格解析器中会嵌套失败
114
+ - 强制换行优先使用空行或 `<br>` 标签,避免行尾两个空格(编辑器常自动去除)
115
+ - 只含空格的行仍会打断段落,注意清理行尾多余空白
116
+
117
+ ### 链接与图片
118
+
119
+ - URL 中含括号时需转义为 `%28` `%29`,或用尖括号语法:`[文字](<含(括号)的URL>)`
120
+ - URL 中含空格时需转义为 `%20`
121
+ - 图片始终提供 alt 文本:`![描述](url)`,即使描述为空也写 `![](url)`
122
+
123
+ ### 代码块
124
+
125
+ - 代码块内部含有三个反引号时,外层围栏改用四个及以上反引号
126
+ - 行内代码含反引号时,用双反引号包裹并在两端加空格:`` ` 代码 ` ``
127
+ - 围栏后的语言标识影响高亮效���,纯文本可省略
128
+
129
+ ### 转义
130
+
131
+ 需要在正文中转义的字符:`\*`、`\_`、`\[`、`\]`、`\#`、`\>`、`` \` ``
132
+
133
+ 代码块和行内代码内部无需转义。
134
+
135
+ ### 兼容性
136
+
137
+ - 优先使用纯 Markdown 语法,避免 HTML 标签(部分渲染器会将其过滤)
138
+ - 脚注、任务列表、emoji 短代码等扩展语法并非通用,按目标平台决定是否使用
139
+ - YAML frontmatter 需用 `---` 包裹,且只能出现在文件最开头
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/skill/members/M001/SKILL.md ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: wechat-article-to-markdown
3
+ description: 将微信公众号文章转换为整洁的 Markdown 文件,自动去除广告、赞赏、推广等无关内容,处理代码块格式,支持图片和视频处理。当用户提供微信公众号链接或要求保存微信文章时使用此技能。
4
+ ---
5
+
6
+ # 微信公众号文章转 Markdown
7
+
8
+ ## 概述
9
+
10
+ 微信公众号文章网页包含大量无关内容(广告、赞赏、留言区、小程序推广等),直接复制粘贴会产生格式问题。此 Skill 提供一套完整的处理流程,将微信文章转换为干净、规范的 Markdown 文件。
11
+
12
+ ## 触发条件
13
+
14
+ - 用户提供微信公众号文章链接(`mp.weixin.qq.com`)
15
+ - 用户说"保存微信文章"、"另存为 Markdown"
16
+ - 用户想要整理微信文章到笔记库
17
+
18
+ ## 完整处理流程
19
+
20
+ ### 第一步:同时获取 HTML 和 Markdown
21
+
22
+ **必须同时获取两种格式**(并行请求):
23
+
24
+ ```
25
+ # 请求 1:HTML 格式(用于提取图片位置)
26
+ mcp__ScraplingServer__stealthy_fetch
27
+ - url: 微信文章链接
28
+ - extraction_type: html
29
+ - main_content_only: true
30
+ - wait: 2000
31
+
32
+ # 请求 2:Markdown 格式(用于提取文本内容)
33
+ mcp__ScraplingServer__stealthy_fetch
34
+ - url: 微信文章链接
35
+ - extraction_type: markdown
36
+ - main_content_only: true
37
+ - wait: 2000
38
+ ```
39
+
40
+ ### 第二步:提取图片并确定位置
41
+
42
+ **关键:图片顺序必须按 HTML 中实际出现顺序,而非 imgIndex 数字**
43
+
44
+ 从 HTML 中提取图片信息:
45
+
46
+ ```bash
47
+ # 提取所有正文图片(按出现顺序)
48
+ cat html_file | tr '>' '\n' | grep -E 'data-src.*mmbiz_(jpg|png)' | grep -v 'mmbiz_svg'
49
+ ```
50
+
51
+ **图片类型判断:**
52
+
53
+ | 类型 | 处理方式 | 说明 |
54
+ |------|---------|------|
55
+ | `mmbiz_jpg` | **保留** | 文章正文图片 |
56
+ | `mmbiz_png` | **保留** | 文章正文图片 |
57
+ | `sz_mmbiz_jpg` | **保留** | 文章正文图片 |
58
+ | `sz_mmbiz_png` | **保留** | 文章正文图片 |
59
+ | `mmbiz_svg` | **丢弃** | 装饰性图标、分隔线 |
60
+ | `data:image/svg+xml` | **丢弃** | SVG 占位符 |
61
+
62
+ **图片位置判断:**
63
+
64
+ 根据 `data-index` 属性或图片在 HTML 中的出现顺序,将图片插入到 Markdown 对应位置:
65
+
66
+ ```
67
+ data-index="2" → 第一张正文图片
68
+ data-index="3" → 第二张正文图片
69
+ ...
70
+ ```
71
+
72
+ **注意**:`#imgIndex=N` 不等于图片在文章中的实际位置!必须按 HTML 源码中的出现顺序排列。
73
+
74
+ ### 第三步:清理无关内容
75
+
76
+ **必须移除的内容:**
77
+
78
+ 1. **广告和推广**
79
+ - 文末的广告推广内容
80
+ - "阅读原文" 相关内容
81
+ - 小程序推广
82
+ - 公众号推荐卡片
83
+
84
+ 2. **赞赏相关**
85
+ - "微信扫一扫赞赏作者"
86
+ - 赞赏二维码
87
+ - 赞赏金额选择界面
88
+
89
+ 3. **互动元素**
90
+ - 留言区("写留言"、"暂无留言")
91
+ - 分享按钮(Like, Share, Popular, Comment)
92
+ - 关注引导("扫码关注"、"继续滑动")
93
+ - 划线功能引导
94
+
95
+ 4. **UI 元素**
96
+ - 无效链接(`javascript:void(0);`)
97
+ - 空图片标签(`![]()`)
98
+ - SVG 占位图片
99
+ - 弹窗和遮罩层内容
100
+ - "预览时标签不可点"
101
+ - 字体调整控件
102
+
103
+ 5. **元数据冗余**
104
+ - 重复的公众号名称和头像
105
+ - 底部 "当前内容可能存在未经审核..." 提示
106
+ - 微信公众平台广告规范指引
107
+
108
+ ### 第四步:规范化 Markdown 格式
109
+
110
+ **标题处理:**
111
+ ```markdown
112
+ # 文章主标题
113
+
114
+ ## 二级标题
115
+
116
+ ### 三级标题
117
+ ```
118
+
119
+ **代码块处理:**
120
+ - 检查代码块是否正确使用三反引号
121
+ - 添加语言标识符(如 ```java, ```python, ```bash)
122
+ - 确保代码缩进正确
123
+
124
+ **图片格式:**
125
+ ```markdown
126
+ ![图片描述](https://mmbiz.qpic.cn/...)
127
+ ```
128
+
129
+ **表格处理:**
130
+ 保留原始表格格式,确保对齐。
131
+
132
+ ### 第五步:添加元信息
133
+
134
+ 在文件开头添加 YAML frontmatter:
135
+
136
+ ```markdown
137
+ ---
138
+ title: 文章标题
139
+ author: 作者名称
140
+ source: 原始链接
141
+ date_saved: 保存日期
142
+ tags: [微信公众号, 其他标签]
143
+ ---
144
+ ```
145
+
146
+ ### 第六步:保存文件
147
+
148
+ **文件命名规则:**
149
+ - 格式:`YYYY-MM-DD-标题摘要.md`
150
+ - 标题摘要:取标题前 30 字符,去除特殊字符
151
+ - 示例:`2026-03-18-IM系统消息收发设计.md`
152
+
153
+ ---
154
+
155
+ ## 图片处理详细指南
156
+
157
+ ### 微信图片的特殊性
158
+
159
+ **重要警告**:微信图片有以下限制:
160
+ 1. **防盗链**:部分图片直接访问可能返回 403
161
+ 2. **时效性**:图片链接可能过期(通常 24-48 小时)
162
+ 3. **无防盗链**:大部分 `mmbiz.qpic.cn` 链接可直接访问
163
+
164
+ ### 图片链接处理
165
+
166
+ **方案 A - 保留原始链接(推荐,简单)**
167
+ ```markdown
168
+ ![图片描述](https://mmbiz.qpic.cn/sz_mmbiz_png/xxx/640?wx_fmt=png)
169
+ ```
170
+ - 优点:简单直接,大多数情况可正常显示
171
+ - 缺点:链接可能过期
172
+
173
+ **方案 B - 下载到本地**
174
+ - 如果用户需要离线使用,可下载图片到 `./images/` 目录
175
+ - 需要处理防盗链问题
176
+
177
+ ### 常见图片问题
178
+
179
+ | 问题 | 原因 | 解决方案 |
180
+ |------|------|---------|
181
+ | 图片不显示 | SVG 占位符 | 过滤掉 `data:image/svg+xml` 和 `mmbiz_svg` |
182
+ | 图片顺序错乱 | 按 imgIndex 排序 | 按 HTML 中实际出现顺序(data-index) |
183
+ | 图片缺失 | 只用了 markdown 提取 | 同时获取 HTML 和 markdown |
184
+
185
+ ---
186
+
187
+ ## 常见问题处理
188
+
189
+ ### 问题 1:图片顺序错乱
190
+
191
+ **原因**:`imgIndex` 数字不代表文章中的实际位置
192
+
193
+ **解决方案**:
194
+ ```
195
+ 错误做法:按 imgIndex=0,1,2... 排序
196
+ 正确做法:按 HTML 中 <img> 标签出现的顺序排列
197
+ ```
198
+
199
+ ### 问题 2:图片缺失
200
+
201
+ **原因**:只用 markdown 格式提取,部分图片链接丢失
202
+
203
+ **解决方案**:同时获取 HTML 和 markdown,从 HTML 中提取完整图片列表
204
+
205
+ ### 问题 3:包含无关的 SVG 图片
206
+
207
+ **原因**:微信使用 SVG 作为占位符和装饰
208
+
209
+ **解决方案**:过滤掉所有 `mmbiz_svg` 类型和 `data:image/svg+xml` 的图片
210
+
211
+ ### 问题 4:代码块无语言标识
212
+
213
+ **原因**:微信文章代码块格式不规范
214
+
215
+ **解决方案**:根据代码内容推断语言,添加标识符
216
+
217
+ ---
218
+
219
+ ## 输出模板
220
+
221
+ ```markdown
222
+ ---
223
+ title: {{文章标题}}
224
+ author: {{作者}}
225
+ source: {{原始链接}}
226
+ date_saved: {{保存日期}}
227
+ tags: [微信公众号, {{其他标签}}]
228
+ ---
229
+
230
+ # {{文章标题}}
231
+
232
+ > 作者:{{作者名称}}
233
+ > 来源:{{公众号名称}}
234
+ > 链接:{{原始链接}}
235
+
236
+ ![封面图片]({{封面图片链接}})
237
+
238
+ {{正文内容,图片按正确位置插入}}
239
+
240
+ ---
241
+
242
+ *本文由 [wechat-article-to-markdown] 自动转换*
243
+ *保存自微信公众号文章,仅供个人学习使用*
244
+ ```
245
+
246
+ ---
247
+
248
+ ## 示例工作流
249
+
250
+ 用户输入:
251
+ ```
252
+ 保存这篇文章 https://mp.weixin.qq.com/s/xxxxx
253
+ ```
254
+
255
+ 处理步骤:
256
+ 1. **并行获取** HTML 和 markdown 两种格式
257
+ 2. **从 HTML 提取图片**:按出现顺序,过滤 SVG
258
+ 3. **解析 markdown**:提取标题、正文、代码块
259
+ 4. **合并内容**:将图片插入到 markdown 正确位置
260
+ 5. **清理无关内容**:移除广告、赞赏、UI 元素
261
+ 6. **格式化代码块**:添加语言标识
262
+ 7. **添加 frontmatter**:元信息
263
+ 8. **保存文件**:按命名规则保存
264
+
265
+ ---
266
+
267
+ ## 注意事项
268
+
269
+ 1. **版权提醒**:保存的文章仅供个人学习使用,请勿二次传播
270
+ 2. **图片链接**:大部分可直接访问,少数有防盗链
271
+ 3. **视频限制**:嵌入的视频记录标题和描述即可
272
+ 4. **表格处理**:微信表格可能需要手动调整对齐
273
+ 5. **公式支持**:如有数学公式,转换为 LaTeX 格式
274
+
275
+ ## 相关技能
276
+
277
+ - `pdf` - 处理 PDF 文件
278
+ - `docx` - 处理 Word 文档
279
+ - `excalidraw-diagram` - 创建图表
benchmarks/skillbench-venus-e/tasks/946da78883724707e43b358e/task.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "skill-search-synthesis-v1",
3
+ "task_id": "946da78883724707e43b358e",
4
+ "environment": {
5
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
6
+ "network": "none"
7
+ },
8
+ "query_id": "946da78883724707e43b358e",
9
+ "outputs": [
10
+ "clean_article.py"
11
+ ],
12
+ "success_criteria": [
13
+ "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.",
14
+ "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md."
15
+ ],
16
+ "evaluation": {
17
+ "kind": "python",
18
+ "type": "verified"
19
+ },
20
+ "source_skill": {
21
+ "sha256": "327c476ac38b364af4a4479c3cefcb90b9e2f6f18e2dbcab4683f269bef3db93",
22
+ "files": {
23
+ "SKILL.md": "c026851d0b60cc1e9687b03a24dfadf626b1e352c79c1d0b3ee85fc61ff4766c",
24
+ "members/M000/SKILL.md": "68b546f5f05728d7440638dd935302abb2f359bc9e1a751a0dd89dc89f4beb49",
25
+ "members/M001/SKILL.md": "eccebc48f5f87a3ac48f28159a037e822f34e5112c94c5fc786c3f126e7374ef"
26
+ }
27
+ },
28
+ "workspace": {
29
+ "candidate_mode": "workspace",
30
+ "input_mappings": [
31
+ {
32
+ "source": "inputs/article.html",
33
+ "workspace_target": "article.html",
34
+ "sha256": "d20625742942de73e231cd9d4b2be7a0a3161c68bbfee1c88e8da73eb33818c3"
35
+ }
36
+ ],
37
+ "skill_packages": [
38
+ {
39
+ "package_path": "skill/members/M000",
40
+ "content_hash": "b65cd17e09aad5339c135b9654142592363b6942e07f445404dfae3a85cd7eb3",
41
+ "member_id": "M000"
42
+ },
43
+ {
44
+ "package_path": "skill/members/M001",
45
+ "content_hash": "062b946a0e2ea2ece3d3d34c71a38c4ea21772039279bdcba45fdabdf0290375",
46
+ "member_id": "M001"
47
+ }
48
+ ]
49
+ },
50
+ "source_group": {
51
+ "schema_version": "multi-skill-source-v1",
52
+ "group_id": "b54fa673db188bf657423c83",
53
+ "members": [
54
+ {
55
+ "skill_id": "skill-8469bc991e49e3f2b58f03bd",
56
+ "store_id": "skill-release",
57
+ "original_package_path": "skill-release-archive/skills/84/skill-8469bc991e49e3f2b58f03bd",
58
+ "snapshot": {
59
+ "sha256": "b65cd17e09aad5339c135b9654142592363b6942e07f445404dfae3a85cd7eb3",
60
+ "files": {
61
+ "SKILL.md": "68b546f5f05728d7440638dd935302abb2f359bc9e1a751a0dd89dc89f4beb49"
62
+ },
63
+ "bytes": 5433
64
+ },
65
+ "skill_md_sha256": "68b546f5f05728d7440638dd935302abb2f359bc9e1a751a0dd89dc89f4beb49",
66
+ "member_id": "M000",
67
+ "package_path": "members/M000"
68
+ },
69
+ {
70
+ "skill_id": "skill-95c6ff1ff719cc51f43a4f8e",
71
+ "store_id": "skill-release",
72
+ "original_package_path": "skill-release-archive/skills/95/skill-95c6ff1ff719cc51f43a4f8e",
73
+ "snapshot": {
74
+ "sha256": "062b946a0e2ea2ece3d3d34c71a38c4ea21772039279bdcba45fdabdf0290375",
75
+ "files": {
76
+ "SKILL.md": "eccebc48f5f87a3ac48f28159a037e822f34e5112c94c5fc786c3f126e7374ef"
77
+ },
78
+ "bytes": 7537
79
+ },
80
+ "skill_md_sha256": "eccebc48f5f87a3ac48f28159a037e822f34e5112c94c5fc786c3f126e7374ef",
81
+ "member_id": "M001",
82
+ "package_path": "members/M001"
83
+ }
84
+ ]
85
+ },
86
+ "label_scope": {
87
+ "comparison": "none_vs_all_members",
88
+ "unit": "skill_group",
89
+ "individual_member_necessity_tested": false
90
+ },
91
+ "member_contributions": [
92
+ {
93
+ "member_id": "M000",
94
+ "contribution": "Markdown 笔记排版规范:标题层级上限(禁止五级标题)、标题与列表的搭配原则、4 空格嵌套缩进、块元素前空行、加粗占比限制、表格空格占位、frontmatter 位置规则",
95
+ "relationship": "为转换产出的 Markdown 文件提供格式规范,是任务第 4 条要求的直接依据"
96
+ },
97
+ {
98
+ "member_id": "M001",
99
+ "contribution": "微信文章清洗流程:按 HTML 出现顺序提取正文图片并过滤 mmbiz_svg / data:image/svg+xml、移除广告/赞赏/留言/关注引导/无效链接、添加 YAML frontmatter、按 YYYY-MM-DD-标题摘要.md 命名保存",
100
+ "relationship": "提供从原始微信 HTML 到干净 Markdown 的转换方法,是任务第 1、2、3、5 条要求的直接依据"
101
+ }
102
+ ],
103
+ "autograde_runtime_contract": {
104
+ "stdlib_only": false,
105
+ "forbid_network": true,
106
+ "forbid_subprocess": false,
107
+ "forbid_native": true,
108
+ "owner_ids": [
109
+ "0"
110
+ ],
111
+ "require_execution": true,
112
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
113
+ "execution_budget_seconds": 60
114
+ },
115
+ "automatic_evaluation_runtime": {
116
+ "stdlib_only": false,
117
+ "forbid_network": true,
118
+ "forbid_subprocess": false,
119
+ "forbid_native": true,
120
+ "owner_ids": [
121
+ "0"
122
+ ],
123
+ "require_execution": true,
124
+ "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
125
+ "execution_budget_seconds": 60,
126
+ "runtime_owner_ids": [
127
+ "0"
128
+ ],
129
+ "total_evaluation_budget_seconds": 420,
130
+ "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score."
131
+ }
132
+ }
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_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/952829163f75b50a_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/952829163f75b50a_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/952829163f75b50a_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/952829163f75b50a_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/952829163f75b50a_q1/evaluator/check.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from auto_entry import main
2
+ raise SystemExit(main())
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy-task.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "mybench-portable-task-v2",
3
+ "task_id": "952829163f75b50a",
4
+ "query_id": "952829163f75b50a_q1",
5
+ "prompt": {
6
+ "path": "instruction.md",
7
+ "sha256": "ee3e6e8399d09a6db7580f4f626c6447684820e8998f85e88558cca82b5261cf"
8
+ },
9
+ "workspace": {
10
+ "input_mappings": [],
11
+ "skill_packages": [
12
+ {
13
+ "content_hash": "c3a720d4f70abaaefeca60c16e23b2bcf927b0bc735c4e74aa27c32af3d0b9e7",
14
+ "name": "duvo-cli",
15
+ "package_path": "environment/skills/duvo-cli-c3a720d4",
16
+ "install_name": "duvo-cli-c3a720d4",
17
+ "archive_provenance": {
18
+ "archive_id": "logical-skill-305ebdd555146ebd5ec85b8c",
19
+ "archive_schema": "skill-release-v1",
20
+ "release_skill_id": "logical-skill-305ebdd555146ebd5ec85b8c",
21
+ "site": "skills-sh",
22
+ "local_path": "skills/30/logical-skill-305ebdd555146ebd5ec85b8c",
23
+ "skill_md_sha256": "89c6c58d5bf4ec80dc54b98fde12665aaf52a91b1e306e341161149fe7feb8a8",
24
+ "release_payload_sha256": "c3a720d4f70abaaefeca60c16e23b2bcf927b0bc735c4e74aa27c32af3d0b9e7",
25
+ "license": "MIT",
26
+ "license_status": "detected",
27
+ "canonical_source_id": "skills-sh:duvoai/skills/duvo-cli"
28
+ },
29
+ "omitted_entries": []
30
+ }
31
+ ],
32
+ "default_skill_target": ".claude/skills",
33
+ "candidate_mode": "workspace"
34
+ },
35
+ "ground_truth_skills": [
36
+ "c3a720d4f70abaaefeca60c16e23b2bcf927b0bc735c4e74aa27c32af3d0b9e7"
37
+ ],
38
+ "evaluation": {
39
+ "type": "verified",
40
+ "ground_truth_answer": {
41
+ "files": [
42
+ {
43
+ "path": "output/duvo_api_probe.sh",
44
+ "content": "#!/usr/bin/env bash\nduvo api GET /v1/agents -F limit=20 -F offset=0\nduvo api POST /v1/agents -f name=\"Ops bot\" -F build[name]=\"v1\"\n"
45
+ }
46
+ ]
47
+ },
48
+ "verifier": {
49
+ "type": "workspace_objective",
50
+ "version": 15,
51
+ "output_mode": "workspace",
52
+ "reference_files": [
53
+ {
54
+ "path": "output/duvo_api_probe.sh",
55
+ "format": "shell",
56
+ "content": "#!/usr/bin/env bash\nduvo api GET /v1/agents -F limit=20 -F offset=0\nduvo api POST /v1/agents -f name=\"Ops bot\" -F build[name]=\"v1\"\n"
57
+ }
58
+ ],
59
+ "checks": [
60
+ {
61
+ "id": "workspace_file_set",
62
+ "type": "workspace_file_set",
63
+ "paths": [
64
+ "output/duvo_api_probe.sh"
65
+ ],
66
+ "roots": [
67
+ "output"
68
+ ]
69
+ },
70
+ {
71
+ "id": "file_001",
72
+ "type": "file_exists",
73
+ "path": "output/duvo_api_probe.sh"
74
+ },
75
+ {
76
+ "id": "shell_001",
77
+ "type": "shell_syntax",
78
+ "path": "output/duvo_api_probe.sh"
79
+ },
80
+ {
81
+ "id": "shell_001_001",
82
+ "type": "shell_command",
83
+ "path": "output/duvo_api_probe.sh",
84
+ "value": "duvo api GET /v1/agents -F limit=20 -F offset=0"
85
+ },
86
+ {
87
+ "id": "shell_001_002",
88
+ "type": "shell_command",
89
+ "path": "output/duvo_api_probe.sh",
90
+ "value": "duvo api POST /v1/agents -f name=\"Ops bot\" -F build[name]=\"v1\""
91
+ },
92
+ {
93
+ "id": "shell_001_sequence",
94
+ "type": "shell_command_sequence",
95
+ "path": "output/duvo_api_probe.sh",
96
+ "values": [
97
+ "duvo api GET /v1/agents -F limit=20 -F offset=0",
98
+ "duvo api POST /v1/agents -f name=\"Ops bot\" -F build[name]=\"v1\""
99
+ ]
100
+ },
101
+ {
102
+ "id": "shell_001_unconditional",
103
+ "type": "shell_unconditional_commands",
104
+ "path": "output/duvo_api_probe.sh",
105
+ "values": [
106
+ "duvo api GET /v1/agents -F limit=20 -F offset=0",
107
+ "duvo api POST /v1/agents -f name=\"Ops bot\" -F build[name]=\"v1\""
108
+ ]
109
+ },
110
+ {
111
+ "id": "shell_straight_line_001",
112
+ "type": "shell_straight_line",
113
+ "path": "output/duvo_api_probe.sh",
114
+ "count": 2
115
+ }
116
+ ],
117
+ "self_test_passed": true
118
+ },
119
+ "dependency_contract": {
120
+ "version": 2,
121
+ "mode": "core_answer",
122
+ "dependency_type": "private_api",
123
+ "requirement_ids": [
124
+ "skill_a097",
125
+ "skill_a098"
126
+ ],
127
+ "forbid_meta_reference": true,
128
+ "forbid_answer_leakage": true
129
+ }
130
+ }
131
+ }
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_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/952829163f75b50a_q1/evaluator/legacy_tests/objective_evaluators.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import ast
11
+ import copy
12
+ import builtins
13
+ import json
14
+ import math
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
+ WORKSPACE_EVALUATOR = 'workspace_objective'
27
+ WORKSPACE_EVALUATOR_VERSION = 15
28
+ SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
29
+ ARTIFACT_FORMATS = {'json', 'toml', 'python', 'shell'}
30
+ _DOTTED = re.compile('^[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*$')
31
+
32
+ class ObjectiveEvaluatorError(ValueError):
33
+ pass
34
+
35
+ def safe_relative_path(value):
36
+ """Return a normalized portable relative path or fail closed."""
37
+ text = str(value or '').strip().replace('\\', '/')
38
+ path = PurePosixPath(text)
39
+ if not text or text.startswith('/') or path.is_absolute() or any((part in {'', '.', '..'} for part in path.parts)):
40
+ raise ObjectiveEvaluatorError(f'unsafe workspace path: {value!r}')
41
+ if len(path.parts) > 8 or len(text) > 180:
42
+ raise ObjectiveEvaluatorError('workspace path is too deep or long')
43
+ return path.as_posix()
44
+
45
+ def _json_value(value):
46
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
47
+ return value
48
+ return json.loads(str(value))
49
+
50
+ def _canonical(value):
51
+ if isinstance(value, dict):
52
+ return {key: _canonical(value[key]) for key in sorted(value)}
53
+ if isinstance(value, list):
54
+ return [_canonical(item) for item in value]
55
+ return value
56
+
57
+
58
+ def _same_native_json_types(actual, expected):
59
+ if type(expected)is float:
60
+ return type(actual)in(int,float)and math.isfinite(actual)
61
+ if type(actual)is not type(expected):return False
62
+ if isinstance(expected,dict):
63
+ return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected)
64
+ if isinstance(expected,list):
65
+ return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected))
66
+ if isinstance(actual,float):return math.isfinite(actual)
67
+ return True
68
+
69
+ def _file_content(item):
70
+ fmt = str(item.get('format') or '').casefold()
71
+ content = item.get('content')
72
+ if fmt == 'json':
73
+ parsed = _json_value(content)
74
+ return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
75
+ if not isinstance(content, str):
76
+ raise ObjectiveEvaluatorError(f'{fmt} artifact content must be text')
77
+ return content.rstrip() + '\n'
78
+
79
+ def _ast_name(node):
80
+ if isinstance(node, ast.Name):
81
+ return node.id
82
+ if isinstance(node, ast.Attribute):
83
+ parent = _ast_name(node.value)
84
+ return f'{parent}.{node.attr}' if parent else node.attr
85
+ return ''
86
+
87
+ def _python_inventory(text):
88
+ tree = ast.parse(text)
89
+ imports, calls = (set(), set())
90
+ for node in ast.walk(tree):
91
+ if isinstance(node, ast.Import):
92
+ imports.update((alias.name for alias in node.names))
93
+ elif isinstance(node, ast.ImportFrom):
94
+ module = node.module or ''
95
+ for alias in node.names:
96
+ imports.add(f'{module}.{alias.name}'.strip('.'))
97
+ elif isinstance(node, ast.Call):
98
+ name = _ast_name(node.func)
99
+ if name:
100
+ calls.add(name)
101
+ return (imports, calls)
102
+
103
+ def _literal_value(node, constants=None):
104
+ constants = constants or {}
105
+ if isinstance(node, ast.Constant) and isinstance(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
+ _UNRESOLVED = object()
115
+
116
+ def _python_semantics(text):
117
+ tree = ast.parse(text)
118
+ _annotate_assignment_contexts(tree)
119
+ imports, calls = _python_inventory(text)
120
+ constants = {}
121
+ for node in tree.body:
122
+ name = None
123
+ value_node = None
124
+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
125
+ name, value_node = (node.targets[0].id, node.value)
126
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
127
+ name, value_node = (node.target.id, node.value)
128
+ if name and value_node is not None:
129
+ value = _literal_value(value_node, constants)
130
+ if value is not _UNRESOLVED:
131
+ constants[name] = value
132
+ elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], (ast.Tuple, ast.List)) and isinstance(node.value, (ast.Tuple, ast.List)) and (len(node.targets[0].elts) == len(node.value.elts)):
133
+ for target, value_node in zip(node.targets[0].elts, node.value.elts):
134
+ if not isinstance(target, ast.Name):
135
+ continue
136
+ value = _literal_value(value_node, constants)
137
+ if value is not _UNRESOLVED:
138
+ constants[target.id] = value
139
+ call_nodes = []
140
+ for node in ast.walk(tree):
141
+ if isinstance(node, ast.Call):
142
+ call_nodes.append((_ast_name(node.func), node))
143
+ return (imports, calls, constants, call_nodes)
144
+
145
+ def _python_resolved_call_nodes(text):
146
+ """Resolve call targets through imports and simple constructor bindings.
147
+
148
+ The evaluator intentionally supports a small static subset: imports,
149
+ local definitions, direct aliases, and names assigned from calls. That is
150
+ enough to recognize semantic equivalents such as ``import datetime`` vs
151
+ ``from datetime import timedelta as td`` and instance-variable renames,
152
+ without pretending to perform general Python type inference.
153
+ """
154
+ tree = ast.parse(text)
155
+ _annotate_assignment_contexts(tree)
156
+ bindings = {}
157
+ nodes = sorted(ast.walk(tree), key=lambda node: (int(getattr(node, 'lineno', -1)), int(getattr(node, 'col_offset', -1))))
158
+
159
+ def resolve(node):
160
+ if isinstance(node, ast.Name):
161
+ return bindings.get(node.id, node.id)
162
+ if isinstance(node, ast.Attribute):
163
+ parent = resolve(node.value)
164
+ return f'{parent}.{node.attr}' if parent else node.attr
165
+ return ''
166
+ for _ in range(4):
167
+ changed = False
168
+ for node in nodes:
169
+ updates = {}
170
+ if isinstance(node, ast.Import):
171
+ for alias in node.names:
172
+ local = alias.asname or alias.name.split('.')[0]
173
+ updates[local] = alias.name if alias.asname else local
174
+ elif isinstance(node, ast.ImportFrom):
175
+ module = node.module or ''
176
+ for alias in node.names:
177
+ if alias.name == '*':
178
+ continue
179
+ updates[alias.asname or alias.name] = f'{module}.{alias.name}'.strip('.')
180
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
181
+ updates[node.name] = '__local__.' + node.name
182
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
183
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
184
+ value = node.value
185
+ if isinstance(value, ast.Call):
186
+ provenance = resolve(value.func)
187
+ elif isinstance(value, (ast.Name, ast.Attribute)):
188
+ provenance = resolve(value)
189
+ else:
190
+ provenance = ''
191
+ if provenance:
192
+ for target in targets:
193
+ if isinstance(target, ast.Name):
194
+ updates[target.id] = provenance
195
+ for name, value in updates.items():
196
+ if bindings.get(name) != value:
197
+ bindings[name] = value
198
+ changed = True
199
+ if not changed:
200
+ break
201
+ return [(_ast_name(node.func), resolve(node.func), node) for node in ast.walk(tree) if isinstance(node, ast.Call)]
202
+
203
+ def _call_name_matches(observed, expected):
204
+ return observed == expected or observed.endswith('.' + expected)
205
+
206
+ def _objective_call_targets(kind, check, resolved_calls, constants):
207
+ """Return canonical targets satisfying one already-validated call check."""
208
+ function = str(check.get('function') or check.get('value') or '')
209
+ targets = set()
210
+ for name, target, node in resolved_calls:
211
+ if not _call_name_matches(name, function):
212
+ continue
213
+ if kind == 'python_call_literal' and (not _node_contains_literal(node, check.get('value'), constants)):
214
+ continue
215
+ if kind == 'python_call_keyword_literal' and (not _call_keyword_matches(node, str(check.get('keyword') or ''), check.get('value'), constants)):
216
+ continue
217
+ if kind == 'python_call_signature' and (not _call_signature_matches(node, check.get('arguments') or [], check.get('keywords') or {}, constants, check.get('argument_expressions') or [], check.get('keyword_expressions') or {}, check.get('assignment'))):
218
+ continue
219
+ if target:
220
+ targets.add(target)
221
+ return targets
222
+
223
+ def python_unbound_call_roots(text):
224
+ """Return call-root names that have no static binding in the module.
225
+
226
+ Objective call checks must not accept a syntactically valid file that will
227
+ immediately raise ``NameError``. This deliberately proves only the
228
+ conservative prerequisite that a root is imported, assigned, declared,
229
+ passed as an argument, or provided by Python builtins; it does not claim to
230
+ execute or type-check the program.
231
+ """
232
+ tree = ast.parse(text)
233
+ bound = set(dir(builtins))
234
+ for node in ast.walk(tree):
235
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
236
+ bound.add(node.id)
237
+ elif isinstance(node, ast.arg):
238
+ bound.add(node.arg)
239
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
240
+ bound.add(node.name)
241
+ elif isinstance(node, ast.Import):
242
+ for alias in node.names:
243
+ bound.add(alias.asname or alias.name.split('.')[0])
244
+ elif isinstance(node, ast.ImportFrom):
245
+ for alias in node.names:
246
+ bound.add(alias.asname or alias.name)
247
+ elif isinstance(node, ast.ExceptHandler) and node.name:
248
+ bound.add(node.name)
249
+ unbound = set()
250
+ for node in ast.walk(tree):
251
+ if not isinstance(node, ast.Call):
252
+ continue
253
+ root = node.func
254
+ while isinstance(root, ast.Attribute):
255
+ root = root.value
256
+ if isinstance(root, ast.Name) and root.id not in bound:
257
+ unbound.add(root.id)
258
+ return sorted(unbound)
259
+
260
+ def _node_contains_literal(node, expected, constants):
261
+ for child in ast.walk(node):
262
+ value = _literal_value(child, constants)
263
+ if value is _UNRESOLVED:
264
+ continue
265
+ if value == expected:
266
+ return True
267
+ if isinstance(value, (list, tuple)) and expected in value:
268
+ return True
269
+ return False
270
+
271
+ def _call_keyword_matches(node, keyword, expected, constants):
272
+ """Return whether a direct call keyword resolves to the expected scalar."""
273
+ return any((item.arg == keyword and _literal_value(item.value, constants) == expected for item in getattr(node, 'keywords', []) if item.arg is not None))
274
+
275
+ def _portable_literal(value):
276
+ if isinstance(value, tuple):
277
+ return [_portable_literal(item) for item in value]
278
+ if isinstance(value, list):
279
+ return [_portable_literal(item) for item in value]
280
+ return value
281
+
282
+ def _expression_text(node):
283
+ """Return a formatting-independent, non-executed Python expression."""
284
+ return ast.unparse(node).strip()
285
+
286
+ def _expression_fingerprint(value):
287
+ if not isinstance(value, str) or not value.strip() or len(value) > 500:
288
+ return None
289
+ try:
290
+ tree = ast.parse(value, mode='eval')
291
+ except SyntaxError:
292
+ return None
293
+ return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
294
+
295
+ def _expression_matches(node, expected):
296
+ fingerprint = _expression_fingerprint(expected)
297
+ return bool(fingerprint and ast.dump(node, annotate_fields=True, include_attributes=False) == fingerprint)
298
+
299
+ def _annotate_assignment_contexts(tree):
300
+ """Attach one conservative simple-assignment context to nested calls."""
301
+ for statement in ast.walk(tree):
302
+ target, value = (None, None)
303
+ if isinstance(statement, ast.Assign) and len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name):
304
+ target, value = (statement.targets[0].id, statement.value)
305
+ elif isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name) and (statement.value is not None):
306
+ target, value = (statement.target.id, statement.value)
307
+ if not target or value is None:
308
+ continue
309
+ context = {'target': target, 'expression': _expression_text(value)}
310
+ for child in ast.walk(value):
311
+ if isinstance(child, ast.Call):
312
+ setattr(child, '_mybench_assignment', context)
313
+
314
+ def _call_signature(node, constants):
315
+ arguments = []
316
+ argument_expressions = []
317
+ for index, argument in enumerate(getattr(node, 'args', [])):
318
+ value = _literal_value(argument, constants)
319
+ if value is not _UNRESOLVED:
320
+ arguments.append({'index': index, 'value': _portable_literal(value)})
321
+ else:
322
+ argument_expressions.append({'index': index, 'expression': _expression_text(argument)})
323
+ keywords = {}
324
+ keyword_expressions = {}
325
+ for keyword in getattr(node, 'keywords', []):
326
+ if keyword.arg is None:
327
+ continue
328
+ value = _literal_value(keyword.value, constants)
329
+ if value is not _UNRESOLVED:
330
+ keywords[keyword.arg] = _portable_literal(value)
331
+ else:
332
+ keyword_expressions[keyword.arg] = _expression_text(keyword.value)
333
+ signature = {'arguments': arguments, 'keywords': keywords, 'argument_expressions': argument_expressions, 'keyword_expressions': keyword_expressions}
334
+ assignment = getattr(node, '_mybench_assignment', None)
335
+ if isinstance(assignment, dict):
336
+ signature['assignment'] = dict(assignment)
337
+ return signature
338
+
339
+ def _call_signature_matches(node, arguments, keywords, constants, argument_expressions=None, keyword_expressions=None, assignment=None):
340
+ for expected in arguments or []:
341
+ index = expected.get('index')
342
+ if not isinstance(index, int) or index < 0 or index >= len(getattr(node, 'args', [])):
343
+ return False
344
+ actual = _literal_value(node.args[index], constants)
345
+ if actual is _UNRESOLVED or _canonical(_portable_literal(actual)) != _canonical(expected.get('value')):
346
+ return False
347
+ for keyword, expected in (keywords or {}).items():
348
+ if not _call_keyword_matches(node, keyword, expected, constants):
349
+ return False
350
+ for expected in argument_expressions or []:
351
+ index = expected.get('index')
352
+ if not isinstance(index, int) or index < 0 or index >= len(getattr(node, 'args', [])) or (not _expression_matches(node.args[index], expected.get('expression'))):
353
+ return False
354
+ node_keywords = {item.arg: item.value for item in getattr(node, 'keywords', []) if item.arg is not None}
355
+ for keyword, expected in (keyword_expressions or {}).items():
356
+ if keyword not in node_keywords or not _expression_matches(node_keywords[keyword], expected):
357
+ return False
358
+ if assignment:
359
+ actual = getattr(node, '_mybench_assignment', None)
360
+ if not isinstance(actual, dict) or actual.get('target') != assignment.get('target') or _expression_fingerprint(actual.get('expression')) != _expression_fingerprint(assignment.get('expression')):
361
+ return False
362
+ return bool(arguments or keywords or argument_expressions or keyword_expressions or assignment)
363
+
364
+ def python_call_literal_signatures(text, function, expected, keyword=None):
365
+ """Return full literal signatures for matching reference call sites."""
366
+ _, _, constants, call_nodes = _python_semantics(text)
367
+ out = []
368
+ for name, node in call_nodes:
369
+ if not (name == function or name.endswith('.' + function)):
370
+ continue
371
+ matches = _call_keyword_matches(node, keyword, expected, constants) if keyword else _node_contains_literal(node, expected, constants)
372
+ if matches:
373
+ out.append(_call_signature(node, constants))
374
+ return out
375
+
376
+ def python_signature_expression_coverage_issues(evaluator, requirements=None):
377
+ """Detect anchored call expressions omitted by a static verifier.
378
+
379
+ Literal-only call checks used to silently discard non-literal positional
380
+ and keyword expressions from the same package-owned call. That allowed a
381
+ candidate to retain one easy literal while replacing the actual callback,
382
+ input binding, or argument tuple. Only expressions present in the
383
+ selected requirement text are required here; unrelated reference-file
384
+ context remains outside the objective contract.
385
+ """
386
+ if not isinstance(evaluator, dict) or evaluator.get('type') != WORKSPACE_EVALUATOR:
387
+ return []
388
+ reference_files = {str(item.get('path') or ''): str(item.get('content') or '') for item in evaluator.get('reference_files') or [] if isinstance(item, dict)}
389
+ requirement_texts = [re.sub('\\s+', '', str(item.get('requirement') or '')) for item in requirements or [] if isinstance(item, dict)]
390
+ issues = []
391
+ for check in evaluator.get('checks') or []:
392
+ if not isinstance(check, dict) or check.get('type') != 'python_call_signature':
393
+ continue
394
+ function = str(check.get('function') or '')
395
+ source = reference_files.get(str(check.get('path') or ''), '')
396
+ if not function or not source:
397
+ continue
398
+ try:
399
+ _, _, constants, call_nodes = _python_semantics(source)
400
+ except SyntaxError:
401
+ issues.append('Python signature reference content is invalid')
402
+ continue
403
+ matches = [node for name, node in call_nodes if _call_name_matches(name, function) and _call_signature_matches(node, check.get('arguments') or [], check.get('keywords') or {}, constants, check.get('argument_expressions') or [], check.get('keyword_expressions') or {}, check.get('assignment'))]
404
+ if len(matches) != 1:
405
+ issues.append('Python call signature does not identify one reference call')
406
+ continue
407
+ reference_signature = _call_signature(matches[0], constants)
408
+ function_tokens = {re.sub('\\s+', '', function), re.sub('\\s+', '', function.rsplit('.', 1)[-1])}
409
+
410
+ def positional_is_anchored(expression):
411
+ compact = re.sub('\\s+', '', str(expression or ''))
412
+ return any((compact and compact in text and any((token and token in text for token in function_tokens)) for text in requirement_texts))
413
+
414
+ def keyword_is_anchored(name, expression):
415
+ compact = re.sub('\\s+', '', str(expression or ''))
416
+ needle = f'{name}={compact}'
417
+ return any((compact and needle in text and any((token and token in text for token in function_tokens)) for text in requirement_texts))
418
+ expected_arguments = {item['index']: item.get('expression') for item in reference_signature.get('argument_expressions') or [] if positional_is_anchored(item.get('expression'))}
419
+ expected_keywords = {name: expression for name, expression in (reference_signature.get('keyword_expressions') or {}).items() if keyword_is_anchored(name, expression)}
420
+ actual_arguments = {item.get('index'): item.get('expression') for item in check.get('argument_expressions') or [] if isinstance(item, dict)}
421
+ actual_keywords = check.get('keyword_expressions') or {}
422
+ expected_assignment = reference_signature.get('assignment')
423
+ if expected_assignment:
424
+ compact_assignment = re.sub('\\s+', '', f"{expected_assignment.get('target')}={expected_assignment.get('expression')}")
425
+ assignment_is_anchored = any((compact_assignment and compact_assignment in text and any((token and token in text for token in function_tokens)) for text in requirement_texts))
426
+ else:
427
+ assignment_is_anchored = False
428
+ actual_assignment = check.get('assignment')
429
+ missing_argument = any((index not in actual_arguments or _expression_fingerprint(actual_arguments[index]) != _expression_fingerprint(expression) for index, expression in expected_arguments.items()))
430
+ missing_keyword = any((name not in actual_keywords or _expression_fingerprint(actual_keywords[name]) != _expression_fingerprint(expression) for name, expression in expected_keywords.items()))
431
+ missing_assignment = bool(assignment_is_anchored and (not isinstance(actual_assignment, dict) or actual_assignment.get('target') != expected_assignment.get('target') or _expression_fingerprint(actual_assignment.get('expression')) != _expression_fingerprint(expected_assignment.get('expression'))))
432
+ if missing_argument or missing_keyword or missing_assignment:
433
+ issues.append('Python call signature omits an anchored expression or assignment')
434
+ return issues
435
+
436
+ def _shell_lines(text):
437
+ """Return executable lines with conservative local scalar substitution.
438
+
439
+ Shell authors routinely name a fixed argument before using it (for example
440
+ ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
441
+ assignments; never evaluate shell expressions, commands, or defaults.
442
+ """
443
+ logical, pending = ([], '')
444
+ for raw in str(text or '').splitlines():
445
+ line = ' '.join(raw.strip().split())
446
+ if not line or line.startswith('#') or line in {'set -e', 'set -eu', 'set -euo pipefail'}:
447
+ continue
448
+ pending = (pending + ' ' + line).strip() if pending else line
449
+ if pending.endswith('\\'):
450
+ pending = pending[:-1].rstrip()
451
+ continue
452
+ logical.append(pending)
453
+ pending = ''
454
+ if pending:
455
+ logical.append(pending)
456
+ constants, out = ({}, [])
457
+ assignment = re.compile('^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:\'([^\'$`]*)\'|\\"([^\\"$`]*)\\"|([A-Za-z0-9_./:+-]+))$')
458
+ variable = re.compile('\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}|\\$([A-Za-z_][A-Za-z0-9_]*)')
459
+ for line in logical:
460
+ match = assignment.fullmatch(line)
461
+ if match:
462
+ constants[match.group(1)] = next((value for value in match.groups()[1:] if value is not None))
463
+ out.append(line)
464
+ continue
465
+
466
+ def replace(match):
467
+ name = match.group(1) or match.group(2)
468
+ return constants.get(name, match.group(0))
469
+ out.append(variable.sub(replace, line))
470
+ return out
471
+
472
+ def _shell_command_matches(expected, actual):
473
+ """Accept the frozen invocation plus documented optional arguments/path prefixes."""
474
+ try:
475
+ wanted = shlex.split(str(expected))
476
+ found = shlex.split(str(actual))
477
+ except ValueError:
478
+ return False
479
+
480
+ def normalize_git_log_limit(tokens):
481
+ if len(tokens) < 2 or tokens[:2] != ['git', 'log']:
482
+ return tokens
483
+ normalized, index = ([], 0)
484
+ while index < len(tokens):
485
+ token = tokens[index]
486
+ short = re.fullmatch('-(\\d+)', token)
487
+ long = re.fullmatch('--max-count=(\\d+)', token)
488
+ if short or long:
489
+ normalized.append('--max-count=' + (short or long).group(1))
490
+ elif token in {'-n', '--max-count'} and index + 1 < len(tokens) and re.fullmatch('\\d+', tokens[index + 1]):
491
+ normalized.append('--max-count=' + tokens[index + 1])
492
+ index += 1
493
+ else:
494
+ normalized.append(token)
495
+ index += 1
496
+ return normalized
497
+ wanted = normalize_git_log_limit(wanted)
498
+ found = normalize_git_log_limit(found)
499
+ if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
500
+ return False
501
+ for index, token in enumerate(wanted[1:], 1):
502
+ observed = found[index]
503
+ if observed == token:
504
+ continue
505
+ if index == 1 and '/' in token and observed.rstrip('/').endswith(token.lstrip('./')):
506
+ continue
507
+ return False
508
+ return True
509
+
510
+ def _shell_command_sequence_matches(expected, actual_lines):
511
+ """Require every frozen command in order while allowing extra lines."""
512
+ cursor = 0
513
+ for command in expected:
514
+ for index in range(cursor, len(actual_lines)):
515
+ if _shell_command_matches(command, actual_lines[index]):
516
+ cursor = index + 1
517
+ break
518
+ else:
519
+ return False
520
+ return True
521
+
522
+ def _shell_unconditional_lines(text):
523
+ """Return conservative top-level command lines from a shell artifact.
524
+
525
+ Checked commands hidden in a conditional branch or an uncalled function do
526
+ not establish that the requested script performs them. This is not a full
527
+ shell parser: unsupported control flow simply makes nested lines
528
+ ineligible, which is appropriate for the small straight-line command
529
+ artifacts compiled by this evaluator.
530
+ """
531
+ lines = _shell_lines(text)
532
+ depth = 0
533
+ out = []
534
+ opener = re.compile('^(?:if\\b|for\\b|while\\b|until\\b|case\\b|select\\b|(?:function\\s+)?[A-Za-z_][A-Za-z0-9_]*\\s*\\(\\s*\\)\\s*\\{)')
535
+ closer = re.compile('^(?:fi\\b|done\\b|esac\\b|\\})')
536
+ for line in lines:
537
+ if closer.match(line):
538
+ depth = max(0, depth - 1)
539
+ continue
540
+ if depth == 0 and (not opener.match(line)):
541
+ out.append(line)
542
+ if opener.match(line):
543
+ depth += 1
544
+ return out
545
+
546
+ def _shell_is_straight_line(text):
547
+ """Return whether every executable logical line is top-level.
548
+
549
+ This deliberately reuses the conservative control-flow recognizer used by
550
+ unconditional command checks. Any recognized conditional, loop, case, or
551
+ function makes the whole-script straight-line contract fail closed.
552
+ """
553
+ lines = _shell_lines(text)
554
+ return lines == _shell_unconditional_lines(text)
555
+
556
+ def compile_workspace_evaluator(deliverables):
557
+ """Compile trusted checks from validated deliverable specifications."""
558
+ if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
559
+ raise ObjectiveEvaluatorError('workspace task requires 1-6 deliverables')
560
+ reference_files, checks, paths = ([], [], set())
561
+ for index, raw in enumerate(deliverables, 1):
562
+ if not isinstance(raw, dict):
563
+ raise ObjectiveEvaluatorError('deliverable is not an object')
564
+ path = safe_relative_path(raw.get('path'))
565
+ if path in paths:
566
+ raise ObjectiveEvaluatorError(f'duplicate deliverable path: {path}')
567
+ paths.add(path)
568
+ fmt = str(raw.get('format') or '').strip().casefold()
569
+ if fmt not in ARTIFACT_FORMATS:
570
+ raise ObjectiveEvaluatorError(f'unsupported artifact format: {fmt}')
571
+ content = _file_content({**raw, 'format': fmt})
572
+ if len(content.encode('utf-8')) > 200000:
573
+ raise ObjectiveEvaluatorError('reference artifact exceeds 200 KB')
574
+ reference_files.append({'path': path, 'format': fmt, 'content': content})
575
+ checks.append({'id': f'file_{index:03d}', 'type': 'file_exists', 'path': path})
576
+ if fmt == 'json':
577
+ checks.append({'id': f'json_{index:03d}', 'type': 'json_exact', 'path': path, 'expected': _json_value(raw.get('content'))})
578
+ elif fmt == 'toml':
579
+ try:
580
+ expected = tomllib.loads(content)
581
+ except (tomllib.TOMLDecodeError, ValueError) as exc:
582
+ raise ObjectiveEvaluatorError('reference TOML is invalid') from exc
583
+ checks.append({'id': f'toml_{index:03d}', 'type': 'toml_exact', 'path': path, 'expected': expected})
584
+ elif fmt == 'python':
585
+ try:
586
+ _, _, constants, call_nodes = _python_semantics(content)
587
+ resolved_calls = _python_resolved_call_nodes(content)
588
+ except SyntaxError as exc:
589
+ raise ObjectiveEvaluatorError('reference Python is invalid') from exc
590
+ checks.append({'id': f'python_{index:03d}', 'type': 'python_syntax', 'path': path})
591
+ checks.append({'id': f'python_{index:03d}_bindings', 'type': 'python_bound_calls', 'path': path})
592
+ raw_checks = raw.get('checks') or []
593
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
594
+ raise ObjectiveEvaluatorError('Python deliverable requires 1-12 objective import/call checks')
595
+ for check_index, check in enumerate(raw_checks, 1):
596
+ if not isinstance(check, dict):
597
+ raise ObjectiveEvaluatorError('Python check is not an object')
598
+ kind = str(check.get('type') or '').strip().casefold()
599
+ if kind in {'python_import', 'python_call'}:
600
+ value = str(check.get('value') or '').strip()
601
+ if not _DOTTED.fullmatch(value):
602
+ raise ObjectiveEvaluatorError('unsupported Python objective check')
603
+ compiled = {'type': kind, 'path': path, 'value': value}
604
+ elif kind == 'python_constant':
605
+ name = str(check.get('name') or '').strip()
606
+ value = check.get('value')
607
+ if not _DOTTED.fullmatch(name) or '.' in name or isinstance(value, (dict, list)) or (value is None) or (constants.get(name, _UNRESOLVED) != value):
608
+ raise ObjectiveEvaluatorError('Python constant check is invalid or fails reference content')
609
+ compiled = {'type': kind, 'path': path, 'name': name, 'value': value}
610
+ elif kind == 'python_call_literal':
611
+ function = str(check.get('function') or '').strip()
612
+ value = check.get('value')
613
+ if not _DOTTED.fullmatch(function) or isinstance(value, (dict, list)) or value is None or (not any(((name == function or name.endswith('.' + function)) and _node_contains_literal(node, value, constants) for name, node in call_nodes))):
614
+ raise ObjectiveEvaluatorError('Python call-literal check is invalid or fails reference content')
615
+ compiled = {'type': kind, 'path': path, 'function': function, 'value': value}
616
+ elif kind == 'python_call_keyword_literal':
617
+ function = str(check.get('function') or '').strip()
618
+ keyword = str(check.get('keyword') or '').strip()
619
+ value = check.get('value')
620
+ if not _DOTTED.fullmatch(function) or not _DOTTED.fullmatch(keyword) or '.' in keyword or isinstance(value, (dict, list)) or (value is None) or (not any(((name == function or name.endswith('.' + function)) and _call_keyword_matches(node, keyword, value, constants) for name, node in call_nodes))):
621
+ raise ObjectiveEvaluatorError('Python call-keyword check is invalid or fails reference content')
622
+ compiled = {'type': kind, 'path': path, 'function': function, 'keyword': keyword, 'value': value}
623
+ elif kind == 'python_call_signature':
624
+ function = str(check.get('function') or '').strip()
625
+ arguments = check.get('arguments') or []
626
+ keywords = check.get('keywords') or {}
627
+ argument_expressions = check.get('argument_expressions') or []
628
+ keyword_expressions = check.get('keyword_expressions') or {}
629
+ assignment = check.get('assignment')
630
+ if not _DOTTED.fullmatch(function) or not isinstance(arguments, list) or (not isinstance(keywords, dict)) or (not isinstance(argument_expressions, list)) or (not isinstance(keyword_expressions, dict)) or (not (arguments or keywords or argument_expressions or keyword_expressions or assignment)) or any((not isinstance(item, dict) or not isinstance(item.get('index'), int) or item.get('index') < 0 or isinstance(item.get('value'), dict) for item in arguments)) or (len({item['index'] for item in arguments}) != len(arguments)) or any((not _DOTTED.fullmatch(str(name)) or '.' in str(name) or isinstance(value, dict) for name, value in keywords.items())) or any((not isinstance(item, dict) or not isinstance(item.get('index'), int) or item.get('index') < 0 or (not _expression_fingerprint(item.get('expression'))) for item in argument_expressions)) or (len({item['index'] for item in argument_expressions}) != len(argument_expressions)) or ({item['index'] for item in arguments} & {item['index'] for item in argument_expressions}) or any((not _DOTTED.fullmatch(str(name)) or '.' in str(name) or (not _expression_fingerprint(value)) for name, value in keyword_expressions.items())) or (set(keywords) & set(keyword_expressions)) or (assignment is not None and (not isinstance(assignment, dict) or not _DOTTED.fullmatch(str(assignment.get('target') or '')) or '.' in str(assignment.get('target') or '') or (not _expression_fingerprint(assignment.get('expression'))))) or (not any(((name == function or name.endswith('.' + function)) and _call_signature_matches(node, arguments, keywords, constants, argument_expressions, keyword_expressions, assignment) for name, node in call_nodes))):
631
+ raise ObjectiveEvaluatorError('Python call-signature check is invalid or fails reference content')
632
+ compiled = {'type': kind, 'path': path, 'function': function, 'arguments': arguments, 'keywords': keywords, 'argument_expressions': argument_expressions, 'keyword_expressions': keyword_expressions, 'assignment': assignment}
633
+ else:
634
+ raise ObjectiveEvaluatorError('unsupported Python objective check')
635
+ if kind in {'python_call', 'python_call_literal', 'python_call_keyword_literal', 'python_call_signature'}:
636
+ targets = _objective_call_targets(kind, compiled, resolved_calls, constants)
637
+ if len(targets) != 1:
638
+ raise ObjectiveEvaluatorError('Python call check has no unique canonical target')
639
+ compiled['target'] = next(iter(targets))
640
+ checks.append({'id': f'python_{index:03d}_{check_index:03d}', **compiled})
641
+ else:
642
+ raw_checks = raw.get('checks') or []
643
+ if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
644
+ raise ObjectiveEvaluatorError('shell deliverable requires 1-12 objective command checks')
645
+ checks.append({'id': f'shell_{index:03d}', 'type': 'shell_syntax', 'path': path})
646
+ reference_sequence = _shell_lines(content)
647
+ reference_lines = set(reference_sequence)
648
+ unconditional_lines = _shell_unconditional_lines(content)
649
+ command_checks = []
650
+ for check in raw_checks:
651
+ value = ' '.join(str(check.get('value') or '').strip().split())
652
+ if not isinstance(check, dict) or str(check.get('type') or '').strip().casefold() != 'shell_command' or (not value) or (value not in reference_lines):
653
+ raise ObjectiveEvaluatorError('unsupported shell objective check')
654
+ command_checks.append({'type': 'shell_command', 'path': path, 'value': value})
655
+ if len({item['value'] for item in command_checks}) != len(command_checks):
656
+ raise ObjectiveEvaluatorError('shell objective checks must be unique')
657
+ command_checks.sort(key=lambda item: reference_sequence.index(item['value']))
658
+ if not all((any((_shell_command_matches(item['value'], line) for line in unconditional_lines)) for item in command_checks)):
659
+ raise ObjectiveEvaluatorError('checked shell commands must be top-level and unconditional')
660
+ for check_index, check in enumerate(command_checks, 1):
661
+ checks.append({'id': f'shell_{index:03d}_{check_index:03d}', **check})
662
+ if len(command_checks) >= 2:
663
+ checks.append({'id': f'shell_{index:03d}_sequence', 'type': 'shell_command_sequence', 'path': path, 'values': [item['value'] for item in command_checks]})
664
+ checks.append({'id': f'shell_{index:03d}_unconditional', 'type': 'shell_unconditional_commands', 'path': path, 'values': [item['value'] for item in command_checks]})
665
+ reference_calls = shell_invocations(content)
666
+ protected = [item['value'] for item in command_checks if any((call['fail_fast'] and _shell_command_matches(item['value'], call['command']) for call in reference_calls))]
667
+ if protected:
668
+ checks.append({'id': f'shell_{index:03d}_failure_propagation', 'type': 'shell_failure_propagation', 'path': path, 'values': protected})
669
+ checks.append({'id': f'shell_{index:03d}_exact_count', 'type': 'shell_exact_command_count', 'path': path, 'count': len(command_checks)})
670
+ output_roots = sorted({path.split('/', 1)[0] for path in paths if '/' in path})
671
+ if len(output_roots) == len({path.split('/', 1)[0] for path in paths}):
672
+ checks.insert(0, {'id': 'workspace_file_set', 'type': 'workspace_file_set', 'paths': sorted(paths), 'roots': output_roots})
673
+ return {'type': WORKSPACE_EVALUATOR, 'version': WORKSPACE_EVALUATOR_VERSION, 'output_mode': 'workspace', 'reference_files': reference_files, 'checks': checks}
674
+
675
+ def reference_bundle(evaluator):
676
+ if evaluator.get('type') != WORKSPACE_EVALUATOR:
677
+ raise ObjectiveEvaluatorError('not a workspace evaluator')
678
+ return {'files': [{'path': item['path'], 'content': item['content']} for item in evaluator.get('reference_files') or []]}
679
+
680
+ def hidden_workspace_values(evaluator):
681
+ """Return decisive package-owned values that public queries must not leak."""
682
+ values = []
683
+ for check in (evaluator or {}).get('checks') or []:
684
+ kind = check.get('type')
685
+ if kind in {'json_exact', 'toml_exact'}:
686
+ values.extend((value for _, value in _flatten(check.get('expected'))))
687
+ elif kind in {'python_import', 'python_call', 'shell_command', 'python_constant', 'python_call_literal', 'python_call_keyword_literal'}:
688
+ values.append(check.get('value'))
689
+ elif kind == 'python_call_signature':
690
+ values.extend((value for _, value in _flatten({'arguments': [item.get('value') for item in check.get('arguments') or []], 'keywords': check.get('keywords') or {}, 'argument_expressions': [item.get('expression') for item in check.get('argument_expressions') or []], 'keyword_expressions': check.get('keyword_expressions') or {}, 'assignment': check.get('assignment')})))
691
+ return [value for value in values if value is not None]
692
+
693
+ def _flatten(value, path=()):
694
+ if isinstance(value, dict):
695
+ out = []
696
+ for key, item in value.items():
697
+ out.extend(_flatten(item, path + (str(key),)))
698
+ return out
699
+ if isinstance(value, list):
700
+ out = []
701
+ for index, item in enumerate(value):
702
+ out.extend(_flatten(item, path + (index,)))
703
+ return out
704
+ return [(path, value)]
705
+
706
+ def _bundle_rows(candidate):
707
+ if isinstance(candidate, str):
708
+ text = candidate.strip()
709
+ decoder = json.JSONDecoder()
710
+ candidate = None
711
+ for match in re.finditer('\\{', text):
712
+ try:
713
+ parsed, _ = decoder.raw_decode(text, match.start())
714
+ except json.JSONDecodeError:
715
+ continue
716
+ if isinstance(parsed, dict) and 'files' in parsed:
717
+ candidate = parsed
718
+ break
719
+ if candidate is None:
720
+ raise ObjectiveEvaluatorError('workspace response contains no complete JSON file bundle')
721
+ if not isinstance(candidate, dict):
722
+ raise ObjectiveEvaluatorError('workspace candidate must be a file bundle object')
723
+ files = candidate.get('files')
724
+ if isinstance(files, dict):
725
+ files = [{'path': path, 'content': content} for path, content in files.items()]
726
+ if not isinstance(files, list) or len(files) > 30:
727
+ raise ObjectiveEvaluatorError('workspace candidate files must be a bounded list')
728
+ return files
729
+
730
+ def materialize_bundle(candidate, workspace):
731
+ root = Path(workspace).resolve()
732
+ root.mkdir(parents=True, exist_ok=True)
733
+ seen = set()
734
+ for item in _bundle_rows(candidate):
735
+ if not isinstance(item, dict):
736
+ raise ObjectiveEvaluatorError('candidate file entry is not an object')
737
+ relative = safe_relative_path(item.get('path'))
738
+ if relative in seen:
739
+ raise ObjectiveEvaluatorError(f'duplicate candidate file: {relative}')
740
+ seen.add(relative)
741
+ content = item.get('content')
742
+ if isinstance(content, (dict, list)):
743
+ content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
744
+ if not isinstance(content, str) or len(content.encode('utf-8')) > 500000:
745
+ raise ObjectiveEvaluatorError('candidate file content is invalid or too large')
746
+ target = (root / relative).resolve()
747
+ if root not in target.parents:
748
+ raise ObjectiveEvaluatorError('candidate file escapes workspace')
749
+ target.parent.mkdir(parents=True, exist_ok=True)
750
+ target.write_text(content, encoding='utf-8')
751
+ return root
752
+
753
+ def evaluate_workspace(evaluator, workspace):
754
+ if not isinstance(evaluator, dict) or evaluator.get('type') != WORKSPACE_EVALUATOR or int(evaluator.get('version') or 0) not in SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS:
755
+ return (False, {'error': 'invalid workspace evaluator contract'})
756
+ root = Path(workspace).resolve()
757
+ results = []
758
+ for check in evaluator.get('checks') or []:
759
+ kind = check.get('type')
760
+ relative, path = ('', None)
761
+ if kind != 'workspace_file_set':
762
+ relative = safe_relative_path(check.get('path'))
763
+ path = (root / relative).resolve()
764
+ if root not in path.parents:
765
+ return (False, {'error': 'evaluator path escapes workspace'})
766
+ passed, detail = (False, '')
767
+ try:
768
+ if kind == 'workspace_file_set':
769
+ expected = {safe_relative_path(value) for value in check.get('paths') or []}
770
+ roots = [safe_relative_path(value) for value in check.get('roots') or []]
771
+ actual = set()
772
+ for relative_root in roots:
773
+ scan_root = (root / relative_root).resolve()
774
+ if root not in scan_root.parents:
775
+ raise ObjectiveEvaluatorError('workspace file-set root escapes workspace')
776
+ if not scan_root.exists():
777
+ continue
778
+ for candidate in scan_root.rglob('*'):
779
+ if candidate.is_file() or candidate.is_symlink():
780
+ actual.add(candidate.relative_to(root).as_posix())
781
+ passed = bool(expected) and actual == expected
782
+ detail = 'exact deliverable file set' if passed else f'expected_files={sorted(expected)}; actual_files={sorted(actual)}'
783
+ elif kind == 'file_exists':
784
+ passed = path.is_file()
785
+ detail = 'present' if passed else 'missing'
786
+ elif kind == 'json_exact':
787
+ actual = json.loads(path.read_text(encoding='utf-8'))
788
+ passed = (_same_native_json_types(actual, check.get("expected")) and
789
+ _canonical(actual) == _canonical(check.get("expected")))
790
+ detail = 'semantic JSON match' if passed else 'JSON value mismatch'
791
+ elif kind == 'toml_exact':
792
+ actual = tomllib.loads(path.read_text(encoding='utf-8'))
793
+ passed = _canonical(actual) == _canonical(check.get('expected'))
794
+ detail = 'semantic TOML match' if passed else 'TOML value mismatch'
795
+ elif kind in {'python_syntax', 'python_bound_calls', 'python_import', 'python_call', 'python_constant', 'python_call_literal', 'python_call_keyword_literal', 'python_call_signature'}:
796
+ source = path.read_text(encoding='utf-8')
797
+ imports, calls, constants, call_nodes = _python_semantics(source)
798
+ resolved_calls = _python_resolved_call_nodes(source)
799
+ if kind == 'python_syntax':
800
+ passed, detail = (True, 'valid Python syntax')
801
+ elif kind == 'python_bound_calls':
802
+ unbound = python_unbound_call_roots(path.read_text(encoding='utf-8'))
803
+ passed = not unbound
804
+ detail = 'all call roots are statically bound' if passed else 'unbound call roots=' + repr(unbound)
805
+ elif kind == 'python_import':
806
+ expected = str(check.get('value') or '')
807
+ passed = expected in imports or any((value == expected or value.startswith(expected + '.') for value in imports))
808
+ detail = f'imports={sorted(imports)}'
809
+ elif kind == 'python_call':
810
+ expected = str(check.get('value') or '')
811
+ target = str(check.get('target') or '')
812
+ passed = any((canonical == target for _, canonical, _ in resolved_calls)) if target else expected in calls or any((value.endswith('.' + expected) for value in calls))
813
+ detail = f'calls={sorted(calls)}'
814
+ elif kind == 'python_constant':
815
+ name, expected = (str(check.get('name') or ''), check.get('value'))
816
+ actual = constants.get(name, _UNRESOLVED)
817
+ passed = actual is not _UNRESOLVED and actual == expected
818
+ detail = f'constant {name}={actual!r}'
819
+ elif kind == 'python_call_literal':
820
+ function, expected = (str(check.get('function') or ''), check.get('value'))
821
+ target = str(check.get('target') or '')
822
+ source_calls = resolved_calls if target else [(name, '', node) for name, node in call_nodes]
823
+ passed = any(((bool(target) or _call_name_matches(name, function)) and (not target or canonical == target) and _node_contains_literal(node, expected, constants) for name, canonical, node in source_calls))
824
+ detail = f'call={function} literal={expected!r}'
825
+ elif kind == 'python_call_keyword_literal':
826
+ function = str(check.get('function') or '')
827
+ keyword = str(check.get('keyword') or '')
828
+ expected = check.get('value')
829
+ target = str(check.get('target') or '')
830
+ source_calls = resolved_calls if target else [(name, '', node) for name, node in call_nodes]
831
+ passed = any(((bool(target) or _call_name_matches(name, function)) and (not target or canonical == target) and _call_keyword_matches(node, keyword, expected, constants) for name, canonical, node in source_calls))
832
+ detail = f'call={function} keyword={keyword} literal={expected!r}'
833
+ else:
834
+ function = str(check.get('function') or '')
835
+ arguments = check.get('arguments') or []
836
+ keywords = check.get('keywords') or {}
837
+ argument_expressions = check.get('argument_expressions') or []
838
+ keyword_expressions = check.get('keyword_expressions') or {}
839
+ assignment = check.get('assignment')
840
+ target = str(check.get('target') or '')
841
+ source_calls = resolved_calls if target else [(name, '', node) for name, node in call_nodes]
842
+ passed = any(((bool(target) or _call_name_matches(name, function)) and (not target or canonical == target) and _call_signature_matches(node, arguments, keywords, constants, argument_expressions, keyword_expressions, assignment) for name, canonical, node in source_calls))
843
+ detail = f'call={function} arguments={arguments!r} keywords={keywords!r} argument_expressions={argument_expressions!r} keyword_expressions={keyword_expressions!r} assignment={assignment!r}'
844
+ elif kind == 'shell_syntax':
845
+ completed = subprocess.run(['bash', '-n', str(path)], capture_output=True, text=True, timeout=5, check=False)
846
+ passed = completed.returncode == 0
847
+ detail = 'valid shell syntax' if passed else (completed.stderr or 'invalid shell syntax').strip()
848
+ elif kind == 'shell_command':
849
+ source = path.read_text(encoding='utf-8')
850
+ lines = [call['command'] for call in shell_invocations(source)] if int(evaluator.get('version', 0)) >= 15 else _shell_lines(source)
851
+ expected = ' '.join(str(check.get('value') or '').split())
852
+ passed = any((_shell_command_matches(expected, line) for line in lines))
853
+ detail = f'executable_lines={lines[:30]}'
854
+ elif kind == 'shell_command_sequence':
855
+ source = path.read_text(encoding='utf-8')
856
+ lines = [call['command'] for call in shell_invocations(source)] if int(evaluator.get('version', 0)) >= 15 else _shell_lines(source)
857
+ expected = [' '.join(str(value).split()) for value in check.get('values') or []]
858
+ passed = len(expected) >= 2 and _shell_command_sequence_matches(expected, lines)
859
+ detail = f'expected_sequence={expected}; executable_lines={lines[:30]}'
860
+ elif kind == 'shell_unconditional_commands':
861
+ source = path.read_text(encoding='utf-8')
862
+ lines = [call['command'] for call in shell_invocations(source)] if int(evaluator.get('version', 0)) >= 15 else _shell_unconditional_lines(source)
863
+ expected = [' '.join(str(value).split()) for value in check.get('values') or []]
864
+ passed = bool(expected) and all((any((_shell_command_matches(command, line) for line in lines)) for command in expected))
865
+ if check.get("require_straight_line"):
866
+ passed = passed and _shell_is_straight_line(source)
867
+ detail = f'expected_unconditional={expected}; top_level_lines={lines[:30]}'
868
+ elif kind == 'shell_failure_propagation':
869
+ calls = shell_invocations(path.read_text(encoding='utf-8'))
870
+ expected = [' '.join(str(value).split()) for value in check.get('values') or []]
871
+ passed = bool(expected) and all((any((call['fail_fast'] and _shell_command_matches(command, call['command']) for call in calls)) for command in expected))
872
+ detail = f'expected_failure_propagation={expected}; invocations={calls[:30]}'
873
+ elif kind == 'shell_straight_line':
874
+ source = path.read_text(encoding='utf-8')
875
+ passed = _shell_is_straight_line(source)
876
+ if "allowed_commands" in check:
877
+ calls = shell_invocations(source)
878
+ allowed = check["allowed_commands"]
879
+ passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and
880
+ all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls))
881
+ detail = 'all executable lines are top-level' if passed else 'shell contains conditional, loop, case, or function'
882
+ _repair_original_straight = passed
883
+ source = path.read_text(encoding='utf-8')
884
+ lines = [call['command'] for call in shell_invocations(source)] if int(evaluator.get('version', 0)) >= 15 else _shell_unconditional_lines(source)
885
+ passed = len(lines) == check.get('count', 0)
886
+ detail = f"expected_command_count={check.get('count')}; actual={len(lines)}; lines={lines[:30]}"
887
+ passed = _repair_original_straight and passed
888
+ elif kind == 'shell_exact_command_count':
889
+ source = path.read_text(encoding='utf-8')
890
+ lines = [call['command'] for call in shell_invocations(source)] if int(evaluator.get('version', 0)) >= 15 else _shell_unconditional_lines(source)
891
+ passed = len(lines) == check.get('count', 0)
892
+ detail = f"expected_command_count={check.get('count')}; actual={len(lines)}; lines={lines[:30]}"
893
+ else:
894
+ detail = f'unsupported check: {kind}'
895
+ except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, json.JSONDecodeError, tomllib.TOMLDecodeError) as exc:
896
+ detail = str(exc)
897
+ results.append({'id': check.get('id'), 'type': kind, 'path': relative, 'passed': bool(passed), 'detail': detail[:1000]})
898
+ return (bool(results) and all((item['passed'] for item in results)), {'type': WORKSPACE_EVALUATOR, 'assertions_passed': sum((item['passed'] for item in results)), 'assertions_total': len(results), 'assertions': results})
899
+
900
+ def evaluate_candidate(evaluator, candidate):
901
+ if isinstance(candidate, os.PathLike):
902
+ try:
903
+ return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (False, {'type': WORKSPACE_EVALUATOR, 'error': 'candidate path is not a directory'})
904
+ except (OSError, ValueError) as exc:
905
+ return (False, {'type': WORKSPACE_EVALUATOR, 'error': str(exc)})
906
+ if isinstance(candidate, str):
907
+ stripped = candidate.strip()
908
+ if len(stripped) <= 4096 and '\n' not in stripped and ('\r' not in stripped) and (not stripped.startswith(('{', '[', '```'))):
909
+ try:
910
+ if Path(stripped).is_dir():
911
+ return evaluate_workspace(evaluator, stripped)
912
+ except (OSError, ValueError):
913
+ pass
914
+ try:
915
+ with tempfile.TemporaryDirectory(prefix='mybench-objective-') as temp:
916
+ materialize_bundle(candidate, temp)
917
+ return evaluate_workspace(evaluator, temp)
918
+ except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
919
+ return (False, {'type': WORKSPACE_EVALUATOR, 'error': str(exc)})
920
+
921
+ def self_test_workspace_evaluator(evaluator):
922
+ correct = reference_bundle(evaluator)
923
+ ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
924
+ rows = list(correct.get('files') or [])
925
+ perturbed = {'files': rows[1:] if len(rows) > 1 else []}
926
+ ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
927
+ mutations = []
928
+ for check in evaluator.get('checks') or []:
929
+ if check.get('type') != 'json_exact':
930
+ continue
931
+ for path, value in _flatten(check.get('expected')):
932
+ candidate = copy.deepcopy(correct)
933
+ file_row = next((row for row in candidate['files'] if row['path'] == check['path']))
934
+ data = json.loads(file_row['content'])
935
+ replacement = not value if isinstance(value, bool) else value + 1 if isinstance(value, (int, float)) else str(value) + '__mutation__'
936
+ if not path:
937
+ data = replacement
938
+ else:
939
+ container = data
940
+ for key in path[:-1]:
941
+ container = container[key]
942
+ container[path[-1]] = replacement
943
+ file_row['content'] = json.dumps(data)
944
+ passed, _ = evaluate_candidate(evaluator, candidate)
945
+ mutations.append({'path': check['path'], 'field': list(path), 'rejected': not passed})
946
+ return (ok_correct and (not ok_wrong) and all((m['rejected'] for m in mutations)), {'correct': correct_detail, 'perturbed': wrong_detail, 'scalar_mutations': mutations})
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/legacy_tests/shell_invocations.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A deliberately bounded, non-executing shell structure recognizer.
2
+
3
+ Supports simple commands, literal scalar assignments, one command substitution
4
+ on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
5
+ It does not interpret shell code or credit commands in branch bodies/functions.
6
+ Pipelines, command lists, substitutions within substitutions, and swallowed
7
+ failures are outside this grammar. bash -n remains a separate required check.
8
+ """
9
+ import re
10
+ import shlex
11
+
12
+
13
+ def _statements(text):
14
+ out, current = [], []
15
+ quote, escaped, comment, depth = None, False, False, 0
16
+ for ch in str(text):
17
+ if comment:
18
+ if ch == '\n':
19
+ comment = False
20
+ else:
21
+ continue
22
+ if escaped:
23
+ if ch != '\n':
24
+ current.extend(('\\', ch))
25
+ escaped = False
26
+ continue
27
+ if ch == '\\' and quote != "'":
28
+ escaped = True
29
+ continue
30
+ if quote:
31
+ current.append(ch)
32
+ if ch == quote:
33
+ quote = None
34
+ continue
35
+ if ch in "'\"":
36
+ quote = ch
37
+ current.append(ch)
38
+ elif ch == '#' and (not current or current[-1].isspace()):
39
+ comment = True
40
+ elif ch == '(':
41
+ depth += 1
42
+ current.append(ch)
43
+ elif ch == ')':
44
+ depth -= 1
45
+ if depth < 0:
46
+ return []
47
+ current.append(ch)
48
+ elif ch in '\n;' and depth == 0:
49
+ value = ''.join(current).strip()
50
+ if value:
51
+ out.append(value)
52
+ current = []
53
+ else:
54
+ current.append(ch)
55
+ if quote or escaped or depth:
56
+ return []
57
+ if ''.join(current).strip():
58
+ out.append(''.join(current).strip())
59
+ expanded = []
60
+ for statement in out:
61
+ inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
62
+ expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
63
+ return expanded
64
+
65
+
66
+ def _simple_argv(text):
67
+ if '$(' in text or '`' in text:
68
+ return None
69
+ try:
70
+ lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
71
+ lexer.whitespace_split = True
72
+ tokens = list(lexer)
73
+ except ValueError:
74
+ return None
75
+ argv, index = [], 0
76
+ redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
77
+ while index < len(tokens):
78
+ token = tokens[index]
79
+ if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
80
+ index += 1
81
+ token = tokens[index]
82
+ if token in redirects:
83
+ if index + 1 >= len(tokens):
84
+ return None
85
+ target = tokens[index + 1]
86
+ if (not target or any(c in target for c in '$`;&|<>()')
87
+ or target in ('{', '}')):
88
+ return None
89
+ index += 2
90
+ continue
91
+ if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
92
+ return None
93
+ argv.append(token)
94
+ index += 1
95
+ return argv or None
96
+
97
+
98
+ def _invocation(text):
99
+ substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
100
+ if substitution:
101
+ inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
102
+ argv = _simple_argv(inner)
103
+ return (argv, 'assignment_substitution') if argv else (None, None)
104
+ return _simple_argv(text), 'simple'
105
+
106
+
107
+ def _guard_end(statements, start):
108
+ depth = 1
109
+ for index in range(start + 1, len(statements)):
110
+ item = statements[index]
111
+ if re.match(r'^if\s', item):
112
+ depth += 1
113
+ elif item == 'fi':
114
+ depth -= 1
115
+ if depth == 0:
116
+ return index
117
+ return None
118
+
119
+
120
+
121
+ # R7: unwrap only execution wrappers whose effect is proved in this subset.
122
+ # In particular `command -v/-V` queries do not run their operand, and `builtin`
123
+ # cannot run an external tool. Keep these distinctions before inspecting state.
124
+ _BASH_BUILTINS = frozenset({
125
+ ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd',
126
+ 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',
127
+ 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
128
+ 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local',
129
+ 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray',
130
+ 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test',
131
+ 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias',
132
+ 'unset', 'wait',
133
+ })
134
+ _UNSUPPORTED_STATE = frozenset({
135
+ '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap',
136
+ 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local',
137
+ 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift',
138
+ '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts',
139
+ })
140
+
141
+
142
+ def _bash_dialect(text):
143
+ """No shebang uses the evaluator's Bash syntax contract; sh is not Bash."""
144
+ first = str(text).splitlines()[0] if str(text).splitlines() else ''
145
+ if not first.startswith('#!'):
146
+ return True
147
+ try:
148
+ words = shlex.split(first[2:])
149
+ except ValueError:
150
+ return False
151
+ if not words:
152
+ return False
153
+ executable = words[0].rsplit('/', 1)[-1]
154
+ if executable == 'env':
155
+ words = words[1:]
156
+ if words[:1] == ['-S']:
157
+ words = words[1:]
158
+ executable = words[0] if words else ''
159
+ return executable.rsplit('/', 1)[-1] == 'bash'
160
+
161
+
162
+ def _execution_argv(argv, bash=True):
163
+ """Normalize a finite chain; unsupported wrappers get no command credit."""
164
+ if not argv:
165
+ return None
166
+ argv = list(argv)
167
+ while argv and argv[0] in ('command', 'builtin'):
168
+ wrapper = argv[0]
169
+ if wrapper == 'builtin':
170
+ if not bash:
171
+ return None
172
+ argv = argv[1:]
173
+ if argv[:1] == ['--']:
174
+ argv = argv[1:]
175
+ if not argv or argv[0] not in _BASH_BUILTINS:
176
+ return None
177
+ continue
178
+ index, query, default_path = 1, False, False
179
+ while index < len(argv) and argv[index].startswith('-'):
180
+ option = argv[index]
181
+ index += 1
182
+ if option == '--':
183
+ break
184
+ if not re.fullmatch(r'-[pvV]+', option):
185
+ return None
186
+ query = query or 'v' in option or 'V' in option
187
+ default_path = default_path or 'p' in option
188
+ if query:
189
+ return argv # Query is an invocation of command, not its target.
190
+ if index == len(argv):
191
+ return None
192
+ argv = argv[index:]
193
+ # -p changes external PATH lookup. It is transparent for builtins only.
194
+ if default_path and argv[0] not in _BASH_BUILTINS:
195
+ return None
196
+ return argv or None
197
+
198
+
199
+ def _set_errexit(argv, current):
200
+ """Return the proven option state, or None for unsupported set options."""
201
+ if not argv or argv[0] != 'set':
202
+ return None
203
+ index = 1
204
+ while index < len(argv):
205
+ flag = argv[index]
206
+ if flag == '--' or not flag.startswith(('-', '+')):
207
+ break # Positional arguments cannot enable errexit.
208
+ if not re.fullmatch(r'[-+][eufxEo]+', flag):
209
+ return None # Includes noexec (-n), which suppresses later work.
210
+ if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1):
211
+ return None
212
+ if 'e' in flag[1:]:
213
+ current = flag[0] == '-'
214
+ if 'o' in flag[1:]:
215
+ if index + 1 >= len(argv):
216
+ return None
217
+ option = argv[index + 1]
218
+ if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
219
+ return None
220
+ if option == 'errexit':
221
+ current = flag[0] == '-'
222
+ index += 1
223
+ index += 1
224
+ return current
225
+
226
+
227
+ def shell_option_setting(text, bash=True):
228
+ """Recognize valid option setup for task-specific operation counters."""
229
+ argv = _execution_argv(_simple_argv(text), bash)
230
+ return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None)
231
+
232
+
233
+ def _exit_status(argv):
234
+ """A literal shell exit status; no-argument exit is handled by its caller."""
235
+ args = argv[1:]
236
+ if args[:1] == ['--']:
237
+ args = args[1:]
238
+ if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0])
239
+ or len(args[0]) > 20):
240
+ return None
241
+ value = int(args[0])
242
+ if not -(2**63) <= value <= 2**63 - 1:
243
+ return 2 # Bash exits for an out-of-range numeric argument.
244
+ return value % 256
245
+
246
+
247
+
248
+ def _nonzero_exit_body(statements, bash=True):
249
+ """Only literal logging followed by a final unconditional nonzero exit."""
250
+ if not statements:
251
+ return False
252
+ for index, statement in enumerate(statements):
253
+ argv = _execution_argv(_simple_argv(statement), bash)
254
+ if not argv:
255
+ return False
256
+ if argv[0] == 'exit':
257
+ status = _exit_status(argv)
258
+ return index == len(statements) - 1 and status is not None and status != 0
259
+ if argv[0] not in ('echo', 'printf'):
260
+ return False
261
+ return False
262
+
263
+
264
+
265
+ def _expand_known_variables(text, constants):
266
+ """Preserve quote/escape expansion semantics in the bounded shell grammar.
267
+
268
+ Active unknown variables stay symbolic. A quoted/escaped literal dollar or
269
+ tilde has a separate token, so it cannot satisfy an expanding shell call.
270
+ This is parsing only; no shell command is evaluated.
271
+ """
272
+ out,quote,i=[],None,0
273
+ variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
274
+ while i<len(text):
275
+ ch=text[i]
276
+ if ch=='\\' and quote!="'" and i+1<len(text):
277
+ nxt=text[i+1]
278
+ if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__')
279
+ elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__')
280
+ else:out.extend((ch,nxt))
281
+ i+=2;continue
282
+ if ch in "'\"":
283
+ if quote is None:quote=ch
284
+ elif quote==ch:quote=None
285
+ out.append(ch);i+=1;continue
286
+ if ch=='$':
287
+ if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue
288
+ m=variable.match(text,i)
289
+ if m:
290
+ value=constants.get(m.group(1)or m.group(2))
291
+ if value is None:out.append(m.group(0))
292
+ elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$'))
293
+ else:out.append(value)
294
+ i=m.end();continue
295
+ if ch=='~' and quote is not None:
296
+ out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue
297
+ out.append(ch);i+=1
298
+ return ''.join(out)
299
+
300
+
301
+ # Ordinary assignment/parameter defaults are not shell control flow. This
302
+ # recognizer never evaluates their text or assumes the inherited value is empty.
303
+ _DEFAULT_STATE_NAMES = frozenset({
304
+ 'PATH', 'IFS', 'ENV', 'BASH_ENV', 'SHELLOPTS', 'BASHOPTS', 'CDPATH',
305
+ 'GLOBIGNORE', 'FIGNORE', 'POSIXLY_CORRECT', 'BASH_COMPAT',
306
+ 'PROMPT_COMMAND', 'PS0', 'PS1', 'PS2', 'PS4', 'UID', 'EUID', 'PPID',
307
+ 'SHELL', 'RANDOM', 'SRANDOM', 'SECONDS', 'LINENO', 'OPTIND', 'OPTARG',
308
+ '_', 'HOME', 'PWD', 'OLDPWD', 'PIPESTATUS', 'DIRSTACK', 'GROUPS',
309
+ 'FUNCNAME', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME',
310
+ })
311
+
312
+ def _ordinary_parameter_default(statement):
313
+ """Recognize X=${Y:-literal}, ${Y-literal}, ${Y:=literal}, ${Y=literal}.
314
+
315
+ Optional export and double quotes do not change the assignment semantics.
316
+ Both names must be ordinary variables, the nonempty fallback must be literal,
317
+ and no nested expansion/command substitution is allowed. Return every name
318
+ which can be assigned; their effective values remain unknown. Reading Y in
319
+ '-' variants does not erase an earlier known Y value; '=' variants may write
320
+ Y, so both Y and X lose any previously inferred constant.
321
+ """
322
+ match = re.fullmatch(
323
+ r'(?:export\s+(?:--\s+)?)?([A-Za-z_][A-Za-z0-9_]*)='
324
+ r'("?)\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-=])'
325
+ r'[A-Za-z0-9_./:+-]+\}\2', statement)
326
+ if not match:
327
+ return None
328
+ target, _, source, operator = match.groups()
329
+ if any(name in _DEFAULT_STATE_NAMES or
330
+ name.startswith(('BASH_', 'BASH_FUNC_', 'LD_', 'DYLD_'))
331
+ for name in (target, source)):
332
+ return None
333
+ return (target, source) if '=' in operator else (target,)
334
+
335
+ def shell_invocations(text):
336
+ """Return ordered, actually evaluated invocation nodes in the supported subset.
337
+
338
+ fail_fast is a structural proof: a simple command/assignment runs under
339
+ errexit, or a negated test exits nonzero on failure. This is not a complete
340
+ shell interpreter, and unsupported syntax earns no invocation credit.
341
+ """
342
+ statements = _statements(text)
343
+ bash = _bash_dialect(text)
344
+ # Function definitions or dynamic shell mutation can shadow the command or
345
+ # `exit` itself. They are outside this objective subset, even if uncalled.
346
+ if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s)
347
+ or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
348
+ for s in statements):
349
+ return []
350
+ constants, result, index, errexit = {}, [], 0, False
351
+ assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
352
+ variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
353
+ while index < len(statements):
354
+ statement = statements[index]
355
+ literal = assignment.fullmatch(statement)
356
+ if literal:
357
+ constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
358
+ index += 1
359
+ continue
360
+ default_names = _ordinary_parameter_default(statement)
361
+ if default_names is not None:
362
+ for default_name in default_names:
363
+ constants.pop(default_name, None)
364
+ index += 1
365
+ continue
366
+ statement = _expand_known_variables(statement, constants)
367
+ if re.match(r'^if\s', statement):
368
+ end = _guard_end(statements, index)
369
+ if end is None:
370
+ return []
371
+ negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
372
+ if (negated and index + 1 < end
373
+ and statements[index + 1] == 'then'
374
+ and _nonzero_exit_body(statements[index + 2:end], bash)):
375
+ argv, kind = _invocation(negated.group(1).strip())
376
+ argv = _execution_argv(argv, bash)
377
+ if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')):
378
+ return []
379
+ if argv:
380
+ if argv[0] == 'false':
381
+ break
382
+ result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
383
+ 'fail_fast': True, 'statement_index': index, 'expanded_statement': statement})
384
+ else:
385
+ return []
386
+ else:
387
+ # Arbitrary conditions may terminate the script or shadow its
388
+ # commands. Do not infer a reachable suffix through them.
389
+ return []
390
+ # Bodies are never credited and may have assigned local variables.
391
+ constants.clear()
392
+ index = end + 1
393
+ continue
394
+ if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
395
+ # Unsupported compounds are not searched for command substrings.
396
+ return []
397
+ argv, kind = _invocation(statement)
398
+ argv = _execution_argv(argv, bash)
399
+ if not argv:
400
+ # An unparsed statement may change control flow or shell state.
401
+ # Skipping it would incorrectly credit an unreachable suffix.
402
+ return []
403
+ if argv[0] in _UNSUPPORTED_STATE:
404
+ return []
405
+ if argv[0] == 'hash':
406
+ # Clearing/querying/cache lookup preserves the command's selected
407
+ # executable. An explicit -p binding can replace a required tool.
408
+ operands, flags = [], ''
409
+ option_mode = True
410
+ for word in argv[1:]:
411
+ if option_mode and word == '--':
412
+ option_mode = False
413
+ elif option_mode and word.startswith('-'):
414
+ if not re.fullmatch(r'-[lrdt]+', word):
415
+ return []
416
+ flags += word[1:]
417
+ else:
418
+ option_mode = False
419
+ if '$' in word:
420
+ return []
421
+ operands.append(word)
422
+ if ('d' in flags or 't' in flags) and not operands:
423
+ return []
424
+ if argv[0] == 'set':
425
+ new_errexit = _set_errexit(argv, errexit)
426
+ if new_errexit is None:
427
+ return []
428
+ if kind == 'simple':
429
+ errexit = new_errexit
430
+ index += 1
431
+ continue
432
+ # An assignment substitution runs in a subshell: set cannot change
433
+ # the parent's flags. Keep it as an ordinary evaluated node.
434
+ if argv[0] == 'exit':
435
+ if kind == 'simple':
436
+ # Only a literal, zero/one-argument exit is proved terminal.
437
+ # An invalid multi-argument exit can return and is unsupported.
438
+ if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None:
439
+ break
440
+ return []
441
+ status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv)
442
+ if status is None:
443
+ return []
444
+ if status and errexit:
445
+ break
446
+ if argv[0] == 'false' and errexit:
447
+ break
448
+ if kind == 'assignment_substitution':
449
+ assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
450
+ if assigned:
451
+ constants.pop(assigned.group(1), None)
452
+ result.append({'command': shlex.join(argv), 'kind': kind,
453
+ 'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement})
454
+ index += 1
455
+ return result
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_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/952829163f75b50a_q1/evaluator/legacy_tests/verifiers.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier execution engine and fail-closed self-tests.
2
+
3
+ New verified tasks use atomic_json (complete shape plus scalar assertions).
4
+ Legacy verifier types remain readable so historical runs can still be audited.
5
+ 自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
6
+ """
7
+ import json
8
+ import math
9
+ import posixpath
10
+ import logging
11
+ import os
12
+ import re
13
+
14
+ try:
15
+ from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
16
+ reference_bundle,
17
+ self_test_workspace_evaluator)
18
+ except ImportError: # portable task copies these modules beside each other
19
+ from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
20
+ reference_bundle,
21
+ self_test_workspace_evaluator)
22
+
23
+ log = logging.getLogger("pipeline")
24
+
25
+
26
+ def _norm(s):
27
+ return str(s).strip().lower()
28
+
29
+
30
+ def _json_value(value):
31
+ """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
32
+ if isinstance(value, (dict, list, int, float, bool)) or value is None:
33
+ return value
34
+ text = str(value).strip()
35
+ match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
36
+ if match:
37
+ text = match.group(1).strip()
38
+ text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
39
+ text = re.sub(r"\s*```$", "", text)
40
+ start_obj, start_arr = text.find("{"), text.find("[")
41
+ starts = [x for x in (start_obj, start_arr) if x >= 0]
42
+ if starts:
43
+ start = min(starts)
44
+ closing = "}" if text[start] == "{" else "]"
45
+ end = text.rfind(closing)
46
+ if end >= start:
47
+ text = text[start:end + 1]
48
+ try:return json.loads(text)
49
+ except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
50
+
51
+
52
+
53
+ def _strict_json_value(value):
54
+ """Atomic answer contract: one complete JSON value, no extra prose/keys."""
55
+ def unique(pairs):
56
+ d={}
57
+ for k,v in pairs:
58
+ if k in d:raise ValueError('duplicate JSON key: '+k)
59
+ d[k]=v
60
+ return d
61
+ def invalid(s):raise ValueError('non-finite JSON number: '+s)
62
+ try:
63
+ result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
64
+ if isinstance(value,str) else value)
65
+ except RecursionError as error:
66
+ raise ValueError('Candidate JSON nesting is too deep') from error
67
+ def finite(v):
68
+ if isinstance(v,dict):return all(finite(x)for x in v.values())
69
+ if isinstance(v,list):return all(finite(x)for x in v)
70
+ return not isinstance(v,float)or math.isfinite(v)
71
+ try:is_finite=finite(result)
72
+ except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
73
+ if not is_finite:raise ValueError('non-finite JSON number')
74
+ return result
75
+
76
+ def _path_equal(actual, expected):
77
+ if not isinstance(actual,str)or not isinstance(expected,str):return False
78
+ # A trailing slash is not a harmless spelling for a named file.
79
+ suffix=posixpath.splitext(expected.rstrip('/'))[1]
80
+ if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
81
+ return _path_value(actual)==_path_value(expected)
82
+
83
+ def _canonical_json(value):
84
+ if isinstance(value, dict):
85
+ return {key: _canonical_json(value[key]) for key in sorted(value)}
86
+ if isinstance(value, list):
87
+ values = [_canonical_json(item) for item in value]
88
+ return sorted(values, key=lambda item: json.dumps(
89
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
90
+ return value
91
+
92
+
93
+ def _atomic_prepare(value, list_order):
94
+ if isinstance(value, dict):
95
+ return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
96
+ if isinstance(value, list):
97
+ values = [_atomic_prepare(item, list_order) for item in value]
98
+ if list_order == "unordered":
99
+ values.sort(key=lambda item: json.dumps(
100
+ item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
101
+ return values
102
+ return value
103
+
104
+
105
+ def _atomic_shape(value):
106
+ if isinstance(value, dict):
107
+ return {"type": "object", "keys": {
108
+ key: _atomic_shape(item) for key, item in value.items()}}
109
+ if isinstance(value, list):
110
+ return {"type": "array", "length": len(value),
111
+ "items": [_atomic_shape(item) for item in value]}
112
+ if isinstance(value, bool):
113
+ return {"type": "boolean"}
114
+ if value is None:
115
+ return {"type": "null"}
116
+ if isinstance(value, (int, float)):
117
+ return {"type": "number"}
118
+ return {"type": "string"}
119
+
120
+
121
+ def _atomic_leaves(value, path="$", tokens=()):
122
+ if isinstance(value, dict):
123
+ out = []
124
+ for key, item in value.items():
125
+ out.extend(_atomic_leaves(
126
+ item, path + "." + key, tokens + (key,)))
127
+ return out
128
+ if isinstance(value, list):
129
+ out = []
130
+ for index, item in enumerate(value):
131
+ out.extend(_atomic_leaves(
132
+ item, f"{path}[{index}]", tokens + (index,)))
133
+ return out
134
+ return [(path, tokens, value)]
135
+
136
+
137
+ def _normalize_path_equivalence_tokens(values):
138
+ """Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
139
+ normalized = []
140
+ for tokens in values or []:
141
+ if (not isinstance(tokens, (list, tuple)) or not tokens or
142
+ any(not isinstance(token, (str, int)) for token in tokens)):
143
+ raise ValueError("path equivalence tokens must be non-empty JSON paths")
144
+ item = list(tokens)
145
+ if item not in normalized:
146
+ normalized.append(item)
147
+ return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
148
+
149
+
150
+ def _path_value(value):
151
+ """Normalize only portable path spelling, not general answer text."""
152
+ if not isinstance(value, str):
153
+ return None
154
+ text = value.strip().replace("\\", "/")
155
+ text = posixpath.normpath(text) if text else text
156
+ if text != "/":
157
+ text = text.rstrip("/")
158
+ return text
159
+
160
+
161
+ def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
162
+ path_equivalence_tokens=None):
163
+ """Freeze a complete JSON shape plus one assertion for every scalar leaf."""
164
+ if list_order not in {"ordered", "unordered"}:
165
+ raise ValueError(f"unsupported atomic list_order: {list_order}")
166
+ tolerance = float(float_tolerance)
167
+ prepared = _atomic_prepare(_json_value(expected), list_order)
168
+ path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
169
+ assertions = []
170
+ for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
171
+ assertion = {"id": f"leaf_{index:03d}", "path": path,
172
+ "tokens": list(tokens), "operator": "eq", "expected": value}
173
+ if isinstance(value, float):
174
+ assertion.update({"operator": "abs_diff", "tolerance": tolerance})
175
+ elif list(tokens) in path_tokens:
176
+ if not isinstance(value, str):
177
+ raise ValueError("path equivalence can only target string leaves")
178
+ assertion["operator"] = "path_eq"
179
+ assertions.append(assertion)
180
+ compiled = {
181
+ "type": "atomic_json", "version": 2 if path_tokens else 1,
182
+ "list_order": list_order,
183
+ "float_tolerance": tolerance,
184
+ "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
185
+ "assertions": assertions,
186
+ }
187
+ if path_tokens:
188
+ compiled["path_equivalence_tokens"] = path_tokens
189
+ return compiled
190
+
191
+
192
+ def _shape_differences(expected, actual, path="$"):
193
+ if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
194
+ return [f"{path}: expected {expected.get('type')}, got "
195
+ f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
196
+ kind = expected.get("type")
197
+ if kind == "object":
198
+ expected_keys = set((expected.get("keys") or {}))
199
+ actual_keys = set((actual.get("keys") or {}))
200
+ differences = [f"{path}: missing key {key}" for key in sorted(
201
+ expected_keys - actual_keys)]
202
+ differences.extend(f"{path}: extra key {key}" for key in sorted(
203
+ actual_keys - expected_keys))
204
+ for key in sorted(expected_keys & actual_keys):
205
+ differences.extend(_shape_differences(
206
+ expected["keys"][key], actual["keys"][key], path + "." + key))
207
+ return differences
208
+ if kind == "array":
209
+ differences = []
210
+ if actual.get("length") != expected.get("length"):
211
+ differences.append(
212
+ f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
213
+ for index, (expected_item, actual_item) in enumerate(zip(
214
+ expected.get("items") or [], actual.get("items") or [])):
215
+ differences.extend(_shape_differences(
216
+ expected_item, actual_item, f"{path}[{index}]"))
217
+ return differences
218
+ return []
219
+
220
+
221
+ def _atomic_get(value, tokens):
222
+ current = value
223
+ for token in tokens:
224
+ current = current[token]
225
+ return current
226
+
227
+
228
+ def _int_values(value):
229
+ if isinstance(value, (list, tuple)):
230
+ out = []
231
+ for item in value:
232
+ out.extend(_int_values(item))
233
+ return out
234
+ if isinstance(value, int) and not isinstance(value, bool):
235
+ return [value]
236
+ return [int(number) for number in re.findall(r"\d+", str(value or ""))]
237
+
238
+
239
+ def _finding_type(value):
240
+ text = str(value or "").lower().replace("-", "_")
241
+ if "duplicate" in text:
242
+ return "duplicate_rows"
243
+ if ("none" in text or "null" in text) and "check" in text:
244
+ return "none_check"
245
+ if "missing" in text or "empty" in text or "null" in text:
246
+ return "missing"
247
+ if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
248
+ return "outlier"
249
+ if "invalid" in text and "config" in text:
250
+ return "invalid_config"
251
+ if "off" in text and "one" in text:
252
+ return "off_by_one"
253
+ return text.strip().replace(" ", "_")
254
+
255
+
256
+ def _normalized_findings(value, family):
257
+ obj = _json_value(value)
258
+ findings = obj.get("findings") if isinstance(obj, dict) else None
259
+ if not isinstance(findings, list):
260
+ raise ValueError("answer must contain a findings array")
261
+ normalized = set()
262
+ for finding in findings:
263
+ if not isinstance(finding, dict):
264
+ raise ValueError("each finding must be an object")
265
+ # The public contract uses type/function. Accept common semantically
266
+ # equivalent aliases as a robustness layer, while still comparing the
267
+ # normalized values and exact locations against generator-owned GT.
268
+ kind = _finding_type(finding.get("type", finding.get(
269
+ "defect_type", finding.get("defect"))))
270
+ if family == "csv":
271
+ if kind == "duplicate_rows":
272
+ rows = _int_values(finding.get("rows", finding.get("row")))
273
+ if len(rows) != 2:
274
+ raise ValueError("duplicate finding requires exactly two row numbers")
275
+ normalized.add((kind, *sorted(rows)))
276
+ elif kind in {"missing", "outlier"}:
277
+ rows = _int_values(finding.get("row"))
278
+ column = str(finding.get("column") or "").strip().lower()
279
+ if len(rows) != 1 or not column:
280
+ raise ValueError(f"{kind} requires one row and column")
281
+ normalized.add((kind, rows[0], column))
282
+ else:
283
+ raise ValueError(f"unsupported CSV finding type: {kind}")
284
+ elif family == "config":
285
+ if kind != "invalid_config":
286
+ raise ValueError(f"unsupported config finding type: {kind}")
287
+ normalized.add((kind, str(finding.get("path") or "").lower(),
288
+ json.dumps(finding.get("value"), sort_keys=True),
289
+ str(finding.get("expected") or "").lower()))
290
+ elif family == "code":
291
+ if kind not in {"off_by_one", "none_check"}:
292
+ raise ValueError(f"unsupported code finding type: {kind}")
293
+ function = finding.get("function", finding.get("function_name"))
294
+ function = str(function or "").strip().lower()
295
+ if not function:
296
+ raise ValueError(f"{kind} requires a function")
297
+ normalized.add((kind, function))
298
+ else:
299
+ raise ValueError(f"unsupported findings family: {family}")
300
+ return normalized
301
+
302
+
303
+ def _normalized_facts(value):
304
+ obj = _json_value(value)
305
+ facts = obj.get("facts") if isinstance(obj, dict) else None
306
+ if not isinstance(facts, list):
307
+ raise ValueError("answer must contain a facts array")
308
+ def textual(item):
309
+ # The document generator serializes scalar values as visible text. JSON
310
+ # has no way to infer whether the source token "30" was authored from an
311
+ # integer or a string, so facts_match compares that surface text. Nested
312
+ # values retain structural JSON comparison.
313
+ if isinstance(item, (dict, list)):
314
+ return json.dumps(item, sort_keys=True, ensure_ascii=False,
315
+ separators=(",", ":"))
316
+ if item is None:
317
+ return "None"
318
+ return str(item)
319
+ return {(str(fact.get("key") or ""), textual(fact.get("value")))
320
+ for fact in facts if isinstance(fact, dict)}
321
+
322
+
323
+ def verify(verifier, gt_answer, solver_output, material_paths=None):
324
+ """执行 verifier。返回 (passed, detail)。"""
325
+ vtype = verifier.get("type")
326
+ try:
327
+ if vtype == WORKSPACE_EVALUATOR:
328
+ return evaluate_candidate(verifier, solver_output)
329
+
330
+ if vtype == "json_exact":
331
+ pred = _canonical_json(_json_value(solver_output))
332
+ gold = _canonical_json(_json_value(gt_answer))
333
+ ok = pred == gold
334
+ return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
335
+
336
+ if vtype == "atomic_json":
337
+ try:
338
+ pred = _atomic_prepare(_strict_json_value(solver_output),
339
+ verifier.get("list_order", "ordered"))
340
+ pred_shape = _atomic_shape(pred)
341
+ except RecursionError:
342
+ return False, "candidate JSON nesting is too deep"
343
+ compiled = compile_atomic_verifier(
344
+ gt_answer, verifier.get("list_order", "ordered"),
345
+ verifier.get("float_tolerance", 0.01),
346
+ verifier.get("path_equivalence_tokens"))
347
+ frozen = {key: verifier.get(key) for key in
348
+ ("type", "version", "list_order", "float_tolerance",
349
+ "completeness", "assertions", "path_equivalence_tokens")}
350
+ expected_frozen = {key: compiled.get(key) for key in frozen}
351
+ if frozen != expected_frozen:
352
+ return False, {"error": "atomic verifier does not match ground truth"}
353
+ shape_failures = _shape_differences(
354
+ verifier["completeness"]["shape"], pred_shape)
355
+ assertion_results = []
356
+ for assertion in verifier.get("assertions") or []:
357
+ try:
358
+ actual = _atomic_get(pred, assertion["tokens"])
359
+ if assertion["operator"] == "abs_diff":
360
+ passed = abs(float(actual) - float(assertion["expected"])) <= float(
361
+ assertion.get("tolerance", 0.0))
362
+ elif assertion["operator"] == "path_eq":
363
+ passed = _path_equal(actual, assertion["expected"])
364
+ else:
365
+ passed = (actual is assertion["expected"] if
366
+ isinstance(assertion["expected"], bool) else
367
+ actual == assertion["expected"])
368
+ message = "" if passed else (
369
+ f"actual={actual!r} expected={assertion['expected']!r}")
370
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
371
+ actual, passed, message = None, False, f"lookup/compare failed: {exc}"
372
+ assertion_results.append({
373
+ "id": assertion["id"], "path": assertion["path"],
374
+ "operator": assertion["operator"], "expected": assertion["expected"],
375
+ "actual": actual, "passed": passed, "message": message})
376
+ passed_count = sum(item["passed"] for item in assertion_results)
377
+ ok = not shape_failures and passed_count == len(assertion_results)
378
+ return ok, {
379
+ "type": "atomic_json", "completeness_passed": not shape_failures,
380
+ "completeness_failures": shape_failures,
381
+ "assertions_passed": passed_count,
382
+ "assertions_total": len(assertion_results),
383
+ "assertion_pass_rate": (passed_count / len(assertion_results)
384
+ if assertion_results else 1.0),
385
+ "assertions": assertion_results,
386
+ }
387
+
388
+ if vtype == "findings_match":
389
+ family = verifier.get("family")
390
+ pred = _normalized_findings(solver_output, family)
391
+ gold = _normalized_findings(gt_answer, family)
392
+ ok = pred == gold
393
+ return ok, ("findings_match: pass" if ok else
394
+ f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
395
+
396
+ if vtype == "facts_match":
397
+ pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
398
+ ok = pred == gold
399
+ return ok, ("facts_match: pass" if ok else
400
+ f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
401
+
402
+ if vtype == "exact_match":
403
+ ok = _norm(solver_output) == _norm(gt_answer)
404
+ return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
405
+
406
+ if vtype == "numeric":
407
+ tol = verifier.get("tolerance") or 1e-6
408
+ pred = float(str(solver_output).strip().split()[0])
409
+ gold = float(gt_answer)
410
+ ok = abs(pred - gold) <= tol
411
+ return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
412
+
413
+ if vtype == "set_match":
414
+ pred = set(_as_list(solver_output))
415
+ gold = set(_as_list(gt_answer))
416
+ ok = pred == gold
417
+ return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
418
+
419
+ if vtype == "structured_match":
420
+ pred = _json_value(solver_output)
421
+ gold = _json_value(gt_answer)
422
+ if not isinstance(pred, dict) or not isinstance(gold, dict):
423
+ return False, "structured_match requires JSON objects"
424
+ missing = [f for f in verifier.get("required_fields", []) if f not in pred]
425
+ wrong = [f for f in verifier.get("required_fields", [])
426
+ if f in pred and f in gold and pred[f] != gold[f]]
427
+ ok = not missing and not wrong
428
+ return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
429
+
430
+ if vtype == "execution":
431
+ return False, "execution verifier is disabled in verified-first v2"
432
+
433
+ if vtype == "constraint":
434
+ fails = _check_constraints(verifier.get("criteria", []), solver_output)
435
+ return not fails, f"constraint: failed={fails[:5]}"
436
+
437
+ if vtype == "file_inspection":
438
+ fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
439
+ return not fails, f"file_inspection: failed={fails[:5]}"
440
+
441
+ return False, f"unknown verifier type: {vtype}"
442
+ except Exception as e:
443
+ return False, f"verifier error: {e}"
444
+
445
+
446
+ def _as_list(x):
447
+ if isinstance(x, list):
448
+ return [_norm(i) for i in x]
449
+ # 逗号/换行分隔的字符串
450
+ return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
451
+
452
+
453
+ def _check_constraints(criteria, solver_output):
454
+ """criteria: ["must contain X", "must be valid json", "length <= 500"]"""
455
+ fails = []
456
+ text = str(solver_output)
457
+ for c in criteria:
458
+ cl = c.lower()
459
+ if cl.startswith("must contain "):
460
+ needle = c[len("must contain "):]
461
+ if needle.lower() not in text.lower():
462
+ fails.append(c)
463
+ elif "valid json" in cl:
464
+ try:
465
+ json.loads(text)
466
+ except Exception:
467
+ fails.append(c)
468
+ elif cl.startswith("length <="):
469
+ limit = int(cl.split("<=")[1].strip())
470
+ if len(text) > limit:
471
+ fails.append(c)
472
+ else:
473
+ # Deterministic verifier DSL is closed-world: unknown checks fail.
474
+ fails.append(f"unsupported criterion: {c}")
475
+ return fails
476
+
477
+
478
+ def _inspect_files(expected, material_paths):
479
+ fails = []
480
+ paths = set(material_paths or [])
481
+ for e in expected:
482
+ fname = e.get("filename") if isinstance(e, dict) else str(e)
483
+ if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
484
+ fails.append(f"missing file: {fname}")
485
+ return fails
486
+
487
+
488
+ # ---------------- 自测 ----------------
489
+
490
+ def build_correct_solution(verifier, gt_answer, planted_info):
491
+ """由埋点/ground truth 直接构造正确解。"""
492
+ vtype = verifier.get("type")
493
+ if vtype == WORKSPACE_EVALUATOR:
494
+ return reference_bundle(verifier)
495
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
496
+ "set_match", "structured_match"):
497
+ return gt_answer
498
+ if vtype == "constraint":
499
+ parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
500
+ if c.lower().startswith("must contain ")]
501
+ return " ".join(parts) if parts else str(gt_answer)
502
+ # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
503
+ return None
504
+
505
+
506
+ def build_perturbed_solution(verifier, gt_answer, planted_info):
507
+ """破坏埋点构造扰动解。"""
508
+ vtype = verifier.get("type")
509
+ if vtype == WORKSPACE_EVALUATOR:
510
+ files = list(reference_bundle(verifier).get("files") or [])
511
+ return {"files": files[1:] if len(files) > 1 else []}
512
+ if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
513
+ gold = _json_value(gt_answer)
514
+ if isinstance(gold, dict):
515
+ perturbed = dict(gold)
516
+ key = next(iter(perturbed), "__missing__")
517
+ if key in perturbed:
518
+ perturbed.pop(key)
519
+ else:
520
+ perturbed["__wrong__"] = True
521
+ return perturbed
522
+ if isinstance(gold, list):
523
+ return gold[:-1] if gold else ["__wrong__"]
524
+ return "__wrong__"
525
+ if vtype in ("exact_match", "numeric"):
526
+ return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
527
+ if vtype == "set_match":
528
+ gold = _as_list(gt_answer)
529
+ return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
530
+ if vtype == "structured_match":
531
+ fields = verifier.get("required_fields", [])
532
+ return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
533
+ if vtype == "constraint":
534
+ return "perturbed output lacking required content"
535
+ return None
536
+
537
+
538
+ def self_test(verifier, gt_answer, planted_info, material_paths):
539
+ """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
540
+
541
+ 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
542
+ 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
543
+ """
544
+ if verifier.get("type") == WORKSPACE_EVALUATOR:
545
+ return self_test_workspace_evaluator(verifier)
546
+ correct = build_correct_solution(verifier, gt_answer, planted_info)
547
+ perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
548
+ if correct is None or perturbed is None:
549
+ return False, (f"cannot self-test verifier type {verifier.get('type')} "
550
+ "(execution/file_inspection need real correct/perturbed solutions)")
551
+ ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
552
+ ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
553
+ passed = ok1 and not ok2
554
+ return passed, {"correct": d1, "perturbed": d2}
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/evaluator/repair_equivalences.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # R11: the public task requires exactly this ordered action inventory.
173
+ by_path={}
174
+ for rule in evaluator.get('checks',[]):
175
+ if rule.get('type')=='shell_command':by_path.setdefault(rule['path'],[]).append(rule['value'])
176
+ for rel,wanted in by_path.items():
177
+ try:calls=objective.shell_invocations((Path(solver_output)/rel).read_text())
178
+ except(OSError,UnicodeError,ValueError):return False,{'error':'required shell artifact is missing or unreadable','path':rel}
179
+ if len(calls)!=2 or len(wanted)!=2 or not all(objective._shell_command_matches(e,c['command']) for e,c in zip(wanted,calls)):
180
+ return False,{'error':'public exact 2 action inventory violated','path':rel,'calls':calls}
181
+ grouped = {}
182
+ for check in evaluator.get('checks', []):
183
+ if check.get('type') == 'shell_command':
184
+ grouped.setdefault(check['path'], []).append(check['value'])
185
+ for path, expected_commands in grouped.items():
186
+ try:
187
+ text = (Path(solver_output) / path).read_text()
188
+ invocations = objective.shell_invocations(text)
189
+ for expected_command in expected_commands:
190
+ tokens = argv(expected_command)
191
+ if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]):
192
+ continue # Required scalar assignment is checked by original rubric.
193
+ if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations):
194
+ return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command}
195
+ except (OSError, UnicodeError, ValueError):
196
+ return False, {'error': 'cannot inspect required shell artifact', 'path': path}
197
+ if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective):
198
+ return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'}
199
+ normalizations = []
200
+ if task_id in RESPONSE_RULES:
201
+ try:
202
+ predicted = verifiers._json_value(solver_output)
203
+ gold = gt_answer
204
+ if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict):
205
+ for key, comparator in RESPONSE_RULES[task_id].items():
206
+ value = predicted['answers'].get(key)
207
+ expected = gold['answers'][key]
208
+ if value != expected and comparator(expected, value):
209
+ predicted['answers'][key] = expected
210
+ normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected})
211
+ solver_output = json.dumps(predicted)
212
+ except (KeyError, ValueError, TypeError):
213
+ pass # Preserve original malformed-answer rejection.
214
+ if task_id == '59f410a185c510f3_q1':
215
+ path = evaluator['reference_files'][0]['path']
216
+ try:
217
+ file_path = Path(solver_output) / path
218
+ predicted = json.loads(file_path.read_text())
219
+ expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact')
220
+ if isinstance(predicted, dict):
221
+ for widget in ('chart', 'banner'):
222
+ row = predicted.get(widget)
223
+ if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')):
224
+ if row.get('hydrate') != expected[widget]['hydrate']:
225
+ normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']})
226
+ row['hydrate'] = expected[widget]['hydrate']
227
+ if normalizations:
228
+ with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary:
229
+ view = Path(temporary) / 'candidate'
230
+ shutil.copytree(solver_output, view, symlinks=True)
231
+ copied = view / path
232
+ resolved = copied.resolve()
233
+ if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink():
234
+ return False, {'error': 'candidate output parent symlink escapes temporary comparison view'}
235
+ if copied.is_symlink():
236
+ copied.unlink() # Do not write through a frozen source symlink.
237
+ copied.write_text(json.dumps(predicted))
238
+ passed, details = original_verify(evaluator, gt_answer, str(view), material_paths)
239
+ if isinstance(details, dict):
240
+ details['equivalence_normalizations'] = normalizations
241
+ return passed, details
242
+ except (KeyError, ValueError, TypeError, OSError, UnicodeError):
243
+ pass
244
+ passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths)
245
+ if normalizations and isinstance(details, dict):
246
+ details['equivalence_normalizations'] = normalizations
247
+ return passed, details
248
+
249
+ verifiers.verify = repaired_verify
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/grading/verified_config.json ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "engine": "portable_verified_v1",
3
+ "grader_file_sha256": {
4
+ "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
5
+ "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
6
+ "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
7
+ "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
8
+ "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d",
9
+ "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
10
+ "legacy-task.json": "59d92618765a332535df3b4fa65e059e5f9402cebeba527c9b07c55ee71684f7",
11
+ "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
12
+ "legacy_tests/objective_evaluators.py": "b9305679e70b1af4176fa7ed69d9ecd783cec9d361179856fb0352a61426a105",
13
+ "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5",
14
+ "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
15
+ "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b",
16
+ "repair_equivalences.py": "b1123d548c389018002edc8fe3eebefcea02abb91e5b626b74afcea75ca09d4a"
17
+ },
18
+ "query_id": "952829163f75b50a_q1",
19
+ "runtime_requirements": {
20
+ "candidate_mode": "workspace",
21
+ "candidate_snapshot_copy_to_ephemeral_app": true,
22
+ "container_private_entry": "/grader/check.py",
23
+ "criterion_weights": {
24
+ "0": 1
25
+ },
26
+ "environment": {
27
+ "CANDIDATE_DIR": "/candidate",
28
+ "CANDIDATE_ROOT": "/candidate",
29
+ "MYBENCH_ANSWER": "/answer.txt",
30
+ "MYBENCH_ANSWER_FILE": "/answer.txt",
31
+ "MYBENCH_CANDIDATE": "/candidate",
32
+ "MYBENCH_EPHEMERAL_APP": "1",
33
+ "MYBENCH_EPHEMERAL_WORKSPACE": "1",
34
+ "MYBENCH_RUN_METADATA": "/run_metadata.json",
35
+ "MYBENCH_SOURCE_TASK": "/source",
36
+ "SOURCE_TASK_DIR": "/source"
37
+ },
38
+ "expected_check_ids": [
39
+ "0"
40
+ ],
41
+ "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
42
+ "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
43
+ "grader_timeout_seconds": 600,
44
+ "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
45
+ "image_included": false,
46
+ "legacy_adapter": true,
47
+ "mounts_readonly": [
48
+ "/candidate",
49
+ "/source",
50
+ "/grader",
51
+ "/answer.txt"
52
+ ],
53
+ "network": "none",
54
+ "original_declared_resources": {
55
+ "agent": {
56
+ "basis": "advisory_not_measured",
57
+ "cpus": 2,
58
+ "memory_mib": 4096,
59
+ "timeout_sec": 1200
60
+ },
61
+ "oracle": {
62
+ "timeout_sec": 120
63
+ },
64
+ "source_agent": {
65
+ "command_timeout_sec": null,
66
+ "max_steps": null
67
+ },
68
+ "verifier": {
69
+ "cpus": 1,
70
+ "memory_mib": 1024,
71
+ "pids": 64,
72
+ "timeout_sec": 900,
73
+ "tmpfs_mib": 128
74
+ }
75
+ },
76
+ "private_entry": "evaluator/check.py",
77
+ "private_tree_environment_tokens": [
78
+ "MYBENCH_CANDIDATE_FILE",
79
+ "MYBENCH_OPEN_JUDGE_COMMAND",
80
+ "MYBENCH_OPEN_JUDGE_TIMEOUT",
81
+ "MYBENCH_TASK_JSON"
82
+ ],
83
+ "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.",
84
+ "trusted_trace_environment_aliases": [
85
+ "MYBENCH_TOOL_TRAJECTORY",
86
+ "MYBENCH_TRUSTED_TRACE",
87
+ "TOOL_TRAJECTORY",
88
+ "TOOL_TRAJECTORY_FILE"
89
+ ],
90
+ "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
91
+ "working_directory": "/candidate",
92
+ "writable_ephemeral_roots": [
93
+ "/app",
94
+ "/workspace",
95
+ "/tmp"
96
+ ]
97
+ },
98
+ "schema": "audited-verified-grader-v1",
99
+ "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703"
100
+ }
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/instruction.md ADDED
@@ -0,0 +1 @@
 
 
1
+ We're wiring our Duvo automation into CI and need a quick terminal probe of the public API using the low-level escape hatch, since there are no dedicated subcommands for what we need. Please write a shell script at output/duvo_api_probe.sh that does exactly two things, straight-line with no loops or conditionals (every command at the top level): first, page through the agents endpoint with limit 20 and offset 0 as query fields using `duvo api` with a GET; then, in the same script, create an agent by POSTing to the agents endpoint with a string name field set to "Ops bot" and a typed build field with name "v1". Keep it as a plain shell script we can run from the terminal.
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/skill/SKILL.md ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: duvo-cli
3
+ description: >
4
+ Drive the Duvo public API from the terminal via the `duvo` CLI
5
+ (`@duvoai/cli`). Use when the user wants to script Duvo — managing
6
+ agents, runs, cases, queues, files, skills, connections, Clarity
7
+ processes, Pulse dashboards, or hitting an arbitrary endpoint via
8
+ `duvo api` — instead of clicking through the Duvo web UI or
9
+ hand-crafting `curl` calls.
10
+ license: MIT
11
+ metadata:
12
+ author: duvoai
13
+ version: "1.9.0"
14
+ website: https://duvo.ai
15
+ docs: https://docs.duvo.ai
16
+ ---
17
+
18
+ # Duvo CLI
19
+
20
+ `duvo` is the official command-line interface for the [Duvo](https://duvo.ai)
21
+ public API. It is published to npm as [`@duvoai/cli`](https://www.npmjs.com/package/@duvoai/cli):
22
+ a single binary with resource-grouped subcommands (`duvo agents …`,
23
+ `duvo runs …`, `duvo cases …`, …) and a low-level `duvo api <method> <path>`
24
+ escape hatch for endpoints that don't yet have a dedicated command.
25
+
26
+ Use the CLI when the user wants to **automate** or **script** Duvo. The
27
+ web UI at <https://app.duvo.ai> is the right answer when they want to
28
+ click around interactively; `duvo` is the right answer the moment they
29
+ ask for a shell snippet, a cron job, a CI step, or "how do I do X
30
+ without opening the browser?". Both surfaces talk to the same public
31
+ API — there is no functional gap to bridge by reaching for `curl`.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ npm install -g @duvoai/cli
37
+ duvo --version
38
+ ```
39
+
40
+ Requires Node.js ≥ 22.22.0. `npx @duvoai/cli <cmd>` also works without
41
+ a global install.
42
+
43
+ ## Authentication
44
+
45
+ `duvo` keeps credentials as **named profiles** on disk. One profile per
46
+ (team, environment). The first profile added becomes the default; from
47
+ then on, every command uses the default unless overridden.
48
+
49
+ ```bash
50
+ duvo login # OAuth flow — opens your browser
51
+ duvo login --name acme # name the profile up front
52
+ duvo login --api-key <key> # skip OAuth and store an API key directly
53
+ duvo whoami # confirm who's signed in
54
+ ```
55
+
56
+ `duvo login` defaults to **browser-based OAuth** against the Duvo
57
+ production tenant. Pass `--api-key <key>` to store a long-lived API key
58
+ instead (grab one from <https://app.duvo.ai/settings/api-keys>).
59
+
60
+ Switching between profiles:
61
+
62
+ ```bash
63
+ duvo profiles list # show all profiles; `▶` marks the default
64
+ duvo profiles use # interactively pick the default profile
65
+ duvo profiles use acme # set a named profile as the default
66
+ duvo --profile acme whoami # one-off override for a single command
67
+ ```
68
+
69
+ **Resolution precedence** (the first match wins):
70
+
71
+ - Profile: `--profile <name>` flag → `DUVO_PROFILE` env → `defaultProfile` in config.
72
+ - Credential: `DUVO_API_KEY` env (bypasses the profile's stored credential lookup) → the profile's stored credential.
73
+ - Base URL: `DUVO_API_BASE_URL` env → the profile's `apiBaseUrl` → `https://api.duvo.ai`.
74
+ - Team: `--team <id>` flag → `DUVO_TEAM_ID` env → the OAuth profile's `defaultTeamId` (set via `duvo team use`) → the team derived from the active credential. API-key profiles are always pinned to the key's team and reject a different `--team` value.
75
+
76
+ ## Reading the help
77
+
78
+ Every command supports `--help`. Reach for it first instead of guessing:
79
+
80
+ ```bash
81
+ duvo --help # global help, lists every top-level group
82
+ duvo agents --help # subcommand group
83
+ duvo agents create --help # exact flags for one command
84
+ ```
85
+
86
+ The CLI's help text is the source of truth — if a flag doesn't appear
87
+ there, it doesn't exist in your installed version. Always show the
88
+ user `duvo <command> --help` rather than copy-pasting flags from
89
+ memory if you're unsure.
90
+
91
+ ## Output modes
92
+
93
+ Each command picks a default output shape based on what it returns:
94
+
95
+ - **Single resource** (`duvo agents get <id>`, `duvo runs get <id>`) →
96
+ human-readable key/value text.
97
+ - **Collection** (`duvo agents list`, `duvo runs list`) → table with a
98
+ fixed column set per resource.
99
+ - **`--json`** on either of the above → raw JSON to stdout. This is the
100
+ **stable contract** for scripts — table and text formats can change
101
+ between versions, JSON is safe to pipe into `jq` or `yq`.
102
+
103
+ ```bash
104
+ duvo agents list --json | jq '.agents[].id'
105
+ ```
106
+
107
+ For scripting, always pass `--json` and parse the response. Don't
108
+ parse the table output — column widths and truncation thresholds are
109
+ not part of the public contract. Envelope keys differ across
110
+ endpoints — `agents list` returns `.agents[]`, `queues list` returns
111
+ `.queues[]`, `runs list` returns `.data[]`, `agents create` returns
112
+ `.agent.id`. Inspect the shape with a one-off `--json` call before
113
+ hard-coding a jq path.
114
+
115
+ ## The `duvo api` escape hatch
116
+
117
+ Any endpoint in the public API is reachable via `duvo api <METHOD>
118
+ <path>`, modelled directly on `gh api`. Reach for it when:
119
+
120
+ - A new public endpoint shipped but doesn't have a dedicated `duvo`
121
+ command yet.
122
+ - You need a very narrow query-string or body shape that the
123
+ high-level command doesn't expose.
124
+ - You're debugging — `duvo api` shows exactly what the API returned,
125
+ with no formatting in the way.
126
+
127
+ ```bash
128
+ duvo api GET /v1/agents -F limit=20 -F offset=0
129
+ duvo api POST /v1/agents -f name="Ops bot" -F build[name]="v1"
130
+ duvo api POST /v1/agents --input body.json
131
+ cat body.json | duvo api POST /v1/agents --input -
132
+ ```
133
+
134
+ `-f` sends the value as a **string**; `-F` parses it as a typed value
135
+ (boolean, number, JSON `null`, or `@file` to load JSON from disk). See
136
+ `references/api-escape-hatch.md` for the full flag table.
137
+
138
+ High-level commands like `duvo agents create` are sugar over `duvo
139
+ api` — they share the same HTTP client, output pipeline, and exit
140
+ codes, so a script can mix the two freely.
141
+
142
+ ## Resource groups
143
+
144
+ See `references/commands.md` for the full command tree with flags.
145
+ The top-level groups are:
146
+
147
+ - **Auth & profiles** — `login`, `logout`, `whoami`, `profiles …`
148
+ - **Agents** — `agents …`, `agents delete`, `agents models`, `agents set-model`, `agents case-triggers …`, `agents schedules …`, `agents triggers …`, `agents slack-triggers …`, `agents memory …`, `agents eval-scores`, `agents eval-rubrics …`
149
+ - **Suggestions** — `suggestions …` (Connection suggestions: list, consume, reject)
150
+ - **Agent folders** — `agent-folders …` (organize agents in a tree)
151
+ - **Revisions** — `revisions …`, `revision-integrations …` (versioned configs)
152
+ - **Runs** — `runs …` (start, get, message, stop, respond to HITL, evaluation)
153
+ - **Queues & cases** — `queues …`, `queue-labels …`, `cases …`
154
+ - **Notifications** — `notifications …` (list, get, feed, get-batch, counts, unread-count, mark-read, mark-batch-read, mark-all-read, dismiss, delete-read, delete-all)
155
+ - **Files & sandboxes** — `files …`, `sandboxes …`
156
+ - **Connections & integrations** — `integrations …`, `connections …`, `oauth …`
157
+ - **Secrets & credentials** — `secrets …` (env-var secrets), `credentials …` (browser logins), `revision-secrets …`, `revision-logins …`
158
+ - **Clarity** — `clarity …` (process search, versions, captures, gaps, evidence, facets, export, generation, promotion, artifact imports, invite links, doctor, process landscape, process links, process tags, process summaries)
159
+ - **Pulse** — `pulse …` (create, get, list, send message, attach files, refresh, stop, rename, share, duplicate, move to another team, pdf/snapshot export, version history, restore, messages, answer HITL, connections, delete Pulse dashboards)
160
+ - **Skills & plugins** — `skills …`, `plugins …`
161
+ - **Team** — `team current`, `team get`, `team members`, `team set-role`, `team remove-member`, `team leave`, `team use`, `teams list`, `teams org`, `teams orgs`, `teams create-org-team`, `teams org-insights`, `teams org-metrics`, `teams org-usage`
162
+ - **Invitations** — `invite list`, `invite create`, `invite bulk`, `invite update`, `invite resend`, `invite delete`, `invite org-member`, `invite link get|create|delete`
163
+ - **Bundled guides** — `guide …` (version-matched CLI guides for AI agents)
164
+ - **Self-update** — `update` (update the installed CLI to the latest version)
165
+ - **Low-level** — `api <method> <path>`
166
+
167
+ For end-to-end recipes (create an agent → start a run → respond to
168
+ HITL; manage a queue and its cases; upload files for a sandboxed run;
169
+ authorize a custom MCP server) see `references/workflows.md`.
170
+
171
+ ## Conventions you can rely on across commands
172
+
173
+ These hold for every command group, so call them out when explaining
174
+ the CLI rather than restating per-command:
175
+
176
+ - `--profile <name>` is a **global** flag that overrides the default
177
+ profile for that single invocation.
178
+ - `--team <id>` is a **global** flag that overrides the resolved team
179
+ for that single invocation (OAuth profiles only; API-key profiles
180
+ reject a mismatched team).
181
+ - `--json` is available on every command that hits the API and is the
182
+ shape to use in scripts.
183
+ - Destructive operations (`duvo logout`, `duvo profiles remove`,
184
+ `duvo runs stop`, `duvo agents delete`, `duvo agents move`,
185
+ `duvo agent-folders delete`,
186
+ `duvo cases delete`, `duvo cases clear`, `duvo cases bulk-delete`,
187
+ `duvo cases bulk-reprocess`, `duvo cases bulk-update-status`,
188
+ `duvo cases bulk-update-priority`,
189
+ `duvo skills delete`, `duvo skills revisions delete`,
190
+ `duvo queues delete`, `duvo secrets delete`,
191
+ `duvo credentials delete`, `duvo revision-secrets detach`,
192
+ `duvo revision-logins detach`, `duvo revision-integrations remove`,
193
+ `duvo revision-integrations connections unpin`,
194
+ `duvo agents schedules delete`, `duvo agents case-triggers delete`,
195
+ `duvo agents slack-triggers delete`,
196
+ `duvo agents eval-rubrics remove`, `duvo agents eval-rubrics replace`,
197
+ `duvo connections delete`, `duvo queue-labels delete`,
198
+ `duvo integrations custom delete`, `duvo clarity process-labels delete`,
199
+ `duvo suggestions reject`, `duvo files delete`,
200
+ `duvo pulse delete`, `duvo pulse move`,
201
+ `duvo notifications delete-read`, `duvo notifications delete-all`,
202
+ `duvo team remove-member`, `duvo team leave`, …)
203
+ prompt for confirmation in a TTY and refuse on a non-TTY stdin. Pass
204
+ `-y` / `--yes` to skip the prompt — never pipe `yes` into the CLI to
205
+ bypass the prompt; it explicitly refuses inferred consent from piped
206
+ input.
207
+ - Exit codes: `0` success, `1` generic error, `2` auth error (missing
208
+ or invalid key, unknown profile), `3` not found. Useful for CI
209
+ scripts that want to branch on the failure mode.
210
+ - IDs are printed bare (no quotes) so they copy cleanly into shell
211
+ pipelines and `$()` substitutions:
212
+ ```bash
213
+ agent=$(duvo agents create --name "Ops bot" --input "What to do" --json | jq -r .agent.id)
214
+ duvo runs start --agent "$agent"
215
+ ```
216
+ - Deprecation warnings print to **stderr** (so they don't corrupt
217
+ `--json` stdout) and can't be silenced. If a user reports an
218
+ unexpected warning, check whether their `@duvoai/cli` version is
219
+ behind.
220
+
221
+ ## Pitfalls and gotchas
222
+
223
+ - **Profile vs credential.** `--profile foo` changes which profile is
224
+ read; `DUVO_API_KEY=…` overrides the **credential** but still uses
225
+ the selected profile's `apiBaseUrl`. To target a totally different
226
+ environment, set both `DUVO_API_KEY` and `DUVO_API_BASE_URL`.
227
+ - **`profiles use` with no argument** opens an interactive picker that
228
+ only works in a TTY. In CI, always pass a name explicitly.
229
+ - **`agents create` is interactive by default.** When `--name` and
230
+ `--input` are omitted and stdin is a TTY, the CLI prompts. In CI,
231
+ pass both flags (and `--no-build` if you don't want an initial
232
+ build) so it never blocks waiting for input.
233
+ - **`cases create --from-file -`** reads JSON from stdin. The file (or
234
+ stdin) is a single case object or an array of up to 100 cases. Each
235
+ case is `{ "title": "…", "data": "…", "labels": [{ "key": "…", "value": "…" }] }`.
236
+ Labels with no `key` are tag-only labels.
237
+ - **Sandbox files vs team files.** `duvo files …` manages persistent
238
+ team files (visible in the Files surface in the UI); `duvo sandboxes …`
239
+ stages files for a single run (`duvo runs start --sandbox-id <id>`). Don't mix them.
240
+ - **Connections vs integrations.** `duvo integrations list` shows the
241
+ team's catalog of integration types; `duvo connections list` shows
242
+ the user's actual connected accounts (one per OAuth/credential
243
+ flow). OAuth-based connections (Gmail, Slack, …) are started by
244
+ `duvo oauth native start <provider>`, not by `duvo connections create`
245
+ — the latter is only for user-provided MCP servers.
246
+ - **Attached ≠ connected.** `revision-integrations attach` only creates
247
+ the integration **slot** on the revision. For OAuth and user-provided
248
+ integrations (HubSpot, Gong, Slack, custom MCP, …) the run can only
249
+ use the slot once one of the user's connections is **pinned** to it —
250
+ an attached slot with no pinned connection fails at runtime with "not
251
+ connected", and nothing warns you at attach time. Find the connection
252
+ with `duvo connections list --type <slug>`, pin it with
253
+ `duvo revision-integrations connections pin`, and verify with
254
+ `duvo revision-integrations connections list` (expect ≥ 1 entry per
255
+ slot). Default integrations (browser, Exa, human-in-the-loop,
256
+ `case-queue-producer`/`case-queue-consumer`, …) need no pin — but
257
+ case-queue slots need a **queue mapped** instead, verified with
258
+ `duvo revision-integrations case-queue-setup`. See workflow 7 and the
259
+ setup checklist in workflow 4 of `references/workflows.md`.
260
+ - **Secrets vs connections vs credentials.** Three separate stores:
261
+ `duvo secrets` holds env-var key/value pairs injected into runs at
262
+ runtime; `duvo credentials` holds browser logins (domain + password
263
+ - optional TOTP) used by the browsing agent; `duvo connections`
264
+ holds OAuth/API-key connections to external services (Gmail, Slack,
265
+ custom MCP, …). They don’t overlap — attach secrets with
266
+ `revision-secrets`, logins with `revision-logins`, and connection
267
+ slots with `revision-integrations connections pin`.
268
+ - **Multi-team OAuth profiles.** An OAuth login can belong to several
269
+ teams. Use `duvo teams list` to see all teams, then `duvo team use <id>`
270
+ to set the default, or `--team <id>` per-command. API-key
271
+ profiles are always single-team and reject `--team`.
272
+ - **Reconnecting an expired OAuth connection.** Don't create a new
273
+ connection for a stale one — pass `--reconnect-instance-id <id>` to
274
+ `duvo oauth native start` or `duvo oauth mcp authorize` with the
275
+ existing connection's ID (from `duvo connections list`) to
276
+ re-authorize it in place instead of creating a duplicate.
277
+ - **Clarity has both read and explicit write commands.** Start with
278
+ `duvo clarity overview <process-id>`, then use `versions`, `current`,
279
+ `proposal`, `compare`, `gaps`, `evidence`, `readiness`, or `facets` to
280
+ understand the process. Use the write commands only when the user
281
+ actually wants to mutate Clarity state: generation, promotion, revert,
282
+ postprocessing, automation build, extra-capture agent, invite
283
+ links, or Miro artifact imports. Those v2-only commands require a
284
+ Clarity v2 process; legacy v1 processes
285
+ support only `overview`, `status`, `captures`, `capture`, and `export`.
286
+ Default output is compact; transcripts and media URLs are included only
287
+ when a JSON command explicitly passes `--include-transcripts`.
288
+ - **Notifications: batches vs individuals.** `duvo notifications feed`
289
+ returns a mix of individual notifications and per-agent batches;
290
+ `get-batch` and `mark-batch-read` only accept a batch ID (from `feed`
291
+ or a notification's `batchId`), not an individual notification ID. On
292
+ `notifications list`, `--sort importance` requires `--batch` — the CLI
293
+ rejects the combination locally if `--batch` is omitted.
294
+ - **Clarity artifact imports use a two-phase API under the hood.** Use
295
+ `duvo clarity import-artifact <process-id> <file>` for local Miro SVG,
296
+ XML, PNG, or JPEG exports. It creates the signed URL, uploads bytes, and
297
+ completes the import. For custom upload clients or artifact-chat
298
+ workflows, use `duvo api` against the public route directly.
299
+ - **Slack channel triggers need a connected workspace first.**
300
+ `agents slack-triggers create` fails unless the Slack workspace is
301
+ already bound to the agent — check with `agents slack-triggers
302
+ workspaces <agent-id>` before creating, and pass `--workspace` when
303
+ the team has more than one installed workspace.
304
+ - **Team member management has per-command role floors.** `team
305
+ set-role` needs Manager and above (only an Owner can grant or remove
306
+ the Owner role); `team remove-member` needs Superadmin and above;
307
+ `team leave` works for any member. All three refuse to act on the
308
+ last remaining Owner.
309
+ - **Two ways to attach a file to Pulse.** `duvo pulse send-message <id>
310
+ --message <text> --attach-file <path>` uploads and references a file
311
+ in one step — use it when you already know the instruction. `duvo
312
+ pulse attach <id> <file>` only stages the file and prints its
313
+ attachment ID, for when the instruction is composed or sent
314
+ separately (e.g. from a script building the message body). Both
315
+ share the same 5-file, 25MB-each limit.
316
+
317
+ ## When the CLI is the wrong tool
318
+
319
+ Steer users to a different surface in these cases:
320
+
321
+ - **They want to read a stream of run events as they happen.** The
322
+ CLI's `runs get` / `runs messages` are point-in-time reads. Use
323
+ `--webhook-url` on `runs start` to receive events asynchronously,
324
+ or open the run in the web UI.
325
+ - **They want to edit an AOP or agent configuration interactively.**
326
+ `revisions create` and `revisions update` accept a config file, but
327
+ composing the config by hand is painful. Direct them to the
328
+ Agent editor in the web UI for anything beyond a small targeted
329
+ patch.
330
+ - **They want to run an agent in their own process rather than on
331
+ Duvo.** That's not what the public API exposes; the CLI is a client
332
+ to the hosted Duvo platform.
333
+
334
+ ## In-skill references
335
+
336
+ - `references/commands.md` — full command tree with flags, grouped by
337
+ resource. Use this when you need the exact flag a command expects.
338
+ - `references/workflows.md` — end-to-end recipes (create an agent and
339
+ start a run; queue + cases lifecycle; sandboxed runs with uploaded
340
+ files; authorize a custom MCP server).
341
+ - `references/api-escape-hatch.md` — `duvo api` flag reference, with
342
+ worked examples of `-f` vs `-F`, `@file` typed fields, and
343
+ `--input` for raw JSON bodies.
344
+
345
+ When in doubt, run `duvo <command> --help` — the installed binary is
346
+ the final source of truth.
347
+
348
+ ## See also
349
+
350
+ - `aop-writer` — author or rewrite the AOP that ships in a Build (`duvo revisions create` / `duvo revisions update`).
351
+ - `run-debugger` — diagnose a failed Run; pairs with `duvo runs get`, `duvo runs messages`, and `duvo revisions get` for API-mode reads.
352
+ - `workflow-debugger` — audit an Agent or workflow across many Runs; pairs with `duvo runs list`, `duvo queues agents`, and `duvo revisions get`.
353
+
354
+ ## Resources
355
+
356
+ - [Duvo](https://duvo.ai) — product website
357
+ - [Duvo documentation](https://docs.duvo.ai) — concepts, building Agents, Connections
358
+ - [Duvo API reference](https://docs.duvo.ai/api-reference) — every endpoint the CLI wraps
359
+ - [`@duvoai/cli` on npm](https://www.npmjs.com/package/@duvoai/cli) — versions, install instructions, changelog
360
+ - [Web app](https://app.duvo.ai) — interactive surface for everything the CLI scripts
361
+ - [API keys](https://app.duvo.ai/settings/api-keys) — issue and revoke API keys for `duvo login --api-key`
362
+ - [Public skill repository](https://github.com/duvoai/skills) — the MIT-licensed community release of this skill, packaged for installation in third-party Claude Code setups
benchmarks/skillbench-venus-e/tasks/952829163f75b50a_q1/skill/references/api-escape-hatch.md ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `duvo api` — Low-level escape hatch
2
+
3
+ `duvo api <METHOD> <path>` makes an authenticated request to any
4
+ endpoint in the Duvo public API. Modelled on `gh api` — same flag
5
+ shapes, same parsing rules. Use it when:
6
+
7
+ - A new endpoint shipped before a dedicated `duvo` command landed.
8
+ - You need a body shape the high-level command doesn't expose.
9
+ - You're debugging — `duvo api` shows the raw API response with no
10
+ formatting in the way.
11
+
12
+ High-level commands (`duvo agents create`, etc.) are sugar over this —
13
+ they share the same HTTP client, auth resolution, output pipeline, and
14
+ exit codes.
15
+
16
+ ## Synopsis
17
+
18
+ ```text
19
+ duvo api <METHOD> <path>
20
+ [-f, --field <key=value> ...]
21
+ [-F, --raw-field <key=value> ...]
22
+ [--input <path|->]
23
+ [--json]
24
+ ```
25
+
26
+ - `METHOD` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`
27
+ (case-insensitive — `get` works too).
28
+ - `path` is a public API path starting with `/v1/…`. Don't include the
29
+ host; the CLI prepends `apiBaseUrl` from the active profile.
30
+
31
+ ## How fields become the request
32
+
33
+ - For **GET** and **HEAD**: every `-f` / `-F` field is appended to the
34
+ **query string**.
35
+ - For **POST**, **PUT**, **PATCH**, **DELETE**: every `-f` / `-F`
36
+ field is merged into the **JSON body**.
37
+ - `--input` overrides both — it sends a raw JSON body verbatim, and is
38
+ rejected on GET/HEAD or when combined with `-f` / `-F`.
39
+
40
+ When the same key appears in both `-f` and `-F`, the typed (`-F`)
41
+ value wins regardless of argument order.
42
+
43
+ ## `-f` vs `-F` — the typing distinction
44
+
45
+ `-f` always sends the value as a **string**. `-F` parses the value
46
+ into a typed JSON value. This is the single most useful disambiguation
47
+ the CLI offers; reach for it whenever the wire type matters.
48
+
49
+ | Flag | Input | Resulting JSON value |
50
+ | -------------------------- | ------------------ | ------------------------------------- |
51
+ | `-f count=42` | string | `"42"` |
52
+ | `-F count=42` | number | `42` |
53
+ | `-F price=3.14` | number | `3.14` |
54
+ | `-F enabled=true` | boolean | `true` |
55
+ | `-F enabled=false` | boolean | `false` |
56
+ | `-F deletedAt=null` | null | `null` |
57
+ | `-F config=@./config.json` | file (parsed JSON) | the parsed contents |
58
+ | `-F note=hello` | non-matching | `"hello"` _(falls through as string)_ |
59
+ | `-f` | (always) | the literal string after the `=` |
60
+
61
+ `-F` recognises typed values only for the **exact** tokens above. A
62
+ value like `-F status=draft` falls through as the string `"draft"` —
63
+ not an error, just a string.
64
+
65
+ The `@path` form reads the file as JSON, parses it, and inlines the
66
+ parsed value at that key. It is the right way to send a nested object
67
+ or an array as a single field value:
68
+
69
+ ```bash
70
+ # Send build={"name":"v2","enabled":true} as part of the JSON body.
71
+ echo '{"name":"v2","enabled":true}' > build.json
72
+ duvo api POST /v1/agents -f name="Ops bot" -F build=@build.json
73
+ ```
74
+
75
+ ## Array fields — `key[]`
76
+
77
+ A field key ending in `[]` accumulates into a JSON **array** under the
78
+ base key. Repeat the flag once per element:
79
+
80
+ ```bash
81
+ # Builds {"queue_ids": ["<id-a>", "<id-b>"]}
82
+ duvo api PUT /v1/agents/<id>/revisions/<rev>/integrations/<int>/queues \
83
+ -F "queue_ids[]=<id-a>" -F "queue_ids[]=<id-b>"
84
+ ```
85
+
86
+ Each element is typed by the same rules as a scalar `-F` (so
87
+ `-F "ids[]=1" -F "ids[]=2"` yields `[1, 2]`). A **single, non-`[]`**
88
+ field never becomes an array — `-F queue_ids=<id>` sends the bare
89
+ string, which a schema expecting an array will reject.
90
+
91
+ **Don't mix `key` and `key[]` for the same base key.** Combining them
92
+ (e.g. `-F tags=x -F "tags[]=y"`) is rejected with a `Conflicting field`
93
+ error rather than silently dropping a value — pick one syntax. When in
94
+ doubt, or for anything beyond a flat array of scalars, send the whole
95
+ body with `--input -`:
96
+
97
+ ```bash
98
+ echo '{"queue_ids":["<id-a>","<id-b>"]}' \
99
+ | duvo api PUT /v1/agents/<id>/revisions/<rev>/integrations/<int>/queues --input -
100
+ ```
101
+
102
+ ## `--input` — raw JSON body
103
+
104
+ When the request body doesn't decompose cleanly into key/value fields,
105
+ hand `duvo api` the whole payload:
106
+
107
+ ```bash
108
+ duvo api POST /v1/agents --input ./agent.json
109
+ cat ./agent.json | duvo api POST /v1/agents --input -
110
+ ```
111
+
112
+ `-` means stdin. `--input` is only valid for `POST` / `PUT` / `PATCH`
113
+ / `DELETE` — `GET`/`HEAD` requests with `--input` are rejected.
114
+
115
+ `--input` cannot be combined with `-f` / `-F`. If you need to mix a
116
+ fixed JSON skeleton with a few computed fields, render the full JSON
117
+ yourself (e.g. with `jq`) and pipe it via `--input -`.
118
+
119
+ ## Worked examples
120
+
121
+ ```bash
122
+ # 1. GET with query params.
123
+ duvo api GET /v1/agents -F limit=20 -F offset=0
124
+ duvo api GET /v1/runs -f status=running -F limit=50
125
+
126
+ # 2. POST a flat body with mixed string + typed fields.
127
+ duvo api POST /v1/agents \
128
+ -f name="Ops bot" \
129
+ -F build[name]="v1" \
130
+ -F build[enabled]=true
131
+
132
+ # 3. POST a nested body by loading JSON from a file.
133
+ duvo api POST /v1/agents \
134
+ -f name="Ops bot" \
135
+ -F build=@build.json \
136
+ -F integrations=@integrations.json
137
+
138
+ # 4. POST a raw body verbatim.
139
+ duvo api POST /v1/agents --input body.json
140
+
141
+ # 5. PATCH from a templated body via stdin.
142
+ jq -n --arg name "New name" '{name: $name}' \
143
+ | duvo api PATCH /v1/agents/<id> --input -
144
+
145
+ # 6. DELETE with a body (rare but supported).
146
+ duvo api DELETE /v1/something -F reason=null
147
+ ```
148
+
149
+ ## Output
150
+
151
+ `duvo api` returns the raw API response. Without `--json` it pretty-prints
152
+ the body for terminal readability; with `--json` it emits the JSON
153
+ unmodified for scripting.
154
+
155
+ ```bash
156
+ duvo api GET /v1/agents --json | jq '.agents | length'
157
+ ```
158
+
159
+ Exit codes match the rest of the CLI:
160
+
161
+ - `0` — success (2xx response).
162
+ - `1` — generic error (network failure, malformed input, 4xx other than `401`/`404`, 5xx).
163
+ - `2` — auth error (missing or invalid credentials, `401` from the API, unknown profile).
164
+ - `3` — not found (`404` from the API).
165
+
166
+ ## Common pitfalls
167
+
168
+ - **Forgetting `-F` on numeric IDs.** `duvo api POST /v1/something -f
169
+ limit=20` sends `"limit": "20"` (a string), which a strict schema
170
+ may reject. Use `-F limit=20` for numbers.
171
+ - **Mixing fields and `--input`.** They're mutually exclusive — pick
172
+ one. If you need both, build the body upstream and use `--input`.
173
+ - **Path prefixes.** `apiBaseUrl` is an origin (host + port, no
174
+ path). Always start `path` with `/v1/…`; don't embed it in the base
175
+ URL.
176
+ - **Query-string serialization of complex `-F` values.** For
177
+ GET/HEAD, an `-F` value that parses to an object or array is
178
+ serialized as JSON in the query string (so `-F filter=@f.json` on a
179
+ GET produces `?filter={"…":"…"}`). That's fine for endpoints
180
+ expecting JSON query params, but watch for endpoints expecting
181
+ repeated keys instead.
182
+ - **`DELETE` requests with bodies.** Supported, but not all upstream
183
+ middleware is happy about them. If a `DELETE` 400s unexpectedly, try
184
+ moving the parameters to the query string with `-f`/`-F` instead of
185
+ `--input`.