Upload folder using huggingface_hub (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_previous_check.py +8 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_program_checks.py +355 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_runtime_compat.py +59 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/repair_manifest.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/grading/verified_config.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/inputs/query_log.tsv +3 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/instruction.md +7 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.md +45 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.ru.md +37 -0
- benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/task.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_contract.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/autograde_task_check.py +14 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy-task.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/evaluate.py +159 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/objective_evaluators.py +1308 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/shell_invocations.py +378 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/test.sh +8 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/verifiers.py +521 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/repair_equivalences.py +253 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/grading/verified_config.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/instruction.md +1 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/SKILL.md +192 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/evals/evals.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/task.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_contract.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/autograde_task_check.py +12 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy-task.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/evaluate.py +159 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/objective_evaluators.py +1309 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/shell_invocations.py +229 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/test.sh +8 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/verifiers.py +525 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/r9_json.py +74 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/grading/verified_config.json +3 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/instruction.md +1 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/skill/SKILL.md +156 -0
- benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/task.json +3 -0
- benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_contract.json +3 -0
- benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/autograde_task_check.py +12 -0
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_previous_check.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
from r9_runtime_compat import install as _r9_runtime_install
|
| 3 |
+
_r9_runtime_install()
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import format_checks
|
| 6 |
+
from more_checks import HANDLERS
|
| 7 |
+
format_checks.HANDLERS.update(HANDLERS)
|
| 8 |
+
format_checks.run('8bd9dcf9cfecdef4b5ec4674',Path(__file__).resolve().parent)
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_program_checks.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supplemental public-contract checks; no stored solution or trajectory input.
|
| 2 |
+
|
| 3 |
+
Run only inside the isolated CPU grader container. Existing criterion IDs and
|
| 4 |
+
weights are preserved. Candidate programs execute in fresh input workspaces.
|
| 5 |
+
"""
|
| 6 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 7 |
+
import collections
|
| 8 |
+
import csv
|
| 9 |
+
import io
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import shutil
|
| 15 |
+
import statistics
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
from r9_json import parse_file, strict_equal
|
| 22 |
+
|
| 23 |
+
HERE = Path(__file__).resolve().parent
|
| 24 |
+
CAND = Path(os.environ.get('MYBENCH_CANDIDATE_DIR', os.environ.get('MYBENCH_CANDIDATE', '/candidate')))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def clone(folder):
|
| 28 |
+
root = Path(folder) / 'workspace'
|
| 29 |
+
shutil.copytree(CAND, root, symlinks=True, ignore=shutil.ignore_patterns('__pycache__', '.git', '.venv'))
|
| 30 |
+
return root
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def remove(path):
|
| 34 |
+
if path.is_symlink() or path.is_file():
|
| 35 |
+
path.unlink()
|
| 36 |
+
elif path.is_dir():
|
| 37 |
+
shutil.rmtree(path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def launch(script, files, output, args=()):
|
| 41 |
+
with tempfile.TemporaryDirectory(prefix='r9-public-panel-') as folder:
|
| 42 |
+
root = clone(folder)
|
| 43 |
+
remove(root / output)
|
| 44 |
+
for name, value in files.items():
|
| 45 |
+
target = root / name
|
| 46 |
+
remove(target)
|
| 47 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 48 |
+
target.write_text(value)
|
| 49 |
+
process = subprocess.run([sys.executable, script] + list(args), cwd=root,
|
| 50 |
+
capture_output=True, text=True, timeout=35)
|
| 51 |
+
try:
|
| 52 |
+
raw = (root / output).read_text()
|
| 53 |
+
except (OSError, UnicodeError):
|
| 54 |
+
raw = None
|
| 55 |
+
try:
|
| 56 |
+
parsed = parse_file(root / output)
|
| 57 |
+
except (OSError, ValueError, TypeError, UnicodeError):
|
| 58 |
+
parsed = None
|
| 59 |
+
return process.returncode, process.stdout, raw, parsed
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def constrain(checks, ids, ok, reason):
|
| 63 |
+
for check in checks:
|
| 64 |
+
if str(check['id']) in set(map(str, ids)):
|
| 65 |
+
check['passed'] = bool(check.get('passed')) and bool(ok)
|
| 66 |
+
check['reason'] = str(check.get('reason', '')) + '; R9 ' + reason
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def old_checks():
|
| 70 |
+
process = subprocess.run([sys.executable, str(HERE / 'r9_previous_check.py')],
|
| 71 |
+
capture_output=True, text=True, timeout=480)
|
| 72 |
+
for line in reversed(process.stdout.splitlines()):
|
| 73 |
+
try:
|
| 74 |
+
value = json.loads(line)
|
| 75 |
+
if isinstance(value, dict) and isinstance(value.get('checks'), list):
|
| 76 |
+
return value['checks']
|
| 77 |
+
except ValueError:
|
| 78 |
+
pass
|
| 79 |
+
raise RuntimeError('previous grader did not return checks')
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def azure(checks):
|
| 83 |
+
# No empty/zero-mean usage: the public CV formula does not define that case.
|
| 84 |
+
panels = [
|
| 85 |
+
({'fresh-a': [7, 13], 'fresh-b': [4, 16], 'single': [5]},
|
| 86 |
+
[('Reservation', 90, 11.75), ('SavingsPlan', 89.99, 17.5),
|
| 87 |
+
('SavingsPlan', 97, 2.25), ('Other', 91, 3)]),
|
| 88 |
+
({'same': [8, 8, 8], 'wide': [1, 4, 9, 20]}, []),
|
| 89 |
+
]
|
| 90 |
+
scripts = sorted(p.name for p in CAND.glob('*.py'))
|
| 91 |
+
entries = []
|
| 92 |
+
for script in scripts:
|
| 93 |
+
states = [True] * 5
|
| 94 |
+
try:
|
| 95 |
+
for usage, rows in panels:
|
| 96 |
+
recs = {'value': [{'id': '/subscriptions/fresh-a', 'kind': kind,
|
| 97 |
+
'properties': {'recommendationDetails': {
|
| 98 |
+
'commitmentAmount': amount,
|
| 99 |
+
'averageUtilizationPercentage': util}}}
|
| 100 |
+
for kind, util, amount in rows]}
|
| 101 |
+
rc, out, raw, data = launch(script, {
|
| 102 |
+
'data/hourly_usage.json': json.dumps(usage),
|
| 103 |
+
'data/recommendations.json': json.dumps(recs)}, 'report.json')
|
| 104 |
+
shape = isinstance(data, dict) and all(k in data for k in (
|
| 105 |
+
'subscriptions', 'counts', 'eligible_commitment_sum', 'mg_scope_commitment'))
|
| 106 |
+
states[0] &= rc == 0 and shape
|
| 107 |
+
states[4] &= shape
|
| 108 |
+
subs = data.get('subscriptions') if shape else None
|
| 109 |
+
valid_subs = isinstance(subs, dict) and set(subs) == set(usage)
|
| 110 |
+
if valid_subs:
|
| 111 |
+
for name, values in usage.items():
|
| 112 |
+
cv = statistics.pstdev(values) / statistics.mean(values)
|
| 113 |
+
classification = 'stable' if cv < .3 else 'variable' if cv < .6 else 'volatile'
|
| 114 |
+
row = subs[name]
|
| 115 |
+
valid_subs &= isinstance(row, dict) and type(row.get('cv')) in (int, float)
|
| 116 |
+
valid_subs &= valid_subs and math.isfinite(row['cv']) and abs(row['cv'] - cv) <= .005
|
| 117 |
+
valid_subs &= valid_subs and row.get('classification') == classification
|
| 118 |
+
states[1] &= valid_subs
|
| 119 |
+
expected_counts = {kind: sum(r[0] == kind for r in rows) for kind in ('Reservation', 'SavingsPlan')}
|
| 120 |
+
states[2] &= shape and strict_equal(data.get('counts'), expected_counts)
|
| 121 |
+
total = sum(amount for kind, util, amount in rows if util >= 90)
|
| 122 |
+
states[3] &= shape and all(type(data.get(k)) in (int, float) and math.isfinite(data[k]) and
|
| 123 |
+
abs(data[k] - value) < 1e-9 for k, value in (
|
| 124 |
+
('eligible_commitment_sum', total), ('mg_scope_commitment', round(total * .7, 2))))
|
| 125 |
+
entries.append(states)
|
| 126 |
+
except Exception:
|
| 127 |
+
entries.append([False] * 5)
|
| 128 |
+
best = next((state for state in entries if all(state)), None)
|
| 129 |
+
if best is None:
|
| 130 |
+
best = max(entries, key=sum) if entries else [False] * 5
|
| 131 |
+
for i, state in enumerate(best):
|
| 132 |
+
constrain(checks, [i], state, 'changed subscription IDs, exact CV .3/.6, singleton/stable/volatile, utilization >=90, empty recommendations, and all-kind eligible sum')
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def provisioning(checks):
|
| 136 |
+
panels = [
|
| 137 |
+
('- covered-a\n- covered-b\n', 'keep-z\ncovered-a\n\nkeep-z\ncovered-b\nkeep-a\ncovered-a\n',
|
| 138 |
+
['keep-z', 'keep-a'], 2),
|
| 139 |
+
('# no covered entries\n', '\nlast\nfirst\nlast\n', ['last', 'first'], 0),
|
| 140 |
+
('plugins:\n - all-a\n - all-b\n', 'all-b\nall-b\nall-a\n', [], 2),
|
| 141 |
+
('- unused\n', '\n', [], 0),
|
| 142 |
+
]
|
| 143 |
+
flags = [True] * 5
|
| 144 |
+
for yml, manifest, kept, excluded in panels:
|
| 145 |
+
rc, stdout, raw, parsed = launch('audit.py', {
|
| 146 |
+
'plugin-recommendations.yml': yml, 'provisioned-manifest.txt': manifest}, 'provision-plan.txt')
|
| 147 |
+
lines = raw.splitlines() if isinstance(raw, str) else None
|
| 148 |
+
expected = kept + ['excluded: ' + str(excluded)]
|
| 149 |
+
flags[0] &= rc == 0
|
| 150 |
+
flags[1] &= lines == expected
|
| 151 |
+
flags[2] &= lines is not None and lines[:-1] == kept
|
| 152 |
+
flags[3] &= lines is not None and lines[-1:] == ['excluded: ' + str(excluded)]
|
| 153 |
+
flags[4] &= ('kept=%d excluded=%d' % (len(kept), excluded)) in [x.strip() for x in stdout.splitlines()]
|
| 154 |
+
for i, state in enumerate(flags):
|
| 155 |
+
constrain(checks, [i], state, 'fresh flat/grouped lists, changed names, duplicate counts, first appearance, all/none excluded, empty manifest')
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def editor(checks):
|
| 159 |
+
empty = {'file': None, 'cursor': None, 'selection': None, 'diagnostics': None, 'quickfix': None}
|
| 160 |
+
panels = [('', {}, empty), ('diagnostics: 0\nquickfix: 7\n', {}, dict(empty, diagnostics=0, quickfix=7)),
|
| 161 |
+
('filepath: file with spaces.py\n', {'file with spaces.py': 'one\ntwo'}, dict(empty, file='file with spaces.py')),
|
| 162 |
+
('cursor_position: 2:1\n', {}, dict(empty, cursor={'line': 2, 'column': 1})),
|
| 163 |
+
('filepath: file with spaces.py\ncursor_position: 2:1\nvisual_selection: 1:2-2:3\ndiagnostics: 1\nquickfix: 4\n',
|
| 164 |
+
{'file with spaces.py': 'first line\nsecond line'},
|
| 165 |
+
{'file': 'file with spaces.py', 'cursor': {'line': 2, 'column': 1},
|
| 166 |
+
'selection': {'start': {'line': 1, 'column': 2}, 'end': {'line': 2, 'column': 3}},
|
| 167 |
+
'diagnostics': 1, 'quickfix': 4, 'line_at_cursor': 'second line'}),
|
| 168 |
+
('filepath: short.py\ncursor_position: 99:3\n', {'short.py': 'only\n'},
|
| 169 |
+
dict(empty, file='short.py', cursor={'line': 99, 'column': 3}, line_at_cursor=None))]
|
| 170 |
+
flags = [True] * 7
|
| 171 |
+
for text, files, expected in panels:
|
| 172 |
+
rc, out, raw, data = launch('report.py', dict(files, **{'agent_output.txt': text}), 'context_report.')
|
| 173 |
+
flags[0] &= rc == 0 and isinstance(data, dict) and set(data) == set(expected)
|
| 174 |
+
for cid, fields in [(1, ['file']), (2, ['cursor']), (3, ['selection']), (4, ['diagnostics', 'quickfix']), (5, ['line_at_cursor'])]:
|
| 175 |
+
flags[cid] &= isinstance(data, dict) and all((key in data) == (key in expected) and
|
| 176 |
+
(key not in expected or strict_equal(data[key], expected[key])) for key in fields)
|
| 177 |
+
flags[6] &= rc == 0
|
| 178 |
+
for i, state in enumerate(flags):
|
| 179 |
+
constrain(checks, [i], state, 'fresh optional/absent fields, null vs omitted line_at_cursor, OOB line, no-final-newline, changed integer fields, spaces in path')
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def validator(checks):
|
| 183 |
+
base = {'SKILL.md': '---\nname: fresh-validator\ndescription: Fresh package\n---\nbody\n',
|
| 184 |
+
'references/REFERENCE.md': 'REMCOCHAT_SKILLS_CONFORMANCE_REFERENCE_v1\n',
|
| 185 |
+
'assets/fixture.json': '{"fixture_id":"fresh-id"}',
|
| 186 |
+
'scripts/echo.sh': '#!/bin/sh\necho REMCOCHAT_SKILLS_SCRIPT_OK\n'}
|
| 187 |
+
scenarios = [('missing_skill', {'SKILL.md': None}, 'frontmatter'),
|
| 188 |
+
('empty_name', {'SKILL.md': '---\nname: \ndescription: Present\n---\n'}, 'frontmatter'),
|
| 189 |
+
('body_name_only', {'SKILL.md': '# body\nname: x\ndescription: y\n'}, 'frontmatter'),
|
| 190 |
+
('bad_fixture', {'assets/fixture.json': '{bad'}, 'fixture_json'),
|
| 191 |
+
('empty_fixture', {'assets/fixture.json': '{"fixture_id":""}'}, 'fixture_json'),
|
| 192 |
+
('wrong_fixture_type', {'assets/fixture.json': '{"fixture_id":123}'}, 'fixture_json'),
|
| 193 |
+
('missing_reference', {'references/REFERENCE.md': None}, 'reference_marker'),
|
| 194 |
+
('failing_echo', {'scripts/echo.sh': '#!/bin/sh\necho REMCOCHAT_SKILLS_SCRIPT_OK\nexit 7\n'}, 'echo_script'),
|
| 195 |
+
('wrong_stdout', {'scripts/echo.sh': '#!/bin/sh\necho unrelated\n'}, 'echo_script'),
|
| 196 |
+
('missing_echo', {'scripts/echo.sh': None}, 'echo_script')]
|
| 197 |
+
flags = {str(i): True for i in range(7)}
|
| 198 |
+
owners = {'frontmatter': '3', 'reference_marker': '2', 'fixture_json': '5', 'echo_script': '4'}
|
| 199 |
+
for name, updates, failed in scenarios:
|
| 200 |
+
with tempfile.TemporaryDirectory(prefix='r9-validator-') as folder:
|
| 201 |
+
root = clone(folder)
|
| 202 |
+
package = root / ('probe_' + name)
|
| 203 |
+
files = dict(base, **updates)
|
| 204 |
+
for rel, content in files.items():
|
| 205 |
+
if content is not None:
|
| 206 |
+
path = package / rel
|
| 207 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 208 |
+
path.write_text(content)
|
| 209 |
+
if rel.endswith('.sh'):
|
| 210 |
+
path.chmod(0o755)
|
| 211 |
+
output = root / 'probe-report.json'
|
| 212 |
+
process = subprocess.run([sys.executable, 'validate_skill.py', str(package), str(output)],
|
| 213 |
+
cwd=root, capture_output=True, text=True, timeout=35)
|
| 214 |
+
try:
|
| 215 |
+
data = parse_file(output)
|
| 216 |
+
except Exception:
|
| 217 |
+
data = None
|
| 218 |
+
rows = data.get('checks') if isinstance(data, dict) else None
|
| 219 |
+
shape = isinstance(rows, list) and len(rows) == 4 and all(isinstance(row, dict) for row in rows)
|
| 220 |
+
shape = shape and sorted(row.get('name', '') for row in rows) == sorted(owners)
|
| 221 |
+
values = {row['name']: row for row in rows} if shape else {}
|
| 222 |
+
flags[owners[failed]] &= shape and all(values[key].get('passed') is (key != failed) for key in owners)
|
| 223 |
+
flags['6'] &= shape and data.get('path') == str(package) and data.get('ok') is False
|
| 224 |
+
flags['6'] &= shape and all(type(row.get('passed')) is bool and isinstance(row.get('detail'), str) for row in rows)
|
| 225 |
+
flags['0'] &= process.returncode == 0
|
| 226 |
+
for cid, state in flags.items():
|
| 227 |
+
constrain(checks, [cid], state, 'missing/body-only/empty frontmatter, missing reference, invalid/empty/nonstring fixture ID, actual echo failure/wrong stdout/missing file, complete typed per-case report')
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def dedup(checks):
|
| 231 |
+
script = CAND / 'dedup.sh'
|
| 232 |
+
source = script.read_text()
|
| 233 |
+
constrain(checks, [0], bool(source.splitlines()) and source.splitlines()[0] == '#!/bin/sh', 'the required POSIX shell shebang is an exact first line, not a prefix of a different interpreter')
|
| 234 |
+
with tempfile.TemporaryDirectory(prefix='r9-dedup-') as folder:
|
| 235 |
+
root = Path(folder)
|
| 236 |
+
missing = root / 'absent'
|
| 237 |
+
not_directory = root / 'file'
|
| 238 |
+
not_directory.write_text('x')
|
| 239 |
+
cases = [[str(missing)], [str(not_directory)], [str(root), str(root)]]
|
| 240 |
+
ok = True
|
| 241 |
+
for args in cases:
|
| 242 |
+
p = subprocess.run(['/bin/sh', str(script)] + args, cwd=root,
|
| 243 |
+
capture_output=True, text=True, timeout=30)
|
| 244 |
+
ok &= p.returncode == 2 and bool(p.stderr.strip())
|
| 245 |
+
constrain(checks, [2], ok, 'nonexistent/file arguments and too many arguments also require stderr usage and exit2')
|
| 246 |
+
tree = root / 'tree'
|
| 247 |
+
tree.mkdir()
|
| 248 |
+
groups = [['a one.txt', 'b two.txt'], ['c.txt', 'd.txt', 'e.txt']]
|
| 249 |
+
for index, names in enumerate(groups):
|
| 250 |
+
for name in names:
|
| 251 |
+
(tree / name).write_text('distinct payload ' + str(index))
|
| 252 |
+
(tree / 'unique.txt').write_text('unique')
|
| 253 |
+
temporary = root / 'temp-files'
|
| 254 |
+
temporary.mkdir()
|
| 255 |
+
env = dict(os.environ, TMPDIR=str(temporary))
|
| 256 |
+
p = subprocess.run(['/bin/sh', str(script), str(tree)], cwd=root, env=env,
|
| 257 |
+
capture_output=True, text=True, timeout=30)
|
| 258 |
+
lines = [line for line in p.stdout.splitlines() if line.strip()]
|
| 259 |
+
ok = p.returncode == 0 and len(lines) == 2 and 'unique.txt' not in p.stdout
|
| 260 |
+
ok &= all(sum(all(name in line for name in names) for line in lines) == 1 for names in groups)
|
| 261 |
+
ok &= all(not any(any(name in line for name in groups[a]) and any(name in line for name in groups[b])
|
| 262 |
+
for a in range(2) for b in range(a + 1, 2)) for line in lines)
|
| 263 |
+
constrain(checks, [5], ok, 'two independent duplicate groups, three-member group, spaces, no merging/unique leak')
|
| 264 |
+
constrain(checks, [3], not list(temporary.iterdir()), 'actual mktemp files under supplied TMPDIR are removed after successful execution')
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def querylog(checks):
|
| 268 |
+
header = ['event_time', 'query_id', 'user', 'query_duration_ms', 'read_rows', 'read_bytes', 'written_rows', 'written_bytes', 'memory_usage', 'exception', 'query']
|
| 269 |
+
panels = [[('z', 2, 10000001, 1000000001, ''), ('x', 20, 10000000, 1000000000, 'failure'),
|
| 270 |
+
('z', 7, 10000001, 7, ''), ('a', 11, 1, 1000000001, '')],
|
| 271 |
+
[('single', 17, 0, 0, '')]]
|
| 272 |
+
bits = [True] * 7
|
| 273 |
+
for rows in panels:
|
| 274 |
+
out = io.StringIO()
|
| 275 |
+
writer = csv.writer(out, delimiter='\t', lineterminator='\n')
|
| 276 |
+
writer.writerow(header)
|
| 277 |
+
for qid, duration, reads, memory, error in rows:
|
| 278 |
+
writer.writerow(['2026-01-01', qid, 'u', duration, reads, 0, 0, 0, memory, error, 'SELECT 1'])
|
| 279 |
+
rc, stdout, raw, data = launch('analyze.py', {'query_log.tsv': out.getvalue()}, 'report.')
|
| 280 |
+
shape = isinstance(data, dict)
|
| 281 |
+
bits[0] &= rc == 0 and shape
|
| 282 |
+
bits[1] &= shape and type(data.get('total_queries')) is int and data['total_queries'] == len(rows)
|
| 283 |
+
bits[1] &= shape and type(data.get('failed_queries')) is int and data['failed_queries'] == sum(bool(row[4]) for row in rows)
|
| 284 |
+
wanted = [{'query_id': row[0], 'query_duration_ms': row[1], 'read_rows': row[2], 'memory_usage': row[3],
|
| 285 |
+
'suspected_cause': 'memory' if row[3] > 1000000000 else 'scan_heavy' if row[2] > 10000000 else 'other'}
|
| 286 |
+
for row in sorted(rows, key=lambda row: -row[1])[:3]]
|
| 287 |
+
bits[2] &= shape and strict_equal(data.get('top_slowest'), wanted)
|
| 288 |
+
bits[3] &= shape and isinstance(data.get('top_slowest'), list) and all(
|
| 289 |
+
isinstance(actual, dict) and actual.get('suspected_cause') == expected['suspected_cause'] for actual, expected in zip(data['top_slowest'], wanted))
|
| 290 |
+
duplicates = sorted(qid for qid, count in collections.Counter(row[0] for row in rows).items() if count > 1)
|
| 291 |
+
bits[4] &= shape and strict_equal(data.get('duplicate_ids'), duplicates)
|
| 292 |
+
durations = sorted(row[1] for row in rows)
|
| 293 |
+
bits[5] &= shape and type(data.get('p95_duration_ms')) in (int, float) and data['p95_duration_ms'] == durations[math.ceil(.95 * len(rows)) - 1]
|
| 294 |
+
bits[6] &= not stdout
|
| 295 |
+
for cid, state in enumerate(bits):
|
| 296 |
+
constrain(checks, [cid], state, 'changed TSV, singleton top list, repeated IDs, exact threshold strict>, cause precedence, nearest-rank, silent stdout')
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def calver(checks):
|
| 300 |
+
changelog = (CAND / 'changelog.md').read_text()
|
| 301 |
+
source = ((Path('/source') if Path('/source/inputs').is_dir() else HERE.parent) / 'inputs/CHANGELOG.md').read_text()
|
| 302 |
+
version_headers = re.findall(r'^##\s*\[2026\.03\.0\].*$', changelog, re.M)
|
| 303 |
+
constrain(checks, [0], len(version_headers) == 1, 'the new release version occurs as exactly one section, not duplicated release sections')
|
| 304 |
+
section = re.search(r'^##\s*\[2026\.03\.0\].*?(?=^##\s|\Z)', changelog, re.M | re.S)
|
| 305 |
+
unreleased = re.search(r'^##\s*\[Unreleased\].*?(?=^##\s|\Z)', source, re.M | re.S)
|
| 306 |
+
items = re.findall(r'^\s*[-*]\s+(.+?)\s*$', unreleased.group(0), re.M) if unreleased else []
|
| 307 |
+
new = section.group(0) if section else ''
|
| 308 |
+
once = bool(section) and all(len(re.findall(r'^\s*[-*]\s+' + re.escape(item) + r'\s*$', new, re.M)) == 1 for item in items)
|
| 309 |
+
once &= all(len(re.findall(r'^###\s*' + name + r'\s*$', new, re.M)) == 1 for name in ['Added', 'Changed', 'Fixed'])
|
| 310 |
+
constrain(checks, [1], once, 'each moved original item and its existing Added/Changed/Fixed subsection appears exactly once')
|
| 311 |
+
expected_package = parse_file((Path('/source') if Path('/source/inputs').is_dir() else HERE.parent) / 'inputs/package.')
|
| 312 |
+
expected_package['version'] = '2026.03.0'
|
| 313 |
+
package = parse_file(CAND / 'package.')
|
| 314 |
+
constrain(checks, [4], strict_equal(package, expected_package), 'strict nonduplicate JSON preserves the complete original package metadata and changes only the release version')
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
HANDLERS = {
|
| 318 |
+
'60c549e81b03fc667586d0d7': azure,
|
| 319 |
+
'7b074d0b21eaa88ed135fd50': provisioning,
|
| 320 |
+
'7bd4a66c3cf0048be68c0caf': editor,
|
| 321 |
+
'8415596226ceae1108c89af2': validator,
|
| 322 |
+
'881ffb8f1cb15a8f6e777090': dedup,
|
| 323 |
+
'8bd9dcf9cfecdef4b5ec4674': querylog,
|
| 324 |
+
'6fae5fc9ab4122d0ae5a7281': calver,
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def main():
|
| 329 |
+
qid = json.loads((Path('/source')/'task.json').read_text())['query_id'] if (Path('/source')/'task.json').is_file() else HERE.parent.name
|
| 330 |
+
checks = old_checks()
|
| 331 |
+
try:
|
| 332 |
+
HANDLERS[qid](checks)
|
| 333 |
+
dependencies = {
|
| 334 |
+
'60c549e81b03fc667586d0d7': ('0', [path.name for path in CAND.glob('*.py')]),
|
| 335 |
+
'7b074d0b21eaa88ed135fd50': ('0', ['audit.py']),
|
| 336 |
+
'7bd4a66c3cf0048be68c0caf': ('6', ['report.py']),
|
| 337 |
+
'8415596226ceae1108c89af2': ('0', ['validate_skill.py']),
|
| 338 |
+
'8bd9dcf9cfecdef4b5ec4674': ('6', ['analyze.py']),
|
| 339 |
+
}
|
| 340 |
+
if qid in dependencies:
|
| 341 |
+
from dependency_scan import scan_stdlib
|
| 342 |
+
owner, entries = dependencies[qid]
|
| 343 |
+
permitted, modules, why = scan_stdlib(CAND, entries)
|
| 344 |
+
for row in checks:
|
| 345 |
+
if str(row['id']) == owner:
|
| 346 |
+
row['passed'] = False if row.get('passed') is False or permitted is False else None if row.get('passed') is None or permitted is None else True
|
| 347 |
+
row['reason'] += '; R9 reachable stdlib/local helper graph: ' + why
|
| 348 |
+
except Exception as error:
|
| 349 |
+
for check in checks:
|
| 350 |
+
check.update(passed=None, reason='R9 public-input supplemental evaluation unavailable: ' + type(error).__name__)
|
| 351 |
+
print(json.dumps({'scoreable': all(type(row.get('passed')) is bool for row in checks), 'checks': checks}))
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
if __name__ == '__main__':
|
| 355 |
+
main()
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_runtime_compat.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preserve ordinary local helper modules in legacy public-input test copies.
|
| 2 |
+
|
| 3 |
+
The parent grader separately scans the original, unmodified stdlib closure.
|
| 4 |
+
This compatibility child process allows a top-level import of a local module;
|
| 5 |
+
it does not grant permission to third-party dependencies inside that module.
|
| 6 |
+
"""
|
| 7 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 8 |
+
import os
|
| 9 |
+
import shutil
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def install():
|
| 15 |
+
candidate = Path(os.environ.get('MYBENCH_CANDIDATE', os.environ.get('MYBENCH_CANDIDATE_DIR', '/candidate')))
|
| 16 |
+
if not candidate.is_dir():
|
| 17 |
+
return
|
| 18 |
+
modules = {path.stem for path in candidate.glob('*.py')}
|
| 19 |
+
packages = [path for path in candidate.iterdir() if path.is_dir() and not path.name.startswith('.') and
|
| 20 |
+
((path / '__init__.py').is_file() or any(path.glob('*.py')))]
|
| 21 |
+
modules.update(path.name for path in packages)
|
| 22 |
+
original_stdlib = set(getattr(sys, 'stdlib_module_names', ()))
|
| 23 |
+
sys.stdlib_module_names = frozenset(original_stdlib | modules)
|
| 24 |
+
original_copy = shutil.copy
|
| 25 |
+
original_copyfile = shutil.copyfile
|
| 26 |
+
|
| 27 |
+
def copy(source, target, *args, **kwargs):
|
| 28 |
+
result = original_copy(source, target, *args, **kwargs)
|
| 29 |
+
src = Path(source)
|
| 30 |
+
if src.parent.resolve() == candidate.resolve() and src.suffix == '.py':
|
| 31 |
+
destination = Path(target)
|
| 32 |
+
folder = destination if destination.is_dir() else destination.parent
|
| 33 |
+
for helper in candidate.glob('*.py'):
|
| 34 |
+
if helper.name != src.name:
|
| 35 |
+
shutil.copy2(helper, folder / helper.name)
|
| 36 |
+
for package in packages:
|
| 37 |
+
shutil.copytree(package, folder / package.name, dirs_exist_ok=True,
|
| 38 |
+
ignore=shutil.ignore_patterns('__pycache__'))
|
| 39 |
+
if src.parent.resolve() == candidate.resolve() and src.suffix == '.py':
|
| 40 |
+
from r12_resources import copy_authored_resources
|
| 41 |
+
copy_authored_resources(candidate,folder)
|
| 42 |
+
return result
|
| 43 |
+
|
| 44 |
+
_copying_modules=False
|
| 45 |
+
def copyfile(source,target,*args,**kwargs):
|
| 46 |
+
nonlocal _copying_modules
|
| 47 |
+
result=original_copyfile(source,target,*args,**kwargs)
|
| 48 |
+
src=Path(source)
|
| 49 |
+
if not _copying_modules and src.parent.resolve()==candidate.resolve() and src.suffix=='.py':
|
| 50 |
+
from r10_support import copy_modules
|
| 51 |
+
_copying_modules=True
|
| 52 |
+
try:
|
| 53 |
+
copy_modules(candidate,Path(target).parent)
|
| 54 |
+
from r12_resources import copy_authored_resources
|
| 55 |
+
copy_authored_resources(candidate,Path(target).parent)
|
| 56 |
+
finally:_copying_modules=False
|
| 57 |
+
return result
|
| 58 |
+
shutil.copy = copy
|
| 59 |
+
shutil.copyfile = copyfile
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/repair_manifest.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64a3a3db315a4dda92a00f95a1df75d2522dc439520fab2c85b943da9edcf674
|
| 3 |
+
size 1092
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/grading/verified_config.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:077ffd511b709732a70e8d2332141041e46f95c6db8cdfadbf8e245a9b12d56b
|
| 3 |
+
size 4867
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/inputs/query_log.tsv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:721a60e08fe80448e7bf95d0f977323cbd1f052b893cf4e77bdb49061f79cbf3
|
| 3 |
+
size 1234
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/instruction.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are given an export of a ClickHouse `system.query_log`-style table as a TSV file (columns: event_time, query_id, user, query_duration_ms, read_rows, read_bytes, written_rows, written_bytes, memory_usage, exception, query). Write a Python 3 script `analyze.py` (standard library only) that reads `query_log.tsv` and writes `report.` with: (1) `total_queries`; (2) `failed_queries` (rows where exception is non-empty); (3) `top_slowest`: the 3 queries with the highest query_duration_ms, each as an object with query_id, query_duration_ms, read_rows, memory_usage, and a `suspected_cause` field that is one of "memory" (memory_usage > 1_000_000_000), "scan_heavy" (read_rows > 10_000_000), or "other" (first matching rule in that order); (4) `duplicate_ids`: a sorted list of query_ids that appear more than once; (5) `p95_duration_ms`: the 95th percentile of query_duration_ms computed with nearest-rank method (ceil(0.95*n)-th value of the sorted durations, 1-indexed). Sort top_slowest by duration descending. Print nothing except writing the file.
|
| 2 |
+
Bounded automatic resource contract: During the actual grader-launched Python invocations, Python imports must resolve to the standard library or submitted local modules/packages (including namespace packages and computed imports). Unused/dead source code and strings are not rejected by static import inference. 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.
|
| 3 |
+
|
| 4 |
+
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.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
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. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. 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/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: clickhouse-debugging
|
| 3 |
+
description: "Debugging for Clickhouse: debugging and troubleshooting"
|
| 4 |
+
category: database
|
| 5 |
+
tags: [clickhouse, debugging, database]
|
| 6 |
+
models: [sonnet, opus]
|
| 7 |
+
version: "1.0"
|
| 8 |
+
language: en
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Clickhouse Debugging
|
| 12 |
+
|
| 13 |
+
> Debugging for Clickhouse: debugging and troubleshooting
|
| 14 |
+
|
| 15 |
+
## Quick Start
|
| 16 |
+
Begin by understanding the core concepts of Debugging with Clickhouse.
|
| 17 |
+
|
| 18 |
+
## When to Use
|
| 19 |
+
- Setting up Clickhouse for debugging and troubleshooting
|
| 20 |
+
- Implementing Debugging patterns
|
| 21 |
+
- Building production-ready solutions with Clickhouse
|
| 22 |
+
|
| 23 |
+
## Step-by-Step
|
| 24 |
+
1. Review prerequisites and requirements
|
| 25 |
+
2. Set up the development environment
|
| 26 |
+
3. Implement the debugging configuration
|
| 27 |
+
4. Test the implementation
|
| 28 |
+
5. Deploy to production
|
| 29 |
+
|
| 30 |
+
## Dependencies
|
| 31 |
+
- Clickhouse
|
| 32 |
+
- Development environment
|
| 33 |
+
- Required SDKs and tools
|
| 34 |
+
|
| 35 |
+
## Examples
|
| 36 |
+
See the official Clickhouse documentation for complete examples.
|
| 37 |
+
|
| 38 |
+
## Resources
|
| 39 |
+
- Clickhouse official documentation
|
| 40 |
+
- Community guides and tutorials
|
| 41 |
+
|
| 42 |
+
## Validation
|
| 43 |
+
- Verify the setup works correctly
|
| 44 |
+
- Run test cases
|
| 45 |
+
- Check logs and metrics
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.ru.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: clickhouse-debugging
|
| 3 |
+
description: "Debugging for Clickhouse: debugging and troubleshooting"
|
| 4 |
+
category: database
|
| 5 |
+
tags: [clickhouse-debugging, database, russian]
|
| 6 |
+
models: [sonnet, opus]
|
| 7 |
+
version: "1.0"
|
| 8 |
+
language: ru
|
| 9 |
+
original: clickhouse-debugging
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Clickhouse Debugging
|
| 13 |
+
|
| 14 |
+
> Debugging for Clickhouse: debugging and troubleshooting
|
| 15 |
+
|
| 16 |
+
## Быстрый старт
|
| 17 |
+
Этот навык на русском языке. Оригинал: `clickhouse-debugging`.
|
| 18 |
+
|
| 19 |
+
## Когда использовать
|
| 20 |
+
- Работа с Базы данных
|
| 21 |
+
- Выполнение задач, связанных с Clickhouse Debugging
|
| 22 |
+
- Профессиональное развитие
|
| 23 |
+
|
| 24 |
+
## Инструкции
|
| 25 |
+
1. Ознакомьтесь с описанием навыка
|
| 26 |
+
2. Изучите английскую версию для полных инструкций
|
| 27 |
+
3. Примените полученные знания на практике
|
| 28 |
+
|
| 29 |
+
## Ресурсы
|
| 30 |
+
- Оригинальный навык: database/clickhouse-debugging/SKILL.md
|
| 31 |
+
- Категория: Базы данных
|
| 32 |
+
- Язык: Русский
|
| 33 |
+
|
| 34 |
+
## Валидация
|
| 35 |
+
- Прочитайте английскую версию для проверки
|
| 36 |
+
- Выполните описанные шаги
|
| 37 |
+
- Убедитесь в правильности результата
|
benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/task.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:48b57def295e7a56e1d54a00b22dc73a930a53b72278b182433af07ba08a669e
|
| 3 |
+
size 4313
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37
|
| 3 |
+
size 83
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_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/8dbd07af72331a25_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/8dbd07af72331a25_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/8dbd07af72331a25_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/8dbd07af72331a25_q1/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy-task.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b1f767b6dc8931e2a02ffa13a9a74ad7c3c231582997ced39696c09847218885
|
| 3 |
+
size 4478
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_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 |
+
ra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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Composable objective evaluators for response and workspace tasks.
|
| 2 |
+
|
| 3 |
+
Task semantics are deliberately *not* enumerated here. A task may describe any
|
| 4 |
+
real user goal; verified membership depends on whether its deliverables compile
|
| 5 |
+
to one of these small, trusted evaluator primitives and pass counterfactual
|
| 6 |
+
execution. This keeps the objective surface closed and auditable without
|
| 7 |
+
turning the benchmark's task ontology into a closed template list.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import ast
|
| 12 |
+
import copy
|
| 13 |
+
import builtins
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import shlex
|
| 18 |
+
import subprocess
|
| 19 |
+
import tempfile
|
| 20 |
+
import tomllib
|
| 21 |
+
from pathlib import Path, PurePosixPath
|
| 22 |
+
try:
|
| 23 |
+
from .shell_invocations import shell_invocations
|
| 24 |
+
except ImportError:
|
| 25 |
+
from shell_invocations import shell_invocations
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
WORKSPACE_EVALUATOR = "workspace_objective"
|
| 29 |
+
WORKSPACE_EVALUATOR_VERSION = 15
|
| 30 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
| 31 |
+
ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
|
| 32 |
+
_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ObjectiveEvaluatorError(ValueError):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def safe_relative_path(value):
|
| 40 |
+
"""Return a normalized portable relative path or fail closed."""
|
| 41 |
+
text = str(value or "").strip().replace("\\", "/")
|
| 42 |
+
path = PurePosixPath(text)
|
| 43 |
+
if (not text or text.startswith("/") or path.is_absolute() or
|
| 44 |
+
any(part in {"", ".", ".."} for part in path.parts)):
|
| 45 |
+
raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
|
| 46 |
+
if len(path.parts) > 8 or len(text) > 180:
|
| 47 |
+
raise ObjectiveEvaluatorError("workspace path is too deep or long")
|
| 48 |
+
return path.as_posix()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _json_value(value):
|
| 52 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 53 |
+
return value
|
| 54 |
+
return json.loads(str(value))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _canonical(value):
|
| 58 |
+
if isinstance(value, dict):
|
| 59 |
+
return {key: _canonical(value[key]) for key in sorted(value)}
|
| 60 |
+
if isinstance(value, list):
|
| 61 |
+
return [_canonical(item) for item in value]
|
| 62 |
+
return value
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _file_content(item):
|
| 66 |
+
fmt = str(item.get("format") or "").casefold()
|
| 67 |
+
content = item.get("content")
|
| 68 |
+
if fmt == "json":
|
| 69 |
+
parsed = _json_value(content)
|
| 70 |
+
return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 71 |
+
if not isinstance(content, str):
|
| 72 |
+
raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
|
| 73 |
+
return content.rstrip() + "\n"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _ast_name(node):
|
| 77 |
+
if isinstance(node, ast.Name):
|
| 78 |
+
return node.id
|
| 79 |
+
if isinstance(node, ast.Attribute):
|
| 80 |
+
parent = _ast_name(node.value)
|
| 81 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 82 |
+
return ""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _python_inventory(text):
|
| 86 |
+
tree = ast.parse(text)
|
| 87 |
+
imports, calls = set(), set()
|
| 88 |
+
for node in ast.walk(tree):
|
| 89 |
+
if isinstance(node, ast.Import):
|
| 90 |
+
imports.update(alias.name for alias in node.names)
|
| 91 |
+
elif isinstance(node, ast.ImportFrom):
|
| 92 |
+
module = node.module or ""
|
| 93 |
+
for alias in node.names:
|
| 94 |
+
imports.add(f"{module}.{alias.name}".strip("."))
|
| 95 |
+
elif isinstance(node, ast.Call):
|
| 96 |
+
name = _ast_name(node.func)
|
| 97 |
+
if name:
|
| 98 |
+
calls.add(name)
|
| 99 |
+
return imports, calls
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _literal_value(node, constants=None):
|
| 103 |
+
constants = constants or {}
|
| 104 |
+
if isinstance(node, ast.Constant) and isinstance(
|
| 105 |
+
node.value, (str, int, float, bool, type(None))):
|
| 106 |
+
return node.value
|
| 107 |
+
if isinstance(node, ast.Name) and node.id in constants:
|
| 108 |
+
return constants[node.id]
|
| 109 |
+
if isinstance(node, (ast.Tuple, ast.List)):
|
| 110 |
+
values = [_literal_value(item, constants) for item in node.elts]
|
| 111 |
+
if all(value is not _UNRESOLVED for value in values):
|
| 112 |
+
return tuple(values) if isinstance(node, ast.Tuple) else values
|
| 113 |
+
return _UNRESOLVED
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
_UNRESOLVED = object()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _python_semantics(text):
|
| 120 |
+
tree = ast.parse(text)
|
| 121 |
+
_annotate_assignment_contexts(tree)
|
| 122 |
+
imports, calls = _python_inventory(text)
|
| 123 |
+
constants = {}
|
| 124 |
+
for node in tree.body:
|
| 125 |
+
name = None
|
| 126 |
+
value_node = None
|
| 127 |
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 128 |
+
isinstance(node.targets[0], ast.Name)):
|
| 129 |
+
name, value_node = node.targets[0].id, node.value
|
| 130 |
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
| 131 |
+
name, value_node = node.target.id, node.value
|
| 132 |
+
if name and value_node is not None:
|
| 133 |
+
value = _literal_value(value_node, constants)
|
| 134 |
+
if value is not _UNRESOLVED:
|
| 135 |
+
constants[name] = value
|
| 136 |
+
elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 137 |
+
isinstance(node.targets[0], (ast.Tuple, ast.List)) and
|
| 138 |
+
isinstance(node.value, (ast.Tuple, ast.List)) and
|
| 139 |
+
len(node.targets[0].elts) == len(node.value.elts)):
|
| 140 |
+
# Treat ordinary constant unpacking as semantically equivalent to
|
| 141 |
+
# separate assignments. Generated implementation files commonly
|
| 142 |
+
# use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
|
| 143 |
+
# test formatting rather than the required repository values.
|
| 144 |
+
for target, value_node in zip(node.targets[0].elts, node.value.elts):
|
| 145 |
+
if not isinstance(target, ast.Name):
|
| 146 |
+
continue
|
| 147 |
+
value = _literal_value(value_node, constants)
|
| 148 |
+
if value is not _UNRESOLVED:
|
| 149 |
+
constants[target.id] = value
|
| 150 |
+
call_nodes = []
|
| 151 |
+
for node in ast.walk(tree):
|
| 152 |
+
if isinstance(node, ast.Call):
|
| 153 |
+
call_nodes.append((_ast_name(node.func), node))
|
| 154 |
+
return imports, calls, constants, call_nodes
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _python_resolved_call_nodes(text):
|
| 158 |
+
"""Resolve call targets through imports and simple constructor bindings.
|
| 159 |
+
|
| 160 |
+
The evaluator intentionally supports a small static subset: imports,
|
| 161 |
+
local definitions, direct aliases, and names assigned from calls. That is
|
| 162 |
+
enough to recognize semantic equivalents such as ``import datetime`` vs
|
| 163 |
+
``from datetime import timedelta as td`` and instance-variable renames,
|
| 164 |
+
without pretending to perform general Python type inference.
|
| 165 |
+
"""
|
| 166 |
+
tree = ast.parse(text)
|
| 167 |
+
_annotate_assignment_contexts(tree)
|
| 168 |
+
bindings = {}
|
| 169 |
+
nodes = sorted(ast.walk(tree), key=lambda node: (
|
| 170 |
+
int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
|
| 171 |
+
|
| 172 |
+
def resolve(node):
|
| 173 |
+
if isinstance(node, ast.Name):
|
| 174 |
+
return bindings.get(node.id, node.id)
|
| 175 |
+
if isinstance(node, ast.Attribute):
|
| 176 |
+
parent = resolve(node.value)
|
| 177 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 178 |
+
return ""
|
| 179 |
+
|
| 180 |
+
# A few fixed-point passes cover aliases declared after an imported name
|
| 181 |
+
# and ordinary ``client = Client()`` instance construction.
|
| 182 |
+
for _ in range(4):
|
| 183 |
+
changed = False
|
| 184 |
+
for node in nodes:
|
| 185 |
+
updates = {}
|
| 186 |
+
if isinstance(node, ast.Import):
|
| 187 |
+
for alias in node.names:
|
| 188 |
+
local = alias.asname or alias.name.split(".")[0]
|
| 189 |
+
updates[local] = alias.name if alias.asname else local
|
| 190 |
+
elif isinstance(node, ast.ImportFrom):
|
| 191 |
+
module = node.module or ""
|
| 192 |
+
for alias in node.names:
|
| 193 |
+
if alias.name == "*":
|
| 194 |
+
continue
|
| 195 |
+
updates[alias.asname or alias.name] = \
|
| 196 |
+
f"{module}.{alias.name}".strip(".")
|
| 197 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 198 |
+
ast.ClassDef)):
|
| 199 |
+
updates[node.name] = "__local__." + node.name
|
| 200 |
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
| 201 |
+
targets = (node.targets if isinstance(node, ast.Assign)
|
| 202 |
+
else [node.target])
|
| 203 |
+
value = node.value
|
| 204 |
+
if isinstance(value, ast.Call):
|
| 205 |
+
provenance = resolve(value.func)
|
| 206 |
+
elif isinstance(value, (ast.Name, ast.Attribute)):
|
| 207 |
+
provenance = resolve(value)
|
| 208 |
+
else:
|
| 209 |
+
provenance = ""
|
| 210 |
+
if provenance:
|
| 211 |
+
for target in targets:
|
| 212 |
+
if isinstance(target, ast.Name):
|
| 213 |
+
updates[target.id] = provenance
|
| 214 |
+
for name, value in updates.items():
|
| 215 |
+
if bindings.get(name) != value:
|
| 216 |
+
bindings[name] = value
|
| 217 |
+
changed = True
|
| 218 |
+
if not changed:
|
| 219 |
+
break
|
| 220 |
+
return [(_ast_name(node.func), resolve(node.func), node)
|
| 221 |
+
for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _call_name_matches(observed, expected):
|
| 225 |
+
return observed == expected or observed.endswith("." + expected)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _objective_call_targets(kind, check, resolved_calls, constants):
|
| 229 |
+
"""Return canonical targets satisfying one already-validated call check."""
|
| 230 |
+
function = str(check.get("function") or check.get("value") or "")
|
| 231 |
+
targets = set()
|
| 232 |
+
for name, target, node in resolved_calls:
|
| 233 |
+
if not _call_name_matches(name, function):
|
| 234 |
+
continue
|
| 235 |
+
if kind == "python_call_literal" and not _node_contains_literal(
|
| 236 |
+
node, check.get("value"), constants):
|
| 237 |
+
continue
|
| 238 |
+
if kind == "python_call_keyword_literal" and not _call_keyword_matches(
|
| 239 |
+
node, str(check.get("keyword") or ""), check.get("value"),
|
| 240 |
+
constants):
|
| 241 |
+
continue
|
| 242 |
+
if kind == "python_call_signature" and not _call_signature_matches(
|
| 243 |
+
node, check.get("arguments") or [],
|
| 244 |
+
check.get("keywords") or {}, constants,
|
| 245 |
+
check.get("argument_expressions") or [],
|
| 246 |
+
check.get("keyword_expressions") or {},
|
| 247 |
+
check.get("assignment")):
|
| 248 |
+
continue
|
| 249 |
+
if target:
|
| 250 |
+
targets.add(target)
|
| 251 |
+
return targets
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def python_unbound_call_roots(text):
|
| 255 |
+
"""Return call-root names that have no static binding in the module.
|
| 256 |
+
|
| 257 |
+
Objective call checks must not accept a syntactically valid file that will
|
| 258 |
+
immediately raise ``NameError``. This deliberately proves only the
|
| 259 |
+
conservative prerequisite that a root is imported, assigned, declared,
|
| 260 |
+
passed as an argument, or provided by Python builtins; it does not claim to
|
| 261 |
+
execute or type-check the program.
|
| 262 |
+
"""
|
| 263 |
+
tree = ast.parse(text)
|
| 264 |
+
bound = set(dir(builtins))
|
| 265 |
+
for node in ast.walk(tree):
|
| 266 |
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
| 267 |
+
bound.add(node.id)
|
| 268 |
+
elif isinstance(node, ast.arg):
|
| 269 |
+
bound.add(node.arg)
|
| 270 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 271 |
+
ast.ClassDef)):
|
| 272 |
+
bound.add(node.name)
|
| 273 |
+
elif isinstance(node, ast.Import):
|
| 274 |
+
for alias in node.names:
|
| 275 |
+
bound.add(alias.asname or alias.name.split(".")[0])
|
| 276 |
+
elif isinstance(node, ast.ImportFrom):
|
| 277 |
+
for alias in node.names:
|
| 278 |
+
bound.add(alias.asname or alias.name)
|
| 279 |
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
| 280 |
+
bound.add(node.name)
|
| 281 |
+
unbound = set()
|
| 282 |
+
for node in ast.walk(tree):
|
| 283 |
+
if not isinstance(node, ast.Call):
|
| 284 |
+
continue
|
| 285 |
+
root = node.func
|
| 286 |
+
while isinstance(root, ast.Attribute):
|
| 287 |
+
root = root.value
|
| 288 |
+
if isinstance(root, ast.Name) and root.id not in bound:
|
| 289 |
+
unbound.add(root.id)
|
| 290 |
+
return sorted(unbound)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _node_contains_literal(node, expected, constants):
|
| 294 |
+
for child in ast.walk(node):
|
| 295 |
+
value = _literal_value(child, constants)
|
| 296 |
+
if value is _UNRESOLVED:
|
| 297 |
+
continue
|
| 298 |
+
if value == expected:
|
| 299 |
+
return True
|
| 300 |
+
if isinstance(value, (list, tuple)) and expected in value:
|
| 301 |
+
return True
|
| 302 |
+
return False
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _call_keyword_matches(node, keyword, expected, constants):
|
| 306 |
+
"""Return whether a direct call keyword resolves to the expected scalar."""
|
| 307 |
+
return any(
|
| 308 |
+
item.arg == keyword and _literal_value(item.value, constants) == expected
|
| 309 |
+
for item in getattr(node, "keywords", [])
|
| 310 |
+
if item.arg is not None)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _portable_literal(value):
|
| 314 |
+
if isinstance(value, tuple):
|
| 315 |
+
return [_portable_literal(item) for item in value]
|
| 316 |
+
if isinstance(value, list):
|
| 317 |
+
return [_portable_literal(item) for item in value]
|
| 318 |
+
return value
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _expression_text(node):
|
| 322 |
+
"""Return a formatting-independent, non-executed Python expression."""
|
| 323 |
+
return ast.unparse(node).strip()
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _expression_fingerprint(value):
|
| 327 |
+
if not isinstance(value, str) or not value.strip() or len(value) > 500:
|
| 328 |
+
return None
|
| 329 |
+
try:
|
| 330 |
+
tree = ast.parse(value, mode="eval")
|
| 331 |
+
except SyntaxError:
|
| 332 |
+
return None
|
| 333 |
+
return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _expression_matches(node, expected):
|
| 337 |
+
fingerprint = _expression_fingerprint(expected)
|
| 338 |
+
return bool(fingerprint and ast.dump(
|
| 339 |
+
node, annotate_fields=True, include_attributes=False) == fingerprint)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _annotate_assignment_contexts(tree):
|
| 343 |
+
"""Attach one conservative simple-assignment context to nested calls."""
|
| 344 |
+
for statement in ast.walk(tree):
|
| 345 |
+
target, value = None, None
|
| 346 |
+
if (isinstance(statement, ast.Assign) and
|
| 347 |
+
len(statement.targets) == 1 and
|
| 348 |
+
isinstance(statement.targets[0], ast.Name)):
|
| 349 |
+
target, value = statement.targets[0].id, statement.value
|
| 350 |
+
elif (isinstance(statement, ast.AnnAssign) and
|
| 351 |
+
isinstance(statement.target, ast.Name) and
|
| 352 |
+
statement.value is not None):
|
| 353 |
+
target, value = statement.target.id, statement.value
|
| 354 |
+
if not target or value is None:
|
| 355 |
+
continue
|
| 356 |
+
context = {"target": target, "expression": _expression_text(value)}
|
| 357 |
+
for child in ast.walk(value):
|
| 358 |
+
if isinstance(child, ast.Call):
|
| 359 |
+
setattr(child, "_mybench_assignment", context)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _call_signature(node, constants):
|
| 363 |
+
arguments = []
|
| 364 |
+
argument_expressions = []
|
| 365 |
+
for index, argument in enumerate(getattr(node, "args", [])):
|
| 366 |
+
value = _literal_value(argument, constants)
|
| 367 |
+
if value is not _UNRESOLVED:
|
| 368 |
+
arguments.append({"index": index,
|
| 369 |
+
"value": _portable_literal(value)})
|
| 370 |
+
else:
|
| 371 |
+
argument_expressions.append({
|
| 372 |
+
"index": index, "expression": _expression_text(argument)})
|
| 373 |
+
keywords = {}
|
| 374 |
+
keyword_expressions = {}
|
| 375 |
+
for keyword in getattr(node, "keywords", []):
|
| 376 |
+
if keyword.arg is None:
|
| 377 |
+
continue
|
| 378 |
+
value = _literal_value(keyword.value, constants)
|
| 379 |
+
if value is not _UNRESOLVED:
|
| 380 |
+
keywords[keyword.arg] = _portable_literal(value)
|
| 381 |
+
else:
|
| 382 |
+
keyword_expressions[keyword.arg] = _expression_text(keyword.value)
|
| 383 |
+
signature = {"arguments": arguments, "keywords": keywords,
|
| 384 |
+
"argument_expressions": argument_expressions,
|
| 385 |
+
"keyword_expressions": keyword_expressions}
|
| 386 |
+
assignment = getattr(node, "_mybench_assignment", None)
|
| 387 |
+
if isinstance(assignment, dict):
|
| 388 |
+
signature["assignment"] = dict(assignment)
|
| 389 |
+
return signature
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _call_signature_matches(node, arguments, keywords, constants,
|
| 393 |
+
argument_expressions=None,
|
| 394 |
+
keyword_expressions=None, assignment=None):
|
| 395 |
+
for expected in arguments or []:
|
| 396 |
+
index = expected.get("index")
|
| 397 |
+
if (not isinstance(index, int) or index < 0 or
|
| 398 |
+
index >= len(getattr(node, "args", []))):
|
| 399 |
+
return False
|
| 400 |
+
actual = _literal_value(node.args[index], constants)
|
| 401 |
+
if (actual is _UNRESOLVED or
|
| 402 |
+
_canonical(_portable_literal(actual)) !=
|
| 403 |
+
_canonical(expected.get("value"))):
|
| 404 |
+
return False
|
| 405 |
+
for keyword, expected in (keywords or {}).items():
|
| 406 |
+
if not _call_keyword_matches(node, keyword, expected, constants):
|
| 407 |
+
return False
|
| 408 |
+
for expected in argument_expressions or []:
|
| 409 |
+
index = expected.get("index")
|
| 410 |
+
if (not isinstance(index, int) or index < 0 or
|
| 411 |
+
index >= len(getattr(node, "args", [])) or
|
| 412 |
+
not _expression_matches(
|
| 413 |
+
node.args[index], expected.get("expression"))):
|
| 414 |
+
return False
|
| 415 |
+
node_keywords = {item.arg: item.value for item in
|
| 416 |
+
getattr(node, "keywords", []) if item.arg is not None}
|
| 417 |
+
for keyword, expected in (keyword_expressions or {}).items():
|
| 418 |
+
if (keyword not in node_keywords or
|
| 419 |
+
not _expression_matches(node_keywords[keyword], expected)):
|
| 420 |
+
return False
|
| 421 |
+
if assignment:
|
| 422 |
+
actual = getattr(node, "_mybench_assignment", None)
|
| 423 |
+
if (not isinstance(actual, dict) or
|
| 424 |
+
actual.get("target") != assignment.get("target") or
|
| 425 |
+
_expression_fingerprint(actual.get("expression")) !=
|
| 426 |
+
_expression_fingerprint(assignment.get("expression"))):
|
| 427 |
+
return False
|
| 428 |
+
return bool(arguments or keywords or argument_expressions or
|
| 429 |
+
keyword_expressions or assignment)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def python_call_literal_signatures(text, function, expected, keyword=None):
|
| 433 |
+
"""Return full literal signatures for matching reference call sites."""
|
| 434 |
+
_, _, constants, call_nodes = _python_semantics(text)
|
| 435 |
+
out = []
|
| 436 |
+
for name, node in call_nodes:
|
| 437 |
+
if not (name == function or name.endswith("." + function)):
|
| 438 |
+
continue
|
| 439 |
+
matches = (_call_keyword_matches(node, keyword, expected, constants)
|
| 440 |
+
if keyword else
|
| 441 |
+
_node_contains_literal(node, expected, constants))
|
| 442 |
+
if matches:
|
| 443 |
+
out.append(_call_signature(node, constants))
|
| 444 |
+
return out
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def python_signature_expression_coverage_issues(evaluator, requirements=None):
|
| 448 |
+
"""Detect anchored call expressions omitted by a static verifier.
|
| 449 |
+
|
| 450 |
+
Literal-only call checks used to silently discard non-literal positional
|
| 451 |
+
and keyword expressions from the same package-owned call. That allowed a
|
| 452 |
+
candidate to retain one easy literal while replacing the actual callback,
|
| 453 |
+
input binding, or argument tuple. Only expressions present in the
|
| 454 |
+
selected requirement text are required here; unrelated reference-file
|
| 455 |
+
context remains outside the objective contract.
|
| 456 |
+
"""
|
| 457 |
+
if not isinstance(evaluator, dict) or evaluator.get("type") != \
|
| 458 |
+
WORKSPACE_EVALUATOR:
|
| 459 |
+
return []
|
| 460 |
+
reference_files = {
|
| 461 |
+
str(item.get("path") or ""): str(item.get("content") or "")
|
| 462 |
+
for item in evaluator.get("reference_files") or []
|
| 463 |
+
if isinstance(item, dict)}
|
| 464 |
+
requirement_texts = [
|
| 465 |
+
re.sub(r"\s+", "", str(item.get("requirement") or ""))
|
| 466 |
+
for item in requirements or [] if isinstance(item, dict)]
|
| 467 |
+
issues = []
|
| 468 |
+
for check in evaluator.get("checks") or []:
|
| 469 |
+
if (not isinstance(check, dict) or
|
| 470 |
+
check.get("type") != "python_call_signature"):
|
| 471 |
+
continue
|
| 472 |
+
function = str(check.get("function") or "")
|
| 473 |
+
source = reference_files.get(str(check.get("path") or ""), "")
|
| 474 |
+
if not function or not source:
|
| 475 |
+
continue
|
| 476 |
+
try:
|
| 477 |
+
_, _, constants, call_nodes = _python_semantics(source)
|
| 478 |
+
except SyntaxError:
|
| 479 |
+
issues.append("Python signature reference content is invalid")
|
| 480 |
+
continue
|
| 481 |
+
matches = [node for name, node in call_nodes
|
| 482 |
+
if _call_name_matches(name, function) and
|
| 483 |
+
_call_signature_matches(
|
| 484 |
+
node, check.get("arguments") or [],
|
| 485 |
+
check.get("keywords") or {}, constants,
|
| 486 |
+
check.get("argument_expressions") or [],
|
| 487 |
+
check.get("keyword_expressions") or {},
|
| 488 |
+
check.get("assignment"))]
|
| 489 |
+
if len(matches) != 1:
|
| 490 |
+
issues.append(
|
| 491 |
+
"Python call signature does not identify one reference call")
|
| 492 |
+
continue
|
| 493 |
+
reference_signature = _call_signature(matches[0], constants)
|
| 494 |
+
function_tokens = {re.sub(r"\s+", "", function),
|
| 495 |
+
re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
|
| 496 |
+
|
| 497 |
+
def positional_is_anchored(expression):
|
| 498 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 499 |
+
return any(compact and compact in text and any(
|
| 500 |
+
token and token in text for token in function_tokens)
|
| 501 |
+
for text in requirement_texts)
|
| 502 |
+
|
| 503 |
+
def keyword_is_anchored(name, expression):
|
| 504 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 505 |
+
needle = f"{name}={compact}"
|
| 506 |
+
return any(compact and needle in text and any(
|
| 507 |
+
token and token in text for token in function_tokens)
|
| 508 |
+
for text in requirement_texts)
|
| 509 |
+
|
| 510 |
+
expected_arguments = {
|
| 511 |
+
item["index"]: item.get("expression")
|
| 512 |
+
for item in reference_signature.get("argument_expressions") or []
|
| 513 |
+
if positional_is_anchored(item.get("expression"))}
|
| 514 |
+
expected_keywords = {
|
| 515 |
+
name: expression for name, expression in
|
| 516 |
+
(reference_signature.get("keyword_expressions") or {}).items()
|
| 517 |
+
if keyword_is_anchored(name, expression)}
|
| 518 |
+
actual_arguments = {
|
| 519 |
+
item.get("index"): item.get("expression")
|
| 520 |
+
for item in check.get("argument_expressions") or []
|
| 521 |
+
if isinstance(item, dict)}
|
| 522 |
+
actual_keywords = check.get("keyword_expressions") or {}
|
| 523 |
+
expected_assignment = reference_signature.get("assignment")
|
| 524 |
+
if expected_assignment:
|
| 525 |
+
compact_assignment = re.sub(
|
| 526 |
+
r"\s+", "", f"{expected_assignment.get('target')}="
|
| 527 |
+
f"{expected_assignment.get('expression')}")
|
| 528 |
+
assignment_is_anchored = any(
|
| 529 |
+
compact_assignment and compact_assignment in text and any(
|
| 530 |
+
token and token in text for token in function_tokens)
|
| 531 |
+
for text in requirement_texts)
|
| 532 |
+
else:
|
| 533 |
+
assignment_is_anchored = False
|
| 534 |
+
actual_assignment = check.get("assignment")
|
| 535 |
+
missing_argument = any(
|
| 536 |
+
index not in actual_arguments or
|
| 537 |
+
_expression_fingerprint(actual_arguments[index]) !=
|
| 538 |
+
_expression_fingerprint(expression)
|
| 539 |
+
for index, expression in expected_arguments.items())
|
| 540 |
+
missing_keyword = any(
|
| 541 |
+
name not in actual_keywords or
|
| 542 |
+
_expression_fingerprint(actual_keywords[name]) !=
|
| 543 |
+
_expression_fingerprint(expression)
|
| 544 |
+
for name, expression in expected_keywords.items())
|
| 545 |
+
missing_assignment = bool(
|
| 546 |
+
assignment_is_anchored and (
|
| 547 |
+
not isinstance(actual_assignment, dict) or
|
| 548 |
+
actual_assignment.get("target") !=
|
| 549 |
+
expected_assignment.get("target") or
|
| 550 |
+
_expression_fingerprint(actual_assignment.get("expression")) !=
|
| 551 |
+
_expression_fingerprint(
|
| 552 |
+
expected_assignment.get("expression"))))
|
| 553 |
+
if missing_argument or missing_keyword or missing_assignment:
|
| 554 |
+
issues.append(
|
| 555 |
+
"Python call signature omits an anchored expression or assignment")
|
| 556 |
+
return issues
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _shell_lines(text):
|
| 560 |
+
"""Return executable lines with conservative local scalar substitution.
|
| 561 |
+
|
| 562 |
+
Shell authors routinely name a fixed argument before using it (for example
|
| 563 |
+
``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
|
| 564 |
+
assignments; never evaluate shell expressions, commands, or defaults.
|
| 565 |
+
"""
|
| 566 |
+
logical, pending = [], ""
|
| 567 |
+
for raw in str(text or "").splitlines():
|
| 568 |
+
line = " ".join(raw.strip().split())
|
| 569 |
+
if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
|
| 570 |
+
continue
|
| 571 |
+
pending = (pending + " " + line).strip() if pending else line
|
| 572 |
+
if pending.endswith("\\"):
|
| 573 |
+
pending = pending[:-1].rstrip()
|
| 574 |
+
continue
|
| 575 |
+
logical.append(pending)
|
| 576 |
+
pending = ""
|
| 577 |
+
if pending:
|
| 578 |
+
logical.append(pending)
|
| 579 |
+
|
| 580 |
+
constants, out = {}, []
|
| 581 |
+
assignment = re.compile(
|
| 582 |
+
r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
|
| 583 |
+
r"([A-Za-z0-9_./:+-]+))$")
|
| 584 |
+
variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
|
| 585 |
+
for line in logical:
|
| 586 |
+
match = assignment.fullmatch(line)
|
| 587 |
+
if match:
|
| 588 |
+
constants[match.group(1)] = next(
|
| 589 |
+
value for value in match.groups()[1:] if value is not None)
|
| 590 |
+
out.append(line)
|
| 591 |
+
continue
|
| 592 |
+
|
| 593 |
+
def replace(match):
|
| 594 |
+
name = match.group(1) or match.group(2)
|
| 595 |
+
return constants.get(name, match.group(0))
|
| 596 |
+
|
| 597 |
+
out.append(variable.sub(replace, line))
|
| 598 |
+
return out
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def _shell_command_matches(expected, actual):
|
| 602 |
+
"""Accept the frozen invocation plus documented optional arguments/path prefixes."""
|
| 603 |
+
try:
|
| 604 |
+
wanted = shlex.split(str(expected))
|
| 605 |
+
found = shlex.split(str(actual))
|
| 606 |
+
except ValueError:
|
| 607 |
+
return False
|
| 608 |
+
def normalize_git_log_limit(tokens):
|
| 609 |
+
if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
|
| 610 |
+
return tokens
|
| 611 |
+
normalized, index = [], 0
|
| 612 |
+
while index < len(tokens):
|
| 613 |
+
token = tokens[index]
|
| 614 |
+
short = re.fullmatch(r"-(\d+)", token)
|
| 615 |
+
long = re.fullmatch(r"--max-count=(\d+)", token)
|
| 616 |
+
if short or long:
|
| 617 |
+
normalized.append("--max-count=" + (short or long).group(1))
|
| 618 |
+
elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
|
| 619 |
+
re.fullmatch(r"\d+", tokens[index + 1])):
|
| 620 |
+
normalized.append("--max-count=" + tokens[index + 1])
|
| 621 |
+
index += 1
|
| 622 |
+
else:
|
| 623 |
+
normalized.append(token)
|
| 624 |
+
index += 1
|
| 625 |
+
return normalized
|
| 626 |
+
|
| 627 |
+
wanted = normalize_git_log_limit(wanted)
|
| 628 |
+
found = normalize_git_log_limit(found)
|
| 629 |
+
if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
|
| 630 |
+
return False
|
| 631 |
+
for index, token in enumerate(wanted[1:], 1):
|
| 632 |
+
observed = found[index]
|
| 633 |
+
if observed == token:
|
| 634 |
+
continue
|
| 635 |
+
# A solver may anchor a package-relative script at $REPO_ROOT while
|
| 636 |
+
# preserving the exact package path selected by the Skill.
|
| 637 |
+
if (index == 1 and "/" in token and
|
| 638 |
+
observed.rstrip("/").endswith(token.lstrip("./"))):
|
| 639 |
+
continue
|
| 640 |
+
return False
|
| 641 |
+
return True
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _shell_command_sequence_matches(expected, actual_lines):
|
| 645 |
+
"""Require every frozen command in order while allowing extra lines."""
|
| 646 |
+
cursor = 0
|
| 647 |
+
for command in expected:
|
| 648 |
+
for index in range(cursor, len(actual_lines)):
|
| 649 |
+
if _shell_command_matches(command, actual_lines[index]):
|
| 650 |
+
cursor = index + 1
|
| 651 |
+
break
|
| 652 |
+
else:
|
| 653 |
+
return False
|
| 654 |
+
return True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _shell_unconditional_lines(text):
|
| 658 |
+
"""Return conservative top-level command lines from a shell artifact.
|
| 659 |
+
|
| 660 |
+
Checked commands hidden in a conditional branch or an uncalled function do
|
| 661 |
+
not establish that the requested script performs them. This is not a full
|
| 662 |
+
shell parser: unsupported control flow simply makes nested lines
|
| 663 |
+
ineligible, which is appropriate for the small straight-line command
|
| 664 |
+
artifacts compiled by this evaluator.
|
| 665 |
+
"""
|
| 666 |
+
lines = _shell_lines(text)
|
| 667 |
+
depth = 0
|
| 668 |
+
out = []
|
| 669 |
+
opener = re.compile(
|
| 670 |
+
r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
|
| 671 |
+
r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
|
| 672 |
+
closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
|
| 673 |
+
for line in lines:
|
| 674 |
+
if closer.match(line):
|
| 675 |
+
depth = max(0, depth - 1)
|
| 676 |
+
continue
|
| 677 |
+
if depth == 0 and not opener.match(line):
|
| 678 |
+
out.append(line)
|
| 679 |
+
if opener.match(line):
|
| 680 |
+
depth += 1
|
| 681 |
+
return out
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _shell_is_straight_line(text):
|
| 685 |
+
"""Return whether every executable logical line is top-level.
|
| 686 |
+
|
| 687 |
+
This deliberately reuses the conservative control-flow recognizer used by
|
| 688 |
+
unconditional command checks. Any recognized conditional, loop, case, or
|
| 689 |
+
function makes the whole-script straight-line contract fail closed.
|
| 690 |
+
"""
|
| 691 |
+
lines = _shell_lines(text)
|
| 692 |
+
return lines == _shell_unconditional_lines(text)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def compile_workspace_evaluator(deliverables):
|
| 696 |
+
"""Compile trusted checks from validated deliverable specifications."""
|
| 697 |
+
if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
|
| 698 |
+
raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
|
| 699 |
+
reference_files, checks, paths = [], [], set()
|
| 700 |
+
for index, raw in enumerate(deliverables, 1):
|
| 701 |
+
if not isinstance(raw, dict):
|
| 702 |
+
raise ObjectiveEvaluatorError("deliverable is not an object")
|
| 703 |
+
path = safe_relative_path(raw.get("path"))
|
| 704 |
+
if path in paths:
|
| 705 |
+
raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
|
| 706 |
+
paths.add(path)
|
| 707 |
+
fmt = str(raw.get("format") or "").strip().casefold()
|
| 708 |
+
if fmt not in ARTIFACT_FORMATS:
|
| 709 |
+
raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
|
| 710 |
+
content = _file_content({**raw, "format": fmt})
|
| 711 |
+
if len(content.encode("utf-8")) > 200_000:
|
| 712 |
+
raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
|
| 713 |
+
reference_files.append({"path": path, "format": fmt, "content": content})
|
| 714 |
+
checks.append({"id": f"file_{index:03d}", "type": "file_exists",
|
| 715 |
+
"path": path})
|
| 716 |
+
if fmt == "json":
|
| 717 |
+
checks.append({"id": f"json_{index:03d}", "type": "json_exact",
|
| 718 |
+
"path": path, "expected": _json_value(raw.get("content"))})
|
| 719 |
+
elif fmt == "toml":
|
| 720 |
+
try:
|
| 721 |
+
expected = tomllib.loads(content)
|
| 722 |
+
except (tomllib.TOMLDecodeError, ValueError) as exc:
|
| 723 |
+
raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
|
| 724 |
+
checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
|
| 725 |
+
"path": path, "expected": expected})
|
| 726 |
+
elif fmt == "python":
|
| 727 |
+
try:
|
| 728 |
+
_, _, constants, call_nodes = _python_semantics(content)
|
| 729 |
+
resolved_calls = _python_resolved_call_nodes(content)
|
| 730 |
+
except SyntaxError as exc:
|
| 731 |
+
raise ObjectiveEvaluatorError("reference Python is invalid") from exc
|
| 732 |
+
checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
|
| 733 |
+
"path": path})
|
| 734 |
+
checks.append({"id": f"python_{index:03d}_bindings",
|
| 735 |
+
"type": "python_bound_calls", "path": path})
|
| 736 |
+
raw_checks = raw.get("checks") or []
|
| 737 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 738 |
+
raise ObjectiveEvaluatorError(
|
| 739 |
+
"Python deliverable requires 1-12 objective import/call checks")
|
| 740 |
+
for check_index, check in enumerate(raw_checks, 1):
|
| 741 |
+
if not isinstance(check, dict):
|
| 742 |
+
raise ObjectiveEvaluatorError("Python check is not an object")
|
| 743 |
+
kind = str(check.get("type") or "").strip().casefold()
|
| 744 |
+
if kind in {"python_import", "python_call"}:
|
| 745 |
+
value = str(check.get("value") or "").strip()
|
| 746 |
+
if not _DOTTED.fullmatch(value):
|
| 747 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 748 |
+
compiled = {"type": kind, "path": path, "value": value}
|
| 749 |
+
elif kind == "python_constant":
|
| 750 |
+
name = str(check.get("name") or "").strip()
|
| 751 |
+
value = check.get("value")
|
| 752 |
+
if (not _DOTTED.fullmatch(name) or "." in name or
|
| 753 |
+
isinstance(value, (dict, list)) or value is None or
|
| 754 |
+
constants.get(name, _UNRESOLVED) != value):
|
| 755 |
+
raise ObjectiveEvaluatorError(
|
| 756 |
+
"Python constant check is invalid or fails reference content")
|
| 757 |
+
compiled = {"type": kind, "path": path, "name": name,
|
| 758 |
+
"value": value}
|
| 759 |
+
elif kind == "python_call_literal":
|
| 760 |
+
function = str(check.get("function") or "").strip()
|
| 761 |
+
value = check.get("value")
|
| 762 |
+
if (not _DOTTED.fullmatch(function) or
|
| 763 |
+
isinstance(value, (dict, list)) or value is None or
|
| 764 |
+
not any(
|
| 765 |
+
(name == function or name.endswith("." + function)) and
|
| 766 |
+
_node_contains_literal(node, value, constants)
|
| 767 |
+
for name, node in call_nodes)):
|
| 768 |
+
raise ObjectiveEvaluatorError(
|
| 769 |
+
"Python call-literal check is invalid or fails reference content")
|
| 770 |
+
compiled = {"type": kind, "path": path,
|
| 771 |
+
"function": function, "value": value}
|
| 772 |
+
elif kind == "python_call_keyword_literal":
|
| 773 |
+
function = str(check.get("function") or "").strip()
|
| 774 |
+
keyword = str(check.get("keyword") or "").strip()
|
| 775 |
+
value = check.get("value")
|
| 776 |
+
if (not _DOTTED.fullmatch(function) or
|
| 777 |
+
not _DOTTED.fullmatch(keyword) or "." in keyword or
|
| 778 |
+
isinstance(value, (dict, list)) or value is None or
|
| 779 |
+
not any(
|
| 780 |
+
(name == function or name.endswith("." + function)) and
|
| 781 |
+
_call_keyword_matches(node, keyword, value, constants)
|
| 782 |
+
for name, node in call_nodes)):
|
| 783 |
+
raise ObjectiveEvaluatorError(
|
| 784 |
+
"Python call-keyword check is invalid or fails reference content")
|
| 785 |
+
compiled = {"type": kind, "path": path,
|
| 786 |
+
"function": function, "keyword": keyword,
|
| 787 |
+
"value": value}
|
| 788 |
+
elif kind == "python_call_signature":
|
| 789 |
+
function = str(check.get("function") or "").strip()
|
| 790 |
+
arguments = check.get("arguments") or []
|
| 791 |
+
keywords = check.get("keywords") or {}
|
| 792 |
+
argument_expressions = check.get(
|
| 793 |
+
"argument_expressions") or []
|
| 794 |
+
keyword_expressions = check.get(
|
| 795 |
+
"keyword_expressions") or {}
|
| 796 |
+
assignment = check.get("assignment")
|
| 797 |
+
if (not _DOTTED.fullmatch(function) or
|
| 798 |
+
not isinstance(arguments, list) or
|
| 799 |
+
not isinstance(keywords, dict) or
|
| 800 |
+
not isinstance(argument_expressions, list) or
|
| 801 |
+
not isinstance(keyword_expressions, dict) or
|
| 802 |
+
not (arguments or keywords or
|
| 803 |
+
argument_expressions or keyword_expressions or
|
| 804 |
+
assignment) or
|
| 805 |
+
any(not isinstance(item, dict) or
|
| 806 |
+
not isinstance(item.get("index"), int) or
|
| 807 |
+
item.get("index") < 0 or
|
| 808 |
+
isinstance(item.get("value"), dict)
|
| 809 |
+
for item in arguments) or
|
| 810 |
+
len({item["index"] for item in arguments}) !=
|
| 811 |
+
len(arguments) or
|
| 812 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 813 |
+
"." in str(name) or isinstance(value, dict)
|
| 814 |
+
for name, value in keywords.items()) or
|
| 815 |
+
any(not isinstance(item, dict) or
|
| 816 |
+
not isinstance(item.get("index"), int) or
|
| 817 |
+
item.get("index") < 0 or
|
| 818 |
+
not _expression_fingerprint(
|
| 819 |
+
item.get("expression"))
|
| 820 |
+
for item in argument_expressions) or
|
| 821 |
+
len({item["index"] for item in
|
| 822 |
+
argument_expressions}) !=
|
| 823 |
+
len(argument_expressions) or
|
| 824 |
+
({item["index"] for item in arguments} &
|
| 825 |
+
{item["index"] for item in
|
| 826 |
+
argument_expressions}) or
|
| 827 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 828 |
+
"." in str(name) or
|
| 829 |
+
not _expression_fingerprint(value)
|
| 830 |
+
for name, value in
|
| 831 |
+
keyword_expressions.items()) or
|
| 832 |
+
(set(keywords) & set(keyword_expressions)) or
|
| 833 |
+
(assignment is not None and (
|
| 834 |
+
not isinstance(assignment, dict) or
|
| 835 |
+
not _DOTTED.fullmatch(str(
|
| 836 |
+
assignment.get("target") or "")) or
|
| 837 |
+
"." in str(assignment.get("target") or "") or
|
| 838 |
+
not _expression_fingerprint(
|
| 839 |
+
assignment.get("expression")))) or
|
| 840 |
+
not any(
|
| 841 |
+
(name == function or
|
| 842 |
+
name.endswith("." + function)) and
|
| 843 |
+
_call_signature_matches(
|
| 844 |
+
node, arguments, keywords, constants,
|
| 845 |
+
argument_expressions,
|
| 846 |
+
keyword_expressions, assignment)
|
| 847 |
+
for name, node in call_nodes)):
|
| 848 |
+
raise ObjectiveEvaluatorError(
|
| 849 |
+
"Python call-signature check is invalid or fails reference content")
|
| 850 |
+
compiled = {"type": kind, "path": path,
|
| 851 |
+
"function": function,
|
| 852 |
+
"arguments": arguments,
|
| 853 |
+
"keywords": keywords,
|
| 854 |
+
"argument_expressions": argument_expressions,
|
| 855 |
+
"keyword_expressions": keyword_expressions,
|
| 856 |
+
"assignment": assignment}
|
| 857 |
+
else:
|
| 858 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 859 |
+
if kind in {"python_call", "python_call_literal",
|
| 860 |
+
"python_call_keyword_literal",
|
| 861 |
+
"python_call_signature"}:
|
| 862 |
+
targets = _objective_call_targets(
|
| 863 |
+
kind, compiled, resolved_calls, constants)
|
| 864 |
+
if len(targets) != 1:
|
| 865 |
+
raise ObjectiveEvaluatorError(
|
| 866 |
+
"Python call check has no unique canonical target")
|
| 867 |
+
compiled["target"] = next(iter(targets))
|
| 868 |
+
checks.append({"id": f"python_{index:03d}_{check_index:03d}",
|
| 869 |
+
**compiled})
|
| 870 |
+
else:
|
| 871 |
+
raw_checks = raw.get("checks") or []
|
| 872 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 873 |
+
raise ObjectiveEvaluatorError(
|
| 874 |
+
"shell deliverable requires 1-12 objective command checks")
|
| 875 |
+
checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
|
| 876 |
+
"path": path})
|
| 877 |
+
reference_sequence = _shell_lines(content)
|
| 878 |
+
reference_lines = set(reference_sequence)
|
| 879 |
+
unconditional_lines = _shell_unconditional_lines(content)
|
| 880 |
+
command_checks = []
|
| 881 |
+
for check in raw_checks:
|
| 882 |
+
value = " ".join(str(check.get("value") or "").strip().split())
|
| 883 |
+
if (not isinstance(check, dict) or
|
| 884 |
+
str(check.get("type") or "").strip().casefold() != "shell_command" or
|
| 885 |
+
not value or value not in reference_lines):
|
| 886 |
+
raise ObjectiveEvaluatorError("unsupported shell objective check")
|
| 887 |
+
command_checks.append({"type": "shell_command", "path": path,
|
| 888 |
+
"value": value})
|
| 889 |
+
if len({item["value"] for item in command_checks}) != len(command_checks):
|
| 890 |
+
raise ObjectiveEvaluatorError("shell objective checks must be unique")
|
| 891 |
+
command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
|
| 892 |
+
if not all(any(_shell_command_matches(
|
| 893 |
+
item["value"], line) for line in unconditional_lines)
|
| 894 |
+
for item in command_checks):
|
| 895 |
+
raise ObjectiveEvaluatorError(
|
| 896 |
+
"checked shell commands must be top-level and unconditional")
|
| 897 |
+
for check_index, check in enumerate(command_checks, 1):
|
| 898 |
+
checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
|
| 899 |
+
**check})
|
| 900 |
+
if len(command_checks) >= 2:
|
| 901 |
+
checks.append({
|
| 902 |
+
"id": f"shell_{index:03d}_sequence",
|
| 903 |
+
"type": "shell_command_sequence", "path": path,
|
| 904 |
+
"values": [item["value"] for item in command_checks],
|
| 905 |
+
})
|
| 906 |
+
checks.append({
|
| 907 |
+
"id": f"shell_{index:03d}_unconditional",
|
| 908 |
+
"type": "shell_unconditional_commands", "path": path,
|
| 909 |
+
"values": [item["value"] for item in command_checks],
|
| 910 |
+
})
|
| 911 |
+
# Preserve the reference's fail-fast behavior when accepting normal
|
| 912 |
+
# command-substitution/guard wrappers. Never turn `|| true` into a
|
| 913 |
+
# passing preflight simply because it contains the correct argv.
|
| 914 |
+
reference_calls = shell_invocations(content)
|
| 915 |
+
protected = [item["value"] for item in command_checks if any(
|
| 916 |
+
call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
|
| 917 |
+
for call in reference_calls)]
|
| 918 |
+
if protected:
|
| 919 |
+
checks.append({"id": f"shell_{index:03d}_failure_propagation",
|
| 920 |
+
"type": "shell_failure_propagation", "path": path,
|
| 921 |
+
"values": protected})
|
| 922 |
+
# Candidate workspaces may also contain root-level public inputs and
|
| 923 |
+
# installed Skill packages. Deliverables use dedicated top-level output
|
| 924 |
+
# directories, so enforce an exact file set inside those namespaces while
|
| 925 |
+
# leaving the read-only environment outside them untouched.
|
| 926 |
+
output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
|
| 927 |
+
if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
|
| 928 |
+
checks.insert(0, {
|
| 929 |
+
"id": "workspace_file_set", "type": "workspace_file_set",
|
| 930 |
+
"paths": sorted(paths), "roots": output_roots,
|
| 931 |
+
})
|
| 932 |
+
return {
|
| 933 |
+
"type": WORKSPACE_EVALUATOR,
|
| 934 |
+
"version": WORKSPACE_EVALUATOR_VERSION,
|
| 935 |
+
"output_mode": "workspace",
|
| 936 |
+
"reference_files": reference_files,
|
| 937 |
+
"checks": checks,
|
| 938 |
+
}
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def reference_bundle(evaluator):
|
| 942 |
+
if evaluator.get("type") != WORKSPACE_EVALUATOR:
|
| 943 |
+
raise ObjectiveEvaluatorError("not a workspace evaluator")
|
| 944 |
+
return {"files": [
|
| 945 |
+
{"path": item["path"], "content": item["content"]}
|
| 946 |
+
for item in evaluator.get("reference_files") or []
|
| 947 |
+
]}
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
def hidden_workspace_values(evaluator):
|
| 951 |
+
"""Return decisive package-owned values that public queries must not leak."""
|
| 952 |
+
values = []
|
| 953 |
+
for check in (evaluator or {}).get("checks") or []:
|
| 954 |
+
kind = check.get("type")
|
| 955 |
+
if kind in {"json_exact", "toml_exact"}:
|
| 956 |
+
values.extend(value for _, value in _flatten(check.get("expected")))
|
| 957 |
+
elif kind in {"python_import", "python_call", "shell_command",
|
| 958 |
+
"python_constant", "python_call_literal",
|
| 959 |
+
"python_call_keyword_literal"}:
|
| 960 |
+
values.append(check.get("value"))
|
| 961 |
+
elif kind == "python_call_signature":
|
| 962 |
+
values.extend(value for _, value in _flatten({
|
| 963 |
+
"arguments": [item.get("value") for item in
|
| 964 |
+
check.get("arguments") or []],
|
| 965 |
+
"keywords": check.get("keywords") or {},
|
| 966 |
+
"argument_expressions": [item.get("expression") for item in
|
| 967 |
+
check.get("argument_expressions") or []],
|
| 968 |
+
"keyword_expressions": check.get("keyword_expressions") or {},
|
| 969 |
+
"assignment": check.get("assignment"),
|
| 970 |
+
}))
|
| 971 |
+
return [value for value in values if value is not None]
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def _flatten(value, path=()):
|
| 975 |
+
if isinstance(value, dict):
|
| 976 |
+
out = []
|
| 977 |
+
for key, item in value.items():
|
| 978 |
+
out.extend(_flatten(item, path + (str(key),)))
|
| 979 |
+
return out
|
| 980 |
+
if isinstance(value, list):
|
| 981 |
+
out = []
|
| 982 |
+
for index, item in enumerate(value):
|
| 983 |
+
out.extend(_flatten(item, path + (index,)))
|
| 984 |
+
return out
|
| 985 |
+
return [(path, value)]
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def _bundle_rows(candidate):
|
| 989 |
+
if isinstance(candidate, str):
|
| 990 |
+
text = candidate.strip()
|
| 991 |
+
# Chat solvers often wrap the requested file bundle in a Markdown fence
|
| 992 |
+
# or append a duplicate FINAL_ANSWER object. Decode one complete JSON
|
| 993 |
+
# value at a time instead of requiring the entire response to be JSON;
|
| 994 |
+
# only an object carrying the explicit ``files`` transport field is
|
| 995 |
+
# eligible, so unrelated prose/objects are not silently accepted.
|
| 996 |
+
decoder = json.JSONDecoder()
|
| 997 |
+
candidate = None
|
| 998 |
+
for match in re.finditer(r"\{", text):
|
| 999 |
+
try:
|
| 1000 |
+
parsed, _ = decoder.raw_decode(text, match.start())
|
| 1001 |
+
except json.JSONDecodeError:
|
| 1002 |
+
continue
|
| 1003 |
+
if isinstance(parsed, dict) and "files" in parsed:
|
| 1004 |
+
candidate = parsed
|
| 1005 |
+
break
|
| 1006 |
+
if candidate is None:
|
| 1007 |
+
raise ObjectiveEvaluatorError(
|
| 1008 |
+
"workspace response contains no complete JSON file bundle")
|
| 1009 |
+
if not isinstance(candidate, dict):
|
| 1010 |
+
raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
|
| 1011 |
+
files = candidate.get("files")
|
| 1012 |
+
if isinstance(files, dict):
|
| 1013 |
+
files = [{"path": path, "content": content}
|
| 1014 |
+
for path, content in files.items()]
|
| 1015 |
+
if not isinstance(files, list) or len(files) > 30:
|
| 1016 |
+
raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
|
| 1017 |
+
return files
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def materialize_bundle(candidate, workspace):
|
| 1021 |
+
root = Path(workspace).resolve()
|
| 1022 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 1023 |
+
seen = set()
|
| 1024 |
+
for item in _bundle_rows(candidate):
|
| 1025 |
+
if not isinstance(item, dict):
|
| 1026 |
+
raise ObjectiveEvaluatorError("candidate file entry is not an object")
|
| 1027 |
+
relative = safe_relative_path(item.get("path"))
|
| 1028 |
+
if relative in seen:
|
| 1029 |
+
raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
|
| 1030 |
+
seen.add(relative)
|
| 1031 |
+
content = item.get("content")
|
| 1032 |
+
if isinstance(content, (dict, list)):
|
| 1033 |
+
content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 1034 |
+
if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
|
| 1035 |
+
raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
|
| 1036 |
+
target = (root / relative).resolve()
|
| 1037 |
+
if root not in target.parents:
|
| 1038 |
+
raise ObjectiveEvaluatorError("candidate file escapes workspace")
|
| 1039 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 1040 |
+
target.write_text(content, encoding="utf-8")
|
| 1041 |
+
return root
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
def evaluate_workspace(evaluator, workspace):
|
| 1045 |
+
if (not isinstance(evaluator, dict) or
|
| 1046 |
+
evaluator.get("type") != WORKSPACE_EVALUATOR or
|
| 1047 |
+
int(evaluator.get("version") or 0) not in
|
| 1048 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
|
| 1049 |
+
return False, {"error": "invalid workspace evaluator contract"}
|
| 1050 |
+
root = Path(workspace).resolve()
|
| 1051 |
+
results = []
|
| 1052 |
+
for check in evaluator.get("checks") or []:
|
| 1053 |
+
kind = check.get("type")
|
| 1054 |
+
relative, path = "", None
|
| 1055 |
+
if kind != "workspace_file_set":
|
| 1056 |
+
relative = safe_relative_path(check.get("path"))
|
| 1057 |
+
path = (root / relative).resolve()
|
| 1058 |
+
if root not in path.parents:
|
| 1059 |
+
return False, {"error": "evaluator path escapes workspace"}
|
| 1060 |
+
passed, detail = False, ""
|
| 1061 |
+
try:
|
| 1062 |
+
if kind == "workspace_file_set":
|
| 1063 |
+
expected = {safe_relative_path(value)
|
| 1064 |
+
for value in check.get("paths") or []}
|
| 1065 |
+
roots = [safe_relative_path(value)
|
| 1066 |
+
for value in check.get("roots") or []]
|
| 1067 |
+
actual = set()
|
| 1068 |
+
for relative_root in roots:
|
| 1069 |
+
scan_root = (root / relative_root).resolve()
|
| 1070 |
+
if root not in scan_root.parents:
|
| 1071 |
+
raise ObjectiveEvaluatorError(
|
| 1072 |
+
"workspace file-set root escapes workspace")
|
| 1073 |
+
if not scan_root.exists():
|
| 1074 |
+
continue
|
| 1075 |
+
for candidate in scan_root.rglob("*"):
|
| 1076 |
+
if candidate.is_file() or candidate.is_symlink():
|
| 1077 |
+
actual.add(candidate.relative_to(root).as_posix())
|
| 1078 |
+
passed = bool(expected) and actual == expected
|
| 1079 |
+
detail = ("exact deliverable file set" if passed else
|
| 1080 |
+
f"expected_files={sorted(expected)}; "
|
| 1081 |
+
f"actual_files={sorted(actual)}")
|
| 1082 |
+
elif kind == "file_exists":
|
| 1083 |
+
passed = path.is_file()
|
| 1084 |
+
detail = "present" if passed else "missing"
|
| 1085 |
+
elif kind == "json_exact":
|
| 1086 |
+
actual = json.loads(path.read_text(encoding="utf-8"))
|
| 1087 |
+
passed = _canonical(actual) == _canonical(check.get("expected"))
|
| 1088 |
+
detail = "semantic JSON match" if passed else "JSON value mismatch"
|
| 1089 |
+
elif kind == "toml_exact":
|
| 1090 |
+
actual = tomllib.loads(path.read_text(encoding="utf-8"))
|
| 1091 |
+
passed = _canonical(actual) == _canonical(check.get("expected"))
|
| 1092 |
+
detail = "semantic TOML match" if passed else "TOML value mismatch"
|
| 1093 |
+
elif kind in {"python_syntax", "python_bound_calls",
|
| 1094 |
+
"python_import", "python_call",
|
| 1095 |
+
"python_constant", "python_call_literal",
|
| 1096 |
+
"python_call_keyword_literal",
|
| 1097 |
+
"python_call_signature"}:
|
| 1098 |
+
source = path.read_text(encoding="utf-8")
|
| 1099 |
+
imports, calls, constants, call_nodes = _python_semantics(source)
|
| 1100 |
+
resolved_calls = _python_resolved_call_nodes(source)
|
| 1101 |
+
if kind == "python_syntax":
|
| 1102 |
+
passed, detail = True, "valid Python syntax"
|
| 1103 |
+
elif kind == "python_bound_calls":
|
| 1104 |
+
unbound = python_unbound_call_roots(
|
| 1105 |
+
path.read_text(encoding="utf-8"))
|
| 1106 |
+
passed = not unbound
|
| 1107 |
+
detail = ("all call roots are statically bound" if passed else
|
| 1108 |
+
"unbound call roots=" + repr(unbound))
|
| 1109 |
+
elif kind == "python_import":
|
| 1110 |
+
expected = str(check.get("value") or "")
|
| 1111 |
+
passed = expected in imports or any(
|
| 1112 |
+
value == expected or value.startswith(expected + ".")
|
| 1113 |
+
for value in imports)
|
| 1114 |
+
detail = f"imports={sorted(imports)}"
|
| 1115 |
+
elif kind == "python_call":
|
| 1116 |
+
expected = str(check.get("value") or "")
|
| 1117 |
+
target = str(check.get("target") or "")
|
| 1118 |
+
passed = (any(
|
| 1119 |
+
canonical == target
|
| 1120 |
+
for _, canonical, _ in resolved_calls)
|
| 1121 |
+
if target else expected in calls or any(
|
| 1122 |
+
value.endswith("." + expected)
|
| 1123 |
+
for value in calls))
|
| 1124 |
+
detail = f"calls={sorted(calls)}"
|
| 1125 |
+
elif kind == "python_constant":
|
| 1126 |
+
name, expected = str(check.get("name") or ""), check.get("value")
|
| 1127 |
+
actual = constants.get(name, _UNRESOLVED)
|
| 1128 |
+
passed = actual is not _UNRESOLVED and actual == expected
|
| 1129 |
+
detail = f"constant {name}={actual!r}"
|
| 1130 |
+
elif kind == "python_call_literal":
|
| 1131 |
+
function, expected = (str(check.get("function") or ""),
|
| 1132 |
+
check.get("value"))
|
| 1133 |
+
target = str(check.get("target") or "")
|
| 1134 |
+
source_calls = (resolved_calls if target else
|
| 1135 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1136 |
+
passed = any(
|
| 1137 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1138 |
+
(not target or canonical == target) and
|
| 1139 |
+
_node_contains_literal(node, expected, constants)
|
| 1140 |
+
for name, canonical, node in source_calls)
|
| 1141 |
+
detail = f"call={function} literal={expected!r}"
|
| 1142 |
+
elif kind == "python_call_keyword_literal":
|
| 1143 |
+
function = str(check.get("function") or "")
|
| 1144 |
+
keyword = str(check.get("keyword") or "")
|
| 1145 |
+
expected = check.get("value")
|
| 1146 |
+
target = str(check.get("target") or "")
|
| 1147 |
+
source_calls = (resolved_calls if target else
|
| 1148 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1149 |
+
passed = any(
|
| 1150 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1151 |
+
(not target or canonical == target) and
|
| 1152 |
+
_call_keyword_matches(node, keyword, expected, constants)
|
| 1153 |
+
for name, canonical, node in source_calls)
|
| 1154 |
+
detail = (f"call={function} keyword={keyword} "
|
| 1155 |
+
f"literal={expected!r}")
|
| 1156 |
+
else:
|
| 1157 |
+
function = str(check.get("function") or "")
|
| 1158 |
+
arguments = check.get("arguments") or []
|
| 1159 |
+
keywords = check.get("keywords") or {}
|
| 1160 |
+
argument_expressions = check.get(
|
| 1161 |
+
"argument_expressions") or []
|
| 1162 |
+
keyword_expressions = check.get(
|
| 1163 |
+
"keyword_expressions") or {}
|
| 1164 |
+
assignment = check.get("assignment")
|
| 1165 |
+
target = str(check.get("target") or "")
|
| 1166 |
+
source_calls = (resolved_calls if target else
|
| 1167 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1168 |
+
passed = any(
|
| 1169 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1170 |
+
(not target or canonical == target) and
|
| 1171 |
+
_call_signature_matches(
|
| 1172 |
+
node, arguments, keywords, constants,
|
| 1173 |
+
argument_expressions, keyword_expressions,
|
| 1174 |
+
assignment)
|
| 1175 |
+
for name, canonical, node in source_calls)
|
| 1176 |
+
detail = (f"call={function} arguments={arguments!r} "
|
| 1177 |
+
f"keywords={keywords!r} "
|
| 1178 |
+
f"argument_expressions={argument_expressions!r} "
|
| 1179 |
+
f"keyword_expressions={keyword_expressions!r} "
|
| 1180 |
+
f"assignment={assignment!r}")
|
| 1181 |
+
elif kind == "shell_syntax":
|
| 1182 |
+
completed = subprocess.run(
|
| 1183 |
+
["bash", "-n", str(path)], capture_output=True, text=True,
|
| 1184 |
+
timeout=5, check=False)
|
| 1185 |
+
passed = completed.returncode == 0
|
| 1186 |
+
detail = ("valid shell syntax" if passed else
|
| 1187 |
+
(completed.stderr or "invalid shell syntax").strip())
|
| 1188 |
+
elif kind == "shell_command":
|
| 1189 |
+
source = path.read_text(encoding="utf-8")
|
| 1190 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1191 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1192 |
+
expected = " ".join(str(check.get("value") or "").split())
|
| 1193 |
+
passed = any(_shell_command_matches(expected, line) for line in lines)
|
| 1194 |
+
detail = f"executable_lines={lines[:30]}"
|
| 1195 |
+
elif kind == "shell_command_sequence":
|
| 1196 |
+
source = path.read_text(encoding="utf-8")
|
| 1197 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1198 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1199 |
+
expected = [" ".join(str(value).split())
|
| 1200 |
+
for value in check.get("values") or []]
|
| 1201 |
+
passed = (len(expected) >= 2 and
|
| 1202 |
+
_shell_command_sequence_matches(expected, lines))
|
| 1203 |
+
detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
|
| 1204 |
+
elif kind == "shell_unconditional_commands":
|
| 1205 |
+
source = path.read_text(encoding="utf-8")
|
| 1206 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1207 |
+
if int(evaluator.get("version", 0)) >= 15
|
| 1208 |
+
else _shell_unconditional_lines(source))
|
| 1209 |
+
expected = [" ".join(str(value).split())
|
| 1210 |
+
for value in check.get("values") or []]
|
| 1211 |
+
passed = (bool(expected) and all(
|
| 1212 |
+
any(_shell_command_matches(command, line) for line in lines)
|
| 1213 |
+
for command in expected))
|
| 1214 |
+
detail = (f"expected_unconditional={expected}; "
|
| 1215 |
+
f"top_level_lines={lines[:30]}")
|
| 1216 |
+
elif kind == "shell_failure_propagation":
|
| 1217 |
+
calls = shell_invocations(path.read_text(encoding="utf-8"))
|
| 1218 |
+
expected = [" ".join(str(value).split())
|
| 1219 |
+
for value in check.get("values") or []]
|
| 1220 |
+
passed = bool(expected) and all(any(
|
| 1221 |
+
call["fail_fast"] and _shell_command_matches(command, call["command"])
|
| 1222 |
+
for call in calls) for command in expected)
|
| 1223 |
+
detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
|
| 1224 |
+
elif kind == "shell_straight_line":
|
| 1225 |
+
source = path.read_text(encoding="utf-8")
|
| 1226 |
+
passed = _shell_is_straight_line(source)
|
| 1227 |
+
detail = ("all executable lines are top-level" if passed else
|
| 1228 |
+
"shell contains conditional, loop, case, or function")
|
| 1229 |
+
else:
|
| 1230 |
+
detail = f"unsupported check: {kind}"
|
| 1231 |
+
except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
|
| 1232 |
+
json.JSONDecodeError,
|
| 1233 |
+
tomllib.TOMLDecodeError) as exc:
|
| 1234 |
+
detail = str(exc)
|
| 1235 |
+
results.append({"id": check.get("id"), "type": kind,
|
| 1236 |
+
"path": relative, "passed": bool(passed),
|
| 1237 |
+
"detail": detail[:1000]})
|
| 1238 |
+
return bool(results) and all(item["passed"] for item in results), {
|
| 1239 |
+
"type": WORKSPACE_EVALUATOR,
|
| 1240 |
+
"assertions_passed": sum(item["passed"] for item in results),
|
| 1241 |
+
"assertions_total": len(results),
|
| 1242 |
+
"assertions": results,
|
| 1243 |
+
}
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
def evaluate_candidate(evaluator, candidate):
|
| 1247 |
+
if isinstance(candidate, os.PathLike):
|
| 1248 |
+
try:
|
| 1249 |
+
return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
|
| 1250 |
+
False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
|
| 1251 |
+
except (OSError, ValueError) as exc:
|
| 1252 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1253 |
+
if isinstance(candidate, str):
|
| 1254 |
+
# A chat file-bundle can be much longer than a filesystem path. Avoid
|
| 1255 |
+
# passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
|
| 1256 |
+
stripped = candidate.strip()
|
| 1257 |
+
if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
|
| 1258 |
+
and not stripped.startswith(("{", "[", "```"))):
|
| 1259 |
+
try:
|
| 1260 |
+
if Path(stripped).is_dir():
|
| 1261 |
+
return evaluate_workspace(evaluator, stripped)
|
| 1262 |
+
except (OSError, ValueError):
|
| 1263 |
+
# Python/platform versions differ on ENAMETOOLONG and invalid
|
| 1264 |
+
# path errors. It is still candidate text: parse it unchanged.
|
| 1265 |
+
pass
|
| 1266 |
+
try:
|
| 1267 |
+
with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
|
| 1268 |
+
materialize_bundle(candidate, temp)
|
| 1269 |
+
return evaluate_workspace(evaluator, temp)
|
| 1270 |
+
except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
|
| 1271 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
def self_test_workspace_evaluator(evaluator):
|
| 1275 |
+
correct = reference_bundle(evaluator)
|
| 1276 |
+
ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
|
| 1277 |
+
rows = list(correct.get("files") or [])
|
| 1278 |
+
perturbed = {"files": rows[1:] if len(rows) > 1 else []}
|
| 1279 |
+
ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
|
| 1280 |
+
mutations = []
|
| 1281 |
+
# Exact JSON fields must each matter, not merely the file's existence.
|
| 1282 |
+
for check in evaluator.get("checks") or []:
|
| 1283 |
+
if check.get("type") != "json_exact":
|
| 1284 |
+
continue
|
| 1285 |
+
for path, value in _flatten(check.get("expected")):
|
| 1286 |
+
candidate = copy.deepcopy(correct)
|
| 1287 |
+
file_row = next(row for row in candidate["files"]
|
| 1288 |
+
if row["path"] == check["path"])
|
| 1289 |
+
data = json.loads(file_row["content"])
|
| 1290 |
+
replacement = (not value if isinstance(value, bool) else
|
| 1291 |
+
value + 1 if isinstance(value, (int, float)) else
|
| 1292 |
+
str(value) + "__mutation__")
|
| 1293 |
+
if not path:
|
| 1294 |
+
data = replacement
|
| 1295 |
+
else:
|
| 1296 |
+
container = data
|
| 1297 |
+
for key in path[:-1]:
|
| 1298 |
+
container = container[key]
|
| 1299 |
+
container[path[-1]] = replacement
|
| 1300 |
+
file_row["content"] = json.dumps(data)
|
| 1301 |
+
passed, _ = evaluate_candidate(evaluator, candidate)
|
| 1302 |
+
mutations.append({"path": check["path"], "field": list(path),
|
| 1303 |
+
"rejected": not passed})
|
| 1304 |
+
return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
|
| 1305 |
+
"correct": correct_detail,
|
| 1306 |
+
"perturbed": wrong_detail,
|
| 1307 |
+
"scalar_mutations": mutations,
|
| 1308 |
+
}
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/shell_invocations.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A deliberately bounded, non-executing shell structure recognizer.
|
| 2 |
+
|
| 3 |
+
Supports simple commands, literal scalar assignments, one command substitution
|
| 4 |
+
on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
|
| 5 |
+
It does not interpret shell code or credit commands in branch bodies/functions.
|
| 6 |
+
Pipelines, command lists, substitutions within substitutions, and swallowed
|
| 7 |
+
failures are outside this grammar. bash -n remains a separate required check.
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
import shlex
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _statements(text):
|
| 14 |
+
out, current = [], []
|
| 15 |
+
quote, escaped, comment, depth = None, False, False, 0
|
| 16 |
+
for ch in str(text):
|
| 17 |
+
if comment:
|
| 18 |
+
if ch == '\n':
|
| 19 |
+
comment = False
|
| 20 |
+
else:
|
| 21 |
+
continue
|
| 22 |
+
if escaped:
|
| 23 |
+
if ch != '\n':
|
| 24 |
+
current.extend(('\\', ch))
|
| 25 |
+
escaped = False
|
| 26 |
+
continue
|
| 27 |
+
if ch == '\\' and quote != "'":
|
| 28 |
+
escaped = True
|
| 29 |
+
continue
|
| 30 |
+
if quote:
|
| 31 |
+
current.append(ch)
|
| 32 |
+
if ch == quote:
|
| 33 |
+
quote = None
|
| 34 |
+
continue
|
| 35 |
+
if ch in "'\"":
|
| 36 |
+
quote = ch
|
| 37 |
+
current.append(ch)
|
| 38 |
+
elif ch == '#' and (not current or current[-1].isspace()):
|
| 39 |
+
comment = True
|
| 40 |
+
elif ch == '(':
|
| 41 |
+
depth += 1
|
| 42 |
+
current.append(ch)
|
| 43 |
+
elif ch == ')':
|
| 44 |
+
depth -= 1
|
| 45 |
+
if depth < 0:
|
| 46 |
+
return []
|
| 47 |
+
current.append(ch)
|
| 48 |
+
elif ch in '\n;' and depth == 0:
|
| 49 |
+
value = ''.join(current).strip()
|
| 50 |
+
if value:
|
| 51 |
+
out.append(value)
|
| 52 |
+
current = []
|
| 53 |
+
else:
|
| 54 |
+
current.append(ch)
|
| 55 |
+
if quote or escaped or depth:
|
| 56 |
+
return []
|
| 57 |
+
if ''.join(current).strip():
|
| 58 |
+
out.append(''.join(current).strip())
|
| 59 |
+
expanded = []
|
| 60 |
+
for statement in out:
|
| 61 |
+
inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
|
| 62 |
+
expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
|
| 63 |
+
return expanded
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _simple_argv(text):
|
| 67 |
+
if '$(' in text or '`' in text:
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
|
| 71 |
+
lexer.whitespace_split = True
|
| 72 |
+
tokens = list(lexer)
|
| 73 |
+
except ValueError:
|
| 74 |
+
return None
|
| 75 |
+
argv, index = [], 0
|
| 76 |
+
redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
|
| 77 |
+
while index < len(tokens):
|
| 78 |
+
token = tokens[index]
|
| 79 |
+
if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
|
| 80 |
+
index += 1
|
| 81 |
+
token = tokens[index]
|
| 82 |
+
if token in redirects:
|
| 83 |
+
if index + 1 >= len(tokens):
|
| 84 |
+
return None
|
| 85 |
+
target = tokens[index + 1]
|
| 86 |
+
if (not target or any(c in target for c in '$`;&|<>()')
|
| 87 |
+
or target in ('{', '}')):
|
| 88 |
+
return None
|
| 89 |
+
index += 2
|
| 90 |
+
continue
|
| 91 |
+
if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
|
| 92 |
+
return None
|
| 93 |
+
argv.append(token)
|
| 94 |
+
index += 1
|
| 95 |
+
return argv or None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _invocation(text):
|
| 99 |
+
substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
|
| 100 |
+
if substitution:
|
| 101 |
+
inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
|
| 102 |
+
argv = _simple_argv(inner)
|
| 103 |
+
return (argv, 'assignment_substitution') if argv else (None, None)
|
| 104 |
+
return _simple_argv(text), 'simple'
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _guard_end(statements, start):
|
| 108 |
+
depth = 1
|
| 109 |
+
for index in range(start + 1, len(statements)):
|
| 110 |
+
item = statements[index]
|
| 111 |
+
if re.match(r'^if\s', item):
|
| 112 |
+
depth += 1
|
| 113 |
+
elif item == 'fi':
|
| 114 |
+
depth -= 1
|
| 115 |
+
if depth == 0:
|
| 116 |
+
return index
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# R7: unwrap only execution wrappers whose effect is proved in this subset.
|
| 122 |
+
# In particular `command -v/-V` queries do not run their operand, and `builtin`
|
| 123 |
+
# cannot run an external tool. Keep these distinctions before inspecting state.
|
| 124 |
+
_BASH_BUILTINS = frozenset({
|
| 125 |
+
':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd',
|
| 126 |
+
'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',
|
| 127 |
+
'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
|
| 128 |
+
'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local',
|
| 129 |
+
'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray',
|
| 130 |
+
'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test',
|
| 131 |
+
'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias',
|
| 132 |
+
'unset', 'wait',
|
| 133 |
+
})
|
| 134 |
+
_UNSUPPORTED_STATE = frozenset({
|
| 135 |
+
'.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap',
|
| 136 |
+
'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local',
|
| 137 |
+
'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift',
|
| 138 |
+
'[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts',
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _bash_dialect(text):
|
| 143 |
+
"""No shebang uses the evaluator's Bash syntax contract; sh is not Bash."""
|
| 144 |
+
first = str(text).splitlines()[0] if str(text).splitlines() else ''
|
| 145 |
+
if not first.startswith('#!'):
|
| 146 |
+
return True
|
| 147 |
+
try:
|
| 148 |
+
words = shlex.split(first[2:])
|
| 149 |
+
except ValueError:
|
| 150 |
+
return False
|
| 151 |
+
if not words:
|
| 152 |
+
return False
|
| 153 |
+
executable = words[0].rsplit('/', 1)[-1]
|
| 154 |
+
if executable == 'env':
|
| 155 |
+
words = words[1:]
|
| 156 |
+
if words[:1] == ['-S']:
|
| 157 |
+
words = words[1:]
|
| 158 |
+
executable = words[0] if words else ''
|
| 159 |
+
return executable.rsplit('/', 1)[-1] == 'bash'
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _execution_argv(argv, bash=True):
|
| 163 |
+
"""Normalize a finite chain; unsupported wrappers get no command credit."""
|
| 164 |
+
if not argv:
|
| 165 |
+
return None
|
| 166 |
+
argv = list(argv)
|
| 167 |
+
while argv and argv[0] in ('command', 'builtin'):
|
| 168 |
+
wrapper = argv[0]
|
| 169 |
+
if wrapper == 'builtin':
|
| 170 |
+
if not bash:
|
| 171 |
+
return None
|
| 172 |
+
argv = argv[1:]
|
| 173 |
+
if argv[:1] == ['--']:
|
| 174 |
+
argv = argv[1:]
|
| 175 |
+
if not argv or argv[0] not in _BASH_BUILTINS:
|
| 176 |
+
return None
|
| 177 |
+
continue
|
| 178 |
+
index, query, default_path = 1, False, False
|
| 179 |
+
while index < len(argv) and argv[index].startswith('-'):
|
| 180 |
+
option = argv[index]
|
| 181 |
+
index += 1
|
| 182 |
+
if option == '--':
|
| 183 |
+
break
|
| 184 |
+
if not re.fullmatch(r'-[pvV]+', option):
|
| 185 |
+
return None
|
| 186 |
+
query = query or 'v' in option or 'V' in option
|
| 187 |
+
default_path = default_path or 'p' in option
|
| 188 |
+
if query:
|
| 189 |
+
return argv # Query is an invocation of command, not its target.
|
| 190 |
+
if index == len(argv):
|
| 191 |
+
return None
|
| 192 |
+
argv = argv[index:]
|
| 193 |
+
# -p changes external PATH lookup. It is transparent for builtins only.
|
| 194 |
+
if default_path and argv[0] not in _BASH_BUILTINS:
|
| 195 |
+
return None
|
| 196 |
+
return argv or None
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _set_errexit(argv, current):
|
| 200 |
+
"""Return the proven option state, or None for unsupported set options."""
|
| 201 |
+
if not argv or argv[0] != 'set':
|
| 202 |
+
return None
|
| 203 |
+
index = 1
|
| 204 |
+
while index < len(argv):
|
| 205 |
+
flag = argv[index]
|
| 206 |
+
if flag == '--' or not flag.startswith(('-', '+')):
|
| 207 |
+
break # Positional arguments cannot enable errexit.
|
| 208 |
+
if not re.fullmatch(r'[-+][eufxEo]+', flag):
|
| 209 |
+
return None # Includes noexec (-n), which suppresses later work.
|
| 210 |
+
if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1):
|
| 211 |
+
return None
|
| 212 |
+
if 'e' in flag[1:]:
|
| 213 |
+
current = flag[0] == '-'
|
| 214 |
+
if 'o' in flag[1:]:
|
| 215 |
+
if index + 1 >= len(argv):
|
| 216 |
+
return None
|
| 217 |
+
option = argv[index + 1]
|
| 218 |
+
if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
|
| 219 |
+
return None
|
| 220 |
+
if option == 'errexit':
|
| 221 |
+
current = flag[0] == '-'
|
| 222 |
+
index += 1
|
| 223 |
+
index += 1
|
| 224 |
+
return current
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def shell_option_setting(text, bash=True):
|
| 228 |
+
"""Recognize valid option setup for task-specific operation counters."""
|
| 229 |
+
argv = _execution_argv(_simple_argv(text), bash)
|
| 230 |
+
return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _exit_status(argv):
|
| 234 |
+
"""A literal shell exit status; no-argument exit is handled by its caller."""
|
| 235 |
+
args = argv[1:]
|
| 236 |
+
if args[:1] == ['--']:
|
| 237 |
+
args = args[1:]
|
| 238 |
+
if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0])
|
| 239 |
+
or len(args[0]) > 20):
|
| 240 |
+
return None
|
| 241 |
+
value = int(args[0])
|
| 242 |
+
if not -(2**63) <= value <= 2**63 - 1:
|
| 243 |
+
return 2 # Bash exits for an out-of-range numeric argument.
|
| 244 |
+
return value % 256
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _nonzero_exit_body(statements, bash=True):
|
| 249 |
+
"""Only literal logging followed by a final unconditional nonzero exit."""
|
| 250 |
+
if not statements:
|
| 251 |
+
return False
|
| 252 |
+
for index, statement in enumerate(statements):
|
| 253 |
+
argv = _execution_argv(_simple_argv(statement), bash)
|
| 254 |
+
if not argv:
|
| 255 |
+
return False
|
| 256 |
+
if argv[0] == 'exit':
|
| 257 |
+
status = _exit_status(argv)
|
| 258 |
+
return index == len(statements) - 1 and status is not None and status != 0
|
| 259 |
+
if argv[0] not in ('echo', 'printf'):
|
| 260 |
+
return False
|
| 261 |
+
return False
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def shell_invocations(text):
|
| 265 |
+
"""Return ordered, actually evaluated invocation nodes in the supported subset.
|
| 266 |
+
|
| 267 |
+
fail_fast is a structural proof: a simple command/assignment runs under
|
| 268 |
+
errexit, or a negated test exits nonzero on failure. This is not a complete
|
| 269 |
+
shell interpreter, and unsupported syntax earns no invocation credit.
|
| 270 |
+
"""
|
| 271 |
+
statements = _statements(text)
|
| 272 |
+
bash = _bash_dialect(text)
|
| 273 |
+
# Function definitions or dynamic shell mutation can shadow the command or
|
| 274 |
+
# `exit` itself. They are outside this objective subset, even if uncalled.
|
| 275 |
+
if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s)
|
| 276 |
+
or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
|
| 277 |
+
for s in statements):
|
| 278 |
+
return []
|
| 279 |
+
constants, result, index, errexit = {}, [], 0, False
|
| 280 |
+
assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
|
| 281 |
+
variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 282 |
+
while index < len(statements):
|
| 283 |
+
statement = statements[index]
|
| 284 |
+
literal = assignment.fullmatch(statement)
|
| 285 |
+
if literal:
|
| 286 |
+
constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
|
| 287 |
+
index += 1
|
| 288 |
+
continue
|
| 289 |
+
statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement)
|
| 290 |
+
if re.match(r'^if\s', statement):
|
| 291 |
+
end = _guard_end(statements, index)
|
| 292 |
+
if end is None:
|
| 293 |
+
return []
|
| 294 |
+
negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
|
| 295 |
+
if (negated and index + 1 < end
|
| 296 |
+
and statements[index + 1] == 'then'
|
| 297 |
+
and _nonzero_exit_body(statements[index + 2:end], bash)):
|
| 298 |
+
argv, kind = _invocation(negated.group(1).strip())
|
| 299 |
+
argv = _execution_argv(argv, bash)
|
| 300 |
+
if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')):
|
| 301 |
+
return []
|
| 302 |
+
if argv:
|
| 303 |
+
if argv[0] == 'false':
|
| 304 |
+
break
|
| 305 |
+
result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
|
| 306 |
+
'fail_fast': True, 'statement_index': index, 'expanded_statement': statement})
|
| 307 |
+
else:
|
| 308 |
+
return []
|
| 309 |
+
else:
|
| 310 |
+
# Arbitrary conditions may terminate the script or shadow its
|
| 311 |
+
# commands. Do not infer a reachable suffix through them.
|
| 312 |
+
return []
|
| 313 |
+
# Bodies are never credited and may have assigned local variables.
|
| 314 |
+
constants.clear()
|
| 315 |
+
index = end + 1
|
| 316 |
+
continue
|
| 317 |
+
if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
|
| 318 |
+
# Unsupported compounds are not searched for command substrings.
|
| 319 |
+
return []
|
| 320 |
+
argv, kind = _invocation(statement)
|
| 321 |
+
argv = _execution_argv(argv, bash)
|
| 322 |
+
if not argv:
|
| 323 |
+
# An unparsed statement may change control flow or shell state.
|
| 324 |
+
# Skipping it would incorrectly credit an unreachable suffix.
|
| 325 |
+
return []
|
| 326 |
+
if argv[0] in _UNSUPPORTED_STATE:
|
| 327 |
+
return []
|
| 328 |
+
if argv[0] == 'hash':
|
| 329 |
+
# Clearing/querying/cache lookup preserves the command's selected
|
| 330 |
+
# executable. An explicit -p binding can replace a required tool.
|
| 331 |
+
operands, flags = [], ''
|
| 332 |
+
option_mode = True
|
| 333 |
+
for word in argv[1:]:
|
| 334 |
+
if option_mode and word == '--':
|
| 335 |
+
option_mode = False
|
| 336 |
+
elif option_mode and word.startswith('-'):
|
| 337 |
+
if not re.fullmatch(r'-[lrdt]+', word):
|
| 338 |
+
return []
|
| 339 |
+
flags += word[1:]
|
| 340 |
+
else:
|
| 341 |
+
option_mode = False
|
| 342 |
+
if '$' in word:
|
| 343 |
+
return []
|
| 344 |
+
operands.append(word)
|
| 345 |
+
if ('d' in flags or 't' in flags) and not operands:
|
| 346 |
+
return []
|
| 347 |
+
if argv[0] == 'set':
|
| 348 |
+
new_errexit = _set_errexit(argv, errexit)
|
| 349 |
+
if new_errexit is None:
|
| 350 |
+
return []
|
| 351 |
+
if kind == 'simple':
|
| 352 |
+
errexit = new_errexit
|
| 353 |
+
index += 1
|
| 354 |
+
continue
|
| 355 |
+
# An assignment substitution runs in a subshell: set cannot change
|
| 356 |
+
# the parent's flags. Keep it as an ordinary evaluated node.
|
| 357 |
+
if argv[0] == 'exit':
|
| 358 |
+
if kind == 'simple':
|
| 359 |
+
# Only a literal, zero/one-argument exit is proved terminal.
|
| 360 |
+
# An invalid multi-argument exit can return and is unsupported.
|
| 361 |
+
if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None:
|
| 362 |
+
break
|
| 363 |
+
return []
|
| 364 |
+
status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv)
|
| 365 |
+
if status is None:
|
| 366 |
+
return []
|
| 367 |
+
if status and errexit:
|
| 368 |
+
break
|
| 369 |
+
if argv[0] == 'false' and errexit:
|
| 370 |
+
break
|
| 371 |
+
if kind == 'assignment_substitution':
|
| 372 |
+
assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
|
| 373 |
+
if assigned:
|
| 374 |
+
constants.pop(assigned.group(1), None)
|
| 375 |
+
result.append({'command': shlex.join(argv), 'kind': kind,
|
| 376 |
+
'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement})
|
| 377 |
+
index += 1
|
| 378 |
+
return result
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_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/8dbd07af72331a25_q1/evaluator/legacy_tests/verifiers.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verifier execution engine and fail-closed self-tests.
|
| 2 |
+
|
| 3 |
+
New verified tasks use atomic_json (complete shape plus scalar assertions).
|
| 4 |
+
Legacy verifier types remain readable so historical runs can still be audited.
|
| 5 |
+
自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 14 |
+
reference_bundle,
|
| 15 |
+
self_test_workspace_evaluator)
|
| 16 |
+
except ImportError: # portable task copies these modules beside each other
|
| 17 |
+
from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 18 |
+
reference_bundle,
|
| 19 |
+
self_test_workspace_evaluator)
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger("pipeline")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _norm(s):
|
| 25 |
+
return str(s).strip().lower()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _json_value(value):
|
| 29 |
+
"""Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
|
| 30 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 31 |
+
return value
|
| 32 |
+
text = str(value).strip()
|
| 33 |
+
match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
|
| 34 |
+
if match:
|
| 35 |
+
text = match.group(1).strip()
|
| 36 |
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
|
| 37 |
+
text = re.sub(r"\s*```$", "", text)
|
| 38 |
+
start_obj, start_arr = text.find("{"), text.find("[")
|
| 39 |
+
starts = [x for x in (start_obj, start_arr) if x >= 0]
|
| 40 |
+
if starts:
|
| 41 |
+
start = min(starts)
|
| 42 |
+
closing = "}" if text[start] == "{" else "]"
|
| 43 |
+
end = text.rfind(closing)
|
| 44 |
+
if end >= start:
|
| 45 |
+
text = text[start:end + 1]
|
| 46 |
+
try:return json.loads(text)
|
| 47 |
+
except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _canonical_json(value):
|
| 51 |
+
if isinstance(value, dict):
|
| 52 |
+
return {key: _canonical_json(value[key]) for key in sorted(value)}
|
| 53 |
+
if isinstance(value, list):
|
| 54 |
+
values = [_canonical_json(item) for item in value]
|
| 55 |
+
return sorted(values, key=lambda item: json.dumps(
|
| 56 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 57 |
+
return value
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _atomic_prepare(value, list_order):
|
| 61 |
+
if isinstance(value, dict):
|
| 62 |
+
return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
|
| 63 |
+
if isinstance(value, list):
|
| 64 |
+
values = [_atomic_prepare(item, list_order) for item in value]
|
| 65 |
+
if list_order == "unordered":
|
| 66 |
+
values.sort(key=lambda item: json.dumps(
|
| 67 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 68 |
+
return values
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _atomic_shape(value):
|
| 73 |
+
if isinstance(value, dict):
|
| 74 |
+
return {"type": "object", "keys": {
|
| 75 |
+
key: _atomic_shape(item) for key, item in value.items()}}
|
| 76 |
+
if isinstance(value, list):
|
| 77 |
+
return {"type": "array", "length": len(value),
|
| 78 |
+
"items": [_atomic_shape(item) for item in value]}
|
| 79 |
+
if isinstance(value, bool):
|
| 80 |
+
return {"type": "boolean"}
|
| 81 |
+
if value is None:
|
| 82 |
+
return {"type": "null"}
|
| 83 |
+
if isinstance(value, (int, float)):
|
| 84 |
+
return {"type": "number"}
|
| 85 |
+
return {"type": "string"}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _atomic_leaves(value, path="$", tokens=()):
|
| 89 |
+
if isinstance(value, dict):
|
| 90 |
+
out = []
|
| 91 |
+
for key, item in value.items():
|
| 92 |
+
out.extend(_atomic_leaves(
|
| 93 |
+
item, path + "." + key, tokens + (key,)))
|
| 94 |
+
return out
|
| 95 |
+
if isinstance(value, list):
|
| 96 |
+
out = []
|
| 97 |
+
for index, item in enumerate(value):
|
| 98 |
+
out.extend(_atomic_leaves(
|
| 99 |
+
item, f"{path}[{index}]", tokens + (index,)))
|
| 100 |
+
return out
|
| 101 |
+
return [(path, tokens, value)]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _normalize_path_equivalence_tokens(values):
|
| 105 |
+
"""Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
|
| 106 |
+
normalized = []
|
| 107 |
+
for tokens in values or []:
|
| 108 |
+
if (not isinstance(tokens, (list, tuple)) or not tokens or
|
| 109 |
+
any(not isinstance(token, (str, int)) for token in tokens)):
|
| 110 |
+
raise ValueError("path equivalence tokens must be non-empty JSON paths")
|
| 111 |
+
item = list(tokens)
|
| 112 |
+
if item not in normalized:
|
| 113 |
+
normalized.append(item)
|
| 114 |
+
return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _path_value(value):
|
| 118 |
+
"""Normalize only portable path spelling, not general answer text."""
|
| 119 |
+
if not isinstance(value, str):
|
| 120 |
+
return None
|
| 121 |
+
text = value.strip().replace("\\", "/")
|
| 122 |
+
if text != "/":
|
| 123 |
+
text = text.rstrip("/")
|
| 124 |
+
return text
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
|
| 128 |
+
path_equivalence_tokens=None):
|
| 129 |
+
"""Freeze a complete JSON shape plus one assertion for every scalar leaf."""
|
| 130 |
+
if list_order not in {"ordered", "unordered"}:
|
| 131 |
+
raise ValueError(f"unsupported atomic list_order: {list_order}")
|
| 132 |
+
tolerance = float(float_tolerance)
|
| 133 |
+
prepared = _atomic_prepare(_json_value(expected), list_order)
|
| 134 |
+
path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
|
| 135 |
+
assertions = []
|
| 136 |
+
for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
|
| 137 |
+
assertion = {"id": f"leaf_{index:03d}", "path": path,
|
| 138 |
+
"tokens": list(tokens), "operator": "eq", "expected": value}
|
| 139 |
+
if isinstance(value, float):
|
| 140 |
+
assertion.update({"operator": "abs_diff", "tolerance": tolerance})
|
| 141 |
+
elif list(tokens) in path_tokens:
|
| 142 |
+
if not isinstance(value, str):
|
| 143 |
+
raise ValueError("path equivalence can only target string leaves")
|
| 144 |
+
assertion["operator"] = "path_eq"
|
| 145 |
+
assertions.append(assertion)
|
| 146 |
+
compiled = {
|
| 147 |
+
"type": "atomic_json", "version": 2 if path_tokens else 1,
|
| 148 |
+
"list_order": list_order,
|
| 149 |
+
"float_tolerance": tolerance,
|
| 150 |
+
"completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
|
| 151 |
+
"assertions": assertions,
|
| 152 |
+
}
|
| 153 |
+
if path_tokens:
|
| 154 |
+
compiled["path_equivalence_tokens"] = path_tokens
|
| 155 |
+
return compiled
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _shape_differences(expected, actual, path="$"):
|
| 159 |
+
if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
|
| 160 |
+
return [f"{path}: expected {expected.get('type')}, got "
|
| 161 |
+
f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
|
| 162 |
+
kind = expected.get("type")
|
| 163 |
+
if kind == "object":
|
| 164 |
+
expected_keys = set((expected.get("keys") or {}))
|
| 165 |
+
actual_keys = set((actual.get("keys") or {}))
|
| 166 |
+
differences = [f"{path}: missing key {key}" for key in sorted(
|
| 167 |
+
expected_keys - actual_keys)]
|
| 168 |
+
differences.extend(f"{path}: extra key {key}" for key in sorted(
|
| 169 |
+
actual_keys - expected_keys))
|
| 170 |
+
for key in sorted(expected_keys & actual_keys):
|
| 171 |
+
differences.extend(_shape_differences(
|
| 172 |
+
expected["keys"][key], actual["keys"][key], path + "." + key))
|
| 173 |
+
return differences
|
| 174 |
+
if kind == "array":
|
| 175 |
+
differences = []
|
| 176 |
+
if actual.get("length") != expected.get("length"):
|
| 177 |
+
differences.append(
|
| 178 |
+
f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
|
| 179 |
+
for index, (expected_item, actual_item) in enumerate(zip(
|
| 180 |
+
expected.get("items") or [], actual.get("items") or [])):
|
| 181 |
+
differences.extend(_shape_differences(
|
| 182 |
+
expected_item, actual_item, f"{path}[{index}]"))
|
| 183 |
+
return differences
|
| 184 |
+
return []
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _atomic_get(value, tokens):
|
| 188 |
+
current = value
|
| 189 |
+
for token in tokens:
|
| 190 |
+
current = current[token]
|
| 191 |
+
return current
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _int_values(value):
|
| 195 |
+
if isinstance(value, (list, tuple)):
|
| 196 |
+
out = []
|
| 197 |
+
for item in value:
|
| 198 |
+
out.extend(_int_values(item))
|
| 199 |
+
return out
|
| 200 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 201 |
+
return [value]
|
| 202 |
+
return [int(number) for number in re.findall(r"\d+", str(value or ""))]
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _finding_type(value):
|
| 206 |
+
text = str(value or "").lower().replace("-", "_")
|
| 207 |
+
if "duplicate" in text:
|
| 208 |
+
return "duplicate_rows"
|
| 209 |
+
if ("none" in text or "null" in text) and "check" in text:
|
| 210 |
+
return "none_check"
|
| 211 |
+
if "missing" in text or "empty" in text or "null" in text:
|
| 212 |
+
return "missing"
|
| 213 |
+
if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
|
| 214 |
+
return "outlier"
|
| 215 |
+
if "invalid" in text and "config" in text:
|
| 216 |
+
return "invalid_config"
|
| 217 |
+
if "off" in text and "one" in text:
|
| 218 |
+
return "off_by_one"
|
| 219 |
+
return text.strip().replace(" ", "_")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _normalized_findings(value, family):
|
| 223 |
+
obj = _json_value(value)
|
| 224 |
+
findings = obj.get("findings") if isinstance(obj, dict) else None
|
| 225 |
+
if not isinstance(findings, list):
|
| 226 |
+
raise ValueError("answer must contain a findings array")
|
| 227 |
+
normalized = set()
|
| 228 |
+
for finding in findings:
|
| 229 |
+
if not isinstance(finding, dict):
|
| 230 |
+
raise ValueError("each finding must be an object")
|
| 231 |
+
# The public contract uses type/function. Accept common semantically
|
| 232 |
+
# equivalent aliases as a robustness layer, while still comparing the
|
| 233 |
+
# normalized values and exact locations against generator-owned GT.
|
| 234 |
+
kind = _finding_type(finding.get("type", finding.get(
|
| 235 |
+
"defect_type", finding.get("defect"))))
|
| 236 |
+
if family == "csv":
|
| 237 |
+
if kind == "duplicate_rows":
|
| 238 |
+
rows = _int_values(finding.get("rows", finding.get("row")))
|
| 239 |
+
if len(rows) != 2:
|
| 240 |
+
raise ValueError("duplicate finding requires exactly two row numbers")
|
| 241 |
+
normalized.add((kind, *sorted(rows)))
|
| 242 |
+
elif kind in {"missing", "outlier"}:
|
| 243 |
+
rows = _int_values(finding.get("row"))
|
| 244 |
+
column = str(finding.get("column") or "").strip().lower()
|
| 245 |
+
if len(rows) != 1 or not column:
|
| 246 |
+
raise ValueError(f"{kind} requires one row and column")
|
| 247 |
+
normalized.add((kind, rows[0], column))
|
| 248 |
+
else:
|
| 249 |
+
raise ValueError(f"unsupported CSV finding type: {kind}")
|
| 250 |
+
elif family == "config":
|
| 251 |
+
if kind != "invalid_config":
|
| 252 |
+
raise ValueError(f"unsupported config finding type: {kind}")
|
| 253 |
+
normalized.add((kind, str(finding.get("path") or "").lower(),
|
| 254 |
+
json.dumps(finding.get("value"), sort_keys=True),
|
| 255 |
+
str(finding.get("expected") or "").lower()))
|
| 256 |
+
elif family == "code":
|
| 257 |
+
if kind not in {"off_by_one", "none_check"}:
|
| 258 |
+
raise ValueError(f"unsupported code finding type: {kind}")
|
| 259 |
+
function = finding.get("function", finding.get("function_name"))
|
| 260 |
+
function = str(function or "").strip().lower()
|
| 261 |
+
if not function:
|
| 262 |
+
raise ValueError(f"{kind} requires a function")
|
| 263 |
+
normalized.add((kind, function))
|
| 264 |
+
else:
|
| 265 |
+
raise ValueError(f"unsupported findings family: {family}")
|
| 266 |
+
return normalized
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _normalized_facts(value):
|
| 270 |
+
obj = _json_value(value)
|
| 271 |
+
facts = obj.get("facts") if isinstance(obj, dict) else None
|
| 272 |
+
if not isinstance(facts, list):
|
| 273 |
+
raise ValueError("answer must contain a facts array")
|
| 274 |
+
def textual(item):
|
| 275 |
+
# The document generator serializes scalar values as visible text. JSON
|
| 276 |
+
# has no way to infer whether the source token "30" was authored from an
|
| 277 |
+
# integer or a string, so facts_match compares that surface text. Nested
|
| 278 |
+
# values retain structural JSON comparison.
|
| 279 |
+
if isinstance(item, (dict, list)):
|
| 280 |
+
return json.dumps(item, sort_keys=True, ensure_ascii=False,
|
| 281 |
+
separators=(",", ":"))
|
| 282 |
+
if item is None:
|
| 283 |
+
return "None"
|
| 284 |
+
return str(item)
|
| 285 |
+
return {(str(fact.get("key") or ""), textual(fact.get("value")))
|
| 286 |
+
for fact in facts if isinstance(fact, dict)}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def verify(verifier, gt_answer, solver_output, material_paths=None):
|
| 290 |
+
"""执行 verifier。返回 (passed, detail)。"""
|
| 291 |
+
vtype = verifier.get("type")
|
| 292 |
+
try:
|
| 293 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 294 |
+
return evaluate_candidate(verifier, solver_output)
|
| 295 |
+
|
| 296 |
+
if vtype == "json_exact":
|
| 297 |
+
pred = _canonical_json(_json_value(solver_output))
|
| 298 |
+
gold = _canonical_json(_json_value(gt_answer))
|
| 299 |
+
ok = pred == gold
|
| 300 |
+
return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
|
| 301 |
+
|
| 302 |
+
if vtype == "atomic_json":
|
| 303 |
+
try:
|
| 304 |
+
pred = _atomic_prepare(_json_value(solver_output),
|
| 305 |
+
verifier.get("list_order", "ordered"))
|
| 306 |
+
pred_shape = _atomic_shape(pred)
|
| 307 |
+
except RecursionError:
|
| 308 |
+
return False, "candidate JSON nesting is too deep"
|
| 309 |
+
compiled = compile_atomic_verifier(
|
| 310 |
+
gt_answer, verifier.get("list_order", "ordered"),
|
| 311 |
+
verifier.get("float_tolerance", 0.01),
|
| 312 |
+
verifier.get("path_equivalence_tokens"))
|
| 313 |
+
frozen = {key: verifier.get(key) for key in
|
| 314 |
+
("type", "version", "list_order", "float_tolerance",
|
| 315 |
+
"completeness", "assertions", "path_equivalence_tokens")}
|
| 316 |
+
expected_frozen = {key: compiled.get(key) for key in frozen}
|
| 317 |
+
if frozen != expected_frozen:
|
| 318 |
+
return False, {"error": "atomic verifier does not match ground truth"}
|
| 319 |
+
shape_failures = _shape_differences(
|
| 320 |
+
verifier["completeness"]["shape"], pred_shape)
|
| 321 |
+
assertion_results = []
|
| 322 |
+
for assertion in verifier.get("assertions") or []:
|
| 323 |
+
try:
|
| 324 |
+
actual = _atomic_get(pred, assertion["tokens"])
|
| 325 |
+
if assertion["operator"] == "abs_diff":
|
| 326 |
+
passed = abs(float(actual) - float(assertion["expected"])) <= float(
|
| 327 |
+
assertion.get("tolerance", 0.0))
|
| 328 |
+
elif assertion["operator"] == "path_eq":
|
| 329 |
+
passed = (_path_value(actual) is not None and
|
| 330 |
+
_path_value(actual) == _path_value(assertion["expected"]))
|
| 331 |
+
else:
|
| 332 |
+
passed = (actual is assertion["expected"] if
|
| 333 |
+
isinstance(assertion["expected"], bool) else
|
| 334 |
+
actual == assertion["expected"])
|
| 335 |
+
message = "" if passed else (
|
| 336 |
+
f"actual={actual!r} expected={assertion['expected']!r}")
|
| 337 |
+
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
| 338 |
+
actual, passed, message = None, False, f"lookup/compare failed: {exc}"
|
| 339 |
+
assertion_results.append({
|
| 340 |
+
"id": assertion["id"], "path": assertion["path"],
|
| 341 |
+
"operator": assertion["operator"], "expected": assertion["expected"],
|
| 342 |
+
"actual": actual, "passed": passed, "message": message})
|
| 343 |
+
passed_count = sum(item["passed"] for item in assertion_results)
|
| 344 |
+
ok = not shape_failures and passed_count == len(assertion_results)
|
| 345 |
+
return ok, {
|
| 346 |
+
"type": "atomic_json", "completeness_passed": not shape_failures,
|
| 347 |
+
"completeness_failures": shape_failures,
|
| 348 |
+
"assertions_passed": passed_count,
|
| 349 |
+
"assertions_total": len(assertion_results),
|
| 350 |
+
"assertion_pass_rate": (passed_count / len(assertion_results)
|
| 351 |
+
if assertion_results else 1.0),
|
| 352 |
+
"assertions": assertion_results,
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
if vtype == "findings_match":
|
| 356 |
+
family = verifier.get("family")
|
| 357 |
+
pred = _normalized_findings(solver_output, family)
|
| 358 |
+
gold = _normalized_findings(gt_answer, family)
|
| 359 |
+
ok = pred == gold
|
| 360 |
+
return ok, ("findings_match: pass" if ok else
|
| 361 |
+
f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 362 |
+
|
| 363 |
+
if vtype == "facts_match":
|
| 364 |
+
pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
|
| 365 |
+
ok = pred == gold
|
| 366 |
+
return ok, ("facts_match: pass" if ok else
|
| 367 |
+
f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 368 |
+
|
| 369 |
+
if vtype == "exact_match":
|
| 370 |
+
ok = _norm(solver_output) == _norm(gt_answer)
|
| 371 |
+
return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
|
| 372 |
+
|
| 373 |
+
if vtype == "numeric":
|
| 374 |
+
tol = verifier.get("tolerance") or 1e-6
|
| 375 |
+
pred = float(str(solver_output).strip().split()[0])
|
| 376 |
+
gold = float(gt_answer)
|
| 377 |
+
ok = abs(pred - gold) <= tol
|
| 378 |
+
return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
|
| 379 |
+
|
| 380 |
+
if vtype == "set_match":
|
| 381 |
+
pred = set(_as_list(solver_output))
|
| 382 |
+
gold = set(_as_list(gt_answer))
|
| 383 |
+
ok = pred == gold
|
| 384 |
+
return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
|
| 385 |
+
|
| 386 |
+
if vtype == "structured_match":
|
| 387 |
+
pred = _json_value(solver_output)
|
| 388 |
+
gold = _json_value(gt_answer)
|
| 389 |
+
if not isinstance(pred, dict) or not isinstance(gold, dict):
|
| 390 |
+
return False, "structured_match requires JSON objects"
|
| 391 |
+
missing = [f for f in verifier.get("required_fields", []) if f not in pred]
|
| 392 |
+
wrong = [f for f in verifier.get("required_fields", [])
|
| 393 |
+
if f in pred and f in gold and pred[f] != gold[f]]
|
| 394 |
+
ok = not missing and not wrong
|
| 395 |
+
return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
|
| 396 |
+
|
| 397 |
+
if vtype == "execution":
|
| 398 |
+
return False, "execution verifier is disabled in verified-first v2"
|
| 399 |
+
|
| 400 |
+
if vtype == "constraint":
|
| 401 |
+
fails = _check_constraints(verifier.get("criteria", []), solver_output)
|
| 402 |
+
return not fails, f"constraint: failed={fails[:5]}"
|
| 403 |
+
|
| 404 |
+
if vtype == "file_inspection":
|
| 405 |
+
fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
|
| 406 |
+
return not fails, f"file_inspection: failed={fails[:5]}"
|
| 407 |
+
|
| 408 |
+
return False, f"unknown verifier type: {vtype}"
|
| 409 |
+
except Exception as e:
|
| 410 |
+
return False, f"verifier error: {e}"
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _as_list(x):
|
| 414 |
+
if isinstance(x, list):
|
| 415 |
+
return [_norm(i) for i in x]
|
| 416 |
+
# 逗号/换行分隔的字符串
|
| 417 |
+
return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _check_constraints(criteria, solver_output):
|
| 421 |
+
"""criteria: ["must contain X", "must be valid json", "length <= 500"]"""
|
| 422 |
+
fails = []
|
| 423 |
+
text = str(solver_output)
|
| 424 |
+
for c in criteria:
|
| 425 |
+
cl = c.lower()
|
| 426 |
+
if cl.startswith("must contain "):
|
| 427 |
+
needle = c[len("must contain "):]
|
| 428 |
+
if needle.lower() not in text.lower():
|
| 429 |
+
fails.append(c)
|
| 430 |
+
elif "valid json" in cl:
|
| 431 |
+
try:
|
| 432 |
+
json.loads(text)
|
| 433 |
+
except Exception:
|
| 434 |
+
fails.append(c)
|
| 435 |
+
elif cl.startswith("length <="):
|
| 436 |
+
limit = int(cl.split("<=")[1].strip())
|
| 437 |
+
if len(text) > limit:
|
| 438 |
+
fails.append(c)
|
| 439 |
+
else:
|
| 440 |
+
# Deterministic verifier DSL is closed-world: unknown checks fail.
|
| 441 |
+
fails.append(f"unsupported criterion: {c}")
|
| 442 |
+
return fails
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _inspect_files(expected, material_paths):
|
| 446 |
+
fails = []
|
| 447 |
+
paths = set(material_paths or [])
|
| 448 |
+
for e in expected:
|
| 449 |
+
fname = e.get("filename") if isinstance(e, dict) else str(e)
|
| 450 |
+
if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
|
| 451 |
+
fails.append(f"missing file: {fname}")
|
| 452 |
+
return fails
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
# ---------------- 自测 ----------------
|
| 456 |
+
|
| 457 |
+
def build_correct_solution(verifier, gt_answer, planted_info):
|
| 458 |
+
"""由埋点/ground truth 直接构造正确解。"""
|
| 459 |
+
vtype = verifier.get("type")
|
| 460 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 461 |
+
return reference_bundle(verifier)
|
| 462 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
|
| 463 |
+
"set_match", "structured_match"):
|
| 464 |
+
return gt_answer
|
| 465 |
+
if vtype == "constraint":
|
| 466 |
+
parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
|
| 467 |
+
if c.lower().startswith("must contain ")]
|
| 468 |
+
return " ".join(parts) if parts else str(gt_answer)
|
| 469 |
+
# execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
|
| 470 |
+
return None
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def build_perturbed_solution(verifier, gt_answer, planted_info):
|
| 474 |
+
"""破坏埋点构造扰动解。"""
|
| 475 |
+
vtype = verifier.get("type")
|
| 476 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 477 |
+
files = list(reference_bundle(verifier).get("files") or [])
|
| 478 |
+
return {"files": files[1:] if len(files) > 1 else []}
|
| 479 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
|
| 480 |
+
gold = _json_value(gt_answer)
|
| 481 |
+
if isinstance(gold, dict):
|
| 482 |
+
perturbed = dict(gold)
|
| 483 |
+
key = next(iter(perturbed), "__missing__")
|
| 484 |
+
if key in perturbed:
|
| 485 |
+
perturbed.pop(key)
|
| 486 |
+
else:
|
| 487 |
+
perturbed["__wrong__"] = True
|
| 488 |
+
return perturbed
|
| 489 |
+
if isinstance(gold, list):
|
| 490 |
+
return gold[:-1] if gold else ["__wrong__"]
|
| 491 |
+
return "__wrong__"
|
| 492 |
+
if vtype in ("exact_match", "numeric"):
|
| 493 |
+
return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
|
| 494 |
+
if vtype == "set_match":
|
| 495 |
+
gold = _as_list(gt_answer)
|
| 496 |
+
return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
|
| 497 |
+
if vtype == "structured_match":
|
| 498 |
+
fields = verifier.get("required_fields", [])
|
| 499 |
+
return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
|
| 500 |
+
if vtype == "constraint":
|
| 501 |
+
return "perturbed output lacking required content"
|
| 502 |
+
return None
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def self_test(verifier, gt_answer, planted_info, material_paths):
|
| 506 |
+
"""返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
|
| 507 |
+
|
| 508 |
+
之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
|
| 509 |
+
可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
|
| 510 |
+
"""
|
| 511 |
+
if verifier.get("type") == WORKSPACE_EVALUATOR:
|
| 512 |
+
return self_test_workspace_evaluator(verifier)
|
| 513 |
+
correct = build_correct_solution(verifier, gt_answer, planted_info)
|
| 514 |
+
perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
|
| 515 |
+
if correct is None or perturbed is None:
|
| 516 |
+
return False, (f"cannot self-test verifier type {verifier.get('type')} "
|
| 517 |
+
"(execution/file_inspection need real correct/perturbed solutions)")
|
| 518 |
+
ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
|
| 519 |
+
ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
|
| 520 |
+
passed = ok1 and not ok2
|
| 521 |
+
return passed, {"correct": d1, "perturbed": d2}
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/repair_equivalences.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
R10_ANY_FAILURE=set(['8dbd07af72331a25_q1', '917337011825a76f_q1', '9231bb5263eb6830_q1', 'a1aad4432dfbb4e2_q1', 'c288addfaf9ced19_q1'])
|
| 9 |
+
import copy
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import shlex
|
| 13 |
+
import shutil
|
| 14 |
+
import tempfile
|
| 15 |
+
from decimal import Decimal, InvalidOperation
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def argv(value):
|
| 20 |
+
if not isinstance(value, str):
|
| 21 |
+
return None
|
| 22 |
+
try:
|
| 23 |
+
result = shlex.split(value, posix=True)
|
| 24 |
+
except ValueError:
|
| 25 |
+
return None
|
| 26 |
+
# Only the Bash execution wrapper is transparent. command -v/-V are queries.
|
| 27 |
+
while len(result) > 1 and result[0] == 'command':
|
| 28 |
+
if result[1] == '--':
|
| 29 |
+
result = result[2:]
|
| 30 |
+
elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]):
|
| 31 |
+
break
|
| 32 |
+
else:
|
| 33 |
+
result = result[1:]
|
| 34 |
+
return result or None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def git_limit(tokens):
|
| 38 |
+
if not tokens or tokens[:2] != ['git', 'log']:
|
| 39 |
+
return tokens
|
| 40 |
+
out, index = [], 0
|
| 41 |
+
while index < len(tokens):
|
| 42 |
+
token = tokens[index]
|
| 43 |
+
compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token)
|
| 44 |
+
if compact:
|
| 45 |
+
out.append('--max-count=' + next(x for x in compact.groups() if x is not None))
|
| 46 |
+
elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit():
|
| 47 |
+
index += 1
|
| 48 |
+
out.append('--max-count=' + tokens[index])
|
| 49 |
+
else:
|
| 50 |
+
out.append(token)
|
| 51 |
+
index += 1
|
| 52 |
+
return out
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def shell_equal(expected, actual, normalize_env=False):
|
| 56 |
+
wanted, found = argv(expected), argv(actual)
|
| 57 |
+
if normalize_env and wanted and found:
|
| 58 |
+
wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted]
|
| 59 |
+
found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found]
|
| 60 |
+
wanted, found = git_limit(wanted), git_limit(found)
|
| 61 |
+
if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]:
|
| 62 |
+
return False
|
| 63 |
+
for index, token in enumerate(wanted[1:], 1):
|
| 64 |
+
observed = found[index]
|
| 65 |
+
if observed == token:
|
| 66 |
+
continue
|
| 67 |
+
if (index == 1 and '/' in token and
|
| 68 |
+
observed.rstrip('/').endswith('/' + token.lstrip('./'))):
|
| 69 |
+
continue # Existing package-path anchoring; no changed basename/arguments.
|
| 70 |
+
return False
|
| 71 |
+
return True
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def command_equal(expected, value):
|
| 75 |
+
# Response command questions ask for one invocation, with no extra commands.
|
| 76 |
+
return argv(expected) is not None and argv(expected) == argv(value)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def convex_equal(expected, value):
|
| 80 |
+
a, b = argv(expected), argv(value)
|
| 81 |
+
if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]:
|
| 82 |
+
return False
|
| 83 |
+
def no_duplicates(pairs):
|
| 84 |
+
result = {}
|
| 85 |
+
for k, v in pairs:
|
| 86 |
+
if k in result:
|
| 87 |
+
raise ValueError('duplicate JSON key')
|
| 88 |
+
result[k] = v
|
| 89 |
+
return result
|
| 90 |
+
try:
|
| 91 |
+
return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates)
|
| 92 |
+
except (ValueError, TypeError):
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def docker_network_equal(expected, value):
|
| 97 |
+
tokens = argv(value)
|
| 98 |
+
return tokens in (['--network', 'none'], ['--network=none'])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def zar_amount(value):
|
| 102 |
+
if not isinstance(value, str):
|
| 103 |
+
return None
|
| 104 |
+
m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I)
|
| 105 |
+
if not m:
|
| 106 |
+
return None
|
| 107 |
+
number = m.group(1)
|
| 108 |
+
if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number):
|
| 109 |
+
return None
|
| 110 |
+
try:
|
| 111 |
+
amount = Decimal(number.replace(',', ''))
|
| 112 |
+
except InvalidOperation:
|
| 113 |
+
return None
|
| 114 |
+
return amount * (Decimal(1000000) if m.group(2) else 1)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def zar_equal(expected, value):
|
| 118 |
+
return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def rust_attribute_equal(expected, value):
|
| 122 |
+
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
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def header_equal(expected, value):
|
| 126 |
+
return isinstance(value, str) and value.casefold() == expected.casefold()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def zero_arg_js_equal(expected, value):
|
| 130 |
+
name = expected[:-2]
|
| 131 |
+
return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
RESPONSE_RULES = {
|
| 135 |
+
'82e94ae96e04ff71_q1': {'q1': convex_equal},
|
| 136 |
+
'df978907fa6f0eea_q1': {'q1': docker_network_equal},
|
| 137 |
+
'dee0c878f5707477_q1': {'q1': command_equal},
|
| 138 |
+
'c51259d0062454b2_q1': {'q1': command_equal},
|
| 139 |
+
'd25a8956477141f2_q1': {'q2': zar_equal},
|
| 140 |
+
'719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal},
|
| 141 |
+
'a4926e403c8165e9_q1': {'q2': header_equal},
|
| 142 |
+
'2b3bd5786727f2fb_q1': {'q1': command_equal},
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def dashboard_contract(evaluator, candidate, objective):
|
| 147 |
+
root = Path(candidate)
|
| 148 |
+
path = evaluator['reference_files'][0]['path']
|
| 149 |
+
try:
|
| 150 |
+
text = (root / path).read_text()
|
| 151 |
+
except (OSError, UnicodeError):
|
| 152 |
+
return False
|
| 153 |
+
lines = objective._shell_lines(text)
|
| 154 |
+
# Public contract explicitly says no other commands/flags. Single quotes
|
| 155 |
+
# would suppress environment expansion; only the correctly quoted form counts.
|
| 156 |
+
return (len(lines) == 2 and
|
| 157 |
+
re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and
|
| 158 |
+
re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def install(task):
|
| 162 |
+
import objective_evaluators as objective
|
| 163 |
+
import verifiers
|
| 164 |
+
task_id = task['query_id']
|
| 165 |
+
original_verify = verifiers.verify
|
| 166 |
+
original_matcher = objective._shell_command_matches
|
| 167 |
+
objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1')
|
| 168 |
+
|
| 169 |
+
def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None):
|
| 170 |
+
if evaluator.get('type') == 'workspace_objective':
|
| 171 |
+
# A text occurrence after exit/return, in echo output or within a
|
| 172 |
+
# non-executed branch does not prove the requested command runs.
|
| 173 |
+
grouped = {}
|
| 174 |
+
for check in evaluator.get('checks', []):
|
| 175 |
+
if check.get('type') == 'shell_command':
|
| 176 |
+
grouped.setdefault(check['path'], []).append(check['value'])
|
| 177 |
+
for path, expected_commands in grouped.items():
|
| 178 |
+
try:
|
| 179 |
+
text = (Path(solver_output) / path).read_text()
|
| 180 |
+
invocations = objective.shell_invocations(text)
|
| 181 |
+
for expected_command in expected_commands:
|
| 182 |
+
tokens = argv(expected_command)
|
| 183 |
+
if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]):
|
| 184 |
+
continue # Required scalar assignment is checked by original rubric.
|
| 185 |
+
if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations):
|
| 186 |
+
return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command}
|
| 187 |
+
except (OSError, UnicodeError, ValueError):
|
| 188 |
+
return False, {'error': 'cannot inspect required shell artifact', 'path': path}
|
| 189 |
+
if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective):
|
| 190 |
+
return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'}
|
| 191 |
+
|
| 192 |
+
# R10: obligations apply to actual invocation nodes, not substrings.
|
| 193 |
+
if evaluator.get('type')=='workspace_objective' and task_id in R10_ANY_FAILURE:
|
| 194 |
+
for path in {c['path']for c in evaluator.get('checks',[])if c.get('type')=='shell_command'}:
|
| 195 |
+
try:nodes=objective.shell_invocations((Path(solver_output)/path).read_text())
|
| 196 |
+
except (OSError,UnicodeError,ValueError):return False,{'error':'cannot read shell artifact'}
|
| 197 |
+
if not nodes or any(not node['fail_fast']for node in nodes):return False,{'error':'every executed command must propagate failure','path':path}
|
| 198 |
+
if evaluator.get('type')=='workspace_objective' and task_id=='af4438bc4d445682_q1':
|
| 199 |
+
for path in {c['path']for c in evaluator.get('checks',[])if c.get('type')=='shell_command'}:
|
| 200 |
+
nodes=objective.shell_invocations((Path(solver_output)/path).read_text())
|
| 201 |
+
count=sum(1 for node in nodes if objective._shell_command_matches('x-openapi-cli get:/2/users/me',node['command']))
|
| 202 |
+
if count!=1:return False,{'error':'public single profile read requires exactly one invocation','count':count}
|
| 203 |
+
normalizations = []
|
| 204 |
+
if task_id in RESPONSE_RULES:
|
| 205 |
+
try:
|
| 206 |
+
predicted = verifiers._json_value(solver_output)
|
| 207 |
+
gold = gt_answer
|
| 208 |
+
if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict):
|
| 209 |
+
for key, comparator in RESPONSE_RULES[task_id].items():
|
| 210 |
+
value = predicted['answers'].get(key)
|
| 211 |
+
expected = gold['answers'][key]
|
| 212 |
+
if value != expected and comparator(expected, value):
|
| 213 |
+
predicted['answers'][key] = expected
|
| 214 |
+
normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected})
|
| 215 |
+
solver_output = json.dumps(predicted)
|
| 216 |
+
except (KeyError, ValueError, TypeError):
|
| 217 |
+
pass # Preserve original malformed-answer rejection.
|
| 218 |
+
if task_id == '59f410a185c510f3_q1':
|
| 219 |
+
path = evaluator['reference_files'][0]['path']
|
| 220 |
+
try:
|
| 221 |
+
file_path = Path(solver_output) / path
|
| 222 |
+
predicted = json.loads(file_path.read_text())
|
| 223 |
+
expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact')
|
| 224 |
+
if isinstance(predicted, dict):
|
| 225 |
+
for widget in ('chart', 'banner'):
|
| 226 |
+
row = predicted.get(widget)
|
| 227 |
+
if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')):
|
| 228 |
+
if row.get('hydrate') != expected[widget]['hydrate']:
|
| 229 |
+
normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']})
|
| 230 |
+
row['hydrate'] = expected[widget]['hydrate']
|
| 231 |
+
if normalizations:
|
| 232 |
+
with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary:
|
| 233 |
+
view = Path(temporary) / 'candidate'
|
| 234 |
+
shutil.copytree(solver_output, view, symlinks=True)
|
| 235 |
+
copied = view / path
|
| 236 |
+
resolved = copied.resolve()
|
| 237 |
+
if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink():
|
| 238 |
+
return False, {'error': 'candidate output parent symlink escapes temporary comparison view'}
|
| 239 |
+
if copied.is_symlink():
|
| 240 |
+
copied.unlink() # Do not write through a frozen source symlink.
|
| 241 |
+
copied.write_text(json.dumps(predicted))
|
| 242 |
+
passed, details = original_verify(evaluator, gt_answer, str(view), material_paths)
|
| 243 |
+
if isinstance(details, dict):
|
| 244 |
+
details['equivalence_normalizations'] = normalizations
|
| 245 |
+
return passed, details
|
| 246 |
+
except (KeyError, ValueError, TypeError, OSError, UnicodeError):
|
| 247 |
+
pass
|
| 248 |
+
passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths)
|
| 249 |
+
if normalizations and isinstance(details, dict):
|
| 250 |
+
details['equivalence_normalizations'] = normalizations
|
| 251 |
+
return passed, details
|
| 252 |
+
|
| 253 |
+
verifiers.verify = repaired_verify
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/grading/verified_config.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b82f51497260fc6ea69029be5b131dcdc58e7788e31a6464aae42c076500b30
|
| 3 |
+
size 4094
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/instruction.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
I use the shaon self-service CLI to manage my Hilan employer portal account. I need a shell script at output/get_payslip.sh that downloads my payslip for month 2026-03 and then views/opens that same month's payslip locally so I can verify it. Write it as a straight-line script: all commands at top level, no control flow. If any command fails, the script must stop immediately and exit with a nonzero status — don't continue on to the next command or suppress the failure.
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/SKILL.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: shaon
|
| 3 |
+
version: 0.8.3
|
| 4 |
+
description: >
|
| 5 |
+
Personal attendance, payslip, salary, and related self-service tasks on the
|
| 6 |
+
user's own Hilan account. Trigger on shaon, attendance, clock in/out, payslip,
|
| 7 |
+
salary slip, work hours, תלוש, תלוש שכר, משכורת, דוח נוכחות, corrections log,
|
| 8 |
+
forgot to clock in, forgot to report, or any request about the user's own
|
| 9 |
+
Israeli employer self-service portal.
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# Shaon
|
| 13 |
+
|
| 14 |
+
Claude Code skill for the `shaon` repo and binary.
|
| 15 |
+
|
| 16 |
+
## Tool Selection
|
| 17 |
+
|
| 18 |
+
- Prefer the **MCP server** when a tool already covers the domain operation.
|
| 19 |
+
- Fall back to the **CLI** for local-machine or interactive operations:
|
| 20 |
+
`auth`, `payroll payslip view`, `reports show`, `cache refresh attendance-types`,
|
| 21 |
+
`serve`, and `completions`.
|
| 22 |
+
- Use this **skill** to pick the right surface, the right command/tool, and the
|
| 23 |
+
right safety flow.
|
| 24 |
+
|
| 25 |
+
## Human-attested writes
|
| 26 |
+
|
| 27 |
+
All write commands (`attendance report today/day/range`, `attendance auto-fill`, `attendance resolve`) submit under the user's identity against their real employer's system. When driving these, ALWAYS:
|
| 28 |
+
|
| 29 |
+
1. Run with `--dry-run` (the default) first.
|
| 30 |
+
2. Show the resulting preview to the user.
|
| 31 |
+
3. Require the user to explicitly confirm in the conversation before rerunning with `--execute`.
|
| 32 |
+
|
| 33 |
+
Never autonomously rerun a write with `--execute`. Writes must be treated as user-authorized actions and must not be submitted without explicit user confirmation.
|
| 34 |
+
|
| 35 |
+
## CLI Entry Point
|
| 36 |
+
|
| 37 |
+
If working from a repo checkout, prefer:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
scripts/run.sh <command> [args]
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
If installed globally:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
shaon <command> [args]
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## First-Time Setup
|
| 50 |
+
|
| 51 |
+
Create `~/.shaon/config.toml`:
|
| 52 |
+
|
| 53 |
+
```toml
|
| 54 |
+
subdomain = "mycompany"
|
| 55 |
+
username = "123456789"
|
| 56 |
+
payslip_folder = "/path/to/payslips" # optional
|
| 57 |
+
payslip_format = "%Y-%m.pdf" # optional
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Then authenticate:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
shaon auth
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
If stored credentials are stale and you want a deterministic refresh prompt:
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
shaon auth --force-prompt
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## Pick The Right Read Command
|
| 73 |
+
|
| 74 |
+
| User intent | Use |
|
| 75 |
+
|-------------|-----|
|
| 76 |
+
| "what's my current month state?" | `shaon attendance overview --json` |
|
| 77 |
+
| "show me the raw calendar / what did Hilan record per day?" | `shaon attendance status --month YYYY-MM` |
|
| 78 |
+
| "what errors do I need to fix?" | `shaon attendance errors --month YYYY-MM` |
|
| 79 |
+
| "what attendance types can I report?" | `shaon attendance types` |
|
| 80 |
+
| "what absence symbols mean?" | `shaon attendance absences` |
|
| 81 |
+
| "show the analyzed hours sheet" | `shaon reports sheet` |
|
| 82 |
+
| "show the manual correction log / audit trail" | `shaon reports corrections` |
|
| 83 |
+
| "show a named Hilan report page" | `shaon reports show <name>` |
|
| 84 |
+
| "download my payslip" | `shaon payroll payslip download --month YYYY-MM` |
|
| 85 |
+
| "open my payslip locally" | `shaon payroll payslip view --month YYYY-MM` |
|
| 86 |
+
| "how much did I earn recently?" | `shaon payroll salary --months N` |
|
| 87 |
+
|
| 88 |
+
`attendance overview` is usually the best first move for an agent because it bundles identity, summary, errors, missing days, and suggested actions.
|
| 89 |
+
|
| 90 |
+
JSON contract notes:
|
| 91 |
+
|
| 92 |
+
- `attendance status --json` returns `{ month, employee_id, days[] }` with `day_name`, `entry_time`, `exit_time`, `attendance_type`, `total_hours`, `has_error`, `error_message`, and `source`.
|
| 93 |
+
- `attendance overview --json` returns `missing_days` as `{ date, day_name }` objects.
|
| 94 |
+
- `suggested_actions` is keyed by `kind`; fields are top-level, not nested inside a generic `params` object.
|
| 95 |
+
- `attendance overview --json --detailed` adds a `days[]` array using the same schema as `attendance status --json`.
|
| 96 |
+
|
| 97 |
+
## Write Commands
|
| 98 |
+
|
| 99 |
+
### Explicit reporting
|
| 100 |
+
|
| 101 |
+
| Intent | Command |
|
| 102 |
+
|--------|---------|
|
| 103 |
+
| clock in now | `shaon attendance report today --in` |
|
| 104 |
+
| clock out now | `shaon attendance report today --out` |
|
| 105 |
+
| report one explicit day | `shaon attendance report day YYYY-MM-DD --type "regular" --hours 09:00-18:00` |
|
| 106 |
+
| report a range | `shaon attendance report range --from YYYY-MM-DD --to YYYY-MM-DD --type "regular" --hours 09:00-18:00` |
|
| 107 |
+
| auto-fill missing days in a month | `shaon attendance auto-fill --month YYYY-MM --type "regular" --hours 09:00-18:00` |
|
| 108 |
+
| resolve an existing error day | `shaon attendance resolve YYYY-MM-DD --type "regular" --hours 09:00-18:00` |
|
| 109 |
+
|
| 110 |
+
### Safety Model
|
| 111 |
+
|
| 112 |
+
- Every write is **preview-only by default**.
|
| 113 |
+
- The agent should show the preview summary to the user before rerunning with `--execute` or `execute: true`.
|
| 114 |
+
- The agent must wait for explicit user confirmation before any live submit.
|
| 115 |
+
- `attendance report range` and `attendance auto-fill` skip Fri/Sat unless explicitly overridden.
|
| 116 |
+
- `attendance auto-fill` is capped at `--max-days 10` by default to prevent accidental bulk edits.
|
| 117 |
+
|
| 118 |
+
## MCP Coverage
|
| 119 |
+
|
| 120 |
+
Current MCP tools cover:
|
| 121 |
+
|
| 122 |
+
- `shaon_status`
|
| 123 |
+
- `shaon_errors`
|
| 124 |
+
- `shaon_types`
|
| 125 |
+
- `shaon_clock_in`
|
| 126 |
+
- `shaon_clock_out`
|
| 127 |
+
- `shaon_fill`
|
| 128 |
+
- `shaon_auto_fill`
|
| 129 |
+
- `shaon_resolve`
|
| 130 |
+
- `shaon_payslip_download`
|
| 131 |
+
- `shaon_salary`
|
| 132 |
+
- `shaon_sheet`
|
| 133 |
+
- `shaon_corrections`
|
| 134 |
+
- `shaon_absences`
|
| 135 |
+
- `shaon_overview`
|
| 136 |
+
|
| 137 |
+
CLI-only features:
|
| 138 |
+
|
| 139 |
+
- `shaon auth`
|
| 140 |
+
- `shaon payroll payslip view`
|
| 141 |
+
- `shaon reports show <name>`
|
| 142 |
+
- `shaon cache refresh attendance-types`
|
| 143 |
+
- `shaon serve`
|
| 144 |
+
- `shaon completions`
|
| 145 |
+
|
| 146 |
+
## Agent Workflows
|
| 147 |
+
|
| 148 |
+
### Review the month first
|
| 149 |
+
|
| 150 |
+
```bash
|
| 151 |
+
shaon attendance overview --json
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
### Fix an attendance error safely
|
| 155 |
+
|
| 156 |
+
```bash
|
| 157 |
+
shaon attendance errors --month 2026-04 --json
|
| 158 |
+
shaon attendance resolve 2026-04-09 --type "regular" --hours 09:00-18:00
|
| 159 |
+
# After explicit user confirmation:
|
| 160 |
+
shaon attendance resolve 2026-04-09 --type "regular" --hours 09:00-18:00 --execute
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
### Fill a missing range safely
|
| 164 |
+
|
| 165 |
+
```bash
|
| 166 |
+
shaon attendance report range --from 2026-04-01 --to 2026-04-05 --type "regular" --hours 09:00-18:00
|
| 167 |
+
# After explicit user confirmation:
|
| 168 |
+
shaon attendance report range --from 2026-04-01 --to 2026-04-05 --type "regular" --hours 09:00-18:00 --execute
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
### Hebrew payslip workflow
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
shaon payroll payslip download --month 2026-03
|
| 175 |
+
shaon payroll payslip view --month 2026-03
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
### Sensitive recovery command
|
| 179 |
+
|
| 180 |
+
`shaon payroll payslip password --force-sensitive-output` prints the current Hilan account password in plaintext to standard output. It does not recover historical passwords used for PDFs encrypted before a password change. Output may be captured by shells, terminals, logs, remote sessions, screenshots, and agent transcripts. Run it only on a private interactive terminal you control.
|
| 181 |
+
|
| 182 |
+
## Troubleshooting
|
| 183 |
+
|
| 184 |
+
- **CAPTCHA**: the user must solve it in the browser first.
|
| 185 |
+
- **Type resolution fails**: run `shaon cache refresh attendance-types` or pass the numeric type code directly.
|
| 186 |
+
- **Session expired or stale stored credentials**: rerun `shaon auth --force-prompt` to verify and replace the stored password.
|
| 187 |
+
|
| 188 |
+
## Further Reading
|
| 189 |
+
|
| 190 |
+
- [README.md](../../README.md)
|
| 191 |
+
- [ARCHITECTURE.md](../../ARCHITECTURE.md)
|
| 192 |
+
- [PROTOCOL.md](../../PROTOCOL.md)
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/evals/evals.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e21176421d761837fb419461338319c6c57ce0f9defe07e78ee9a61b9d14e2d4
|
| 3 |
+
size 1279
|
benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/task.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:61eb165900ff1cec8c169cf0a7a84c48f79f29f11a0fb56bcb75001b123a4d9d
|
| 3 |
+
size 1695
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37
|
| 3 |
+
size 83
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_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/8fe6482e81e3ebba_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/8fe6482e81e3ebba_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/8fe6482e81e3ebba_q1/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
root=Path(__file__).resolve().parent
|
| 5 |
+
sys.path.insert(0,str(root/'legacy_tests'))
|
| 6 |
+
from evaluate import evaluate
|
| 7 |
+
t=json.loads((root/'legacy-task.json').read_text())
|
| 8 |
+
mode=t['workspace']['candidate_mode']
|
| 9 |
+
r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
|
| 10 |
+
if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
|
| 11 |
+
if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
|
| 12 |
+
print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy-task.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b2e6ed5235643f8b2766addd315e07145fabcf203779c4ccd18560d23e63125
|
| 3 |
+
size 3885
|
benchmarks/skillbench-venus-e/t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 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/8fe6482e81e3ebba_q1/evaluator/legacy_tests/objective_evaluators.py
ADDED
|
@@ -0,0 +1,1309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Composable objective evaluators for response and workspace tasks.
|
| 2 |
+
|
| 3 |
+
Task semantics are deliberately *not* enumerated here. A task may describe any
|
| 4 |
+
real user goal; verified membership depends on whether its deliverables compile
|
| 5 |
+
to one of these small, trusted evaluator primitives and pass counterfactual
|
| 6 |
+
execution. This keeps the objective surface closed and auditable without
|
| 7 |
+
turning the benchmark's task ontology into a closed template list.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import ast
|
| 12 |
+
import copy
|
| 13 |
+
import builtins
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import re
|
| 17 |
+
import shlex
|
| 18 |
+
import subprocess
|
| 19 |
+
import tempfile
|
| 20 |
+
import tomllib
|
| 21 |
+
from pathlib import Path, PurePosixPath
|
| 22 |
+
try:
|
| 23 |
+
from .shell_invocations import shell_invocations
|
| 24 |
+
except ImportError:
|
| 25 |
+
from shell_invocations import shell_invocations
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
WORKSPACE_EVALUATOR = "workspace_objective"
|
| 29 |
+
WORKSPACE_EVALUATOR_VERSION = 15
|
| 30 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
| 31 |
+
ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
|
| 32 |
+
_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ObjectiveEvaluatorError(ValueError):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def safe_relative_path(value):
|
| 40 |
+
"""Return a normalized portable relative path or fail closed."""
|
| 41 |
+
text = str(value or "").strip().replace("\\", "/")
|
| 42 |
+
path = PurePosixPath(text)
|
| 43 |
+
if (not text or text.startswith("/") or path.is_absolute() or
|
| 44 |
+
any(part in {"", ".", ".."} for part in path.parts)):
|
| 45 |
+
raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
|
| 46 |
+
if len(path.parts) > 8 or len(text) > 180:
|
| 47 |
+
raise ObjectiveEvaluatorError("workspace path is too deep or long")
|
| 48 |
+
return path.as_posix()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _json_value(value):
|
| 52 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 53 |
+
return value
|
| 54 |
+
return json.loads(str(value))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _canonical(value):
|
| 58 |
+
if isinstance(value, dict):
|
| 59 |
+
return {key: _canonical(value[key]) for key in sorted(value)}
|
| 60 |
+
if isinstance(value, list):
|
| 61 |
+
return [_canonical(item) for item in value]
|
| 62 |
+
return value
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _file_content(item):
|
| 66 |
+
fmt = str(item.get("format") or "").casefold()
|
| 67 |
+
content = item.get("content")
|
| 68 |
+
if fmt == "json":
|
| 69 |
+
parsed = _json_value(content)
|
| 70 |
+
return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 71 |
+
if not isinstance(content, str):
|
| 72 |
+
raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
|
| 73 |
+
return content.rstrip() + "\n"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _ast_name(node):
|
| 77 |
+
if isinstance(node, ast.Name):
|
| 78 |
+
return node.id
|
| 79 |
+
if isinstance(node, ast.Attribute):
|
| 80 |
+
parent = _ast_name(node.value)
|
| 81 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 82 |
+
return ""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _python_inventory(text):
|
| 86 |
+
tree = ast.parse(text)
|
| 87 |
+
imports, calls = set(), set()
|
| 88 |
+
for node in ast.walk(tree):
|
| 89 |
+
if isinstance(node, ast.Import):
|
| 90 |
+
imports.update(alias.name for alias in node.names)
|
| 91 |
+
elif isinstance(node, ast.ImportFrom):
|
| 92 |
+
module = node.module or ""
|
| 93 |
+
for alias in node.names:
|
| 94 |
+
imports.add(f"{module}.{alias.name}".strip("."))
|
| 95 |
+
elif isinstance(node, ast.Call):
|
| 96 |
+
name = _ast_name(node.func)
|
| 97 |
+
if name:
|
| 98 |
+
calls.add(name)
|
| 99 |
+
return imports, calls
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _literal_value(node, constants=None):
|
| 103 |
+
constants = constants or {}
|
| 104 |
+
if isinstance(node, ast.Constant) and isinstance(
|
| 105 |
+
node.value, (str, int, float, bool, type(None))):
|
| 106 |
+
return node.value
|
| 107 |
+
if isinstance(node, ast.Name) and node.id in constants:
|
| 108 |
+
return constants[node.id]
|
| 109 |
+
if isinstance(node, (ast.Tuple, ast.List)):
|
| 110 |
+
values = [_literal_value(item, constants) for item in node.elts]
|
| 111 |
+
if all(value is not _UNRESOLVED for value in values):
|
| 112 |
+
return tuple(values) if isinstance(node, ast.Tuple) else values
|
| 113 |
+
return _UNRESOLVED
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
_UNRESOLVED = object()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _python_semantics(text):
|
| 120 |
+
tree = ast.parse(text)
|
| 121 |
+
_annotate_assignment_contexts(tree)
|
| 122 |
+
imports, calls = _python_inventory(text)
|
| 123 |
+
constants = {}
|
| 124 |
+
for node in tree.body:
|
| 125 |
+
name = None
|
| 126 |
+
value_node = None
|
| 127 |
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 128 |
+
isinstance(node.targets[0], ast.Name)):
|
| 129 |
+
name, value_node = node.targets[0].id, node.value
|
| 130 |
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
| 131 |
+
name, value_node = node.target.id, node.value
|
| 132 |
+
if name and value_node is not None:
|
| 133 |
+
value = _literal_value(value_node, constants)
|
| 134 |
+
if value is not _UNRESOLVED:
|
| 135 |
+
constants[name] = value
|
| 136 |
+
elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 137 |
+
isinstance(node.targets[0], (ast.Tuple, ast.List)) and
|
| 138 |
+
isinstance(node.value, (ast.Tuple, ast.List)) and
|
| 139 |
+
len(node.targets[0].elts) == len(node.value.elts)):
|
| 140 |
+
# Treat ordinary constant unpacking as semantically equivalent to
|
| 141 |
+
# separate assignments. Generated implementation files commonly
|
| 142 |
+
# use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
|
| 143 |
+
# test formatting rather than the required repository values.
|
| 144 |
+
for target, value_node in zip(node.targets[0].elts, node.value.elts):
|
| 145 |
+
if not isinstance(target, ast.Name):
|
| 146 |
+
continue
|
| 147 |
+
value = _literal_value(value_node, constants)
|
| 148 |
+
if value is not _UNRESOLVED:
|
| 149 |
+
constants[target.id] = value
|
| 150 |
+
call_nodes = []
|
| 151 |
+
for node in ast.walk(tree):
|
| 152 |
+
if isinstance(node, ast.Call):
|
| 153 |
+
call_nodes.append((_ast_name(node.func), node))
|
| 154 |
+
return imports, calls, constants, call_nodes
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _python_resolved_call_nodes(text):
|
| 158 |
+
"""Resolve call targets through imports and simple constructor bindings.
|
| 159 |
+
|
| 160 |
+
The evaluator intentionally supports a small static subset: imports,
|
| 161 |
+
local definitions, direct aliases, and names assigned from calls. That is
|
| 162 |
+
enough to recognize semantic equivalents such as ``import datetime`` vs
|
| 163 |
+
``from datetime import timedelta as td`` and instance-variable renames,
|
| 164 |
+
without pretending to perform general Python type inference.
|
| 165 |
+
"""
|
| 166 |
+
tree = ast.parse(text)
|
| 167 |
+
_annotate_assignment_contexts(tree)
|
| 168 |
+
bindings = {}
|
| 169 |
+
nodes = sorted(ast.walk(tree), key=lambda node: (
|
| 170 |
+
int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
|
| 171 |
+
|
| 172 |
+
def resolve(node):
|
| 173 |
+
if isinstance(node, ast.Name):
|
| 174 |
+
return bindings.get(node.id, node.id)
|
| 175 |
+
if isinstance(node, ast.Attribute):
|
| 176 |
+
parent = resolve(node.value)
|
| 177 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 178 |
+
return ""
|
| 179 |
+
|
| 180 |
+
# A few fixed-point passes cover aliases declared after an imported name
|
| 181 |
+
# and ordinary ``client = Client()`` instance construction.
|
| 182 |
+
for _ in range(4):
|
| 183 |
+
changed = False
|
| 184 |
+
for node in nodes:
|
| 185 |
+
updates = {}
|
| 186 |
+
if isinstance(node, ast.Import):
|
| 187 |
+
for alias in node.names:
|
| 188 |
+
local = alias.asname or alias.name.split(".")[0]
|
| 189 |
+
updates[local] = alias.name if alias.asname else local
|
| 190 |
+
elif isinstance(node, ast.ImportFrom):
|
| 191 |
+
module = node.module or ""
|
| 192 |
+
for alias in node.names:
|
| 193 |
+
if alias.name == "*":
|
| 194 |
+
continue
|
| 195 |
+
updates[alias.asname or alias.name] = \
|
| 196 |
+
f"{module}.{alias.name}".strip(".")
|
| 197 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 198 |
+
ast.ClassDef)):
|
| 199 |
+
updates[node.name] = "__local__." + node.name
|
| 200 |
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
| 201 |
+
targets = (node.targets if isinstance(node, ast.Assign)
|
| 202 |
+
else [node.target])
|
| 203 |
+
value = node.value
|
| 204 |
+
if isinstance(value, ast.Call):
|
| 205 |
+
provenance = resolve(value.func)
|
| 206 |
+
elif isinstance(value, (ast.Name, ast.Attribute)):
|
| 207 |
+
provenance = resolve(value)
|
| 208 |
+
else:
|
| 209 |
+
provenance = ""
|
| 210 |
+
if provenance:
|
| 211 |
+
for target in targets:
|
| 212 |
+
if isinstance(target, ast.Name):
|
| 213 |
+
updates[target.id] = provenance
|
| 214 |
+
for name, value in updates.items():
|
| 215 |
+
if bindings.get(name) != value:
|
| 216 |
+
bindings[name] = value
|
| 217 |
+
changed = True
|
| 218 |
+
if not changed:
|
| 219 |
+
break
|
| 220 |
+
return [(_ast_name(node.func), resolve(node.func), node)
|
| 221 |
+
for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _call_name_matches(observed, expected):
|
| 225 |
+
return observed == expected or observed.endswith("." + expected)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _objective_call_targets(kind, check, resolved_calls, constants):
|
| 229 |
+
"""Return canonical targets satisfying one already-validated call check."""
|
| 230 |
+
function = str(check.get("function") or check.get("value") or "")
|
| 231 |
+
targets = set()
|
| 232 |
+
for name, target, node in resolved_calls:
|
| 233 |
+
if not _call_name_matches(name, function):
|
| 234 |
+
continue
|
| 235 |
+
if kind == "python_call_literal" and not _node_contains_literal(
|
| 236 |
+
node, check.get("value"), constants):
|
| 237 |
+
continue
|
| 238 |
+
if kind == "python_call_keyword_literal" and not _call_keyword_matches(
|
| 239 |
+
node, str(check.get("keyword") or ""), check.get("value"),
|
| 240 |
+
constants):
|
| 241 |
+
continue
|
| 242 |
+
if kind == "python_call_signature" and not _call_signature_matches(
|
| 243 |
+
node, check.get("arguments") or [],
|
| 244 |
+
check.get("keywords") or {}, constants,
|
| 245 |
+
check.get("argument_expressions") or [],
|
| 246 |
+
check.get("keyword_expressions") or {},
|
| 247 |
+
check.get("assignment")):
|
| 248 |
+
continue
|
| 249 |
+
if target:
|
| 250 |
+
targets.add(target)
|
| 251 |
+
return targets
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def python_unbound_call_roots(text):
|
| 255 |
+
"""Return call-root names that have no static binding in the module.
|
| 256 |
+
|
| 257 |
+
Objective call checks must not accept a syntactically valid file that will
|
| 258 |
+
immediately raise ``NameError``. This deliberately proves only the
|
| 259 |
+
conservative prerequisite that a root is imported, assigned, declared,
|
| 260 |
+
passed as an argument, or provided by Python builtins; it does not claim to
|
| 261 |
+
execute or type-check the program.
|
| 262 |
+
"""
|
| 263 |
+
tree = ast.parse(text)
|
| 264 |
+
bound = set(dir(builtins))
|
| 265 |
+
for node in ast.walk(tree):
|
| 266 |
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
| 267 |
+
bound.add(node.id)
|
| 268 |
+
elif isinstance(node, ast.arg):
|
| 269 |
+
bound.add(node.arg)
|
| 270 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 271 |
+
ast.ClassDef)):
|
| 272 |
+
bound.add(node.name)
|
| 273 |
+
elif isinstance(node, ast.Import):
|
| 274 |
+
for alias in node.names:
|
| 275 |
+
bound.add(alias.asname or alias.name.split(".")[0])
|
| 276 |
+
elif isinstance(node, ast.ImportFrom):
|
| 277 |
+
for alias in node.names:
|
| 278 |
+
bound.add(alias.asname or alias.name)
|
| 279 |
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
| 280 |
+
bound.add(node.name)
|
| 281 |
+
unbound = set()
|
| 282 |
+
for node in ast.walk(tree):
|
| 283 |
+
if not isinstance(node, ast.Call):
|
| 284 |
+
continue
|
| 285 |
+
root = node.func
|
| 286 |
+
while isinstance(root, ast.Attribute):
|
| 287 |
+
root = root.value
|
| 288 |
+
if isinstance(root, ast.Name) and root.id not in bound:
|
| 289 |
+
unbound.add(root.id)
|
| 290 |
+
return sorted(unbound)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _node_contains_literal(node, expected, constants):
|
| 294 |
+
for child in ast.walk(node):
|
| 295 |
+
value = _literal_value(child, constants)
|
| 296 |
+
if value is _UNRESOLVED:
|
| 297 |
+
continue
|
| 298 |
+
if value == expected:
|
| 299 |
+
return True
|
| 300 |
+
if isinstance(value, (list, tuple)) and expected in value:
|
| 301 |
+
return True
|
| 302 |
+
return False
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _call_keyword_matches(node, keyword, expected, constants):
|
| 306 |
+
"""Return whether a direct call keyword resolves to the expected scalar."""
|
| 307 |
+
return any(
|
| 308 |
+
item.arg == keyword and _literal_value(item.value, constants) == expected
|
| 309 |
+
for item in getattr(node, "keywords", [])
|
| 310 |
+
if item.arg is not None)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _portable_literal(value):
|
| 314 |
+
if isinstance(value, tuple):
|
| 315 |
+
return [_portable_literal(item) for item in value]
|
| 316 |
+
if isinstance(value, list):
|
| 317 |
+
return [_portable_literal(item) for item in value]
|
| 318 |
+
return value
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _expression_text(node):
|
| 322 |
+
"""Return a formatting-independent, non-executed Python expression."""
|
| 323 |
+
return ast.unparse(node).strip()
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _expression_fingerprint(value):
|
| 327 |
+
if not isinstance(value, str) or not value.strip() or len(value) > 500:
|
| 328 |
+
return None
|
| 329 |
+
try:
|
| 330 |
+
tree = ast.parse(value, mode="eval")
|
| 331 |
+
except SyntaxError:
|
| 332 |
+
return None
|
| 333 |
+
return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _expression_matches(node, expected):
|
| 337 |
+
fingerprint = _expression_fingerprint(expected)
|
| 338 |
+
return bool(fingerprint and ast.dump(
|
| 339 |
+
node, annotate_fields=True, include_attributes=False) == fingerprint)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _annotate_assignment_contexts(tree):
|
| 343 |
+
"""Attach one conservative simple-assignment context to nested calls."""
|
| 344 |
+
for statement in ast.walk(tree):
|
| 345 |
+
target, value = None, None
|
| 346 |
+
if (isinstance(statement, ast.Assign) and
|
| 347 |
+
len(statement.targets) == 1 and
|
| 348 |
+
isinstance(statement.targets[0], ast.Name)):
|
| 349 |
+
target, value = statement.targets[0].id, statement.value
|
| 350 |
+
elif (isinstance(statement, ast.AnnAssign) and
|
| 351 |
+
isinstance(statement.target, ast.Name) and
|
| 352 |
+
statement.value is not None):
|
| 353 |
+
target, value = statement.target.id, statement.value
|
| 354 |
+
if not target or value is None:
|
| 355 |
+
continue
|
| 356 |
+
context = {"target": target, "expression": _expression_text(value)}
|
| 357 |
+
for child in ast.walk(value):
|
| 358 |
+
if isinstance(child, ast.Call):
|
| 359 |
+
setattr(child, "_mybench_assignment", context)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _call_signature(node, constants):
|
| 363 |
+
arguments = []
|
| 364 |
+
argument_expressions = []
|
| 365 |
+
for index, argument in enumerate(getattr(node, "args", [])):
|
| 366 |
+
value = _literal_value(argument, constants)
|
| 367 |
+
if value is not _UNRESOLVED:
|
| 368 |
+
arguments.append({"index": index,
|
| 369 |
+
"value": _portable_literal(value)})
|
| 370 |
+
else:
|
| 371 |
+
argument_expressions.append({
|
| 372 |
+
"index": index, "expression": _expression_text(argument)})
|
| 373 |
+
keywords = {}
|
| 374 |
+
keyword_expressions = {}
|
| 375 |
+
for keyword in getattr(node, "keywords", []):
|
| 376 |
+
if keyword.arg is None:
|
| 377 |
+
continue
|
| 378 |
+
value = _literal_value(keyword.value, constants)
|
| 379 |
+
if value is not _UNRESOLVED:
|
| 380 |
+
keywords[keyword.arg] = _portable_literal(value)
|
| 381 |
+
else:
|
| 382 |
+
keyword_expressions[keyword.arg] = _expression_text(keyword.value)
|
| 383 |
+
signature = {"arguments": arguments, "keywords": keywords,
|
| 384 |
+
"argument_expressions": argument_expressions,
|
| 385 |
+
"keyword_expressions": keyword_expressions}
|
| 386 |
+
assignment = getattr(node, "_mybench_assignment", None)
|
| 387 |
+
if isinstance(assignment, dict):
|
| 388 |
+
signature["assignment"] = dict(assignment)
|
| 389 |
+
return signature
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _call_signature_matches(node, arguments, keywords, constants,
|
| 393 |
+
argument_expressions=None,
|
| 394 |
+
keyword_expressions=None, assignment=None):
|
| 395 |
+
for expected in arguments or []:
|
| 396 |
+
index = expected.get("index")
|
| 397 |
+
if (not isinstance(index, int) or index < 0 or
|
| 398 |
+
index >= len(getattr(node, "args", []))):
|
| 399 |
+
return False
|
| 400 |
+
actual = _literal_value(node.args[index], constants)
|
| 401 |
+
if (actual is _UNRESOLVED or
|
| 402 |
+
_canonical(_portable_literal(actual)) !=
|
| 403 |
+
_canonical(expected.get("value"))):
|
| 404 |
+
return False
|
| 405 |
+
for keyword, expected in (keywords or {}).items():
|
| 406 |
+
if not _call_keyword_matches(node, keyword, expected, constants):
|
| 407 |
+
return False
|
| 408 |
+
for expected in argument_expressions or []:
|
| 409 |
+
index = expected.get("index")
|
| 410 |
+
if (not isinstance(index, int) or index < 0 or
|
| 411 |
+
index >= len(getattr(node, "args", [])) or
|
| 412 |
+
not _expression_matches(
|
| 413 |
+
node.args[index], expected.get("expression"))):
|
| 414 |
+
return False
|
| 415 |
+
node_keywords = {item.arg: item.value for item in
|
| 416 |
+
getattr(node, "keywords", []) if item.arg is not None}
|
| 417 |
+
for keyword, expected in (keyword_expressions or {}).items():
|
| 418 |
+
if (keyword not in node_keywords or
|
| 419 |
+
not _expression_matches(node_keywords[keyword], expected)):
|
| 420 |
+
return False
|
| 421 |
+
if assignment:
|
| 422 |
+
actual = getattr(node, "_mybench_assignment", None)
|
| 423 |
+
if (not isinstance(actual, dict) or
|
| 424 |
+
actual.get("target") != assignment.get("target") or
|
| 425 |
+
_expression_fingerprint(actual.get("expression")) !=
|
| 426 |
+
_expression_fingerprint(assignment.get("expression"))):
|
| 427 |
+
return False
|
| 428 |
+
return bool(arguments or keywords or argument_expressions or
|
| 429 |
+
keyword_expressions or assignment)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def python_call_literal_signatures(text, function, expected, keyword=None):
|
| 433 |
+
"""Return full literal signatures for matching reference call sites."""
|
| 434 |
+
_, _, constants, call_nodes = _python_semantics(text)
|
| 435 |
+
out = []
|
| 436 |
+
for name, node in call_nodes:
|
| 437 |
+
if not (name == function or name.endswith("." + function)):
|
| 438 |
+
continue
|
| 439 |
+
matches = (_call_keyword_matches(node, keyword, expected, constants)
|
| 440 |
+
if keyword else
|
| 441 |
+
_node_contains_literal(node, expected, constants))
|
| 442 |
+
if matches:
|
| 443 |
+
out.append(_call_signature(node, constants))
|
| 444 |
+
return out
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def python_signature_expression_coverage_issues(evaluator, requirements=None):
|
| 448 |
+
"""Detect anchored call expressions omitted by a static verifier.
|
| 449 |
+
|
| 450 |
+
Literal-only call checks used to silently discard non-literal positional
|
| 451 |
+
and keyword expressions from the same package-owned call. That allowed a
|
| 452 |
+
candidate to retain one easy literal while replacing the actual callback,
|
| 453 |
+
input binding, or argument tuple. Only expressions present in the
|
| 454 |
+
selected requirement text are required here; unrelated reference-file
|
| 455 |
+
context remains outside the objective contract.
|
| 456 |
+
"""
|
| 457 |
+
if not isinstance(evaluator, dict) or evaluator.get("type") != \
|
| 458 |
+
WORKSPACE_EVALUATOR:
|
| 459 |
+
return []
|
| 460 |
+
reference_files = {
|
| 461 |
+
str(item.get("path") or ""): str(item.get("content") or "")
|
| 462 |
+
for item in evaluator.get("reference_files") or []
|
| 463 |
+
if isinstance(item, dict)}
|
| 464 |
+
requirement_texts = [
|
| 465 |
+
re.sub(r"\s+", "", str(item.get("requirement") or ""))
|
| 466 |
+
for item in requirements or [] if isinstance(item, dict)]
|
| 467 |
+
issues = []
|
| 468 |
+
for check in evaluator.get("checks") or []:
|
| 469 |
+
if (not isinstance(check, dict) or
|
| 470 |
+
check.get("type") != "python_call_signature"):
|
| 471 |
+
continue
|
| 472 |
+
function = str(check.get("function") or "")
|
| 473 |
+
source = reference_files.get(str(check.get("path") or ""), "")
|
| 474 |
+
if not function or not source:
|
| 475 |
+
continue
|
| 476 |
+
try:
|
| 477 |
+
_, _, constants, call_nodes = _python_semantics(source)
|
| 478 |
+
except SyntaxError:
|
| 479 |
+
issues.append("Python signature reference content is invalid")
|
| 480 |
+
continue
|
| 481 |
+
matches = [node for name, node in call_nodes
|
| 482 |
+
if _call_name_matches(name, function) and
|
| 483 |
+
_call_signature_matches(
|
| 484 |
+
node, check.get("arguments") or [],
|
| 485 |
+
check.get("keywords") or {}, constants,
|
| 486 |
+
check.get("argument_expressions") or [],
|
| 487 |
+
check.get("keyword_expressions") or {},
|
| 488 |
+
check.get("assignment"))]
|
| 489 |
+
if len(matches) != 1:
|
| 490 |
+
issues.append(
|
| 491 |
+
"Python call signature does not identify one reference call")
|
| 492 |
+
continue
|
| 493 |
+
reference_signature = _call_signature(matches[0], constants)
|
| 494 |
+
function_tokens = {re.sub(r"\s+", "", function),
|
| 495 |
+
re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
|
| 496 |
+
|
| 497 |
+
def positional_is_anchored(expression):
|
| 498 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 499 |
+
return any(compact and compact in text and any(
|
| 500 |
+
token and token in text for token in function_tokens)
|
| 501 |
+
for text in requirement_texts)
|
| 502 |
+
|
| 503 |
+
def keyword_is_anchored(name, expression):
|
| 504 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 505 |
+
needle = f"{name}={compact}"
|
| 506 |
+
return any(compact and needle in text and any(
|
| 507 |
+
token and token in text for token in function_tokens)
|
| 508 |
+
for text in requirement_texts)
|
| 509 |
+
|
| 510 |
+
expected_arguments = {
|
| 511 |
+
item["index"]: item.get("expression")
|
| 512 |
+
for item in reference_signature.get("argument_expressions") or []
|
| 513 |
+
if positional_is_anchored(item.get("expression"))}
|
| 514 |
+
expected_keywords = {
|
| 515 |
+
name: expression for name, expression in
|
| 516 |
+
(reference_signature.get("keyword_expressions") or {}).items()
|
| 517 |
+
if keyword_is_anchored(name, expression)}
|
| 518 |
+
actual_arguments = {
|
| 519 |
+
item.get("index"): item.get("expression")
|
| 520 |
+
for item in check.get("argument_expressions") or []
|
| 521 |
+
if isinstance(item, dict)}
|
| 522 |
+
actual_keywords = check.get("keyword_expressions") or {}
|
| 523 |
+
expected_assignment = reference_signature.get("assignment")
|
| 524 |
+
if expected_assignment:
|
| 525 |
+
compact_assignment = re.sub(
|
| 526 |
+
r"\s+", "", f"{expected_assignment.get('target')}="
|
| 527 |
+
f"{expected_assignment.get('expression')}")
|
| 528 |
+
assignment_is_anchored = any(
|
| 529 |
+
compact_assignment and compact_assignment in text and any(
|
| 530 |
+
token and token in text for token in function_tokens)
|
| 531 |
+
for text in requirement_texts)
|
| 532 |
+
else:
|
| 533 |
+
assignment_is_anchored = False
|
| 534 |
+
actual_assignment = check.get("assignment")
|
| 535 |
+
missing_argument = any(
|
| 536 |
+
index not in actual_arguments or
|
| 537 |
+
_expression_fingerprint(actual_arguments[index]) !=
|
| 538 |
+
_expression_fingerprint(expression)
|
| 539 |
+
for index, expression in expected_arguments.items())
|
| 540 |
+
missing_keyword = any(
|
| 541 |
+
name not in actual_keywords or
|
| 542 |
+
_expression_fingerprint(actual_keywords[name]) !=
|
| 543 |
+
_expression_fingerprint(expression)
|
| 544 |
+
for name, expression in expected_keywords.items())
|
| 545 |
+
missing_assignment = bool(
|
| 546 |
+
assignment_is_anchored and (
|
| 547 |
+
not isinstance(actual_assignment, dict) or
|
| 548 |
+
actual_assignment.get("target") !=
|
| 549 |
+
expected_assignment.get("target") or
|
| 550 |
+
_expression_fingerprint(actual_assignment.get("expression")) !=
|
| 551 |
+
_expression_fingerprint(
|
| 552 |
+
expected_assignment.get("expression"))))
|
| 553 |
+
if missing_argument or missing_keyword or missing_assignment:
|
| 554 |
+
issues.append(
|
| 555 |
+
"Python call signature omits an anchored expression or assignment")
|
| 556 |
+
return issues
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _shell_lines(text):
|
| 560 |
+
"""Return executable lines with conservative local scalar substitution.
|
| 561 |
+
|
| 562 |
+
Shell authors routinely name a fixed argument before using it (for example
|
| 563 |
+
``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
|
| 564 |
+
assignments; never evaluate shell expressions, commands, or defaults.
|
| 565 |
+
"""
|
| 566 |
+
logical, pending = [], ""
|
| 567 |
+
for raw in str(text or "").splitlines():
|
| 568 |
+
line = " ".join(raw.strip().split())
|
| 569 |
+
if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
|
| 570 |
+
continue
|
| 571 |
+
pending = (pending + " " + line).strip() if pending else line
|
| 572 |
+
if pending.endswith("\\"):
|
| 573 |
+
pending = pending[:-1].rstrip()
|
| 574 |
+
continue
|
| 575 |
+
logical.append(pending)
|
| 576 |
+
pending = ""
|
| 577 |
+
if pending:
|
| 578 |
+
logical.append(pending)
|
| 579 |
+
|
| 580 |
+
constants, out = {}, []
|
| 581 |
+
assignment = re.compile(
|
| 582 |
+
r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
|
| 583 |
+
r"([A-Za-z0-9_./:+-]+))$")
|
| 584 |
+
variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
|
| 585 |
+
for line in logical:
|
| 586 |
+
match = assignment.fullmatch(line)
|
| 587 |
+
if match:
|
| 588 |
+
constants[match.group(1)] = next(
|
| 589 |
+
value for value in match.groups()[1:] if value is not None)
|
| 590 |
+
out.append(line)
|
| 591 |
+
continue
|
| 592 |
+
|
| 593 |
+
def replace(match):
|
| 594 |
+
name = match.group(1) or match.group(2)
|
| 595 |
+
return constants.get(name, match.group(0))
|
| 596 |
+
|
| 597 |
+
out.append(variable.sub(replace, line))
|
| 598 |
+
return out
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def _shell_command_matches(expected, actual):
|
| 602 |
+
"""Accept the frozen invocation plus documented optional arguments/path prefixes."""
|
| 603 |
+
try:
|
| 604 |
+
wanted = shlex.split(str(expected))
|
| 605 |
+
found = shlex.split(str(actual))
|
| 606 |
+
except ValueError:
|
| 607 |
+
return False
|
| 608 |
+
def normalize_git_log_limit(tokens):
|
| 609 |
+
if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
|
| 610 |
+
return tokens
|
| 611 |
+
normalized, index = [], 0
|
| 612 |
+
while index < len(tokens):
|
| 613 |
+
token = tokens[index]
|
| 614 |
+
short = re.fullmatch(r"-(\d+)", token)
|
| 615 |
+
long = re.fullmatch(r"--max-count=(\d+)", token)
|
| 616 |
+
if short or long:
|
| 617 |
+
normalized.append("--max-count=" + (short or long).group(1))
|
| 618 |
+
elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
|
| 619 |
+
re.fullmatch(r"\d+", tokens[index + 1])):
|
| 620 |
+
normalized.append("--max-count=" + tokens[index + 1])
|
| 621 |
+
index += 1
|
| 622 |
+
else:
|
| 623 |
+
normalized.append(token)
|
| 624 |
+
index += 1
|
| 625 |
+
return normalized
|
| 626 |
+
|
| 627 |
+
wanted = normalize_git_log_limit(wanted)
|
| 628 |
+
found = normalize_git_log_limit(found)
|
| 629 |
+
if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
|
| 630 |
+
return False
|
| 631 |
+
for index, token in enumerate(wanted[1:], 1):
|
| 632 |
+
observed = found[index]
|
| 633 |
+
if observed == token:
|
| 634 |
+
continue
|
| 635 |
+
# A solver may anchor a package-relative script at $REPO_ROOT while
|
| 636 |
+
# preserving the exact package path selected by the Skill.
|
| 637 |
+
if (index == 1 and "/" in token and
|
| 638 |
+
observed.rstrip("/").endswith(token.lstrip("./"))):
|
| 639 |
+
continue
|
| 640 |
+
return False
|
| 641 |
+
return True
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _shell_command_sequence_matches(expected, actual_lines):
|
| 645 |
+
"""Require every frozen command in order while allowing extra lines."""
|
| 646 |
+
cursor = 0
|
| 647 |
+
for command in expected:
|
| 648 |
+
for index in range(cursor, len(actual_lines)):
|
| 649 |
+
if _shell_command_matches(command, actual_lines[index]):
|
| 650 |
+
cursor = index + 1
|
| 651 |
+
break
|
| 652 |
+
else:
|
| 653 |
+
return False
|
| 654 |
+
return True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _shell_unconditional_lines(text):
|
| 658 |
+
"""Return conservative top-level command lines from a shell artifact.
|
| 659 |
+
|
| 660 |
+
Checked commands hidden in a conditional branch or an uncalled function do
|
| 661 |
+
not establish that the requested script performs them. This is not a full
|
| 662 |
+
shell parser: unsupported control flow simply makes nested lines
|
| 663 |
+
ineligible, which is appropriate for the small straight-line command
|
| 664 |
+
artifacts compiled by this evaluator.
|
| 665 |
+
"""
|
| 666 |
+
lines = _shell_lines(text)
|
| 667 |
+
depth = 0
|
| 668 |
+
out = []
|
| 669 |
+
opener = re.compile(
|
| 670 |
+
r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
|
| 671 |
+
r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
|
| 672 |
+
closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
|
| 673 |
+
for line in lines:
|
| 674 |
+
if closer.match(line):
|
| 675 |
+
depth = max(0, depth - 1)
|
| 676 |
+
continue
|
| 677 |
+
if depth == 0 and not opener.match(line):
|
| 678 |
+
out.append(line)
|
| 679 |
+
if opener.match(line):
|
| 680 |
+
depth += 1
|
| 681 |
+
return out
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _shell_is_straight_line(text):
|
| 685 |
+
"""Return whether every executable logical line is top-level.
|
| 686 |
+
|
| 687 |
+
This deliberately reuses the conservative control-flow recognizer used by
|
| 688 |
+
unconditional command checks. Any recognized conditional, loop, case, or
|
| 689 |
+
function makes the whole-script straight-line contract fail closed.
|
| 690 |
+
"""
|
| 691 |
+
lines = _shell_lines(text)
|
| 692 |
+
return lines == _shell_unconditional_lines(text)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def compile_workspace_evaluator(deliverables):
|
| 696 |
+
"""Compile trusted checks from validated deliverable specifications."""
|
| 697 |
+
if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
|
| 698 |
+
raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
|
| 699 |
+
reference_files, checks, paths = [], [], set()
|
| 700 |
+
for index, raw in enumerate(deliverables, 1):
|
| 701 |
+
if not isinstance(raw, dict):
|
| 702 |
+
raise ObjectiveEvaluatorError("deliverable is not an object")
|
| 703 |
+
path = safe_relative_path(raw.get("path"))
|
| 704 |
+
if path in paths:
|
| 705 |
+
raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
|
| 706 |
+
paths.add(path)
|
| 707 |
+
fmt = str(raw.get("format") or "").strip().casefold()
|
| 708 |
+
if fmt not in ARTIFACT_FORMATS:
|
| 709 |
+
raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
|
| 710 |
+
content = _file_content({**raw, "format": fmt})
|
| 711 |
+
if len(content.encode("utf-8")) > 200_000:
|
| 712 |
+
raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
|
| 713 |
+
reference_files.append({"path": path, "format": fmt, "content": content})
|
| 714 |
+
checks.append({"id": f"file_{index:03d}", "type": "file_exists",
|
| 715 |
+
"path": path})
|
| 716 |
+
if fmt == "json":
|
| 717 |
+
checks.append({"id": f"json_{index:03d}", "type": "json_exact",
|
| 718 |
+
"path": path, "expected": _json_value(raw.get("content"))})
|
| 719 |
+
elif fmt == "toml":
|
| 720 |
+
try:
|
| 721 |
+
expected = tomllib.loads(content)
|
| 722 |
+
except (tomllib.TOMLDecodeError, ValueError) as exc:
|
| 723 |
+
raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
|
| 724 |
+
checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
|
| 725 |
+
"path": path, "expected": expected})
|
| 726 |
+
elif fmt == "python":
|
| 727 |
+
try:
|
| 728 |
+
_, _, constants, call_nodes = _python_semantics(content)
|
| 729 |
+
resolved_calls = _python_resolved_call_nodes(content)
|
| 730 |
+
except SyntaxError as exc:
|
| 731 |
+
raise ObjectiveEvaluatorError("reference Python is invalid") from exc
|
| 732 |
+
checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
|
| 733 |
+
"path": path})
|
| 734 |
+
checks.append({"id": f"python_{index:03d}_bindings",
|
| 735 |
+
"type": "python_bound_calls", "path": path})
|
| 736 |
+
raw_checks = raw.get("checks") or []
|
| 737 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 738 |
+
raise ObjectiveEvaluatorError(
|
| 739 |
+
"Python deliverable requires 1-12 objective import/call checks")
|
| 740 |
+
for check_index, check in enumerate(raw_checks, 1):
|
| 741 |
+
if not isinstance(check, dict):
|
| 742 |
+
raise ObjectiveEvaluatorError("Python check is not an object")
|
| 743 |
+
kind = str(check.get("type") or "").strip().casefold()
|
| 744 |
+
if kind in {"python_import", "python_call"}:
|
| 745 |
+
value = str(check.get("value") or "").strip()
|
| 746 |
+
if not _DOTTED.fullmatch(value):
|
| 747 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 748 |
+
compiled = {"type": kind, "path": path, "value": value}
|
| 749 |
+
elif kind == "python_constant":
|
| 750 |
+
name = str(check.get("name") or "").strip()
|
| 751 |
+
value = check.get("value")
|
| 752 |
+
if (not _DOTTED.fullmatch(name) or "." in name or
|
| 753 |
+
isinstance(value, (dict, list)) or value is None or
|
| 754 |
+
constants.get(name, _UNRESOLVED) != value):
|
| 755 |
+
raise ObjectiveEvaluatorError(
|
| 756 |
+
"Python constant check is invalid or fails reference content")
|
| 757 |
+
compiled = {"type": kind, "path": path, "name": name,
|
| 758 |
+
"value": value}
|
| 759 |
+
elif kind == "python_call_literal":
|
| 760 |
+
function = str(check.get("function") or "").strip()
|
| 761 |
+
value = check.get("value")
|
| 762 |
+
if (not _DOTTED.fullmatch(function) or
|
| 763 |
+
isinstance(value, (dict, list)) or value is None or
|
| 764 |
+
not any(
|
| 765 |
+
(name == function or name.endswith("." + function)) and
|
| 766 |
+
_node_contains_literal(node, value, constants)
|
| 767 |
+
for name, node in call_nodes)):
|
| 768 |
+
raise ObjectiveEvaluatorError(
|
| 769 |
+
"Python call-literal check is invalid or fails reference content")
|
| 770 |
+
compiled = {"type": kind, "path": path,
|
| 771 |
+
"function": function, "value": value}
|
| 772 |
+
elif kind == "python_call_keyword_literal":
|
| 773 |
+
function = str(check.get("function") or "").strip()
|
| 774 |
+
keyword = str(check.get("keyword") or "").strip()
|
| 775 |
+
value = check.get("value")
|
| 776 |
+
if (not _DOTTED.fullmatch(function) or
|
| 777 |
+
not _DOTTED.fullmatch(keyword) or "." in keyword or
|
| 778 |
+
isinstance(value, (dict, list)) or value is None or
|
| 779 |
+
not any(
|
| 780 |
+
(name == function or name.endswith("." + function)) and
|
| 781 |
+
_call_keyword_matches(node, keyword, value, constants)
|
| 782 |
+
for name, node in call_nodes)):
|
| 783 |
+
raise ObjectiveEvaluatorError(
|
| 784 |
+
"Python call-keyword check is invalid or fails reference content")
|
| 785 |
+
compiled = {"type": kind, "path": path,
|
| 786 |
+
"function": function, "keyword": keyword,
|
| 787 |
+
"value": value}
|
| 788 |
+
elif kind == "python_call_signature":
|
| 789 |
+
function = str(check.get("function") or "").strip()
|
| 790 |
+
arguments = check.get("arguments") or []
|
| 791 |
+
keywords = check.get("keywords") or {}
|
| 792 |
+
argument_expressions = check.get(
|
| 793 |
+
"argument_expressions") or []
|
| 794 |
+
keyword_expressions = check.get(
|
| 795 |
+
"keyword_expressions") or {}
|
| 796 |
+
assignment = check.get("assignment")
|
| 797 |
+
if (not _DOTTED.fullmatch(function) or
|
| 798 |
+
not isinstance(arguments, list) or
|
| 799 |
+
not isinstance(keywords, dict) or
|
| 800 |
+
not isinstance(argument_expressions, list) or
|
| 801 |
+
not isinstance(keyword_expressions, dict) or
|
| 802 |
+
not (arguments or keywords or
|
| 803 |
+
argument_expressions or keyword_expressions or
|
| 804 |
+
assignment) or
|
| 805 |
+
any(not isinstance(item, dict) or
|
| 806 |
+
not isinstance(item.get("index"), int) or
|
| 807 |
+
item.get("index") < 0 or
|
| 808 |
+
isinstance(item.get("value"), dict)
|
| 809 |
+
for item in arguments) or
|
| 810 |
+
len({item["index"] for item in arguments}) !=
|
| 811 |
+
len(arguments) or
|
| 812 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 813 |
+
"." in str(name) or isinstance(value, dict)
|
| 814 |
+
for name, value in keywords.items()) or
|
| 815 |
+
any(not isinstance(item, dict) or
|
| 816 |
+
not isinstance(item.get("index"), int) or
|
| 817 |
+
item.get("index") < 0 or
|
| 818 |
+
not _expression_fingerprint(
|
| 819 |
+
item.get("expression"))
|
| 820 |
+
for item in argument_expressions) or
|
| 821 |
+
len({item["index"] for item in
|
| 822 |
+
argument_expressions}) !=
|
| 823 |
+
len(argument_expressions) or
|
| 824 |
+
({item["index"] for item in arguments} &
|
| 825 |
+
{item["index"] for item in
|
| 826 |
+
argument_expressions}) or
|
| 827 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 828 |
+
"." in str(name) or
|
| 829 |
+
not _expression_fingerprint(value)
|
| 830 |
+
for name, value in
|
| 831 |
+
keyword_expressions.items()) or
|
| 832 |
+
(set(keywords) & set(keyword_expressions)) or
|
| 833 |
+
(assignment is not None and (
|
| 834 |
+
not isinstance(assignment, dict) or
|
| 835 |
+
not _DOTTED.fullmatch(str(
|
| 836 |
+
assignment.get("target") or "")) or
|
| 837 |
+
"." in str(assignment.get("target") or "") or
|
| 838 |
+
not _expression_fingerprint(
|
| 839 |
+
assignment.get("expression")))) or
|
| 840 |
+
not any(
|
| 841 |
+
(name == function or
|
| 842 |
+
name.endswith("." + function)) and
|
| 843 |
+
_call_signature_matches(
|
| 844 |
+
node, arguments, keywords, constants,
|
| 845 |
+
argument_expressions,
|
| 846 |
+
keyword_expressions, assignment)
|
| 847 |
+
for name, node in call_nodes)):
|
| 848 |
+
raise ObjectiveEvaluatorError(
|
| 849 |
+
"Python call-signature check is invalid or fails reference content")
|
| 850 |
+
compiled = {"type": kind, "path": path,
|
| 851 |
+
"function": function,
|
| 852 |
+
"arguments": arguments,
|
| 853 |
+
"keywords": keywords,
|
| 854 |
+
"argument_expressions": argument_expressions,
|
| 855 |
+
"keyword_expressions": keyword_expressions,
|
| 856 |
+
"assignment": assignment}
|
| 857 |
+
else:
|
| 858 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 859 |
+
if kind in {"python_call", "python_call_literal",
|
| 860 |
+
"python_call_keyword_literal",
|
| 861 |
+
"python_call_signature"}:
|
| 862 |
+
targets = _objective_call_targets(
|
| 863 |
+
kind, compiled, resolved_calls, constants)
|
| 864 |
+
if len(targets) != 1:
|
| 865 |
+
raise ObjectiveEvaluatorError(
|
| 866 |
+
"Python call check has no unique canonical target")
|
| 867 |
+
compiled["target"] = next(iter(targets))
|
| 868 |
+
checks.append({"id": f"python_{index:03d}_{check_index:03d}",
|
| 869 |
+
**compiled})
|
| 870 |
+
else:
|
| 871 |
+
raw_checks = raw.get("checks") or []
|
| 872 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 873 |
+
raise ObjectiveEvaluatorError(
|
| 874 |
+
"shell deliverable requires 1-12 objective command checks")
|
| 875 |
+
checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
|
| 876 |
+
"path": path})
|
| 877 |
+
reference_sequence = _shell_lines(content)
|
| 878 |
+
reference_lines = set(reference_sequence)
|
| 879 |
+
unconditional_lines = _shell_unconditional_lines(content)
|
| 880 |
+
command_checks = []
|
| 881 |
+
for check in raw_checks:
|
| 882 |
+
value = " ".join(str(check.get("value") or "").strip().split())
|
| 883 |
+
if (not isinstance(check, dict) or
|
| 884 |
+
str(check.get("type") or "").strip().casefold() != "shell_command" or
|
| 885 |
+
not value or value not in reference_lines):
|
| 886 |
+
raise ObjectiveEvaluatorError("unsupported shell objective check")
|
| 887 |
+
command_checks.append({"type": "shell_command", "path": path,
|
| 888 |
+
"value": value})
|
| 889 |
+
if len({item["value"] for item in command_checks}) != len(command_checks):
|
| 890 |
+
raise ObjectiveEvaluatorError("shell objective checks must be unique")
|
| 891 |
+
command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
|
| 892 |
+
if not all(any(_shell_command_matches(
|
| 893 |
+
item["value"], line) for line in unconditional_lines)
|
| 894 |
+
for item in command_checks):
|
| 895 |
+
raise ObjectiveEvaluatorError(
|
| 896 |
+
"checked shell commands must be top-level and unconditional")
|
| 897 |
+
for check_index, check in enumerate(command_checks, 1):
|
| 898 |
+
checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
|
| 899 |
+
**check})
|
| 900 |
+
if len(command_checks) >= 2:
|
| 901 |
+
checks.append({
|
| 902 |
+
"id": f"shell_{index:03d}_sequence",
|
| 903 |
+
"type": "shell_command_sequence", "path": path,
|
| 904 |
+
"values": [item["value"] for item in command_checks],
|
| 905 |
+
})
|
| 906 |
+
checks.append({
|
| 907 |
+
"id": f"shell_{index:03d}_unconditional",
|
| 908 |
+
"type": "shell_unconditional_commands", "path": path,
|
| 909 |
+
"values": [item["value"] for item in command_checks],
|
| 910 |
+
})
|
| 911 |
+
# Preserve the reference's fail-fast behavior when accepting normal
|
| 912 |
+
# command-substitution/guard wrappers. Never turn `|| true` into a
|
| 913 |
+
# passing preflight simply because it contains the correct argv.
|
| 914 |
+
reference_calls = shell_invocations(content)
|
| 915 |
+
protected = [item["value"] for item in command_checks if any(
|
| 916 |
+
call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
|
| 917 |
+
for call in reference_calls)]
|
| 918 |
+
if protected:
|
| 919 |
+
checks.append({"id": f"shell_{index:03d}_failure_propagation",
|
| 920 |
+
"type": "shell_failure_propagation", "path": path,
|
| 921 |
+
"values": protected})
|
| 922 |
+
# Candidate workspaces may also contain root-level public inputs and
|
| 923 |
+
# installed Skill packages. Deliverables use dedicated top-level output
|
| 924 |
+
# directories, so enforce an exact file set inside those namespaces while
|
| 925 |
+
# leaving the read-only environment outside them untouched.
|
| 926 |
+
output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
|
| 927 |
+
if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
|
| 928 |
+
checks.insert(0, {
|
| 929 |
+
"id": "workspace_file_set", "type": "workspace_file_set",
|
| 930 |
+
"paths": sorted(paths), "roots": output_roots,
|
| 931 |
+
})
|
| 932 |
+
return {
|
| 933 |
+
"type": WORKSPACE_EVALUATOR,
|
| 934 |
+
"version": WORKSPACE_EVALUATOR_VERSION,
|
| 935 |
+
"output_mode": "workspace",
|
| 936 |
+
"reference_files": reference_files,
|
| 937 |
+
"checks": checks,
|
| 938 |
+
}
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def reference_bundle(evaluator):
|
| 942 |
+
if evaluator.get("type") != WORKSPACE_EVALUATOR:
|
| 943 |
+
raise ObjectiveEvaluatorError("not a workspace evaluator")
|
| 944 |
+
return {"files": [
|
| 945 |
+
{"path": item["path"], "content": item["content"]}
|
| 946 |
+
for item in evaluator.get("reference_files") or []
|
| 947 |
+
]}
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
def hidden_workspace_values(evaluator):
|
| 951 |
+
"""Return decisive package-owned values that public queries must not leak."""
|
| 952 |
+
values = []
|
| 953 |
+
for check in (evaluator or {}).get("checks") or []:
|
| 954 |
+
kind = check.get("type")
|
| 955 |
+
if kind in {"json_exact", "toml_exact"}:
|
| 956 |
+
values.extend(value for _, value in _flatten(check.get("expected")))
|
| 957 |
+
elif kind in {"python_import", "python_call", "shell_command",
|
| 958 |
+
"python_constant", "python_call_literal",
|
| 959 |
+
"python_call_keyword_literal"}:
|
| 960 |
+
values.append(check.get("value"))
|
| 961 |
+
elif kind == "python_call_signature":
|
| 962 |
+
values.extend(value for _, value in _flatten({
|
| 963 |
+
"arguments": [item.get("value") for item in
|
| 964 |
+
check.get("arguments") or []],
|
| 965 |
+
"keywords": check.get("keywords") or {},
|
| 966 |
+
"argument_expressions": [item.get("expression") for item in
|
| 967 |
+
check.get("argument_expressions") or []],
|
| 968 |
+
"keyword_expressions": check.get("keyword_expressions") or {},
|
| 969 |
+
"assignment": check.get("assignment"),
|
| 970 |
+
}))
|
| 971 |
+
return [value for value in values if value is not None]
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def _flatten(value, path=()):
|
| 975 |
+
if isinstance(value, dict):
|
| 976 |
+
out = []
|
| 977 |
+
for key, item in value.items():
|
| 978 |
+
out.extend(_flatten(item, path + (str(key),)))
|
| 979 |
+
return out
|
| 980 |
+
if isinstance(value, list):
|
| 981 |
+
out = []
|
| 982 |
+
for index, item in enumerate(value):
|
| 983 |
+
out.extend(_flatten(item, path + (index,)))
|
| 984 |
+
return out
|
| 985 |
+
return [(path, value)]
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def _bundle_rows(candidate):
|
| 989 |
+
if isinstance(candidate, str):
|
| 990 |
+
text = candidate.strip()
|
| 991 |
+
# Chat solvers often wrap the requested file bundle in a Markdown fence
|
| 992 |
+
# or append a duplicate FINAL_ANSWER object. Decode one complete JSON
|
| 993 |
+
# value at a time instead of requiring the entire response to be JSON;
|
| 994 |
+
# only an object carrying the explicit ``files`` transport field is
|
| 995 |
+
# eligible, so unrelated prose/objects are not silently accepted.
|
| 996 |
+
decoder = json.JSONDecoder()
|
| 997 |
+
candidate = None
|
| 998 |
+
for match in re.finditer(r"\{", text):
|
| 999 |
+
try:
|
| 1000 |
+
parsed, _ = decoder.raw_decode(text, match.start())
|
| 1001 |
+
except json.JSONDecodeError:
|
| 1002 |
+
continue
|
| 1003 |
+
if isinstance(parsed, dict) and "files" in parsed:
|
| 1004 |
+
candidate = parsed
|
| 1005 |
+
break
|
| 1006 |
+
if candidate is None:
|
| 1007 |
+
raise ObjectiveEvaluatorError(
|
| 1008 |
+
"workspace response contains no complete JSON file bundle")
|
| 1009 |
+
if not isinstance(candidate, dict):
|
| 1010 |
+
raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
|
| 1011 |
+
files = candidate.get("files")
|
| 1012 |
+
if isinstance(files, dict):
|
| 1013 |
+
files = [{"path": path, "content": content}
|
| 1014 |
+
for path, content in files.items()]
|
| 1015 |
+
if not isinstance(files, list) or len(files) > 30:
|
| 1016 |
+
raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
|
| 1017 |
+
return files
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def materialize_bundle(candidate, workspace):
|
| 1021 |
+
root = Path(workspace).resolve()
|
| 1022 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 1023 |
+
seen = set()
|
| 1024 |
+
for item in _bundle_rows(candidate):
|
| 1025 |
+
if not isinstance(item, dict):
|
| 1026 |
+
raise ObjectiveEvaluatorError("candidate file entry is not an object")
|
| 1027 |
+
relative = safe_relative_path(item.get("path"))
|
| 1028 |
+
if relative in seen:
|
| 1029 |
+
raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
|
| 1030 |
+
seen.add(relative)
|
| 1031 |
+
content = item.get("content")
|
| 1032 |
+
if isinstance(content, (dict, list)):
|
| 1033 |
+
content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 1034 |
+
if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
|
| 1035 |
+
raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
|
| 1036 |
+
target = (root / relative).resolve()
|
| 1037 |
+
if root not in target.parents:
|
| 1038 |
+
raise ObjectiveEvaluatorError("candidate file escapes workspace")
|
| 1039 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 1040 |
+
target.write_text(content, encoding="utf-8")
|
| 1041 |
+
return root
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
def evaluate_workspace(evaluator, workspace):
|
| 1045 |
+
if (not isinstance(evaluator, dict) or
|
| 1046 |
+
evaluator.get("type") != WORKSPACE_EVALUATOR or
|
| 1047 |
+
int(evaluator.get("version") or 0) not in
|
| 1048 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
|
| 1049 |
+
return False, {"error": "invalid workspace evaluator contract"}
|
| 1050 |
+
root = Path(workspace).resolve()
|
| 1051 |
+
results = []
|
| 1052 |
+
for check in evaluator.get("checks") or []:
|
| 1053 |
+
kind = check.get("type")
|
| 1054 |
+
relative, path = "", None
|
| 1055 |
+
if kind != "workspace_file_set":
|
| 1056 |
+
relative = safe_relative_path(check.get("path"))
|
| 1057 |
+
path = (root / relative).resolve()
|
| 1058 |
+
if root not in path.parents:
|
| 1059 |
+
return False, {"error": "evaluator path escapes workspace"}
|
| 1060 |
+
passed, detail = False, ""
|
| 1061 |
+
try:
|
| 1062 |
+
if kind == "workspace_file_set":
|
| 1063 |
+
expected = {safe_relative_path(value)
|
| 1064 |
+
for value in check.get("paths") or []}
|
| 1065 |
+
roots = [safe_relative_path(value)
|
| 1066 |
+
for value in check.get("roots") or []]
|
| 1067 |
+
actual = set()
|
| 1068 |
+
for relative_root in roots:
|
| 1069 |
+
scan_root = (root / relative_root).resolve()
|
| 1070 |
+
if root not in scan_root.parents:
|
| 1071 |
+
raise ObjectiveEvaluatorError(
|
| 1072 |
+
"workspace file-set root escapes workspace")
|
| 1073 |
+
if not scan_root.exists():
|
| 1074 |
+
continue
|
| 1075 |
+
for candidate in scan_root.rglob("*"):
|
| 1076 |
+
if candidate.is_file() or candidate.is_symlink():
|
| 1077 |
+
actual.add(candidate.relative_to(root).as_posix())
|
| 1078 |
+
passed = bool(expected) and actual == expected
|
| 1079 |
+
detail = ("exact deliverable file set" if passed else
|
| 1080 |
+
f"expected_files={sorted(expected)}; "
|
| 1081 |
+
f"actual_files={sorted(actual)}")
|
| 1082 |
+
elif kind == "file_exists":
|
| 1083 |
+
passed = path.is_file()
|
| 1084 |
+
detail = "present" if passed else "missing"
|
| 1085 |
+
elif kind == "json_exact":
|
| 1086 |
+
from r9_json import parse_file, strict_equal
|
| 1087 |
+
actual = parse_file(path)
|
| 1088 |
+
passed = strict_equal(actual, check.get("expected"))
|
| 1089 |
+
detail = "semantic JSON match" if passed else "JSON value mismatch"
|
| 1090 |
+
elif kind == "toml_exact":
|
| 1091 |
+
actual = tomllib.loads(path.read_text(encoding="utf-8"))
|
| 1092 |
+
passed = _canonical(actual) == _canonical(check.get("expected"))
|
| 1093 |
+
detail = "semantic TOML match" if passed else "TOML value mismatch"
|
| 1094 |
+
elif kind in {"python_syntax", "python_bound_calls",
|
| 1095 |
+
"python_import", "python_call",
|
| 1096 |
+
"python_constant", "python_call_literal",
|
| 1097 |
+
"python_call_keyword_literal",
|
| 1098 |
+
"python_call_signature"}:
|
| 1099 |
+
source = path.read_text(encoding="utf-8")
|
| 1100 |
+
imports, calls, constants, call_nodes = _python_semantics(source)
|
| 1101 |
+
resolved_calls = _python_resolved_call_nodes(source)
|
| 1102 |
+
if kind == "python_syntax":
|
| 1103 |
+
passed, detail = True, "valid Python syntax"
|
| 1104 |
+
elif kind == "python_bound_calls":
|
| 1105 |
+
unbound = python_unbound_call_roots(
|
| 1106 |
+
path.read_text(encoding="utf-8"))
|
| 1107 |
+
passed = not unbound
|
| 1108 |
+
detail = ("all call roots are statically bound" if passed else
|
| 1109 |
+
"unbound call roots=" + repr(unbound))
|
| 1110 |
+
elif kind == "python_import":
|
| 1111 |
+
expected = str(check.get("value") or "")
|
| 1112 |
+
passed = expected in imports or any(
|
| 1113 |
+
value == expected or value.startswith(expected + ".")
|
| 1114 |
+
for value in imports)
|
| 1115 |
+
detail = f"imports={sorted(imports)}"
|
| 1116 |
+
elif kind == "python_call":
|
| 1117 |
+
expected = str(check.get("value") or "")
|
| 1118 |
+
target = str(check.get("target") or "")
|
| 1119 |
+
passed = (any(
|
| 1120 |
+
canonical == target
|
| 1121 |
+
for _, canonical, _ in resolved_calls)
|
| 1122 |
+
if target else expected in calls or any(
|
| 1123 |
+
value.endswith("." + expected)
|
| 1124 |
+
for value in calls))
|
| 1125 |
+
detail = f"calls={sorted(calls)}"
|
| 1126 |
+
elif kind == "python_constant":
|
| 1127 |
+
name, expected = str(check.get("name") or ""), check.get("value")
|
| 1128 |
+
actual = constants.get(name, _UNRESOLVED)
|
| 1129 |
+
passed = actual is not _UNRESOLVED and actual == expected
|
| 1130 |
+
detail = f"constant {name}={actual!r}"
|
| 1131 |
+
elif kind == "python_call_literal":
|
| 1132 |
+
function, expected = (str(check.get("function") or ""),
|
| 1133 |
+
check.get("value"))
|
| 1134 |
+
target = str(check.get("target") or "")
|
| 1135 |
+
source_calls = (resolved_calls if target else
|
| 1136 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1137 |
+
passed = any(
|
| 1138 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1139 |
+
(not target or canonical == target) and
|
| 1140 |
+
_node_contains_literal(node, expected, constants)
|
| 1141 |
+
for name, canonical, node in source_calls)
|
| 1142 |
+
detail = f"call={function} literal={expected!r}"
|
| 1143 |
+
elif kind == "python_call_keyword_literal":
|
| 1144 |
+
function = str(check.get("function") or "")
|
| 1145 |
+
keyword = str(check.get("keyword") or "")
|
| 1146 |
+
expected = check.get("value")
|
| 1147 |
+
target = str(check.get("target") or "")
|
| 1148 |
+
source_calls = (resolved_calls if target else
|
| 1149 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1150 |
+
passed = any(
|
| 1151 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1152 |
+
(not target or canonical == target) and
|
| 1153 |
+
_call_keyword_matches(node, keyword, expected, constants)
|
| 1154 |
+
for name, canonical, node in source_calls)
|
| 1155 |
+
detail = (f"call={function} keyword={keyword} "
|
| 1156 |
+
f"literal={expected!r}")
|
| 1157 |
+
else:
|
| 1158 |
+
function = str(check.get("function") or "")
|
| 1159 |
+
arguments = check.get("arguments") or []
|
| 1160 |
+
keywords = check.get("keywords") or {}
|
| 1161 |
+
argument_expressions = check.get(
|
| 1162 |
+
"argument_expressions") or []
|
| 1163 |
+
keyword_expressions = check.get(
|
| 1164 |
+
"keyword_expressions") or {}
|
| 1165 |
+
assignment = check.get("assignment")
|
| 1166 |
+
target = str(check.get("target") or "")
|
| 1167 |
+
source_calls = (resolved_calls if target else
|
| 1168 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1169 |
+
passed = any(
|
| 1170 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1171 |
+
(not target or canonical == target) and
|
| 1172 |
+
_call_signature_matches(
|
| 1173 |
+
node, arguments, keywords, constants,
|
| 1174 |
+
argument_expressions, keyword_expressions,
|
| 1175 |
+
assignment)
|
| 1176 |
+
for name, canonical, node in source_calls)
|
| 1177 |
+
detail = (f"call={function} arguments={arguments!r} "
|
| 1178 |
+
f"keywords={keywords!r} "
|
| 1179 |
+
f"argument_expressions={argument_expressions!r} "
|
| 1180 |
+
f"keyword_expressions={keyword_expressions!r} "
|
| 1181 |
+
f"assignment={assignment!r}")
|
| 1182 |
+
elif kind == "shell_syntax":
|
| 1183 |
+
completed = subprocess.run(
|
| 1184 |
+
["bash", "-n", str(path)], capture_output=True, text=True,
|
| 1185 |
+
timeout=5, check=False)
|
| 1186 |
+
passed = completed.returncode == 0
|
| 1187 |
+
detail = ("valid shell syntax" if passed else
|
| 1188 |
+
(completed.stderr or "invalid shell syntax").strip())
|
| 1189 |
+
elif kind == "shell_command":
|
| 1190 |
+
source = path.read_text(encoding="utf-8")
|
| 1191 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1192 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1193 |
+
expected = " ".join(str(check.get("value") or "").split())
|
| 1194 |
+
passed = any(_shell_command_matches(expected, line) for line in lines)
|
| 1195 |
+
detail = f"executable_lines={lines[:30]}"
|
| 1196 |
+
elif kind == "shell_command_sequence":
|
| 1197 |
+
source = path.read_text(encoding="utf-8")
|
| 1198 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1199 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1200 |
+
expected = [" ".join(str(value).split())
|
| 1201 |
+
for value in check.get("values") or []]
|
| 1202 |
+
passed = (len(expected) >= 2 and
|
| 1203 |
+
_shell_command_sequence_matches(expected, lines))
|
| 1204 |
+
detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
|
| 1205 |
+
elif kind == "shell_unconditional_commands":
|
| 1206 |
+
source = path.read_text(encoding="utf-8")
|
| 1207 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1208 |
+
if int(evaluator.get("version", 0)) >= 15
|
| 1209 |
+
else _shell_unconditional_lines(source))
|
| 1210 |
+
expected = [" ".join(str(value).split())
|
| 1211 |
+
for value in check.get("values") or []]
|
| 1212 |
+
passed = (bool(expected) and all(
|
| 1213 |
+
any(_shell_command_matches(command, line) for line in lines)
|
| 1214 |
+
for command in expected))
|
| 1215 |
+
detail = (f"expected_unconditional={expected}; "
|
| 1216 |
+
f"top_level_lines={lines[:30]}")
|
| 1217 |
+
elif kind == "shell_failure_propagation":
|
| 1218 |
+
calls = shell_invocations(path.read_text(encoding="utf-8"))
|
| 1219 |
+
expected = [" ".join(str(value).split())
|
| 1220 |
+
for value in check.get("values") or []]
|
| 1221 |
+
passed = bool(expected) and all(any(
|
| 1222 |
+
call["fail_fast"] and _shell_command_matches(command, call["command"])
|
| 1223 |
+
for call in calls) for command in expected)
|
| 1224 |
+
detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
|
| 1225 |
+
elif kind == "shell_straight_line":
|
| 1226 |
+
source = path.read_text(encoding="utf-8")
|
| 1227 |
+
passed = _shell_is_straight_line(source)
|
| 1228 |
+
detail = ("all executable lines are top-level" if passed else
|
| 1229 |
+
"shell contains conditional, loop, case, or function")
|
| 1230 |
+
else:
|
| 1231 |
+
detail = f"unsupported check: {kind}"
|
| 1232 |
+
except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
|
| 1233 |
+
json.JSONDecodeError,
|
| 1234 |
+
tomllib.TOMLDecodeError) as exc:
|
| 1235 |
+
detail = str(exc)
|
| 1236 |
+
results.append({"id": check.get("id"), "type": kind,
|
| 1237 |
+
"path": relative, "passed": bool(passed),
|
| 1238 |
+
"detail": detail[:1000]})
|
| 1239 |
+
return bool(results) and all(item["passed"] for item in results), {
|
| 1240 |
+
"type": WORKSPACE_EVALUATOR,
|
| 1241 |
+
"assertions_passed": sum(item["passed"] for item in results),
|
| 1242 |
+
"assertions_total": len(results),
|
| 1243 |
+
"assertions": results,
|
| 1244 |
+
}
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
def evaluate_candidate(evaluator, candidate):
|
| 1248 |
+
if isinstance(candidate, os.PathLike):
|
| 1249 |
+
try:
|
| 1250 |
+
return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
|
| 1251 |
+
False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
|
| 1252 |
+
except (OSError, ValueError) as exc:
|
| 1253 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1254 |
+
if isinstance(candidate, str):
|
| 1255 |
+
# A chat file-bundle can be much longer than a filesystem path. Avoid
|
| 1256 |
+
# passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
|
| 1257 |
+
stripped = candidate.strip()
|
| 1258 |
+
if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
|
| 1259 |
+
and not stripped.startswith(("{", "[", "```"))):
|
| 1260 |
+
try:
|
| 1261 |
+
if Path(stripped).is_dir():
|
| 1262 |
+
return evaluate_workspace(evaluator, stripped)
|
| 1263 |
+
except (OSError, ValueError):
|
| 1264 |
+
# Python/platform versions differ on ENAMETOOLONG and invalid
|
| 1265 |
+
# path errors. It is still candidate text: parse it unchanged.
|
| 1266 |
+
pass
|
| 1267 |
+
try:
|
| 1268 |
+
with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
|
| 1269 |
+
materialize_bundle(candidate, temp)
|
| 1270 |
+
return evaluate_workspace(evaluator, temp)
|
| 1271 |
+
except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
|
| 1272 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
def self_test_workspace_evaluator(evaluator):
|
| 1276 |
+
correct = reference_bundle(evaluator)
|
| 1277 |
+
ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
|
| 1278 |
+
rows = list(correct.get("files") or [])
|
| 1279 |
+
perturbed = {"files": rows[1:] if len(rows) > 1 else []}
|
| 1280 |
+
ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
|
| 1281 |
+
mutations = []
|
| 1282 |
+
# Exact JSON fields must each matter, not merely the file's existence.
|
| 1283 |
+
for check in evaluator.get("checks") or []:
|
| 1284 |
+
if check.get("type") != "json_exact":
|
| 1285 |
+
continue
|
| 1286 |
+
for path, value in _flatten(check.get("expected")):
|
| 1287 |
+
candidate = copy.deepcopy(correct)
|
| 1288 |
+
file_row = next(row for row in candidate["files"]
|
| 1289 |
+
if row["path"] == check["path"])
|
| 1290 |
+
data = json.loads(file_row["content"])
|
| 1291 |
+
replacement = (not value if isinstance(value, bool) else
|
| 1292 |
+
value + 1 if isinstance(value, (int, float)) else
|
| 1293 |
+
str(value) + "__mutation__")
|
| 1294 |
+
if not path:
|
| 1295 |
+
data = replacement
|
| 1296 |
+
else:
|
| 1297 |
+
container = data
|
| 1298 |
+
for key in path[:-1]:
|
| 1299 |
+
container = container[key]
|
| 1300 |
+
container[path[-1]] = replacement
|
| 1301 |
+
file_row["content"] = json.dumps(data)
|
| 1302 |
+
passed, _ = evaluate_candidate(evaluator, candidate)
|
| 1303 |
+
mutations.append({"path": check["path"], "field": list(path),
|
| 1304 |
+
"rejected": not passed})
|
| 1305 |
+
return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
|
| 1306 |
+
"correct": correct_detail,
|
| 1307 |
+
"perturbed": wrong_detail,
|
| 1308 |
+
"scalar_mutations": mutations,
|
| 1309 |
+
}
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/shell_invocations.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A deliberately bounded, non-executing shell structure recognizer.
|
| 2 |
+
|
| 3 |
+
Supports simple commands, literal scalar assignments, one command substitution
|
| 4 |
+
on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
|
| 5 |
+
It does not interpret shell code or credit commands in branch bodies/functions.
|
| 6 |
+
Pipelines, command lists, substitutions within substitutions, and swallowed
|
| 7 |
+
failures are outside this grammar. bash -n remains a separate required check.
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
import shlex
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _statements(text):
|
| 14 |
+
out, current = [], []
|
| 15 |
+
quote, escaped, comment, depth = None, False, False, 0
|
| 16 |
+
for ch in str(text):
|
| 17 |
+
if comment:
|
| 18 |
+
if ch == '\n':
|
| 19 |
+
comment = False
|
| 20 |
+
else:
|
| 21 |
+
continue
|
| 22 |
+
if escaped:
|
| 23 |
+
if ch != '\n':
|
| 24 |
+
current.extend(('\\', ch))
|
| 25 |
+
escaped = False
|
| 26 |
+
continue
|
| 27 |
+
if ch == '\\' and quote != "'":
|
| 28 |
+
escaped = True
|
| 29 |
+
continue
|
| 30 |
+
if quote:
|
| 31 |
+
current.append(ch)
|
| 32 |
+
if ch == quote:
|
| 33 |
+
quote = None
|
| 34 |
+
continue
|
| 35 |
+
if ch in "'\"":
|
| 36 |
+
quote = ch
|
| 37 |
+
current.append(ch)
|
| 38 |
+
elif ch == '#' and (not current or current[-1].isspace()):
|
| 39 |
+
comment = True
|
| 40 |
+
elif ch == '(':
|
| 41 |
+
depth += 1
|
| 42 |
+
current.append(ch)
|
| 43 |
+
elif ch == ')':
|
| 44 |
+
depth -= 1
|
| 45 |
+
if depth < 0:
|
| 46 |
+
return []
|
| 47 |
+
current.append(ch)
|
| 48 |
+
elif ch in '\n;' and depth == 0:
|
| 49 |
+
value = ''.join(current).strip()
|
| 50 |
+
if value:
|
| 51 |
+
out.append(value)
|
| 52 |
+
current = []
|
| 53 |
+
else:
|
| 54 |
+
current.append(ch)
|
| 55 |
+
if quote or escaped or depth:
|
| 56 |
+
return []
|
| 57 |
+
if ''.join(current).strip():
|
| 58 |
+
out.append(''.join(current).strip())
|
| 59 |
+
expanded = []
|
| 60 |
+
for statement in out:
|
| 61 |
+
inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
|
| 62 |
+
expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
|
| 63 |
+
return expanded
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _simple_argv(text):
|
| 67 |
+
if '$(' in text or '`' in text:
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
|
| 71 |
+
lexer.whitespace_split = True
|
| 72 |
+
tokens = list(lexer)
|
| 73 |
+
except ValueError:
|
| 74 |
+
return None
|
| 75 |
+
argv, index = [], 0
|
| 76 |
+
redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
|
| 77 |
+
while index < len(tokens):
|
| 78 |
+
token = tokens[index]
|
| 79 |
+
if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
|
| 80 |
+
index += 1
|
| 81 |
+
token = tokens[index]
|
| 82 |
+
if token in redirects:
|
| 83 |
+
if index + 1 >= len(tokens):
|
| 84 |
+
return None
|
| 85 |
+
target = tokens[index + 1]
|
| 86 |
+
if (not target or any(c in target for c in '$`;&|<>()')
|
| 87 |
+
or target in ('{', '}')):
|
| 88 |
+
return None
|
| 89 |
+
index += 2
|
| 90 |
+
continue
|
| 91 |
+
if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
|
| 92 |
+
return None
|
| 93 |
+
argv.append(token)
|
| 94 |
+
index += 1
|
| 95 |
+
return argv or None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _invocation(text):
|
| 99 |
+
substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
|
| 100 |
+
if substitution:
|
| 101 |
+
inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
|
| 102 |
+
argv = _simple_argv(inner)
|
| 103 |
+
return (argv, 'assignment_substitution') if argv else (None, None)
|
| 104 |
+
return _simple_argv(text), 'simple'
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _guard_end(statements, start):
|
| 108 |
+
depth = 1
|
| 109 |
+
for index in range(start + 1, len(statements)):
|
| 110 |
+
item = statements[index]
|
| 111 |
+
if re.match(r'^if\s', item):
|
| 112 |
+
depth += 1
|
| 113 |
+
elif item == 'fi':
|
| 114 |
+
depth -= 1
|
| 115 |
+
if depth == 0:
|
| 116 |
+
return index
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _nonzero_exit_body(statements):
|
| 121 |
+
"""Only literal logging followed by a final unconditional nonzero exit."""
|
| 122 |
+
if not statements:
|
| 123 |
+
return False
|
| 124 |
+
for index, statement in enumerate(statements):
|
| 125 |
+
argv = _simple_argv(statement)
|
| 126 |
+
if not argv:
|
| 127 |
+
return False
|
| 128 |
+
if argv[0] == 'exit':
|
| 129 |
+
return (index == len(statements) - 1 and len(argv) == 2
|
| 130 |
+
and argv[1].isdigit() and 1 <= int(argv[1]) <= 255)
|
| 131 |
+
if argv[0] not in ('echo', 'printf'):
|
| 132 |
+
return False
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def shell_invocations(text):
|
| 137 |
+
"""Return ordered, actually evaluated invocation nodes in the supported subset.
|
| 138 |
+
|
| 139 |
+
fail_fast is a structural proof: a simple command/assignment runs under
|
| 140 |
+
errexit, or a negated test exits nonzero on failure. This is not a complete
|
| 141 |
+
shell interpreter, and unsupported syntax earns no invocation credit.
|
| 142 |
+
"""
|
| 143 |
+
statements = _statements(text)
|
| 144 |
+
# Function definitions or dynamic shell mutation can shadow the command or
|
| 145 |
+
# `exit` itself. They are outside this objective subset, even if uncalled.
|
| 146 |
+
if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s)
|
| 147 |
+
or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
|
| 148 |
+
for s in statements):
|
| 149 |
+
return []
|
| 150 |
+
constants, result, index, errexit = {}, [], 0, False
|
| 151 |
+
assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
|
| 152 |
+
variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 153 |
+
while index < len(statements):
|
| 154 |
+
statement = statements[index]
|
| 155 |
+
literal = assignment.fullmatch(statement)
|
| 156 |
+
if literal:
|
| 157 |
+
constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
|
| 158 |
+
index += 1
|
| 159 |
+
continue
|
| 160 |
+
statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement)
|
| 161 |
+
setting = _simple_argv(statement)
|
| 162 |
+
if setting and setting[0] == 'set':
|
| 163 |
+
flag_index = 1
|
| 164 |
+
while flag_index < len(setting):
|
| 165 |
+
flag = setting[flag_index]
|
| 166 |
+
if flag == '--' or not flag.startswith(('-', '+')):
|
| 167 |
+
break # Remaining words set positional parameters.
|
| 168 |
+
if not re.fullmatch(r'[-+][eufxEo]+', flag):
|
| 169 |
+
return [] # e.g. `set -n` suppresses execution entirely.
|
| 170 |
+
if 'e' in flag[1:]:
|
| 171 |
+
errexit = flag[0] == '-'
|
| 172 |
+
if 'o' in flag[1:]:
|
| 173 |
+
if flag_index + 1 >= len(setting):
|
| 174 |
+
return []
|
| 175 |
+
option = setting[flag_index + 1]
|
| 176 |
+
if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
|
| 177 |
+
return []
|
| 178 |
+
if option == 'errexit':
|
| 179 |
+
errexit = flag[0] == '-'
|
| 180 |
+
flag_index += 1
|
| 181 |
+
flag_index += 1
|
| 182 |
+
index += 1
|
| 183 |
+
continue
|
| 184 |
+
if re.match(r'^if\s', statement):
|
| 185 |
+
end = _guard_end(statements, index)
|
| 186 |
+
if end is None:
|
| 187 |
+
return []
|
| 188 |
+
negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
|
| 189 |
+
if (negated and index + 1 < end
|
| 190 |
+
and statements[index + 1] == 'then'
|
| 191 |
+
and _nonzero_exit_body(statements[index + 2:end])):
|
| 192 |
+
argv, kind = _invocation(negated.group(1).strip())
|
| 193 |
+
if argv:
|
| 194 |
+
if argv[0] == 'false':
|
| 195 |
+
break
|
| 196 |
+
result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
|
| 197 |
+
'fail_fast': True, 'statement_index': index})
|
| 198 |
+
else:
|
| 199 |
+
return []
|
| 200 |
+
else:
|
| 201 |
+
# Arbitrary conditions may terminate the script or shadow its
|
| 202 |
+
# commands. Do not infer a reachable suffix through them.
|
| 203 |
+
return []
|
| 204 |
+
# Bodies are never credited and may have assigned local variables.
|
| 205 |
+
constants.clear()
|
| 206 |
+
index = end + 1
|
| 207 |
+
continue
|
| 208 |
+
if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
|
| 209 |
+
# Unsupported compounds are not searched for command substrings.
|
| 210 |
+
return []
|
| 211 |
+
argv, kind = _invocation(statement)
|
| 212 |
+
if not argv:
|
| 213 |
+
# An unparsed statement may change control flow or shell state.
|
| 214 |
+
# Skipping it would incorrectly credit an unreachable suffix.
|
| 215 |
+
return []
|
| 216 |
+
if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare',
|
| 217 |
+
'typeset', 'local', 'read', 'mapfile', 'readarray',
|
| 218 |
+
'unset', 'readonly', '[', '[[', 'test'):
|
| 219 |
+
return []
|
| 220 |
+
if argv[0] == 'exit' or (argv[0] == 'false' and errexit):
|
| 221 |
+
break
|
| 222 |
+
if kind == 'assignment_substitution':
|
| 223 |
+
assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
|
| 224 |
+
if assigned:
|
| 225 |
+
constants.pop(assigned.group(1), None)
|
| 226 |
+
result.append({'command': shlex.join(argv), 'kind': kind,
|
| 227 |
+
'fail_fast': errexit, 'statement_index': index})
|
| 228 |
+
index += 1
|
| 229 |
+
return result
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_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/8fe6482e81e3ebba_q1/evaluator/legacy_tests/verifiers.py
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verifier execution engine and fail-closed self-tests.
|
| 2 |
+
|
| 3 |
+
New verified tasks use atomic_json (complete shape plus scalar assertions).
|
| 4 |
+
Legacy verifier types remain readable so historical runs can still be audited.
|
| 5 |
+
自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 14 |
+
reference_bundle,
|
| 15 |
+
self_test_workspace_evaluator)
|
| 16 |
+
except ImportError: # portable task copies these modules beside each other
|
| 17 |
+
from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 18 |
+
reference_bundle,
|
| 19 |
+
self_test_workspace_evaluator)
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger("pipeline")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _norm(s):
|
| 25 |
+
return str(s).strip().lower()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _json_value(value):
|
| 29 |
+
"""Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
|
| 30 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 31 |
+
return value
|
| 32 |
+
text = str(value).strip()
|
| 33 |
+
match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
|
| 34 |
+
if match:
|
| 35 |
+
text = match.group(1).strip()
|
| 36 |
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
|
| 37 |
+
text = re.sub(r"\s*```$", "", text)
|
| 38 |
+
start_obj, start_arr = text.find("{"), text.find("[")
|
| 39 |
+
starts = [x for x in (start_obj, start_arr) if x >= 0]
|
| 40 |
+
if starts:
|
| 41 |
+
start = min(starts)
|
| 42 |
+
closing = "}" if text[start] == "{" else "]"
|
| 43 |
+
end = text.rfind(closing)
|
| 44 |
+
if end >= start:
|
| 45 |
+
text = text[start:end + 1]
|
| 46 |
+
try:return json.loads(text)
|
| 47 |
+
except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
from r9_json import parse_single as _r9_parse_single
|
| 51 |
+
_json_value = _r9_parse_single
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _canonical_json(value):
|
| 55 |
+
if isinstance(value, dict):
|
| 56 |
+
return {key: _canonical_json(value[key]) for key in sorted(value)}
|
| 57 |
+
if isinstance(value, list):
|
| 58 |
+
values = [_canonical_json(item) for item in value]
|
| 59 |
+
return sorted(values, key=lambda item: json.dumps(
|
| 60 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 61 |
+
return value
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _atomic_prepare(value, list_order):
|
| 65 |
+
if isinstance(value, dict):
|
| 66 |
+
return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
|
| 67 |
+
if isinstance(value, list):
|
| 68 |
+
values = [_atomic_prepare(item, list_order) for item in value]
|
| 69 |
+
if list_order == "unordered":
|
| 70 |
+
values.sort(key=lambda item: json.dumps(
|
| 71 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 72 |
+
return values
|
| 73 |
+
return value
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _atomic_shape(value):
|
| 77 |
+
if isinstance(value, dict):
|
| 78 |
+
return {"type": "object", "keys": {
|
| 79 |
+
key: _atomic_shape(item) for key, item in value.items()}}
|
| 80 |
+
if isinstance(value, list):
|
| 81 |
+
return {"type": "array", "length": len(value),
|
| 82 |
+
"items": [_atomic_shape(item) for item in value]}
|
| 83 |
+
if isinstance(value, bool):
|
| 84 |
+
return {"type": "boolean"}
|
| 85 |
+
if value is None:
|
| 86 |
+
return {"type": "null"}
|
| 87 |
+
if isinstance(value, (int, float)):
|
| 88 |
+
return {"type": "number"}
|
| 89 |
+
return {"type": "string"}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _atomic_leaves(value, path="$", tokens=()):
|
| 93 |
+
if isinstance(value, dict):
|
| 94 |
+
out = []
|
| 95 |
+
for key, item in value.items():
|
| 96 |
+
out.extend(_atomic_leaves(
|
| 97 |
+
item, path + "." + key, tokens + (key,)))
|
| 98 |
+
return out
|
| 99 |
+
if isinstance(value, list):
|
| 100 |
+
out = []
|
| 101 |
+
for index, item in enumerate(value):
|
| 102 |
+
out.extend(_atomic_leaves(
|
| 103 |
+
item, f"{path}[{index}]", tokens + (index,)))
|
| 104 |
+
return out
|
| 105 |
+
return [(path, tokens, value)]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _normalize_path_equivalence_tokens(values):
|
| 109 |
+
"""Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
|
| 110 |
+
normalized = []
|
| 111 |
+
for tokens in values or []:
|
| 112 |
+
if (not isinstance(tokens, (list, tuple)) or not tokens or
|
| 113 |
+
any(not isinstance(token, (str, int)) for token in tokens)):
|
| 114 |
+
raise ValueError("path equivalence tokens must be non-empty JSON paths")
|
| 115 |
+
item = list(tokens)
|
| 116 |
+
if item not in normalized:
|
| 117 |
+
normalized.append(item)
|
| 118 |
+
return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _path_value(value):
|
| 122 |
+
"""Normalize only portable path spelling, not general answer text."""
|
| 123 |
+
if not isinstance(value, str):
|
| 124 |
+
return None
|
| 125 |
+
text = value.strip().replace("\\", "/")
|
| 126 |
+
if text != "/":
|
| 127 |
+
text = text.rstrip("/")
|
| 128 |
+
return text
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
|
| 132 |
+
path_equivalence_tokens=None):
|
| 133 |
+
"""Freeze a complete JSON shape plus one assertion for every scalar leaf."""
|
| 134 |
+
if list_order not in {"ordered", "unordered"}:
|
| 135 |
+
raise ValueError(f"unsupported atomic list_order: {list_order}")
|
| 136 |
+
tolerance = float(float_tolerance)
|
| 137 |
+
prepared = _atomic_prepare(_json_value(expected), list_order)
|
| 138 |
+
path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
|
| 139 |
+
assertions = []
|
| 140 |
+
for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
|
| 141 |
+
assertion = {"id": f"leaf_{index:03d}", "path": path,
|
| 142 |
+
"tokens": list(tokens), "operator": "eq", "expected": value}
|
| 143 |
+
if isinstance(value, float):
|
| 144 |
+
assertion.update({"operator": "abs_diff", "tolerance": tolerance})
|
| 145 |
+
elif list(tokens) in path_tokens:
|
| 146 |
+
if not isinstance(value, str):
|
| 147 |
+
raise ValueError("path equivalence can only target string leaves")
|
| 148 |
+
assertion["operator"] = "path_eq"
|
| 149 |
+
assertions.append(assertion)
|
| 150 |
+
compiled = {
|
| 151 |
+
"type": "atomic_json", "version": 2 if path_tokens else 1,
|
| 152 |
+
"list_order": list_order,
|
| 153 |
+
"float_tolerance": tolerance,
|
| 154 |
+
"completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
|
| 155 |
+
"assertions": assertions,
|
| 156 |
+
}
|
| 157 |
+
if path_tokens:
|
| 158 |
+
compiled["path_equivalence_tokens"] = path_tokens
|
| 159 |
+
return compiled
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _shape_differences(expected, actual, path="$"):
|
| 163 |
+
if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
|
| 164 |
+
return [f"{path}: expected {expected.get('type')}, got "
|
| 165 |
+
f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
|
| 166 |
+
kind = expected.get("type")
|
| 167 |
+
if kind == "object":
|
| 168 |
+
expected_keys = set((expected.get("keys") or {}))
|
| 169 |
+
actual_keys = set((actual.get("keys") or {}))
|
| 170 |
+
differences = [f"{path}: missing key {key}" for key in sorted(
|
| 171 |
+
expected_keys - actual_keys)]
|
| 172 |
+
differences.extend(f"{path}: extra key {key}" for key in sorted(
|
| 173 |
+
actual_keys - expected_keys))
|
| 174 |
+
for key in sorted(expected_keys & actual_keys):
|
| 175 |
+
differences.extend(_shape_differences(
|
| 176 |
+
expected["keys"][key], actual["keys"][key], path + "." + key))
|
| 177 |
+
return differences
|
| 178 |
+
if kind == "array":
|
| 179 |
+
differences = []
|
| 180 |
+
if actual.get("length") != expected.get("length"):
|
| 181 |
+
differences.append(
|
| 182 |
+
f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
|
| 183 |
+
for index, (expected_item, actual_item) in enumerate(zip(
|
| 184 |
+
expected.get("items") or [], actual.get("items") or [])):
|
| 185 |
+
differences.extend(_shape_differences(
|
| 186 |
+
expected_item, actual_item, f"{path}[{index}]"))
|
| 187 |
+
return differences
|
| 188 |
+
return []
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _atomic_get(value, tokens):
|
| 192 |
+
current = value
|
| 193 |
+
for token in tokens:
|
| 194 |
+
current = current[token]
|
| 195 |
+
return current
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _int_values(value):
|
| 199 |
+
if isinstance(value, (list, tuple)):
|
| 200 |
+
out = []
|
| 201 |
+
for item in value:
|
| 202 |
+
out.extend(_int_values(item))
|
| 203 |
+
return out
|
| 204 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 205 |
+
return [value]
|
| 206 |
+
return [int(number) for number in re.findall(r"\d+", str(value or ""))]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _finding_type(value):
|
| 210 |
+
text = str(value or "").lower().replace("-", "_")
|
| 211 |
+
if "duplicate" in text:
|
| 212 |
+
return "duplicate_rows"
|
| 213 |
+
if ("none" in text or "null" in text) and "check" in text:
|
| 214 |
+
return "none_check"
|
| 215 |
+
if "missing" in text or "empty" in text or "null" in text:
|
| 216 |
+
return "missing"
|
| 217 |
+
if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
|
| 218 |
+
return "outlier"
|
| 219 |
+
if "invalid" in text and "config" in text:
|
| 220 |
+
return "invalid_config"
|
| 221 |
+
if "off" in text and "one" in text:
|
| 222 |
+
return "off_by_one"
|
| 223 |
+
return text.strip().replace(" ", "_")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _normalized_findings(value, family):
|
| 227 |
+
obj = _json_value(value)
|
| 228 |
+
findings = obj.get("findings") if isinstance(obj, dict) else None
|
| 229 |
+
if not isinstance(findings, list):
|
| 230 |
+
raise ValueError("answer must contain a findings array")
|
| 231 |
+
normalized = set()
|
| 232 |
+
for finding in findings:
|
| 233 |
+
if not isinstance(finding, dict):
|
| 234 |
+
raise ValueError("each finding must be an object")
|
| 235 |
+
# The public contract uses type/function. Accept common semantically
|
| 236 |
+
# equivalent aliases as a robustness layer, while still comparing the
|
| 237 |
+
# normalized values and exact locations against generator-owned GT.
|
| 238 |
+
kind = _finding_type(finding.get("type", finding.get(
|
| 239 |
+
"defect_type", finding.get("defect"))))
|
| 240 |
+
if family == "csv":
|
| 241 |
+
if kind == "duplicate_rows":
|
| 242 |
+
rows = _int_values(finding.get("rows", finding.get("row")))
|
| 243 |
+
if len(rows) != 2:
|
| 244 |
+
raise ValueError("duplicate finding requires exactly two row numbers")
|
| 245 |
+
normalized.add((kind, *sorted(rows)))
|
| 246 |
+
elif kind in {"missing", "outlier"}:
|
| 247 |
+
rows = _int_values(finding.get("row"))
|
| 248 |
+
column = str(finding.get("column") or "").strip().lower()
|
| 249 |
+
if len(rows) != 1 or not column:
|
| 250 |
+
raise ValueError(f"{kind} requires one row and column")
|
| 251 |
+
normalized.add((kind, rows[0], column))
|
| 252 |
+
else:
|
| 253 |
+
raise ValueError(f"unsupported CSV finding type: {kind}")
|
| 254 |
+
elif family == "config":
|
| 255 |
+
if kind != "invalid_config":
|
| 256 |
+
raise ValueError(f"unsupported config finding type: {kind}")
|
| 257 |
+
normalized.add((kind, str(finding.get("path") or "").lower(),
|
| 258 |
+
json.dumps(finding.get("value"), sort_keys=True),
|
| 259 |
+
str(finding.get("expected") or "").lower()))
|
| 260 |
+
elif family == "code":
|
| 261 |
+
if kind not in {"off_by_one", "none_check"}:
|
| 262 |
+
raise ValueError(f"unsupported code finding type: {kind}")
|
| 263 |
+
function = finding.get("function", finding.get("function_name"))
|
| 264 |
+
function = str(function or "").strip().lower()
|
| 265 |
+
if not function:
|
| 266 |
+
raise ValueError(f"{kind} requires a function")
|
| 267 |
+
normalized.add((kind, function))
|
| 268 |
+
else:
|
| 269 |
+
raise ValueError(f"unsupported findings family: {family}")
|
| 270 |
+
return normalized
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _normalized_facts(value):
|
| 274 |
+
obj = _json_value(value)
|
| 275 |
+
facts = obj.get("facts") if isinstance(obj, dict) else None
|
| 276 |
+
if not isinstance(facts, list):
|
| 277 |
+
raise ValueError("answer must contain a facts array")
|
| 278 |
+
def textual(item):
|
| 279 |
+
# The document generator serializes scalar values as visible text. JSON
|
| 280 |
+
# has no way to infer whether the source token "30" was authored from an
|
| 281 |
+
# integer or a string, so facts_match compares that surface text. Nested
|
| 282 |
+
# values retain structural JSON comparison.
|
| 283 |
+
if isinstance(item, (dict, list)):
|
| 284 |
+
return json.dumps(item, sort_keys=True, ensure_ascii=False,
|
| 285 |
+
separators=(",", ":"))
|
| 286 |
+
if item is None:
|
| 287 |
+
return "None"
|
| 288 |
+
return str(item)
|
| 289 |
+
return {(str(fact.get("key") or ""), textual(fact.get("value")))
|
| 290 |
+
for fact in facts if isinstance(fact, dict)}
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def verify(verifier, gt_answer, solver_output, material_paths=None):
|
| 294 |
+
"""执行 verifier。返回 (passed, detail)。"""
|
| 295 |
+
vtype = verifier.get("type")
|
| 296 |
+
try:
|
| 297 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 298 |
+
return evaluate_candidate(verifier, solver_output)
|
| 299 |
+
|
| 300 |
+
if vtype == "json_exact":
|
| 301 |
+
pred = _canonical_json(_json_value(solver_output))
|
| 302 |
+
gold = _canonical_json(_json_value(gt_answer))
|
| 303 |
+
ok = pred == gold
|
| 304 |
+
return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
|
| 305 |
+
|
| 306 |
+
if vtype == "atomic_json":
|
| 307 |
+
try:
|
| 308 |
+
pred = _atomic_prepare(_json_value(solver_output),
|
| 309 |
+
verifier.get("list_order", "ordered"))
|
| 310 |
+
pred_shape = _atomic_shape(pred)
|
| 311 |
+
except RecursionError:
|
| 312 |
+
return False, "candidate JSON nesting is too deep"
|
| 313 |
+
compiled = compile_atomic_verifier(
|
| 314 |
+
gt_answer, verifier.get("list_order", "ordered"),
|
| 315 |
+
verifier.get("float_tolerance", 0.01),
|
| 316 |
+
verifier.get("path_equivalence_tokens"))
|
| 317 |
+
frozen = {key: verifier.get(key) for key in
|
| 318 |
+
("type", "version", "list_order", "float_tolerance",
|
| 319 |
+
"completeness", "assertions", "path_equivalence_tokens")}
|
| 320 |
+
expected_frozen = {key: compiled.get(key) for key in frozen}
|
| 321 |
+
if frozen != expected_frozen:
|
| 322 |
+
return False, {"error": "atomic verifier does not match ground truth"}
|
| 323 |
+
shape_failures = _shape_differences(
|
| 324 |
+
verifier["completeness"]["shape"], pred_shape)
|
| 325 |
+
assertion_results = []
|
| 326 |
+
for assertion in verifier.get("assertions") or []:
|
| 327 |
+
try:
|
| 328 |
+
actual = _atomic_get(pred, assertion["tokens"])
|
| 329 |
+
if assertion["operator"] == "abs_diff":
|
| 330 |
+
passed = abs(float(actual) - float(assertion["expected"])) <= float(
|
| 331 |
+
assertion.get("tolerance", 0.0))
|
| 332 |
+
elif assertion["operator"] == "path_eq":
|
| 333 |
+
passed = (_path_value(actual) is not None and
|
| 334 |
+
_path_value(actual) == _path_value(assertion["expected"]))
|
| 335 |
+
else:
|
| 336 |
+
passed = (actual is assertion["expected"] if
|
| 337 |
+
isinstance(assertion["expected"], bool) else
|
| 338 |
+
actual == assertion["expected"])
|
| 339 |
+
message = "" if passed else (
|
| 340 |
+
f"actual={actual!r} expected={assertion['expected']!r}")
|
| 341 |
+
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
| 342 |
+
actual, passed, message = None, False, f"lookup/compare failed: {exc}"
|
| 343 |
+
assertion_results.append({
|
| 344 |
+
"id": assertion["id"], "path": assertion["path"],
|
| 345 |
+
"operator": assertion["operator"], "expected": assertion["expected"],
|
| 346 |
+
"actual": actual, "passed": passed, "message": message})
|
| 347 |
+
passed_count = sum(item["passed"] for item in assertion_results)
|
| 348 |
+
ok = not shape_failures and passed_count == len(assertion_results)
|
| 349 |
+
return ok, {
|
| 350 |
+
"type": "atomic_json", "completeness_passed": not shape_failures,
|
| 351 |
+
"completeness_failures": shape_failures,
|
| 352 |
+
"assertions_passed": passed_count,
|
| 353 |
+
"assertions_total": len(assertion_results),
|
| 354 |
+
"assertion_pass_rate": (passed_count / len(assertion_results)
|
| 355 |
+
if assertion_results else 1.0),
|
| 356 |
+
"assertions": assertion_results,
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
if vtype == "findings_match":
|
| 360 |
+
family = verifier.get("family")
|
| 361 |
+
pred = _normalized_findings(solver_output, family)
|
| 362 |
+
gold = _normalized_findings(gt_answer, family)
|
| 363 |
+
ok = pred == gold
|
| 364 |
+
return ok, ("findings_match: pass" if ok else
|
| 365 |
+
f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 366 |
+
|
| 367 |
+
if vtype == "facts_match":
|
| 368 |
+
pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
|
| 369 |
+
ok = pred == gold
|
| 370 |
+
return ok, ("facts_match: pass" if ok else
|
| 371 |
+
f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 372 |
+
|
| 373 |
+
if vtype == "exact_match":
|
| 374 |
+
ok = _norm(solver_output) == _norm(gt_answer)
|
| 375 |
+
return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
|
| 376 |
+
|
| 377 |
+
if vtype == "numeric":
|
| 378 |
+
tol = verifier.get("tolerance") or 1e-6
|
| 379 |
+
pred = float(str(solver_output).strip().split()[0])
|
| 380 |
+
gold = float(gt_answer)
|
| 381 |
+
ok = abs(pred - gold) <= tol
|
| 382 |
+
return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
|
| 383 |
+
|
| 384 |
+
if vtype == "set_match":
|
| 385 |
+
pred = set(_as_list(solver_output))
|
| 386 |
+
gold = set(_as_list(gt_answer))
|
| 387 |
+
ok = pred == gold
|
| 388 |
+
return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
|
| 389 |
+
|
| 390 |
+
if vtype == "structured_match":
|
| 391 |
+
pred = _json_value(solver_output)
|
| 392 |
+
gold = _json_value(gt_answer)
|
| 393 |
+
if not isinstance(pred, dict) or not isinstance(gold, dict):
|
| 394 |
+
return False, "structured_match requires JSON objects"
|
| 395 |
+
missing = [f for f in verifier.get("required_fields", []) if f not in pred]
|
| 396 |
+
wrong = [f for f in verifier.get("required_fields", [])
|
| 397 |
+
if f in pred and f in gold and pred[f] != gold[f]]
|
| 398 |
+
ok = not missing and not wrong
|
| 399 |
+
return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
|
| 400 |
+
|
| 401 |
+
if vtype == "execution":
|
| 402 |
+
return False, "execution verifier is disabled in verified-first v2"
|
| 403 |
+
|
| 404 |
+
if vtype == "constraint":
|
| 405 |
+
fails = _check_constraints(verifier.get("criteria", []), solver_output)
|
| 406 |
+
return not fails, f"constraint: failed={fails[:5]}"
|
| 407 |
+
|
| 408 |
+
if vtype == "file_inspection":
|
| 409 |
+
fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
|
| 410 |
+
return not fails, f"file_inspection: failed={fails[:5]}"
|
| 411 |
+
|
| 412 |
+
return False, f"unknown verifier type: {vtype}"
|
| 413 |
+
except Exception as e:
|
| 414 |
+
return False, f"verifier error: {e}"
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _as_list(x):
|
| 418 |
+
if isinstance(x, list):
|
| 419 |
+
return [_norm(i) for i in x]
|
| 420 |
+
# 逗号/换行分隔的字符串
|
| 421 |
+
return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def _check_constraints(criteria, solver_output):
|
| 425 |
+
"""criteria: ["must contain X", "must be valid json", "length <= 500"]"""
|
| 426 |
+
fails = []
|
| 427 |
+
text = str(solver_output)
|
| 428 |
+
for c in criteria:
|
| 429 |
+
cl = c.lower()
|
| 430 |
+
if cl.startswith("must contain "):
|
| 431 |
+
needle = c[len("must contain "):]
|
| 432 |
+
if needle.lower() not in text.lower():
|
| 433 |
+
fails.append(c)
|
| 434 |
+
elif "valid json" in cl:
|
| 435 |
+
try:
|
| 436 |
+
json.loads(text)
|
| 437 |
+
except Exception:
|
| 438 |
+
fails.append(c)
|
| 439 |
+
elif cl.startswith("length <="):
|
| 440 |
+
limit = int(cl.split("<=")[1].strip())
|
| 441 |
+
if len(text) > limit:
|
| 442 |
+
fails.append(c)
|
| 443 |
+
else:
|
| 444 |
+
# Deterministic verifier DSL is closed-world: unknown checks fail.
|
| 445 |
+
fails.append(f"unsupported criterion: {c}")
|
| 446 |
+
return fails
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _inspect_files(expected, material_paths):
|
| 450 |
+
fails = []
|
| 451 |
+
paths = set(material_paths or [])
|
| 452 |
+
for e in expected:
|
| 453 |
+
fname = e.get("filename") if isinstance(e, dict) else str(e)
|
| 454 |
+
if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
|
| 455 |
+
fails.append(f"missing file: {fname}")
|
| 456 |
+
return fails
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
# ---------------- 自测 ----------------
|
| 460 |
+
|
| 461 |
+
def build_correct_solution(verifier, gt_answer, planted_info):
|
| 462 |
+
"""由埋点/ground truth 直接构造正确解。"""
|
| 463 |
+
vtype = verifier.get("type")
|
| 464 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 465 |
+
return reference_bundle(verifier)
|
| 466 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
|
| 467 |
+
"set_match", "structured_match"):
|
| 468 |
+
return gt_answer
|
| 469 |
+
if vtype == "constraint":
|
| 470 |
+
parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
|
| 471 |
+
if c.lower().startswith("must contain ")]
|
| 472 |
+
return " ".join(parts) if parts else str(gt_answer)
|
| 473 |
+
# execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
|
| 474 |
+
return None
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def build_perturbed_solution(verifier, gt_answer, planted_info):
|
| 478 |
+
"""破坏埋点构造扰动解。"""
|
| 479 |
+
vtype = verifier.get("type")
|
| 480 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 481 |
+
files = list(reference_bundle(verifier).get("files") or [])
|
| 482 |
+
return {"files": files[1:] if len(files) > 1 else []}
|
| 483 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
|
| 484 |
+
gold = _json_value(gt_answer)
|
| 485 |
+
if isinstance(gold, dict):
|
| 486 |
+
perturbed = dict(gold)
|
| 487 |
+
key = next(iter(perturbed), "__missing__")
|
| 488 |
+
if key in perturbed:
|
| 489 |
+
perturbed.pop(key)
|
| 490 |
+
else:
|
| 491 |
+
perturbed["__wrong__"] = True
|
| 492 |
+
return perturbed
|
| 493 |
+
if isinstance(gold, list):
|
| 494 |
+
return gold[:-1] if gold else ["__wrong__"]
|
| 495 |
+
return "__wrong__"
|
| 496 |
+
if vtype in ("exact_match", "numeric"):
|
| 497 |
+
return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
|
| 498 |
+
if vtype == "set_match":
|
| 499 |
+
gold = _as_list(gt_answer)
|
| 500 |
+
return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
|
| 501 |
+
if vtype == "structured_match":
|
| 502 |
+
fields = verifier.get("required_fields", [])
|
| 503 |
+
return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
|
| 504 |
+
if vtype == "constraint":
|
| 505 |
+
return "perturbed output lacking required content"
|
| 506 |
+
return None
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def self_test(verifier, gt_answer, planted_info, material_paths):
|
| 510 |
+
"""返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
|
| 511 |
+
|
| 512 |
+
之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
|
| 513 |
+
可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
|
| 514 |
+
"""
|
| 515 |
+
if verifier.get("type") == WORKSPACE_EVALUATOR:
|
| 516 |
+
return self_test_workspace_evaluator(verifier)
|
| 517 |
+
correct = build_correct_solution(verifier, gt_answer, planted_info)
|
| 518 |
+
perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
|
| 519 |
+
if correct is None or perturbed is None:
|
| 520 |
+
return False, (f"cannot self-test verifier type {verifier.get('type')} "
|
| 521 |
+
"(execution/file_inspection need real correct/perturbed solutions)")
|
| 522 |
+
ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
|
| 523 |
+
ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
|
| 524 |
+
passed = ok1 and not ok2
|
| 525 |
+
return passed, {"correct": d1, "perturbed": d2}
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/r9_json.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""JSON wire parsing and native-type equality for the R9 task copies.
|
| 2 |
+
|
| 3 |
+
No expected answers are defined here. Single complete JSON fences are accepted
|
| 4 |
+
only as a transport wrapper when requested by the calling task.
|
| 5 |
+
"""
|
| 6 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def no_duplicates(pairs):
|
| 13 |
+
result = {}
|
| 14 |
+
for key, value in pairs:
|
| 15 |
+
if key in result:
|
| 16 |
+
raise ValueError('duplicate JSON key')
|
| 17 |
+
result[key] = value
|
| 18 |
+
return result
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _finite_tree(value):
|
| 22 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 23 |
+
raise ValueError('non-finite JSON number')
|
| 24 |
+
if isinstance(value, dict):
|
| 25 |
+
for item in value.values():
|
| 26 |
+
_finite_tree(item)
|
| 27 |
+
elif isinstance(value, list):
|
| 28 |
+
for item in value:
|
| 29 |
+
_finite_tree(item)
|
| 30 |
+
return value
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def parse_single(value, allow_fence=True):
|
| 34 |
+
"""Parse the entire response; no prefix/suffix or duplicate keys allowed."""
|
| 35 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 36 |
+
return _finite_tree(value)
|
| 37 |
+
if isinstance(value, bytes):
|
| 38 |
+
value = value.decode('utf-8-sig')
|
| 39 |
+
text = str(value).lstrip('\ufeff').strip()
|
| 40 |
+
if allow_fence and text.startswith('```'):
|
| 41 |
+
match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I)
|
| 42 |
+
if match is None:
|
| 43 |
+
raise ValueError('not one complete JSON fence')
|
| 44 |
+
text = match.group(1)
|
| 45 |
+
return _finite_tree(json.loads(
|
| 46 |
+
text, object_pairs_hook=no_duplicates,
|
| 47 |
+
parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number'))))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_file(path):
|
| 51 |
+
"""Files must contain raw JSON; Markdown fences are not JSON file bytes."""
|
| 52 |
+
with open(path, 'r', encoding='utf-8-sig') as stream:
|
| 53 |
+
return parse_single(stream.read(), allow_fence=False)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def strict_equal(actual, expected, number_equivalence=False):
|
| 57 |
+
"""Preserve keys, order and every native type; booleans never equal numbers.
|
| 58 |
+
|
| 59 |
+
Set number_equivalence only if the public contract says a generic number
|
| 60 |
+
rather than an integer. It accepts finite integral numeric equivalents.
|
| 61 |
+
"""
|
| 62 |
+
if type(actual) is not type(expected):
|
| 63 |
+
if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float):
|
| 64 |
+
return math.isfinite(actual) and math.isfinite(expected) and actual == expected
|
| 65 |
+
return False
|
| 66 |
+
if isinstance(expected, dict):
|
| 67 |
+
return set(actual) == set(expected) and all(
|
| 68 |
+
strict_equal(actual[key], value, number_equivalence) for key, value in expected.items())
|
| 69 |
+
if isinstance(expected, list):
|
| 70 |
+
return len(actual) == len(expected) and all(
|
| 71 |
+
strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected))
|
| 72 |
+
if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)):
|
| 73 |
+
return False
|
| 74 |
+
return actual == expected
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/grading/verified_config.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:02bcf80063d9a42df51c0d7e4289e2c6f78a92e85f02d2f29178510732e50ca6
|
| 3 |
+
size 4081
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/instruction.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
We're building a display-only custom component for our admin panel on a Laravel project running MoonShine 3.x and need to follow the project's mandated component conventions. Answer these four questions: q1: Which base class must a component extend when it contains other components? q2: What must fluent configuration methods return for method chaining? q3: In which directory should the component's Blade view file be placed? q4: What visibility must the assets() method have? Return one JSON object using this schema exactly once, replacing each placeholder with the bare project-defined value: {"answers":{"q1":"string","q2":"string","q3":"string","q4":"string"}}
|
benchmarks/skillbench-venus-e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-component
|
| 3 |
+
description: Create custom MoonShine display components for dashboards, widgets, badges, and UI decoration. Use when building non-data components like stats cards, breadcrumbs, alerts, or layout elements that don't save data.
|
| 4 |
+
argument-hint: [component description]
|
| 5 |
+
allowed-tools: Read Grep Glob Edit Write Bash
|
| 6 |
+
compatibility: Requires Laravel with MoonShine 3.x package installed
|
| 7 |
+
metadata:
|
| 8 |
+
author: moonshine-software
|
| 9 |
+
version: "1.0"
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
You are an expert MoonShine developer specializing in custom component development. Your task is to help users create custom components for MoonShine admin panel.
|
| 13 |
+
|
| 14 |
+
## Your Resources
|
| 15 |
+
|
| 16 |
+
You have access to comprehensive guidelines in `.guidelines/components-development.md` file. This file contains:
|
| 17 |
+
- Complete component structure and anatomy
|
| 18 |
+
- Components vs Fields comparison
|
| 19 |
+
- Fluent methods and viewData()
|
| 20 |
+
- Slots and nested components patterns
|
| 21 |
+
- Complete examples (Alert, StatsCard, Breadcrumbs)
|
| 22 |
+
|
| 23 |
+
## Critical Rules (Read from guidelines)
|
| 24 |
+
|
| 25 |
+
Before starting, you MUST read and follow these rules from `.guidelines/components-development.md`:
|
| 26 |
+
|
| 27 |
+
1. **Components are for DISPLAY only** - They don't save data, only show content
|
| 28 |
+
2. **No field modes** - Components don't have default/preview/raw modes
|
| 29 |
+
3. **Fluent methods MUST return `static`** - For method chaining
|
| 30 |
+
4. **ALWAYS add `{{ $attributes }}`** - To root element for customization
|
| 31 |
+
5. **Use `value()` for closures** - Import `use function MoonShine\UI\Components\Layout\value`
|
| 32 |
+
6. **`viewData()` passes ALL data** - Unlike fields, no automatic system data
|
| 33 |
+
7. **`assets()` method MUST be `protected`** - NOT public
|
| 34 |
+
8. **Extend correct base class** - `MoonShineComponent` or `AbstractWithComponents`
|
| 35 |
+
9. **Move logic to `prepareBeforeRender()`** - NEVER write `@php` blocks in Blade views
|
| 36 |
+
|
| 37 |
+
## Components vs Fields
|
| 38 |
+
|
| 39 |
+
**Critical difference:**
|
| 40 |
+
|
| 41 |
+
| Feature | Fields | Components |
|
| 42 |
+
|---------|--------|-----------|
|
| 43 |
+
| Purpose | Data input/output | UI decoration |
|
| 44 |
+
| Saves data | Yes | No |
|
| 45 |
+
| Has modes | Yes | No |
|
| 46 |
+
| System data | Auto (value, attributes, etc.) | None |
|
| 47 |
+
| Used for | Forms, Tables | Layouts, Pages |
|
| 48 |
+
|
| 49 |
+
**When to use Components:**
|
| 50 |
+
- Displaying static content
|
| 51 |
+
- UI decoration (headers, footers, alerts)
|
| 52 |
+
- Grouping other components
|
| 53 |
+
- Dashboard widgets
|
| 54 |
+
- Breadcrumbs, menus, badges
|
| 55 |
+
|
| 56 |
+
**When to use Fields:**
|
| 57 |
+
- User input required
|
| 58 |
+
- Data needs to be saved
|
| 59 |
+
- Forms and tables
|
| 60 |
+
|
| 61 |
+
## Your Task
|
| 62 |
+
|
| 63 |
+
When creating custom components:
|
| 64 |
+
|
| 65 |
+
1. **Read the guidelines**: Open and study `.guidelines/components-development.md`
|
| 66 |
+
2. **Understand the request**: What kind of component does the user need?
|
| 67 |
+
3. **Choose base class**:
|
| 68 |
+
- `MoonShineComponent` - Simple components
|
| 69 |
+
- `AbstractWithComponents` - Components that contain other components
|
| 70 |
+
4. **Plan component structure**:
|
| 71 |
+
- What properties does it need?
|
| 72 |
+
- What fluent methods should it have?
|
| 73 |
+
- Does it need slots?
|
| 74 |
+
5. **Implement the component**:
|
| 75 |
+
- Create PHP class in `app/MoonShine/Components/ComponentName.php`
|
| 76 |
+
- Create Blade view in `resources/views/admin/components/component-name.blade.php`
|
| 77 |
+
- Add fluent methods
|
| 78 |
+
- Implement `viewData()`
|
| 79 |
+
|
| 80 |
+
## Important Notes
|
| 81 |
+
|
| 82 |
+
### File Locations
|
| 83 |
+
- **PHP Class**: `app/MoonShine/Components/YourComponent.php`
|
| 84 |
+
- **Blade View**: `resources/views/admin/components/your-component.blade.php`
|
| 85 |
+
|
| 86 |
+
### Essential Methods
|
| 87 |
+
|
| 88 |
+
**`viewData()`** - Pass ALL data to Blade view:
|
| 89 |
+
```php
|
| 90 |
+
protected function viewData(): array
|
| 91 |
+
{
|
| 92 |
+
return [
|
| 93 |
+
'title' => value($this->title),
|
| 94 |
+
'items' => $this->items,
|
| 95 |
+
];
|
| 96 |
+
}
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
**`prepareBeforeRender()`** - Process logic BEFORE rendering:
|
| 100 |
+
```php
|
| 101 |
+
protected function prepareBeforeRender(): void
|
| 102 |
+
{
|
| 103 |
+
parent::prepareBeforeRender();
|
| 104 |
+
// Prepare attributes, merge styles here
|
| 105 |
+
}
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
**Fluent methods** - Configure the component:
|
| 109 |
+
```php
|
| 110 |
+
public function title(string $title): static
|
| 111 |
+
{
|
| 112 |
+
$this->title = $title;
|
| 113 |
+
return $this;
|
| 114 |
+
}
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
### Blade Template
|
| 118 |
+
|
| 119 |
+
```blade
|
| 120 |
+
@props([
|
| 121 |
+
'title' => '',
|
| 122 |
+
'items' => [],
|
| 123 |
+
])
|
| 124 |
+
|
| 125 |
+
<div {{ $attributes->merge(['class' => 'my-component']) }}>
|
| 126 |
+
<h3>{{ $title }}</h3>
|
| 127 |
+
@foreach($items as $item)
|
| 128 |
+
<div>{{ $item }}</div>
|
| 129 |
+
@endforeach
|
| 130 |
+
</div>
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
### Nested Components
|
| 134 |
+
|
| 135 |
+
For components containing other components, extend `AbstractWithComponents`:
|
| 136 |
+
|
| 137 |
+
```php
|
| 138 |
+
class Container extends AbstractWithComponents
|
| 139 |
+
{
|
| 140 |
+
public function __construct(
|
| 141 |
+
iterable $components = [],
|
| 142 |
+
protected string $title = ''
|
| 143 |
+
) {
|
| 144 |
+
parent::__construct($components);
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
**In Blade:**
|
| 150 |
+
```blade
|
| 151 |
+
<x-moonshine::components :components="$components" />
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
## User Request
|
| 155 |
+
|
| 156 |
+
$ARGUMENTS
|
benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/task.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4c38b0b33163ffd50dfd9b6190fb12571f4d8846de05b2e9c1ce0ab3a3330b34
|
| 3 |
+
size 1597
|
benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37
|
| 3 |
+
size 83
|
benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_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/903718834b4c9bd4_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/903718834b4c9bd4_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/903718834b4c9bd4_q1/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
root=Path(__file__).resolve().parent
|
| 5 |
+
sys.path.insert(0,str(root/'legacy_tests'))
|
| 6 |
+
from evaluate import evaluate
|
| 7 |
+
t=json.loads((root/'legacy-task.json').read_text())
|
| 8 |
+
mode=t['workspace']['candidate_mode']
|
| 9 |
+
r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
|
| 10 |
+
if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
|
| 11 |
+
if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
|
| 12 |
+
print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
|