diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_previous_check.py b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_previous_check.py new file mode 100644 index 0000000000000000000000000000000000000000..49036eb979f7cc74e83068ca7631e34e0e44c637 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_previous_check.py @@ -0,0 +1,8 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from r9_runtime_compat import install as _r9_runtime_install +_r9_runtime_install() +from pathlib import Path +import format_checks +from more_checks import HANDLERS +format_checks.HANDLERS.update(HANDLERS) +format_checks.run('8bd9dcf9cfecdef4b5ec4674',Path(__file__).resolve().parent) diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_program_checks.py b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_program_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..95489975be78d6cae5e2f56cff58a940f1697efd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_program_checks.py @@ -0,0 +1,355 @@ +"""Supplemental public-contract checks; no stored solution or trajectory input. + +Run only inside the isolated CPU grader container. Existing criterion IDs and +weights are preserved. Candidate programs execute in fresh input workspaces. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import collections +import csv +import io +import json +import math +import os +import re +import shutil +import statistics +import subprocess +import sys +import tempfile +from pathlib import Path + +from r9_json import parse_file, strict_equal + +HERE = Path(__file__).resolve().parent +CAND = Path(os.environ.get('MYBENCH_CANDIDATE_DIR', os.environ.get('MYBENCH_CANDIDATE', '/candidate'))) + + +def clone(folder): + root = Path(folder) / 'workspace' + shutil.copytree(CAND, root, symlinks=True, ignore=shutil.ignore_patterns('__pycache__', '.git', '.venv')) + return root + + +def remove(path): + if path.is_symlink() or path.is_file(): + path.unlink() + elif path.is_dir(): + shutil.rmtree(path) + + +def launch(script, files, output, args=()): + with tempfile.TemporaryDirectory(prefix='r9-public-panel-') as folder: + root = clone(folder) + remove(root / output) + for name, value in files.items(): + target = root / name + remove(target) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(value) + process = subprocess.run([sys.executable, script] + list(args), cwd=root, + capture_output=True, text=True, timeout=35) + try: + raw = (root / output).read_text() + except (OSError, UnicodeError): + raw = None + try: + parsed = parse_file(root / output) + except (OSError, ValueError, TypeError, UnicodeError): + parsed = None + return process.returncode, process.stdout, raw, parsed + + +def constrain(checks, ids, ok, reason): + for check in checks: + if str(check['id']) in set(map(str, ids)): + check['passed'] = bool(check.get('passed')) and bool(ok) + check['reason'] = str(check.get('reason', '')) + '; R9 ' + reason + + +def old_checks(): + process = subprocess.run([sys.executable, str(HERE / 'r9_previous_check.py')], + capture_output=True, text=True, timeout=480) + for line in reversed(process.stdout.splitlines()): + try: + value = json.loads(line) + if isinstance(value, dict) and isinstance(value.get('checks'), list): + return value['checks'] + except ValueError: + pass + raise RuntimeError('previous grader did not return checks') + + +def azure(checks): + # No empty/zero-mean usage: the public CV formula does not define that case. + panels = [ + ({'fresh-a': [7, 13], 'fresh-b': [4, 16], 'single': [5]}, + [('Reservation', 90, 11.75), ('SavingsPlan', 89.99, 17.5), + ('SavingsPlan', 97, 2.25), ('Other', 91, 3)]), + ({'same': [8, 8, 8], 'wide': [1, 4, 9, 20]}, []), + ] + scripts = sorted(p.name for p in CAND.glob('*.py')) + entries = [] + for script in scripts: + states = [True] * 5 + try: + for usage, rows in panels: + recs = {'value': [{'id': '/subscriptions/fresh-a', 'kind': kind, + 'properties': {'recommendationDetails': { + 'commitmentAmount': amount, + 'averageUtilizationPercentage': util}}} + for kind, util, amount in rows]} + rc, out, raw, data = launch(script, { + 'data/hourly_usage.json': json.dumps(usage), + 'data/recommendations.json': json.dumps(recs)}, 'report.json') + shape = isinstance(data, dict) and all(k in data for k in ( + 'subscriptions', 'counts', 'eligible_commitment_sum', 'mg_scope_commitment')) + states[0] &= rc == 0 and shape + states[4] &= shape + subs = data.get('subscriptions') if shape else None + valid_subs = isinstance(subs, dict) and set(subs) == set(usage) + if valid_subs: + for name, values in usage.items(): + cv = statistics.pstdev(values) / statistics.mean(values) + classification = 'stable' if cv < .3 else 'variable' if cv < .6 else 'volatile' + row = subs[name] + valid_subs &= isinstance(row, dict) and type(row.get('cv')) in (int, float) + valid_subs &= valid_subs and math.isfinite(row['cv']) and abs(row['cv'] - cv) <= .005 + valid_subs &= valid_subs and row.get('classification') == classification + states[1] &= valid_subs + expected_counts = {kind: sum(r[0] == kind for r in rows) for kind in ('Reservation', 'SavingsPlan')} + states[2] &= shape and strict_equal(data.get('counts'), expected_counts) + total = sum(amount for kind, util, amount in rows if util >= 90) + states[3] &= shape and all(type(data.get(k)) in (int, float) and math.isfinite(data[k]) and + abs(data[k] - value) < 1e-9 for k, value in ( + ('eligible_commitment_sum', total), ('mg_scope_commitment', round(total * .7, 2)))) + entries.append(states) + except Exception: + entries.append([False] * 5) + best = next((state for state in entries if all(state)), None) + if best is None: + best = max(entries, key=sum) if entries else [False] * 5 + for i, state in enumerate(best): + constrain(checks, [i], state, 'changed subscription IDs, exact CV .3/.6, singleton/stable/volatile, utilization >=90, empty recommendations, and all-kind eligible sum') + + +def provisioning(checks): + panels = [ + ('- covered-a\n- covered-b\n', 'keep-z\ncovered-a\n\nkeep-z\ncovered-b\nkeep-a\ncovered-a\n', + ['keep-z', 'keep-a'], 2), + ('# no covered entries\n', '\nlast\nfirst\nlast\n', ['last', 'first'], 0), + ('plugins:\n - all-a\n - all-b\n', 'all-b\nall-b\nall-a\n', [], 2), + ('- unused\n', '\n', [], 0), + ] + flags = [True] * 5 + for yml, manifest, kept, excluded in panels: + rc, stdout, raw, parsed = launch('audit.py', { + 'plugin-recommendations.yml': yml, 'provisioned-manifest.txt': manifest}, 'provision-plan.txt') + lines = raw.splitlines() if isinstance(raw, str) else None + expected = kept + ['excluded: ' + str(excluded)] + flags[0] &= rc == 0 + flags[1] &= lines == expected + flags[2] &= lines is not None and lines[:-1] == kept + flags[3] &= lines is not None and lines[-1:] == ['excluded: ' + str(excluded)] + flags[4] &= ('kept=%d excluded=%d' % (len(kept), excluded)) in [x.strip() for x in stdout.splitlines()] + for i, state in enumerate(flags): + constrain(checks, [i], state, 'fresh flat/grouped lists, changed names, duplicate counts, first appearance, all/none excluded, empty manifest') + + +def editor(checks): + empty = {'file': None, 'cursor': None, 'selection': None, 'diagnostics': None, 'quickfix': None} + panels = [('', {}, empty), ('diagnostics: 0\nquickfix: 7\n', {}, dict(empty, diagnostics=0, quickfix=7)), + ('filepath: file with spaces.py\n', {'file with spaces.py': 'one\ntwo'}, dict(empty, file='file with spaces.py')), + ('cursor_position: 2:1\n', {}, dict(empty, cursor={'line': 2, 'column': 1})), + ('filepath: file with spaces.py\ncursor_position: 2:1\nvisual_selection: 1:2-2:3\ndiagnostics: 1\nquickfix: 4\n', + {'file with spaces.py': 'first line\nsecond line'}, + {'file': 'file with spaces.py', 'cursor': {'line': 2, 'column': 1}, + 'selection': {'start': {'line': 1, 'column': 2}, 'end': {'line': 2, 'column': 3}}, + 'diagnostics': 1, 'quickfix': 4, 'line_at_cursor': 'second line'}), + ('filepath: short.py\ncursor_position: 99:3\n', {'short.py': 'only\n'}, + dict(empty, file='short.py', cursor={'line': 99, 'column': 3}, line_at_cursor=None))] + flags = [True] * 7 + for text, files, expected in panels: + rc, out, raw, data = launch('report.py', dict(files, **{'agent_output.txt': text}), 'context_report.') + flags[0] &= rc == 0 and isinstance(data, dict) and set(data) == set(expected) + for cid, fields in [(1, ['file']), (2, ['cursor']), (3, ['selection']), (4, ['diagnostics', 'quickfix']), (5, ['line_at_cursor'])]: + flags[cid] &= isinstance(data, dict) and all((key in data) == (key in expected) and + (key not in expected or strict_equal(data[key], expected[key])) for key in fields) + flags[6] &= rc == 0 + for i, state in enumerate(flags): + 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') + + +def validator(checks): + base = {'SKILL.md': '---\nname: fresh-validator\ndescription: Fresh package\n---\nbody\n', + 'references/REFERENCE.md': 'REMCOCHAT_SKILLS_CONFORMANCE_REFERENCE_v1\n', + 'assets/fixture.json': '{"fixture_id":"fresh-id"}', + 'scripts/echo.sh': '#!/bin/sh\necho REMCOCHAT_SKILLS_SCRIPT_OK\n'} + scenarios = [('missing_skill', {'SKILL.md': None}, 'frontmatter'), + ('empty_name', {'SKILL.md': '---\nname: \ndescription: Present\n---\n'}, 'frontmatter'), + ('body_name_only', {'SKILL.md': '# body\nname: x\ndescription: y\n'}, 'frontmatter'), + ('bad_fixture', {'assets/fixture.json': '{bad'}, 'fixture_json'), + ('empty_fixture', {'assets/fixture.json': '{"fixture_id":""}'}, 'fixture_json'), + ('wrong_fixture_type', {'assets/fixture.json': '{"fixture_id":123}'}, 'fixture_json'), + ('missing_reference', {'references/REFERENCE.md': None}, 'reference_marker'), + ('failing_echo', {'scripts/echo.sh': '#!/bin/sh\necho REMCOCHAT_SKILLS_SCRIPT_OK\nexit 7\n'}, 'echo_script'), + ('wrong_stdout', {'scripts/echo.sh': '#!/bin/sh\necho unrelated\n'}, 'echo_script'), + ('missing_echo', {'scripts/echo.sh': None}, 'echo_script')] + flags = {str(i): True for i in range(7)} + owners = {'frontmatter': '3', 'reference_marker': '2', 'fixture_json': '5', 'echo_script': '4'} + for name, updates, failed in scenarios: + with tempfile.TemporaryDirectory(prefix='r9-validator-') as folder: + root = clone(folder) + package = root / ('probe_' + name) + files = dict(base, **updates) + for rel, content in files.items(): + if content is not None: + path = package / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + if rel.endswith('.sh'): + path.chmod(0o755) + output = root / 'probe-report.json' + process = subprocess.run([sys.executable, 'validate_skill.py', str(package), str(output)], + cwd=root, capture_output=True, text=True, timeout=35) + try: + data = parse_file(output) + except Exception: + data = None + rows = data.get('checks') if isinstance(data, dict) else None + shape = isinstance(rows, list) and len(rows) == 4 and all(isinstance(row, dict) for row in rows) + shape = shape and sorted(row.get('name', '') for row in rows) == sorted(owners) + values = {row['name']: row for row in rows} if shape else {} + flags[owners[failed]] &= shape and all(values[key].get('passed') is (key != failed) for key in owners) + flags['6'] &= shape and data.get('path') == str(package) and data.get('ok') is False + flags['6'] &= shape and all(type(row.get('passed')) is bool and isinstance(row.get('detail'), str) for row in rows) + flags['0'] &= process.returncode == 0 + for cid, state in flags.items(): + 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') + + +def dedup(checks): + script = CAND / 'dedup.sh' + source = script.read_text() + 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') + with tempfile.TemporaryDirectory(prefix='r9-dedup-') as folder: + root = Path(folder) + missing = root / 'absent' + not_directory = root / 'file' + not_directory.write_text('x') + cases = [[str(missing)], [str(not_directory)], [str(root), str(root)]] + ok = True + for args in cases: + p = subprocess.run(['/bin/sh', str(script)] + args, cwd=root, + capture_output=True, text=True, timeout=30) + ok &= p.returncode == 2 and bool(p.stderr.strip()) + constrain(checks, [2], ok, 'nonexistent/file arguments and too many arguments also require stderr usage and exit2') + tree = root / 'tree' + tree.mkdir() + groups = [['a one.txt', 'b two.txt'], ['c.txt', 'd.txt', 'e.txt']] + for index, names in enumerate(groups): + for name in names: + (tree / name).write_text('distinct payload ' + str(index)) + (tree / 'unique.txt').write_text('unique') + temporary = root / 'temp-files' + temporary.mkdir() + env = dict(os.environ, TMPDIR=str(temporary)) + p = subprocess.run(['/bin/sh', str(script), str(tree)], cwd=root, env=env, + capture_output=True, text=True, timeout=30) + lines = [line for line in p.stdout.splitlines() if line.strip()] + ok = p.returncode == 0 and len(lines) == 2 and 'unique.txt' not in p.stdout + ok &= all(sum(all(name in line for name in names) for line in lines) == 1 for names in groups) + ok &= all(not any(any(name in line for name in groups[a]) and any(name in line for name in groups[b]) + for a in range(2) for b in range(a + 1, 2)) for line in lines) + constrain(checks, [5], ok, 'two independent duplicate groups, three-member group, spaces, no merging/unique leak') + constrain(checks, [3], not list(temporary.iterdir()), 'actual mktemp files under supplied TMPDIR are removed after successful execution') + + +def querylog(checks): + header = ['event_time', 'query_id', 'user', 'query_duration_ms', 'read_rows', 'read_bytes', 'written_rows', 'written_bytes', 'memory_usage', 'exception', 'query'] + panels = [[('z', 2, 10000001, 1000000001, ''), ('x', 20, 10000000, 1000000000, 'failure'), + ('z', 7, 10000001, 7, ''), ('a', 11, 1, 1000000001, '')], + [('single', 17, 0, 0, '')]] + bits = [True] * 7 + for rows in panels: + out = io.StringIO() + writer = csv.writer(out, delimiter='\t', lineterminator='\n') + writer.writerow(header) + for qid, duration, reads, memory, error in rows: + writer.writerow(['2026-01-01', qid, 'u', duration, reads, 0, 0, 0, memory, error, 'SELECT 1']) + rc, stdout, raw, data = launch('analyze.py', {'query_log.tsv': out.getvalue()}, 'report.') + shape = isinstance(data, dict) + bits[0] &= rc == 0 and shape + bits[1] &= shape and type(data.get('total_queries')) is int and data['total_queries'] == len(rows) + bits[1] &= shape and type(data.get('failed_queries')) is int and data['failed_queries'] == sum(bool(row[4]) for row in rows) + wanted = [{'query_id': row[0], 'query_duration_ms': row[1], 'read_rows': row[2], 'memory_usage': row[3], + 'suspected_cause': 'memory' if row[3] > 1000000000 else 'scan_heavy' if row[2] > 10000000 else 'other'} + for row in sorted(rows, key=lambda row: -row[1])[:3]] + bits[2] &= shape and strict_equal(data.get('top_slowest'), wanted) + bits[3] &= shape and isinstance(data.get('top_slowest'), list) and all( + isinstance(actual, dict) and actual.get('suspected_cause') == expected['suspected_cause'] for actual, expected in zip(data['top_slowest'], wanted)) + duplicates = sorted(qid for qid, count in collections.Counter(row[0] for row in rows).items() if count > 1) + bits[4] &= shape and strict_equal(data.get('duplicate_ids'), duplicates) + durations = sorted(row[1] for row in rows) + 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] + bits[6] &= not stdout + for cid, state in enumerate(bits): + constrain(checks, [cid], state, 'changed TSV, singleton top list, repeated IDs, exact threshold strict>, cause precedence, nearest-rank, silent stdout') + + +def calver(checks): + changelog = (CAND / 'changelog.md').read_text() + source = ((Path('/source') if Path('/source/inputs').is_dir() else HERE.parent) / 'inputs/CHANGELOG.md').read_text() + version_headers = re.findall(r'^##\s*\[2026\.03\.0\].*$', changelog, re.M) + constrain(checks, [0], len(version_headers) == 1, 'the new release version occurs as exactly one section, not duplicated release sections') + section = re.search(r'^##\s*\[2026\.03\.0\].*?(?=^##\s|\Z)', changelog, re.M | re.S) + unreleased = re.search(r'^##\s*\[Unreleased\].*?(?=^##\s|\Z)', source, re.M | re.S) + items = re.findall(r'^\s*[-*]\s+(.+?)\s*$', unreleased.group(0), re.M) if unreleased else [] + new = section.group(0) if section else '' + once = bool(section) and all(len(re.findall(r'^\s*[-*]\s+' + re.escape(item) + r'\s*$', new, re.M)) == 1 for item in items) + once &= all(len(re.findall(r'^###\s*' + name + r'\s*$', new, re.M)) == 1 for name in ['Added', 'Changed', 'Fixed']) + constrain(checks, [1], once, 'each moved original item and its existing Added/Changed/Fixed subsection appears exactly once') + expected_package = parse_file((Path('/source') if Path('/source/inputs').is_dir() else HERE.parent) / 'inputs/package.') + expected_package['version'] = '2026.03.0' + package = parse_file(CAND / 'package.') + constrain(checks, [4], strict_equal(package, expected_package), 'strict nonduplicate JSON preserves the complete original package metadata and changes only the release version') + + +HANDLERS = { + '60c549e81b03fc667586d0d7': azure, + '7b074d0b21eaa88ed135fd50': provisioning, + '7bd4a66c3cf0048be68c0caf': editor, + '8415596226ceae1108c89af2': validator, + '881ffb8f1cb15a8f6e777090': dedup, + '8bd9dcf9cfecdef4b5ec4674': querylog, + '6fae5fc9ab4122d0ae5a7281': calver, +} + + +def main(): + qid = json.loads((Path('/source')/'task.json').read_text())['query_id'] if (Path('/source')/'task.json').is_file() else HERE.parent.name + checks = old_checks() + try: + HANDLERS[qid](checks) + dependencies = { + '60c549e81b03fc667586d0d7': ('0', [path.name for path in CAND.glob('*.py')]), + '7b074d0b21eaa88ed135fd50': ('0', ['audit.py']), + '7bd4a66c3cf0048be68c0caf': ('6', ['report.py']), + '8415596226ceae1108c89af2': ('0', ['validate_skill.py']), + '8bd9dcf9cfecdef4b5ec4674': ('6', ['analyze.py']), + } + if qid in dependencies: + from dependency_scan import scan_stdlib + owner, entries = dependencies[qid] + permitted, modules, why = scan_stdlib(CAND, entries) + for row in checks: + if str(row['id']) == owner: + 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 + row['reason'] += '; R9 reachable stdlib/local helper graph: ' + why + except Exception as error: + for check in checks: + check.update(passed=None, reason='R9 public-input supplemental evaluation unavailable: ' + type(error).__name__) + print(json.dumps({'scoreable': all(type(row.get('passed')) is bool for row in checks), 'checks': checks})) + + +if __name__ == '__main__': + main() diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_runtime_compat.py b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_runtime_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..1830bf8f66f5de372ff939288902d2c5dec6d447 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/r9_runtime_compat.py @@ -0,0 +1,59 @@ +"""Preserve ordinary local helper modules in legacy public-input test copies. + +The parent grader separately scans the original, unmodified stdlib closure. +This compatibility child process allows a top-level import of a local module; +it does not grant permission to third-party dependencies inside that module. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import os +import shutil +import sys +from pathlib import Path + + +def install(): + candidate = Path(os.environ.get('MYBENCH_CANDIDATE', os.environ.get('MYBENCH_CANDIDATE_DIR', '/candidate'))) + if not candidate.is_dir(): + return + modules = {path.stem for path in candidate.glob('*.py')} + packages = [path for path in candidate.iterdir() if path.is_dir() and not path.name.startswith('.') and + ((path / '__init__.py').is_file() or any(path.glob('*.py')))] + modules.update(path.name for path in packages) + original_stdlib = set(getattr(sys, 'stdlib_module_names', ())) + sys.stdlib_module_names = frozenset(original_stdlib | modules) + original_copy = shutil.copy + original_copyfile = shutil.copyfile + + def copy(source, target, *args, **kwargs): + result = original_copy(source, target, *args, **kwargs) + src = Path(source) + if src.parent.resolve() == candidate.resolve() and src.suffix == '.py': + destination = Path(target) + folder = destination if destination.is_dir() else destination.parent + for helper in candidate.glob('*.py'): + if helper.name != src.name: + shutil.copy2(helper, folder / helper.name) + for package in packages: + shutil.copytree(package, folder / package.name, dirs_exist_ok=True, + ignore=shutil.ignore_patterns('__pycache__')) + if src.parent.resolve() == candidate.resolve() and src.suffix == '.py': + from r12_resources import copy_authored_resources + copy_authored_resources(candidate,folder) + return result + + _copying_modules=False + def copyfile(source,target,*args,**kwargs): + nonlocal _copying_modules + result=original_copyfile(source,target,*args,**kwargs) + src=Path(source) + if not _copying_modules and src.parent.resolve()==candidate.resolve() and src.suffix=='.py': + from r10_support import copy_modules + _copying_modules=True + try: + copy_modules(candidate,Path(target).parent) + from r12_resources import copy_authored_resources + copy_authored_resources(candidate,Path(target).parent) + finally:_copying_modules=False + return result + shutil.copy = copy + shutil.copyfile = copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c889f3bf223fe0dc4ecf2011ab8c5ceb54ddd6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/evaluator/repair_manifest.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64a3a3db315a4dda92a00f95a1df75d2522dc439520fab2c85b943da9edcf674 +size 1092 diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..de727a78741224ffda3449e3614561833fca6311 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/grading/verified_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:077ffd511b709732a70e8d2332141041e46f95c6db8cdfadbf8e245a9b12d56b +size 4867 diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/inputs/query_log.tsv b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/inputs/query_log.tsv new file mode 100644 index 0000000000000000000000000000000000000000..133d4118c33f0e0f7452062be2f73bd7ff4f9e39 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/inputs/query_log.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:721a60e08fe80448e7bf95d0f977323cbd1f052b893cf4e77bdb49061f79cbf3 +size 1234 diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/instruction.md b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7eb9d45d1dd332c8bda4c48a0588f07827d8c36f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/instruction.md @@ -0,0 +1,7 @@ +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. +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. + +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. + + +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. diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..7b77c3169bca804840e9b3c66fbfcd45868371e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.md @@ -0,0 +1,45 @@ +--- +name: clickhouse-debugging +description: "Debugging for Clickhouse: debugging and troubleshooting" +category: database +tags: [clickhouse, debugging, database] +models: [sonnet, opus] +version: "1.0" +language: en +--- + +# Clickhouse Debugging + +> Debugging for Clickhouse: debugging and troubleshooting + +## Quick Start +Begin by understanding the core concepts of Debugging with Clickhouse. + +## When to Use +- Setting up Clickhouse for debugging and troubleshooting +- Implementing Debugging patterns +- Building production-ready solutions with Clickhouse + +## Step-by-Step +1. Review prerequisites and requirements +2. Set up the development environment +3. Implement the debugging configuration +4. Test the implementation +5. Deploy to production + +## Dependencies +- Clickhouse +- Development environment +- Required SDKs and tools + +## Examples +See the official Clickhouse documentation for complete examples. + +## Resources +- Clickhouse official documentation +- Community guides and tutorials + +## Validation +- Verify the setup works correctly +- Run test cases +- Check logs and metrics diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.ru.md b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.ru.md new file mode 100644 index 0000000000000000000000000000000000000000..72007cafd2d3491f382427245332c2188d28ef1f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/skill/SKILL.ru.md @@ -0,0 +1,37 @@ +--- +name: clickhouse-debugging +description: "Debugging for Clickhouse: debugging and troubleshooting" +category: database +tags: [clickhouse-debugging, database, russian] +models: [sonnet, opus] +version: "1.0" +language: ru +original: clickhouse-debugging +--- + +# Clickhouse Debugging + +> Debugging for Clickhouse: debugging and troubleshooting + +## Быстрый старт +Этот навык на русском языке. Оригинал: `clickhouse-debugging`. + +## Когда использовать +- Работа с Базы данных +- Выполнение задач, связанных с Clickhouse Debugging +- Профессиональное развитие + +## Инструкции +1. Ознакомьтесь с описанием навыка +2. Изучите английскую версию для полных инструкций +3. Примените полученные знания на практике + +## Ресурсы +- Оригинальный навык: database/clickhouse-debugging/SKILL.md +- Категория: Базы данных +- Язык: Русский + +## Валидация +- Прочитайте английскую версию для проверки +- Выполните описанные шаги +- Убедитесь в правильности результата diff --git a/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/task.json b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ff632c4ac3d365bed4d3aec3f17aa7a8222618dc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8bd9dcf9cfecdef4b5ec4674/task.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48b57def295e7a56e1d54a00b22dc73a930a53b72278b182433af07ba08a669e +size 4313 diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..79617b5fa082232f7de0b756c12039b89d742878 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_contract.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37 +size 83 diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..4ceeece0450bce94cfe0f2be0809fb33708d5b5b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1308 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + actual = json.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..954d08b8187699c9486e6e9e10703e47cc899d5e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,378 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + + +# R7: unwrap only execution wrappers whose effect is proved in this subset. +# In particular `command -v/-V` queries do not run their operand, and `builtin` +# cannot run an external tool. Keep these distinctions before inspecting state. +_BASH_BUILTINS = frozenset({ + ':', '.', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', + 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs', + 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', + 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', + 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', + 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', + 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', + 'unset', 'wait', +}) +_UNSUPPORTED_STATE = frozenset({ + '.', 'source', 'eval', 'alias', 'unalias', 'enable', 'shopt', 'trap', + 'return', 'exec', 'break', 'continue', 'let', 'declare', 'typeset', 'local', + 'read', 'mapfile', 'readarray', 'unset', 'readonly', 'export', 'shift', + '[', '[[', 'test', 'logout', 'suspend', 'bind', 'getopts', +}) + + +def _bash_dialect(text): + """No shebang uses the evaluator's Bash syntax contract; sh is not Bash.""" + first = str(text).splitlines()[0] if str(text).splitlines() else '' + if not first.startswith('#!'): + return True + try: + words = shlex.split(first[2:]) + except ValueError: + return False + if not words: + return False + executable = words[0].rsplit('/', 1)[-1] + if executable == 'env': + words = words[1:] + if words[:1] == ['-S']: + words = words[1:] + executable = words[0] if words else '' + return executable.rsplit('/', 1)[-1] == 'bash' + + +def _execution_argv(argv, bash=True): + """Normalize a finite chain; unsupported wrappers get no command credit.""" + if not argv: + return None + argv = list(argv) + while argv and argv[0] in ('command', 'builtin'): + wrapper = argv[0] + if wrapper == 'builtin': + if not bash: + return None + argv = argv[1:] + if argv[:1] == ['--']: + argv = argv[1:] + if not argv or argv[0] not in _BASH_BUILTINS: + return None + continue + index, query, default_path = 1, False, False + while index < len(argv) and argv[index].startswith('-'): + option = argv[index] + index += 1 + if option == '--': + break + if not re.fullmatch(r'-[pvV]+', option): + return None + query = query or 'v' in option or 'V' in option + default_path = default_path or 'p' in option + if query: + return argv # Query is an invocation of command, not its target. + if index == len(argv): + return None + argv = argv[index:] + # -p changes external PATH lookup. It is transparent for builtins only. + if default_path and argv[0] not in _BASH_BUILTINS: + return None + return argv or None + + +def _set_errexit(argv, current): + """Return the proven option state, or None for unsupported set options.""" + if not argv or argv[0] != 'set': + return None + index = 1 + while index < len(argv): + flag = argv[index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Positional arguments cannot enable errexit. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return None # Includes noexec (-n), which suppresses later work. + if 'o' in flag[1:] and (flag[-1] != 'o' or flag.count('o') != 1): + return None + if 'e' in flag[1:]: + current = flag[0] == '-' + if 'o' in flag[1:]: + if index + 1 >= len(argv): + return None + option = argv[index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return None + if option == 'errexit': + current = flag[0] == '-' + index += 1 + index += 1 + return current + + +def shell_option_setting(text, bash=True): + """Recognize valid option setup for task-specific operation counters.""" + argv = _execution_argv(_simple_argv(text), bash) + return bool(argv and argv[0] == 'set' and _set_errexit(argv, False) is not None) + + +def _exit_status(argv): + """A literal shell exit status; no-argument exit is handled by its caller.""" + args = argv[1:] + if args[:1] == ['--']: + args = args[1:] + if (len(args) != 1 or not re.fullmatch(r'[+-]?[0-9]+', args[0]) + or len(args[0]) > 20): + return None + value = int(args[0]) + if not -(2**63) <= value <= 2**63 - 1: + return 2 # Bash exits for an out-of-range numeric argument. + return value % 256 + + + +def _nonzero_exit_body(statements, bash=True): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _execution_argv(_simple_argv(statement), bash) + if not argv: + return False + if argv[0] == 'exit': + status = _exit_status(argv) + return index == len(statements) - 1 and status is not None and status != 0 + if argv[0] not in ('echo', 'printf'): + return False + return False + + +def shell_invocations(text): + """Return ordered, actually evaluated invocation nodes in the supported subset. + + fail_fast is a structural proof: a simple command/assignment runs under + errexit, or a negated test exits nonzero on failure. This is not a complete + shell interpreter, and unsupported syntax earns no invocation credit. + """ + statements = _statements(text) + bash = _bash_dialect(text) + # Function definitions or dynamic shell mutation can shadow the command or + # `exit` itself. They are outside this objective subset, even if uncalled. + if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s) + or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s) + for s in statements): + return [] + constants, result, index, errexit = {}, [], 0, False + assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while index < len(statements): + statement = statements[index] + literal = assignment.fullmatch(statement) + if literal: + constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None) + index += 1 + continue + statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement) + if re.match(r'^if\s', statement): + end = _guard_end(statements, index) + if end is None: + return [] + negated = re.fullmatch(r'if\s+!\s+(.+)', statement) + if (negated and index + 1 < end + and statements[index + 1] == 'then' + and _nonzero_exit_body(statements[index + 2:end], bash)): + argv, kind = _invocation(negated.group(1).strip()) + argv = _execution_argv(argv, bash) + if argv and (argv[0] in _UNSUPPORTED_STATE or argv[0] in ('set', 'exit')): + return [] + if argv: + if argv[0] == 'false': + break + result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind, + 'fail_fast': True, 'statement_index': index, 'expanded_statement': statement}) + else: + return [] + else: + # Arbitrary conditions may terminate the script or shadow its + # commands. Do not infer a reachable suffix through them. + return [] + # Bodies are never credited and may have assigned local variables. + constants.clear() + index = end + 1 + continue + if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{': + # Unsupported compounds are not searched for command substrings. + return [] + argv, kind = _invocation(statement) + argv = _execution_argv(argv, bash) + if not argv: + # An unparsed statement may change control flow or shell state. + # Skipping it would incorrectly credit an unreachable suffix. + return [] + if argv[0] in _UNSUPPORTED_STATE: + return [] + if argv[0] == 'hash': + # Clearing/querying/cache lookup preserves the command's selected + # executable. An explicit -p binding can replace a required tool. + operands, flags = [], '' + option_mode = True + for word in argv[1:]: + if option_mode and word == '--': + option_mode = False + elif option_mode and word.startswith('-'): + if not re.fullmatch(r'-[lrdt]+', word): + return [] + flags += word[1:] + else: + option_mode = False + if '$' in word: + return [] + operands.append(word) + if ('d' in flags or 't' in flags) and not operands: + return [] + if argv[0] == 'set': + new_errexit = _set_errexit(argv, errexit) + if new_errexit is None: + return [] + if kind == 'simple': + errexit = new_errexit + index += 1 + continue + # An assignment substitution runs in a subshell: set cannot change + # the parent's flags. Keep it as an ordinary evaluated node. + if argv[0] == 'exit': + if kind == 'simple': + # Only a literal, zero/one-argument exit is proved terminal. + # An invalid multi-argument exit can return and is unsupported. + if len(argv) == 1 or argv == ['exit', '--'] or _exit_status(argv) is not None: + break + return [] + status = 0 if argv in (['exit'], ['exit', '--']) else _exit_status(argv) + if status is None: + return [] + if status and errexit: + break + if argv[0] == 'false' and errexit: + break + if kind == 'assignment_substitution': + assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement) + if assigned: + constants.pop(assigned.group(1), None) + result.append({'command': shlex.join(argv), 'kind': kind, + 'fail_fast': errexit, 'statement_index': index, 'expanded_statement': statement}) + index += 1 + return result diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}} +if [[ -z "$candidate" ]]; then + echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f26010fd64685994571e9b3b9e1390af92b51f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,521 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + try:return json.loads(text) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + try: + pred = _atomic_prepare(_json_value(solver_output), + verifier.get("list_order", "ordered")) + pred_shape = _atomic_shape(pred) + except RecursionError: + return False, "candidate JSON nesting is too deep" + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], pred_shape) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = (_path_value(actual) is not None and + _path_value(actual) == _path_value(assertion["expected"])) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..22bdb4df05c8e0e71b92b559a241072fd46cace3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/evaluator/repair_equivalences.py @@ -0,0 +1,253 @@ +"""Task-scoped semantic equivalences for the 112 legacy verifier repairs. + +No solver, oracle label, historical score or answer hash influences comparison. +The original private rubric, completeness checks and binary aggregation remain. +""" +from __future__ import annotations +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +R10_ANY_FAILURE=set(['8dbd07af72331a25_q1', '917337011825a76f_q1', '9231bb5263eb6830_q1', 'a1aad4432dfbb4e2_q1', 'c288addfaf9ced19_q1']) +import copy +import json +import re +import shlex +import shutil +import tempfile +from decimal import Decimal, InvalidOperation +from pathlib import Path + + +def argv(value): + if not isinstance(value, str): + return None + try: + result = shlex.split(value, posix=True) + except ValueError: + return None + # Only the Bash execution wrapper is transparent. command -v/-V are queries. + while len(result) > 1 and result[0] == 'command': + if result[1] == '--': + result = result[2:] + elif result[1].startswith('-') or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', result[1]): + break + else: + result = result[1:] + return result or None + + +def git_limit(tokens): + if not tokens or tokens[:2] != ['git', 'log']: + return tokens + out, index = [], 0 + while index < len(tokens): + token = tokens[index] + compact = re.fullmatch(r'-(\d+)|--max-count=(\d+)', token) + if compact: + out.append('--max-count=' + next(x for x in compact.groups() if x is not None)) + elif token in ('-n', '--max-count') and index + 1 < len(tokens) and tokens[index+1].isdigit(): + index += 1 + out.append('--max-count=' + tokens[index]) + else: + out.append(token) + index += 1 + return out + + +def shell_equal(expected, actual, normalize_env=False): + wanted, found = argv(expected), argv(actual) + if normalize_env and wanted and found: + wanted = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in wanted] + found = [re.sub(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}', r'$\1', x) for x in found] + wanted, found = git_limit(wanted), git_limit(found) + if not wanted or not found or len(wanted) != len(found) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + if (index == 1 and '/' in token and + observed.rstrip('/').endswith('/' + token.lstrip('./'))): + continue # Existing package-path anchoring; no changed basename/arguments. + return False + return True + + +def command_equal(expected, value): + # Response command questions ask for one invocation, with no extra commands. + return argv(expected) is not None and argv(expected) == argv(value) + + +def convex_equal(expected, value): + a, b = argv(expected), argv(value) + if not a or not b or len(a) != len(b) or a[:-1] != b[:-1]: + return False + def no_duplicates(pairs): + result = {} + for k, v in pairs: + if k in result: + raise ValueError('duplicate JSON key') + result[k] = v + return result + try: + return json.loads(a[-1], object_pairs_hook=no_duplicates) == json.loads(b[-1], object_pairs_hook=no_duplicates) + except (ValueError, TypeError): + return False + + +def docker_network_equal(expected, value): + tokens = argv(value) + return tokens in (['--network', 'none'], ['--network=none']) + + +def zar_amount(value): + if not isinstance(value, str): + return None + m = re.fullmatch(r'\s*(?:ZAR|R|rand)\s*(\d+(?:,\d{3})*(?:\.\d+)?)\s*(million|m)?\s*', value, re.I) + if not m: + return None + number = m.group(1) + if ',' in number and not re.fullmatch(r'\d{1,3}(?:,\d{3})+(?:\.\d+)?', number): + return None + try: + amount = Decimal(number.replace(',', '')) + except InvalidOperation: + return None + return amount * (Decimal(1000000) if m.group(2) else 1) + + +def zar_equal(expected, value): + return zar_amount(expected) is not None and zar_amount(expected) == zar_amount(value) + + +def rust_attribute_equal(expected, value): + return isinstance(value, str) and re.fullmatch(r'\s*#\s*\[\s*serde\s*\(\s*rename_all\s*=\s*"camelCase"\s*,?\s*\)\s*\]\s*', value) is not None + + +def header_equal(expected, value): + return isinstance(value, str) and value.casefold() == expected.casefold() + + +def zero_arg_js_equal(expected, value): + name = expected[:-2] + return isinstance(value, str) and re.fullmatch(r'\s*' + re.escape(name) + r'\s*\(\s*\)\s*', value) is not None + + +RESPONSE_RULES = { + '82e94ae96e04ff71_q1': {'q1': convex_equal}, + 'df978907fa6f0eea_q1': {'q1': docker_network_equal}, + 'dee0c878f5707477_q1': {'q1': command_equal}, + 'c51259d0062454b2_q1': {'q1': command_equal}, + 'd25a8956477141f2_q1': {'q2': zar_equal}, + '719eda04e56bf901_q1': {'q1': command_equal, 'q3': rust_attribute_equal}, + 'a4926e403c8165e9_q1': {'q2': header_equal}, + '2b3bd5786727f2fb_q1': {'q1': command_equal}, +} + + +def dashboard_contract(evaluator, candidate, objective): + root = Path(candidate) + path = evaluator['reference_files'][0]['path'] + try: + text = (root / path).read_text() + except (OSError, UnicodeError): + return False + lines = objective._shell_lines(text) + # Public contract explicitly says no other commands/flags. Single quotes + # would suppress environment expansion; only the correctly quoted form counts. + return (len(lines) == 2 and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/start\.sh"\s+--open', lines[0]) is not None and + re.fullmatch(r'bash\s+"(?:\$SCRIPTS|\$\{SCRIPTS\})/stop\.sh"', lines[1]) is not None) + + +def install(task): + import objective_evaluators as objective + import verifiers + task_id = task['query_id'] + original_verify = verifiers.verify + original_matcher = objective._shell_command_matches + objective._shell_command_matches = lambda e, a: shell_equal(e, a, task_id == 'f9ab8deb175f67e2_q1') + + def repaired_verify(evaluator, gt_answer, solver_output, material_paths=None): + if evaluator.get('type') == 'workspace_objective': + # A text occurrence after exit/return, in echo output or within a + # non-executed branch does not prove the requested command runs. + grouped = {} + for check in evaluator.get('checks', []): + if check.get('type') == 'shell_command': + grouped.setdefault(check['path'], []).append(check['value']) + for path, expected_commands in grouped.items(): + try: + text = (Path(solver_output) / path).read_text() + invocations = objective.shell_invocations(text) + for expected_command in expected_commands: + tokens = argv(expected_command) + if tokens and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', tokens[0]): + continue # Required scalar assignment is checked by original rubric. + if not any(objective._shell_command_matches(expected_command, node['command']) for node in invocations): + return False, {'error': 'required shell invocation is not reachable in the bounded straight-line grammar', 'path': path, 'command': expected_command} + except (OSError, UnicodeError, ValueError): + return False, {'error': 'cannot inspect required shell artifact', 'path': path} + if task_id == 'f9ab8deb175f67e2_q1' and not dashboard_contract(evaluator, solver_output, objective): + return False, {'error': 'dashboard script must contain exactly the two quoted environment-directory calls and mandated arguments'} + + # R10: obligations apply to actual invocation nodes, not substrings. + if evaluator.get('type')=='workspace_objective' and task_id in R10_ANY_FAILURE: + for path in {c['path']for c in evaluator.get('checks',[])if c.get('type')=='shell_command'}: + try:nodes=objective.shell_invocations((Path(solver_output)/path).read_text()) + except (OSError,UnicodeError,ValueError):return False,{'error':'cannot read shell artifact'} + if not nodes or any(not node['fail_fast']for node in nodes):return False,{'error':'every executed command must propagate failure','path':path} + if evaluator.get('type')=='workspace_objective' and task_id=='af4438bc4d445682_q1': + for path in {c['path']for c in evaluator.get('checks',[])if c.get('type')=='shell_command'}: + nodes=objective.shell_invocations((Path(solver_output)/path).read_text()) + count=sum(1 for node in nodes if objective._shell_command_matches('x-openapi-cli get:/2/users/me',node['command'])) + if count!=1:return False,{'error':'public single profile read requires exactly one invocation','count':count} + normalizations = [] + if task_id in RESPONSE_RULES: + try: + predicted = verifiers._json_value(solver_output) + gold = gt_answer + if isinstance(predicted, dict) and isinstance(predicted.get('answers'), dict): + for key, comparator in RESPONSE_RULES[task_id].items(): + value = predicted['answers'].get(key) + expected = gold['answers'][key] + if value != expected and comparator(expected, value): + predicted['answers'][key] = expected + normalizations.append({'path': '$.answers.' + key, 'original': value, 'comparison_value': expected}) + solver_output = json.dumps(predicted) + except (KeyError, ValueError, TypeError): + pass # Preserve original malformed-answer rejection. + if task_id == '59f410a185c510f3_q1': + path = evaluator['reference_files'][0]['path'] + try: + file_path = Path(solver_output) / path + predicted = json.loads(file_path.read_text()) + expected = next(c['expected'] for c in evaluator['checks'] if c['type'] == 'json_exact') + if isinstance(predicted, dict): + for widget in ('chart', 'banner'): + row = predicted.get(widget) + if isinstance(row, dict) and zero_arg_js_equal(expected[widget]['hydrate'], row.get('hydrate')): + if row.get('hydrate') != expected[widget]['hydrate']: + normalizations.append({'path': path + '/' + widget + '/hydrate', 'original': row['hydrate'], 'comparison_value': expected[widget]['hydrate']}) + row['hydrate'] = expected[widget]['hydrate'] + if normalizations: + with tempfile.TemporaryDirectory(prefix='legacy-equivalence-') as temporary: + view = Path(temporary) / 'candidate' + shutil.copytree(solver_output, view, symlinks=True) + copied = view / path + resolved = copied.resolve() + if not resolved.is_relative_to(view.resolve()) and not copied.is_symlink(): + return False, {'error': 'candidate output parent symlink escapes temporary comparison view'} + if copied.is_symlink(): + copied.unlink() # Do not write through a frozen source symlink. + copied.write_text(json.dumps(predicted)) + passed, details = original_verify(evaluator, gt_answer, str(view), material_paths) + if isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + except (KeyError, ValueError, TypeError, OSError, UnicodeError): + pass + passed, details = original_verify(evaluator, gt_answer, solver_output, material_paths) + if normalizations and isinstance(details, dict): + details['equivalence_normalizations'] = normalizations + return passed, details + + verifiers.verify = repaired_verify diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6c176767d4399d200a6ccbc29a2700693f9df468 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/grading/verified_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b82f51497260fc6ea69029be5b131dcdc58e7788e31a6464aae42c076500b30 +size 4094 diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e1c0f978266c8af6fbc2465541675d64020bbdd9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/instruction.md @@ -0,0 +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. diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1d175c89537e9851c19f758cb106a8133e0c356d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/SKILL.md @@ -0,0 +1,192 @@ +--- +name: shaon +version: 0.8.3 +description: > + Personal attendance, payslip, salary, and related self-service tasks on the + user's own Hilan account. Trigger on shaon, attendance, clock in/out, payslip, + salary slip, work hours, תלוש, תלוש שכר, משכורת, דוח נוכחות, corrections log, + forgot to clock in, forgot to report, or any request about the user's own + Israeli employer self-service portal. +--- + +# Shaon + +Claude Code skill for the `shaon` repo and binary. + +## Tool Selection + +- Prefer the **MCP server** when a tool already covers the domain operation. +- Fall back to the **CLI** for local-machine or interactive operations: + `auth`, `payroll payslip view`, `reports show`, `cache refresh attendance-types`, + `serve`, and `completions`. +- Use this **skill** to pick the right surface, the right command/tool, and the + right safety flow. + +## Human-attested writes + +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: + +1. Run with `--dry-run` (the default) first. +2. Show the resulting preview to the user. +3. Require the user to explicitly confirm in the conversation before rerunning with `--execute`. + +Never autonomously rerun a write with `--execute`. Writes must be treated as user-authorized actions and must not be submitted without explicit user confirmation. + +## CLI Entry Point + +If working from a repo checkout, prefer: + +```bash +scripts/run.sh [args] +``` + +If installed globally: + +```bash +shaon [args] +``` + +## First-Time Setup + +Create `~/.shaon/config.toml`: + +```toml +subdomain = "mycompany" +username = "123456789" +payslip_folder = "/path/to/payslips" # optional +payslip_format = "%Y-%m.pdf" # optional +``` + +Then authenticate: + +```bash +shaon auth +``` + +If stored credentials are stale and you want a deterministic refresh prompt: + +```bash +shaon auth --force-prompt +``` + +## Pick The Right Read Command + +| User intent | Use | +|-------------|-----| +| "what's my current month state?" | `shaon attendance overview --json` | +| "show me the raw calendar / what did Hilan record per day?" | `shaon attendance status --month YYYY-MM` | +| "what errors do I need to fix?" | `shaon attendance errors --month YYYY-MM` | +| "what attendance types can I report?" | `shaon attendance types` | +| "what absence symbols mean?" | `shaon attendance absences` | +| "show the analyzed hours sheet" | `shaon reports sheet` | +| "show the manual correction log / audit trail" | `shaon reports corrections` | +| "show a named Hilan report page" | `shaon reports show ` | +| "download my payslip" | `shaon payroll payslip download --month YYYY-MM` | +| "open my payslip locally" | `shaon payroll payslip view --month YYYY-MM` | +| "how much did I earn recently?" | `shaon payroll salary --months N` | + +`attendance overview` is usually the best first move for an agent because it bundles identity, summary, errors, missing days, and suggested actions. + +JSON contract notes: + +- `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`. +- `attendance overview --json` returns `missing_days` as `{ date, day_name }` objects. +- `suggested_actions` is keyed by `kind`; fields are top-level, not nested inside a generic `params` object. +- `attendance overview --json --detailed` adds a `days[]` array using the same schema as `attendance status --json`. + +## Write Commands + +### Explicit reporting + +| Intent | Command | +|--------|---------| +| clock in now | `shaon attendance report today --in` | +| clock out now | `shaon attendance report today --out` | +| report one explicit day | `shaon attendance report day YYYY-MM-DD --type "regular" --hours 09:00-18:00` | +| report a range | `shaon attendance report range --from YYYY-MM-DD --to YYYY-MM-DD --type "regular" --hours 09:00-18:00` | +| auto-fill missing days in a month | `shaon attendance auto-fill --month YYYY-MM --type "regular" --hours 09:00-18:00` | +| resolve an existing error day | `shaon attendance resolve YYYY-MM-DD --type "regular" --hours 09:00-18:00` | + +### Safety Model + +- Every write is **preview-only by default**. +- The agent should show the preview summary to the user before rerunning with `--execute` or `execute: true`. +- The agent must wait for explicit user confirmation before any live submit. +- `attendance report range` and `attendance auto-fill` skip Fri/Sat unless explicitly overridden. +- `attendance auto-fill` is capped at `--max-days 10` by default to prevent accidental bulk edits. + +## MCP Coverage + +Current MCP tools cover: + +- `shaon_status` +- `shaon_errors` +- `shaon_types` +- `shaon_clock_in` +- `shaon_clock_out` +- `shaon_fill` +- `shaon_auto_fill` +- `shaon_resolve` +- `shaon_payslip_download` +- `shaon_salary` +- `shaon_sheet` +- `shaon_corrections` +- `shaon_absences` +- `shaon_overview` + +CLI-only features: + +- `shaon auth` +- `shaon payroll payslip view` +- `shaon reports show ` +- `shaon cache refresh attendance-types` +- `shaon serve` +- `shaon completions` + +## Agent Workflows + +### Review the month first + +```bash +shaon attendance overview --json +``` + +### Fix an attendance error safely + +```bash +shaon attendance errors --month 2026-04 --json +shaon attendance resolve 2026-04-09 --type "regular" --hours 09:00-18:00 +# After explicit user confirmation: +shaon attendance resolve 2026-04-09 --type "regular" --hours 09:00-18:00 --execute +``` + +### Fill a missing range safely + +```bash +shaon attendance report range --from 2026-04-01 --to 2026-04-05 --type "regular" --hours 09:00-18:00 +# After explicit user confirmation: +shaon attendance report range --from 2026-04-01 --to 2026-04-05 --type "regular" --hours 09:00-18:00 --execute +``` + +### Hebrew payslip workflow + +```bash +shaon payroll payslip download --month 2026-03 +shaon payroll payslip view --month 2026-03 +``` + +### Sensitive recovery command + +`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. + +## Troubleshooting + +- **CAPTCHA**: the user must solve it in the browser first. +- **Type resolution fails**: run `shaon cache refresh attendance-types` or pass the numeric type code directly. +- **Session expired or stale stored credentials**: rerun `shaon auth --force-prompt` to verify and replace the stored password. + +## Further Reading + +- [README.md](../../README.md) +- [ARCHITECTURE.md](../../ARCHITECTURE.md) +- [PROTOCOL.md](../../PROTOCOL.md) diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/evals/evals.json b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/evals/evals.json new file mode 100644 index 0000000000000000000000000000000000000000..06b1696970789580b189642d621ad798b04d818b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/skill/evals/evals.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e21176421d761837fb419461338319c6c57ce0f9defe07e78ee9a61b9d14e2d4 +size 1279 diff --git a/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/task.json b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..374030cef7dfc4a0cdeb2c1762125eb40de3f692 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8dbd07af72331a25_q1/task.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61eb165900ff1cec8c169cf0a7a84c48f79f29f11a0fb56bcb75001b123a4d9d +size 1695 diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..79617b5fa082232f7de0b756c12039b89d742878 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_contract.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37 +size 83 diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..f77164f6102520f73c75d3adb38fc7a54860b4e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1309 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + from r9_json import parse_file, strict_equal + actual = parse_file(path) + passed = strict_equal(actual, check.get("expected")) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..b84dc8f2b2af4bebe2eb4c48e55c3aeaef091cad --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,229 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + +def _nonzero_exit_body(statements): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _simple_argv(statement) + if not argv: + return False + if argv[0] == 'exit': + return (index == len(statements) - 1 and len(argv) == 2 + and argv[1].isdigit() and 1 <= int(argv[1]) <= 255) + if argv[0] not in ('echo', 'printf'): + return False + return False + + +def shell_invocations(text): + """Return ordered, actually evaluated invocation nodes in the supported subset. + + fail_fast is a structural proof: a simple command/assignment runs under + errexit, or a negated test exits nonzero on failure. This is not a complete + shell interpreter, and unsupported syntax earns no invocation credit. + """ + statements = _statements(text) + # Function definitions or dynamic shell mutation can shadow the command or + # `exit` itself. They are outside this objective subset, even if uncalled. + if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s) + or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s) + for s in statements): + return [] + constants, result, index, errexit = {}, [], 0, False + assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while index < len(statements): + statement = statements[index] + literal = assignment.fullmatch(statement) + if literal: + constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None) + index += 1 + continue + statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement) + setting = _simple_argv(statement) + if setting and setting[0] == 'set': + flag_index = 1 + while flag_index < len(setting): + flag = setting[flag_index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Remaining words set positional parameters. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return [] # e.g. `set -n` suppresses execution entirely. + if 'e' in flag[1:]: + errexit = flag[0] == '-' + if 'o' in flag[1:]: + if flag_index + 1 >= len(setting): + return [] + option = setting[flag_index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return [] + if option == 'errexit': + errexit = flag[0] == '-' + flag_index += 1 + flag_index += 1 + index += 1 + continue + if re.match(r'^if\s', statement): + end = _guard_end(statements, index) + if end is None: + return [] + negated = re.fullmatch(r'if\s+!\s+(.+)', statement) + if (negated and index + 1 < end + and statements[index + 1] == 'then' + and _nonzero_exit_body(statements[index + 2:end])): + argv, kind = _invocation(negated.group(1).strip()) + if argv: + if argv[0] == 'false': + break + result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind, + 'fail_fast': True, 'statement_index': index}) + else: + return [] + else: + # Arbitrary conditions may terminate the script or shadow its + # commands. Do not infer a reachable suffix through them. + return [] + # Bodies are never credited and may have assigned local variables. + constants.clear() + index = end + 1 + continue + if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{': + # Unsupported compounds are not searched for command substrings. + return [] + argv, kind = _invocation(statement) + if not argv: + # An unparsed statement may change control flow or shell state. + # Skipping it would incorrectly credit an unreachable suffix. + return [] + if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare', + 'typeset', 'local', 'read', 'mapfile', 'readarray', + 'unset', 'readonly', '[', '[[', 'test'): + return [] + if argv[0] == 'exit' or (argv[0] == 'false' and errexit): + break + if kind == 'assignment_substitution': + assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement) + if assigned: + constants.pop(assigned.group(1), None) + result.append({'command': shlex.join(argv), 'kind': kind, + 'fail_fast': errexit, 'statement_index': index}) + index += 1 + return result diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}} +if [[ -z "$candidate" ]]; then + echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..c6290e83629e9f84ece58ae2c4cfd0f5b3f932e2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,525 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + try:return json.loads(text) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + + +from r9_json import parse_single as _r9_parse_single +_json_value = _r9_parse_single + + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + try: + pred = _atomic_prepare(_json_value(solver_output), + verifier.get("list_order", "ordered")) + pred_shape = _atomic_shape(pred) + except RecursionError: + return False, "candidate JSON nesting is too deep" + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], pred_shape) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = (_path_value(actual) is not None and + _path_value(actual) == _path_value(assertion["expected"])) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/r9_json.py b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/r9_json.py new file mode 100644 index 0000000000000000000000000000000000000000..9038b5dcda483f3b1fb11794bb030669af07eccb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/evaluator/r9_json.py @@ -0,0 +1,74 @@ +"""JSON wire parsing and native-type equality for the R9 task copies. + +No expected answers are defined here. Single complete JSON fences are accepted +only as a transport wrapper when requested by the calling task. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json +import math +import re + + +def no_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError('duplicate JSON key') + result[key] = value + return result + + +def _finite_tree(value): + if isinstance(value, float) and not math.isfinite(value): + raise ValueError('non-finite JSON number') + if isinstance(value, dict): + for item in value.values(): + _finite_tree(item) + elif isinstance(value, list): + for item in value: + _finite_tree(item) + return value + + +def parse_single(value, allow_fence=True): + """Parse the entire response; no prefix/suffix or duplicate keys allowed.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return _finite_tree(value) + if isinstance(value, bytes): + value = value.decode('utf-8-sig') + text = str(value).lstrip('\ufeff').strip() + if allow_fence and text.startswith('```'): + match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I) + if match is None: + raise ValueError('not one complete JSON fence') + text = match.group(1) + return _finite_tree(json.loads( + text, object_pairs_hook=no_duplicates, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number')))) + + +def parse_file(path): + """Files must contain raw JSON; Markdown fences are not JSON file bytes.""" + with open(path, 'r', encoding='utf-8-sig') as stream: + return parse_single(stream.read(), allow_fence=False) + + +def strict_equal(actual, expected, number_equivalence=False): + """Preserve keys, order and every native type; booleans never equal numbers. + + Set number_equivalence only if the public contract says a generic number + rather than an integer. It accepts finite integral numeric equivalents. + """ + if type(actual) is not type(expected): + if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float): + return math.isfinite(actual) and math.isfinite(expected) and actual == expected + return False + if isinstance(expected, dict): + return set(actual) == set(expected) and all( + strict_equal(actual[key], value, number_equivalence) for key, value in expected.items()) + if isinstance(expected, list): + return len(actual) == len(expected) and all( + strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected)) + if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)): + return False + return actual == expected diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..88120f0a96eeaff34342d3129f9fd4b56e4f3d8d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/grading/verified_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02bcf80063d9a42df51c0d7e4289e2c6f78a92e85f02d2f29178510732e50ca6 +size 4081 diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3614e4b7d3c4ffbf598c67418618e62aec26f1e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/instruction.md @@ -0,0 +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"}} diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..0a77735561e8abd0ea0c2d762d7a911aa2f957f2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/skill/SKILL.md @@ -0,0 +1,156 @@ +--- +name: moonshine-component +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. +argument-hint: [component description] +allowed-tools: Read Grep Glob Edit Write Bash +compatibility: Requires Laravel with MoonShine 3.x package installed +metadata: + author: moonshine-software + version: "1.0" +--- + +You are an expert MoonShine developer specializing in custom component development. Your task is to help users create custom components for MoonShine admin panel. + +## Your Resources + +You have access to comprehensive guidelines in `.guidelines/components-development.md` file. This file contains: +- Complete component structure and anatomy +- Components vs Fields comparison +- Fluent methods and viewData() +- Slots and nested components patterns +- Complete examples (Alert, StatsCard, Breadcrumbs) + +## Critical Rules (Read from guidelines) + +Before starting, you MUST read and follow these rules from `.guidelines/components-development.md`: + +1. **Components are for DISPLAY only** - They don't save data, only show content +2. **No field modes** - Components don't have default/preview/raw modes +3. **Fluent methods MUST return `static`** - For method chaining +4. **ALWAYS add `{{ $attributes }}`** - To root element for customization +5. **Use `value()` for closures** - Import `use function MoonShine\UI\Components\Layout\value` +6. **`viewData()` passes ALL data** - Unlike fields, no automatic system data +7. **`assets()` method MUST be `protected`** - NOT public +8. **Extend correct base class** - `MoonShineComponent` or `AbstractWithComponents` +9. **Move logic to `prepareBeforeRender()`** - NEVER write `@php` blocks in Blade views + +## Components vs Fields + +**Critical difference:** + +| Feature | Fields | Components | +|---------|--------|-----------| +| Purpose | Data input/output | UI decoration | +| Saves data | Yes | No | +| Has modes | Yes | No | +| System data | Auto (value, attributes, etc.) | None | +| Used for | Forms, Tables | Layouts, Pages | + +**When to use Components:** +- Displaying static content +- UI decoration (headers, footers, alerts) +- Grouping other components +- Dashboard widgets +- Breadcrumbs, menus, badges + +**When to use Fields:** +- User input required +- Data needs to be saved +- Forms and tables + +## Your Task + +When creating custom components: + +1. **Read the guidelines**: Open and study `.guidelines/components-development.md` +2. **Understand the request**: What kind of component does the user need? +3. **Choose base class**: + - `MoonShineComponent` - Simple components + - `AbstractWithComponents` - Components that contain other components +4. **Plan component structure**: + - What properties does it need? + - What fluent methods should it have? + - Does it need slots? +5. **Implement the component**: + - Create PHP class in `app/MoonShine/Components/ComponentName.php` + - Create Blade view in `resources/views/admin/components/component-name.blade.php` + - Add fluent methods + - Implement `viewData()` + +## Important Notes + +### File Locations +- **PHP Class**: `app/MoonShine/Components/YourComponent.php` +- **Blade View**: `resources/views/admin/components/your-component.blade.php` + +### Essential Methods + +**`viewData()`** - Pass ALL data to Blade view: +```php +protected function viewData(): array +{ + return [ + 'title' => value($this->title), + 'items' => $this->items, + ]; +} +``` + +**`prepareBeforeRender()`** - Process logic BEFORE rendering: +```php +protected function prepareBeforeRender(): void +{ + parent::prepareBeforeRender(); + // Prepare attributes, merge styles here +} +``` + +**Fluent methods** - Configure the component: +```php +public function title(string $title): static +{ + $this->title = $title; + return $this; +} +``` + +### Blade Template + +```blade +@props([ + 'title' => '', + 'items' => [], +]) + +
merge(['class' => 'my-component']) }}> +

{{ $title }}

+ @foreach($items as $item) +
{{ $item }}
+ @endforeach +
+``` + +### Nested Components + +For components containing other components, extend `AbstractWithComponents`: + +```php +class Container extends AbstractWithComponents +{ + public function __construct( + iterable $components = [], + protected string $title = '' + ) { + parent::__construct($components); + } +} +``` + +**In Blade:** +```blade + +``` + +## User Request + +$ARGUMENTS diff --git a/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/task.json b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..09f7904b36bab0bdb6bdc28df055a6269959d6f4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/8fe6482e81e3ebba_q1/task.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c38b0b33163ffd50dfd9b6190fb12571f4d8846de05b2e9c1ce0ab3a3330b34 +size 1597 diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..79617b5fa082232f7de0b756c12039b89d742878 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_contract.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37 +size 83 diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_entry.py @@ -0,0 +1,38 @@ +"""Stable result protocol; candidate failures and evaluator errors stay distinct.""" +from pathlib import Path +import contextlib,io,json,runpy,sys +from auto_policy import install,finalize +HERE=Path(__file__).resolve().parent + +def main(): + captured=io.StringIO() + try: + install() + with contextlib.redirect_stdout(captured): + try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') + except SystemExit as error: + if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) + body=None + for line in reversed(captured.getvalue().splitlines()): + try:value=json.loads(line) + except(ValueError,TypeError):continue + if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break + if body is None:raise RuntimeError('Trusted checker did not emit its result schema') + if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) + cfgfile=HERE/'auto_policy.json' + if cfgfile.is_file(): + cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) + if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) + checks=body['checks'] + if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') + ids=[str(c['id'])for c in checks] + if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') + contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] + if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') + weights=contract['criterion_weights'] + body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) + print(json.dumps(body,ensure_ascii=True));return 0 + except Exception as error: + print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy.py @@ -0,0 +1,133 @@ +"""Trusted bounded-invocation policy; never infer whole-program properties.""" +from pathlib import Path +import hashlib,json,os,subprocess,sys,tempfile,time,uuid + +HERE=Path(__file__).resolve().parent +ENV='MYBENCH_AUTO_POLICY_RECEIPTS' +DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE' +class PolicyInfrastructureError(RuntimeError): pass +_installed=False +_original_popen=subprocess.Popen +_original_run=subprocess.run + +def _config(): + p=HERE/'auto_policy.json' + if not p.is_file():return None + value=json.loads(p.read_text()) + if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') + return value + +def _folder(): + if ENV not in os.environ: + os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') + p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p + +def _python_target(command,cwd): + if not isinstance(command,(list,tuple))or not command:return None + argv=[os.fspath(x)for x in command] + if 'python'not in Path(argv[0]).name.lower():return None + i=1;flags=[] + while i=len(argv):return None + name=argv[i+1];p=Path(cwd)/name.replace('.','/') + if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None + return argv[0],flags,'module',name,argv[i+2:] + if flag in ['-c','-']:return None + flags.append(flag);i+=1 + if flag in ['-W','-X']and i=len(argv)or not argv[i].endswith('.py'):return None + path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path + path=path.resolve() + if path==HERE or HERE in path.parents: + if path.name in ['auto_policy.py','auto_policy_guard.py']:return None + for value in argv[i+1:]: + if not value.endswith('.py')or value.startswith('-'):continue + subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject + subject=subject.resolve() + if HERE not in subject.parents: + return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] + return None + return argv[0],flags,'script',str(path),argv[i+1:] + +def install(): + global _installed + if _installed:return + _installed=True + cfg=_config() + if cfg is None:return + _folder() + os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) + class GuardedPopen(_original_popen): + def __init__(self,args,*pos,**kwargs): + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) + receipt=None + if target: + executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) + if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] + args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] + env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env + if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] + try:super().__init__(args,*pos,**kwargs) + except OSError as error: + if receipt: + receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) + raise + subprocess.Popen=GuardedPopen + def bounded_run(*pos,**kwargs): + command=pos[0]if pos else kwargs.get('args') + cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() + target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) + if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' + if target is not None and cfg.get('execution_budget_seconds')is not None: + budget=cfg['execution_budget_seconds'] + if type(budget)not in(int,float)or not 00:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) + try: + if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) + result=_original_run(*pos,**kwargs) + if target is not None and result.returncode<0: + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) + return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) + return result + except subprocess.TimeoutExpired as error: + if target is None:raise + (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) + textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') + empty=''if textual else b'' + def output(value): + if value is None:return empty + return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value + return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) + subprocess.run=bounded_run + +def status(require_execution=True): + install();p=_folder();rows=[] + for receipt in sorted(p.glob('*.json')): + try:row=json.loads(receipt.read_text()) + except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error + if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: + raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) + rows.append(row) + if require_execution and not any(r.get('target_present')for r in rows):return False + return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows) + +def finalize(body,owner_ids,require_execution=True): + observed=status(require_execution=require_execution) + wanted=set(map(str,owner_ids)) + for row in body.get('checks',[]): + if str(row['id'])in wanted: + if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) + row['passed']=row['passed']and observed + row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' + body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) + body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) + return body + +def run(*args,**kwargs): + install();return subprocess.run(*args,**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/auto_policy_guard.py @@ -0,0 +1,86 @@ +"""Child-side observer for the exact public bounded-invocation policy.""" +from pathlib import Path +import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig + +receipt,config_file,kind,target,*arguments=sys.argv[1:] +subject=arguments.pop(0)if kind=='probe'else target +subject_filename=os.path.abspath(subject) +receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve() +local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]] +if kind=='script':local_roots.insert(0,Path(target).resolve().parent) +if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent] +candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader'] +observer_filename=__file__ +stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names) +stdlib_root=Path(sysconfig.get_path('stdlib')).resolve() +if not getattr(sys,'stdlib_module_names',None): + for p in stdlib_root.iterdir(): + if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name) +state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[]) +busy=False +def save(): + global busy + was=busy;busy=True + try: + temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt) + finally:busy=was +def violation(code,detail): + state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code) +def local_module(name): + first=name.partition('.')[0] + roots=list(local_roots) + for value in sys.path: + try:p=Path(value or cwd).resolve() + except (OSError,TypeError,ValueError):continue + if any(p==r or r in p.parents for r in local_roots):roots.append(p) + return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots) +def subject_active(): + if kind!='probe':return True + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if isinstance(filename,str): + absolute=os.path.abspath(filename) + if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True + frame=frame.f_back + return False +def audit(event,args): + relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.') + if busy or not relevant or not subject_active():return + if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate(): + check_import(str(args[0])) + if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event) + if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event) + if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event) +def check_import(name): + if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name) + base=name.partition('.')[0] + if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name) +def import_requested_by_candidate(): + frame=sys._getframe(1) + while frame: + filename=frame.f_globals.get('__file__',frame.f_code.co_filename) + if not isinstance(filename,str)or filename==observer_filename or filename.startswith(' max_score: + return "Judge score must be between zero and max_score" + return None + + +def evaluate(task_json, candidate_path, open_judge_command=None, + open_judge_timeout=None): + task_json = Path(task_json).resolve() + candidate_path = Path(candidate_path).resolve() + task = json.loads(task_json.read_text(encoding="utf-8")) + evaluation = task.get("evaluation") or {} + track = evaluation.get("type") + base = { + "schema_version": task.get("schema_version"), + "task_id": task.get("task_id"), + "query_id": task.get("query_id"), + "track": track, + } + if track == "verified": + workspace_mode = ((evaluation.get("verifier") or {}).get("type") == + "workspace_objective") + if workspace_mode and not candidate_path.is_dir(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "workspace evaluator requires a candidate directory"}, 2 + if not workspace_mode and not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "response evaluator requires a candidate file"}, 2 + if workspace_mode: + candidate = str(candidate_path) + else: + try: + candidate = candidate_path.read_text(encoding="utf-8") + except UnicodeError: + return {**base, "status": "candidate_contract_error", "passed": False, + "score": 0, "max_score": 1, + "details": "candidate response must use valid UTF-8"}, 2 + passed, detail = _load_verify()( + evaluation.get("verifier") or {}, + evaluation.get("ground_truth_answer"), + candidate, + None, + ) + return {**base, "status": "scored", "passed": bool(passed), + "score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1 + if track != "open": + return {**base, "status": "unsupported_track", "passed": False, + "score": None, "details": f"unsupported track: {track}"}, 2 + if not candidate_path.is_file(): + return {**base, "status": "candidate_contract_error", "passed": False, + "score": None, "details": "open judge requires a candidate response file"}, 2 + candidate_file = candidate_path + command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND") + if not command: + return {**base, "status": "requires_external_judge", "passed": None, + "score": None, "details": ( + "Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads " + "MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2 + environment = os.environ.copy() + environment["MYBENCH_TASK_JSON"] = str(task_json) + environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file) + timeout = float(open_judge_timeout or os.environ.get( + "MYBENCH_OPEN_JUDGE_TIMEOUT", 600)) + if not math.isfinite(timeout) or timeout <= 0: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": "Judge timeout must be a positive number"}, 2 + try: + completed = subprocess.run( + shlex.split(command), cwd=str(task_json.parent), env=environment, + text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return {**base, "status": "judge_error", "passed": False, + "score": None, "details": str(exc)}, 2 + if completed.returncode: + return {**base, "status": "judge_error", "passed": False, "score": None, + "details": completed.stderr.strip() or completed.stdout.strip()}, 2 + try: + judge = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": str(exc)}, 2 + contract_error = _judge_contract(judge) + if contract_error: + return {**base, "status": "judge_contract_error", "passed": False, + "score": None, "details": contract_error}, 2 + result = {**base, "status": "scored", "passed": judge.get("passed"), + "score": judge.get("score"), "max_score": judge.get("max_score", 100), + "details": judge.get("details", judge)} + return result, 0 if result["passed"] else 1 + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--task-json", required=True) + candidates = parser.add_mutually_exclusive_group(required=True) + candidates.add_argument("--candidate-path") + candidates.add_argument("--candidate-file") # v1 compatibility + parser.add_argument("--result-output") + parser.add_argument("--open-judge-command") + parser.add_argument("--open-judge-timeout", type=float) + args = parser.parse_args() + result, code = evaluate(args.task_json, + args.candidate_path or args.candidate_file, + args.open_judge_command, args.open_judge_timeout) + _emit(result, args.result_output) + raise SystemExit(code) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..f77164f6102520f73c75d3adb38fc7a54860b4e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1309 @@ +"""Composable objective evaluators for response and workspace tasks. + +Task semantics are deliberately *not* enumerated here. A task may describe any +real user goal; verified membership depends on whether its deliverables compile +to one of these small, trusted evaluator primitives and pass counterfactual +execution. This keeps the objective surface closed and auditable without +turning the benchmark's task ontology into a closed template list. +""" +from __future__ import annotations + +import ast +import copy +import builtins +import json +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath +try: + from .shell_invocations import shell_invocations +except ImportError: + from shell_invocations import shell_invocations + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 15 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +ARTIFACT_FORMATS = {"json", "toml", "python", "shell"} +_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +class ObjectiveEvaluatorError(ValueError): + pass + + +def safe_relative_path(value): + """Return a normalized portable relative path or fail closed.""" + text = str(value or "").strip().replace("\\", "/") + path = PurePosixPath(text) + if (not text or text.startswith("/") or path.is_absolute() or + any(part in {"", ".", ".."} for part in path.parts)): + raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}") + if len(path.parts) > 8 or len(text) > 180: + raise ObjectiveEvaluatorError("workspace path is too deep or long") + return path.as_posix() + + +def _json_value(value): + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + return json.loads(str(value)) + + +def _canonical(value): + if isinstance(value, dict): + return {key: _canonical(value[key]) for key in sorted(value)} + if isinstance(value, list): + return [_canonical(item) for item in value] + return value + + +def _file_content(item): + fmt = str(item.get("format") or "").casefold() + content = item.get("content") + if fmt == "json": + parsed = _json_value(content) + return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str): + raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text") + return content.rstrip() + "\n" + + +def _ast_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = _ast_name(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + +def _python_inventory(text): + tree = ast.parse(text) + imports, calls = set(), set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + imports.add(f"{module}.{alias.name}".strip(".")) + elif isinstance(node, ast.Call): + name = _ast_name(node.func) + if name: + calls.add(name) + return imports, calls + + +def _literal_value(node, constants=None): + constants = constants or {} + if isinstance(node, ast.Constant) and isinstance( + node.value, (str, int, float, bool, type(None))): + return node.value + if isinstance(node, ast.Name) and node.id in constants: + return constants[node.id] + if isinstance(node, (ast.Tuple, ast.List)): + values = [_literal_value(item, constants) for item in node.elts] + if all(value is not _UNRESOLVED for value in values): + return tuple(values) if isinstance(node, ast.Tuple) else values + return _UNRESOLVED + + +_UNRESOLVED = object() + + +def _python_semantics(text): + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + imports, calls = _python_inventory(text) + constants = {} + for node in tree.body: + name = None + value_node = None + if (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name)): + name, value_node = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value_node = node.target.id, node.value + if name and value_node is not None: + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[name] = value + elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and + isinstance(node.targets[0], (ast.Tuple, ast.List)) and + isinstance(node.value, (ast.Tuple, ast.List)) and + len(node.targets[0].elts) == len(node.value.elts)): + # Treat ordinary constant unpacking as semantically equivalent to + # separate assignments. Generated implementation files commonly + # use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would + # test formatting rather than the required repository values. + for target, value_node in zip(node.targets[0].elts, node.value.elts): + if not isinstance(target, ast.Name): + continue + value = _literal_value(value_node, constants) + if value is not _UNRESOLVED: + constants[target.id] = value + call_nodes = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + call_nodes.append((_ast_name(node.func), node)) + return imports, calls, constants, call_nodes + + +def _python_resolved_call_nodes(text): + """Resolve call targets through imports and simple constructor bindings. + + The evaluator intentionally supports a small static subset: imports, + local definitions, direct aliases, and names assigned from calls. That is + enough to recognize semantic equivalents such as ``import datetime`` vs + ``from datetime import timedelta as td`` and instance-variable renames, + without pretending to perform general Python type inference. + """ + tree = ast.parse(text) + _annotate_assignment_contexts(tree) + bindings = {} + nodes = sorted(ast.walk(tree), key=lambda node: ( + int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1)))) + + def resolve(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id) + if isinstance(node, ast.Attribute): + parent = resolve(node.value) + return f"{parent}.{node.attr}" if parent else node.attr + return "" + + # A few fixed-point passes cover aliases declared after an imported name + # and ordinary ``client = Client()`` instance construction. + for _ in range(4): + changed = False + for node in nodes: + updates = {} + if isinstance(node, ast.Import): + for alias in node.names: + local = alias.asname or alias.name.split(".")[0] + updates[local] = alias.name if alias.asname else local + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + if alias.name == "*": + continue + updates[alias.asname or alias.name] = \ + f"{module}.{alias.name}".strip(".") + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + updates[node.name] = "__local__." + node.name + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = (node.targets if isinstance(node, ast.Assign) + else [node.target]) + value = node.value + if isinstance(value, ast.Call): + provenance = resolve(value.func) + elif isinstance(value, (ast.Name, ast.Attribute)): + provenance = resolve(value) + else: + provenance = "" + if provenance: + for target in targets: + if isinstance(target, ast.Name): + updates[target.id] = provenance + for name, value in updates.items(): + if bindings.get(name) != value: + bindings[name] = value + changed = True + if not changed: + break + return [(_ast_name(node.func), resolve(node.func), node) + for node in ast.walk(tree) if isinstance(node, ast.Call)] + + +def _call_name_matches(observed, expected): + return observed == expected or observed.endswith("." + expected) + + +def _objective_call_targets(kind, check, resolved_calls, constants): + """Return canonical targets satisfying one already-validated call check.""" + function = str(check.get("function") or check.get("value") or "") + targets = set() + for name, target, node in resolved_calls: + if not _call_name_matches(name, function): + continue + if kind == "python_call_literal" and not _node_contains_literal( + node, check.get("value"), constants): + continue + if kind == "python_call_keyword_literal" and not _call_keyword_matches( + node, str(check.get("keyword") or ""), check.get("value"), + constants): + continue + if kind == "python_call_signature" and not _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment")): + continue + if target: + targets.add(target) + return targets + + +def python_unbound_call_roots(text): + """Return call-root names that have no static binding in the module. + + Objective call checks must not accept a syntactically valid file that will + immediately raise ``NameError``. This deliberately proves only the + conservative prerequisite that a root is imported, assigned, declared, + passed as an argument, or provided by Python builtins; it does not claim to + execute or type-check the program. + """ + tree = ast.parse(text) + bound = set(dir(builtins)) + for node in ast.walk(tree): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): + bound.add(node.id) + elif isinstance(node, ast.arg): + bound.add(node.arg) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, + ast.ClassDef)): + bound.add(node.name) + elif isinstance(node, ast.Import): + for alias in node.names: + bound.add(alias.asname or alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + for alias in node.names: + bound.add(alias.asname or alias.name) + elif isinstance(node, ast.ExceptHandler) and node.name: + bound.add(node.name) + unbound = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + root = node.func + while isinstance(root, ast.Attribute): + root = root.value + if isinstance(root, ast.Name) and root.id not in bound: + unbound.add(root.id) + return sorted(unbound) + + +def _node_contains_literal(node, expected, constants): + for child in ast.walk(node): + value = _literal_value(child, constants) + if value is _UNRESOLVED: + continue + if value == expected: + return True + if isinstance(value, (list, tuple)) and expected in value: + return True + return False + + +def _call_keyword_matches(node, keyword, expected, constants): + """Return whether a direct call keyword resolves to the expected scalar.""" + return any( + item.arg == keyword and _literal_value(item.value, constants) == expected + for item in getattr(node, "keywords", []) + if item.arg is not None) + + +def _portable_literal(value): + if isinstance(value, tuple): + return [_portable_literal(item) for item in value] + if isinstance(value, list): + return [_portable_literal(item) for item in value] + return value + + +def _expression_text(node): + """Return a formatting-independent, non-executed Python expression.""" + return ast.unparse(node).strip() + + +def _expression_fingerprint(value): + if not isinstance(value, str) or not value.strip() or len(value) > 500: + return None + try: + tree = ast.parse(value, mode="eval") + except SyntaxError: + return None + return ast.dump(tree.body, annotate_fields=True, include_attributes=False) + + +def _expression_matches(node, expected): + fingerprint = _expression_fingerprint(expected) + return bool(fingerprint and ast.dump( + node, annotate_fields=True, include_attributes=False) == fingerprint) + + +def _annotate_assignment_contexts(tree): + """Attach one conservative simple-assignment context to nested calls.""" + for statement in ast.walk(tree): + target, value = None, None + if (isinstance(statement, ast.Assign) and + len(statement.targets) == 1 and + isinstance(statement.targets[0], ast.Name)): + target, value = statement.targets[0].id, statement.value + elif (isinstance(statement, ast.AnnAssign) and + isinstance(statement.target, ast.Name) and + statement.value is not None): + target, value = statement.target.id, statement.value + if not target or value is None: + continue + context = {"target": target, "expression": _expression_text(value)} + for child in ast.walk(value): + if isinstance(child, ast.Call): + setattr(child, "_mybench_assignment", context) + + +def _call_signature(node, constants): + arguments = [] + argument_expressions = [] + for index, argument in enumerate(getattr(node, "args", [])): + value = _literal_value(argument, constants) + if value is not _UNRESOLVED: + arguments.append({"index": index, + "value": _portable_literal(value)}) + else: + argument_expressions.append({ + "index": index, "expression": _expression_text(argument)}) + keywords = {} + keyword_expressions = {} + for keyword in getattr(node, "keywords", []): + if keyword.arg is None: + continue + value = _literal_value(keyword.value, constants) + if value is not _UNRESOLVED: + keywords[keyword.arg] = _portable_literal(value) + else: + keyword_expressions[keyword.arg] = _expression_text(keyword.value) + signature = {"arguments": arguments, "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions} + assignment = getattr(node, "_mybench_assignment", None) + if isinstance(assignment, dict): + signature["assignment"] = dict(assignment) + return signature + + +def _call_signature_matches(node, arguments, keywords, constants, + argument_expressions=None, + keyword_expressions=None, assignment=None): + for expected in arguments or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", []))): + return False + actual = _literal_value(node.args[index], constants) + if (actual is _UNRESOLVED or + _canonical(_portable_literal(actual)) != + _canonical(expected.get("value"))): + return False + for keyword, expected in (keywords or {}).items(): + if not _call_keyword_matches(node, keyword, expected, constants): + return False + for expected in argument_expressions or []: + index = expected.get("index") + if (not isinstance(index, int) or index < 0 or + index >= len(getattr(node, "args", [])) or + not _expression_matches( + node.args[index], expected.get("expression"))): + return False + node_keywords = {item.arg: item.value for item in + getattr(node, "keywords", []) if item.arg is not None} + for keyword, expected in (keyword_expressions or {}).items(): + if (keyword not in node_keywords or + not _expression_matches(node_keywords[keyword], expected)): + return False + if assignment: + actual = getattr(node, "_mybench_assignment", None) + if (not isinstance(actual, dict) or + actual.get("target") != assignment.get("target") or + _expression_fingerprint(actual.get("expression")) != + _expression_fingerprint(assignment.get("expression"))): + return False + return bool(arguments or keywords or argument_expressions or + keyword_expressions or assignment) + + +def python_call_literal_signatures(text, function, expected, keyword=None): + """Return full literal signatures for matching reference call sites.""" + _, _, constants, call_nodes = _python_semantics(text) + out = [] + for name, node in call_nodes: + if not (name == function or name.endswith("." + function)): + continue + matches = (_call_keyword_matches(node, keyword, expected, constants) + if keyword else + _node_contains_literal(node, expected, constants)) + if matches: + out.append(_call_signature(node, constants)) + return out + + +def python_signature_expression_coverage_issues(evaluator, requirements=None): + """Detect anchored call expressions omitted by a static verifier. + + Literal-only call checks used to silently discard non-literal positional + and keyword expressions from the same package-owned call. That allowed a + candidate to retain one easy literal while replacing the actual callback, + input binding, or argument tuple. Only expressions present in the + selected requirement text are required here; unrelated reference-file + context remains outside the objective contract. + """ + if not isinstance(evaluator, dict) or evaluator.get("type") != \ + WORKSPACE_EVALUATOR: + return [] + reference_files = { + str(item.get("path") or ""): str(item.get("content") or "") + for item in evaluator.get("reference_files") or [] + if isinstance(item, dict)} + requirement_texts = [ + re.sub(r"\s+", "", str(item.get("requirement") or "")) + for item in requirements or [] if isinstance(item, dict)] + issues = [] + for check in evaluator.get("checks") or []: + if (not isinstance(check, dict) or + check.get("type") != "python_call_signature"): + continue + function = str(check.get("function") or "") + source = reference_files.get(str(check.get("path") or ""), "") + if not function or not source: + continue + try: + _, _, constants, call_nodes = _python_semantics(source) + except SyntaxError: + issues.append("Python signature reference content is invalid") + continue + matches = [node for name, node in call_nodes + if _call_name_matches(name, function) and + _call_signature_matches( + node, check.get("arguments") or [], + check.get("keywords") or {}, constants, + check.get("argument_expressions") or [], + check.get("keyword_expressions") or {}, + check.get("assignment"))] + if len(matches) != 1: + issues.append( + "Python call signature does not identify one reference call") + continue + reference_signature = _call_signature(matches[0], constants) + function_tokens = {re.sub(r"\s+", "", function), + re.sub(r"\s+", "", function.rsplit(".", 1)[-1])} + + def positional_is_anchored(expression): + compact = re.sub(r"\s+", "", str(expression or "")) + return any(compact and compact in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + def keyword_is_anchored(name, expression): + compact = re.sub(r"\s+", "", str(expression or "")) + needle = f"{name}={compact}" + return any(compact and needle in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + + expected_arguments = { + item["index"]: item.get("expression") + for item in reference_signature.get("argument_expressions") or [] + if positional_is_anchored(item.get("expression"))} + expected_keywords = { + name: expression for name, expression in + (reference_signature.get("keyword_expressions") or {}).items() + if keyword_is_anchored(name, expression)} + actual_arguments = { + item.get("index"): item.get("expression") + for item in check.get("argument_expressions") or [] + if isinstance(item, dict)} + actual_keywords = check.get("keyword_expressions") or {} + expected_assignment = reference_signature.get("assignment") + if expected_assignment: + compact_assignment = re.sub( + r"\s+", "", f"{expected_assignment.get('target')}=" + f"{expected_assignment.get('expression')}") + assignment_is_anchored = any( + compact_assignment and compact_assignment in text and any( + token and token in text for token in function_tokens) + for text in requirement_texts) + else: + assignment_is_anchored = False + actual_assignment = check.get("assignment") + missing_argument = any( + index not in actual_arguments or + _expression_fingerprint(actual_arguments[index]) != + _expression_fingerprint(expression) + for index, expression in expected_arguments.items()) + missing_keyword = any( + name not in actual_keywords or + _expression_fingerprint(actual_keywords[name]) != + _expression_fingerprint(expression) + for name, expression in expected_keywords.items()) + missing_assignment = bool( + assignment_is_anchored and ( + not isinstance(actual_assignment, dict) or + actual_assignment.get("target") != + expected_assignment.get("target") or + _expression_fingerprint(actual_assignment.get("expression")) != + _expression_fingerprint( + expected_assignment.get("expression")))) + if missing_argument or missing_keyword or missing_assignment: + issues.append( + "Python call signature omits an anchored expression or assignment") + return issues + + +def _shell_lines(text): + """Return executable lines with conservative local scalar substitution. + + Shell authors routinely name a fixed argument before using it (for example + ``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar + assignments; never evaluate shell expressions, commands, or defaults. + """ + logical, pending = [], "" + for raw in str(text or "").splitlines(): + line = " ".join(raw.strip().split()) + if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}: + continue + pending = (pending + " " + line).strip() if pending else line + if pending.endswith("\\"): + pending = pending[:-1].rstrip() + continue + logical.append(pending) + pending = "" + if pending: + logical.append(pending) + + constants, out = {}, [] + assignment = re.compile( + r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|" + r"([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)") + for line in logical: + match = assignment.fullmatch(line) + if match: + constants[match.group(1)] = next( + value for value in match.groups()[1:] if value is not None) + out.append(line) + continue + + def replace(match): + name = match.group(1) or match.group(2) + return constants.get(name, match.group(0)) + + out.append(variable.sub(replace, line)) + return out + + +def _shell_command_matches(expected, actual): + """Accept the frozen invocation plus documented optional arguments/path prefixes.""" + try: + wanted = shlex.split(str(expected)) + found = shlex.split(str(actual)) + except ValueError: + return False + def normalize_git_log_limit(tokens): + if len(tokens) < 2 or tokens[:2] != ["git", "log"]: + return tokens + normalized, index = [], 0 + while index < len(tokens): + token = tokens[index] + short = re.fullmatch(r"-(\d+)", token) + long = re.fullmatch(r"--max-count=(\d+)", token) + if short or long: + normalized.append("--max-count=" + (short or long).group(1)) + elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and + re.fullmatch(r"\d+", tokens[index + 1])): + normalized.append("--max-count=" + tokens[index + 1]) + index += 1 + else: + normalized.append(token) + index += 1 + return normalized + + wanted = normalize_git_log_limit(wanted) + found = normalize_git_log_limit(found) + if not wanted or len(found) < len(wanted) or found[0] != wanted[0]: + return False + for index, token in enumerate(wanted[1:], 1): + observed = found[index] + if observed == token: + continue + # A solver may anchor a package-relative script at $REPO_ROOT while + # preserving the exact package path selected by the Skill. + if (index == 1 and "/" in token and + observed.rstrip("/").endswith(token.lstrip("./"))): + continue + return False + return True + + +def _shell_command_sequence_matches(expected, actual_lines): + """Require every frozen command in order while allowing extra lines.""" + cursor = 0 + for command in expected: + for index in range(cursor, len(actual_lines)): + if _shell_command_matches(command, actual_lines[index]): + cursor = index + 1 + break + else: + return False + return True + + +def _shell_unconditional_lines(text): + """Return conservative top-level command lines from a shell artifact. + + Checked commands hidden in a conditional branch or an uncalled function do + not establish that the requested script performs them. This is not a full + shell parser: unsupported control flow simply makes nested lines + ineligible, which is appropriate for the small straight-line command + artifacts compiled by this evaluator. + """ + lines = _shell_lines(text) + depth = 0 + out = [] + opener = re.compile( + r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|" + r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)") + closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})") + for line in lines: + if closer.match(line): + depth = max(0, depth - 1) + continue + if depth == 0 and not opener.match(line): + out.append(line) + if opener.match(line): + depth += 1 + return out + + +def _shell_is_straight_line(text): + """Return whether every executable logical line is top-level. + + This deliberately reuses the conservative control-flow recognizer used by + unconditional command checks. Any recognized conditional, loop, case, or + function makes the whole-script straight-line contract fail closed. + """ + lines = _shell_lines(text) + return lines == _shell_unconditional_lines(text) + + +def compile_workspace_evaluator(deliverables): + """Compile trusted checks from validated deliverable specifications.""" + if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6: + raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables") + reference_files, checks, paths = [], [], set() + for index, raw in enumerate(deliverables, 1): + if not isinstance(raw, dict): + raise ObjectiveEvaluatorError("deliverable is not an object") + path = safe_relative_path(raw.get("path")) + if path in paths: + raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}") + paths.add(path) + fmt = str(raw.get("format") or "").strip().casefold() + if fmt not in ARTIFACT_FORMATS: + raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}") + content = _file_content({**raw, "format": fmt}) + if len(content.encode("utf-8")) > 200_000: + raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB") + reference_files.append({"path": path, "format": fmt, "content": content}) + checks.append({"id": f"file_{index:03d}", "type": "file_exists", + "path": path}) + if fmt == "json": + checks.append({"id": f"json_{index:03d}", "type": "json_exact", + "path": path, "expected": _json_value(raw.get("content"))}) + elif fmt == "toml": + try: + expected = tomllib.loads(content) + except (tomllib.TOMLDecodeError, ValueError) as exc: + raise ObjectiveEvaluatorError("reference TOML is invalid") from exc + checks.append({"id": f"toml_{index:03d}", "type": "toml_exact", + "path": path, "expected": expected}) + elif fmt == "python": + try: + _, _, constants, call_nodes = _python_semantics(content) + resolved_calls = _python_resolved_call_nodes(content) + except SyntaxError as exc: + raise ObjectiveEvaluatorError("reference Python is invalid") from exc + checks.append({"id": f"python_{index:03d}", "type": "python_syntax", + "path": path}) + checks.append({"id": f"python_{index:03d}_bindings", + "type": "python_bound_calls", "path": path}) + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "Python deliverable requires 1-12 objective import/call checks") + for check_index, check in enumerate(raw_checks, 1): + if not isinstance(check, dict): + raise ObjectiveEvaluatorError("Python check is not an object") + kind = str(check.get("type") or "").strip().casefold() + if kind in {"python_import", "python_call"}: + value = str(check.get("value") or "").strip() + if not _DOTTED.fullmatch(value): + raise ObjectiveEvaluatorError("unsupported Python objective check") + compiled = {"type": kind, "path": path, "value": value} + elif kind == "python_constant": + name = str(check.get("name") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(name) or "." in name or + isinstance(value, (dict, list)) or value is None or + constants.get(name, _UNRESOLVED) != value): + raise ObjectiveEvaluatorError( + "Python constant check is invalid or fails reference content") + compiled = {"type": kind, "path": path, "name": name, + "value": value} + elif kind == "python_call_literal": + function = str(check.get("function") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _node_contains_literal(node, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-literal check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "value": value} + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "").strip() + keyword = str(check.get("keyword") or "").strip() + value = check.get("value") + if (not _DOTTED.fullmatch(function) or + not _DOTTED.fullmatch(keyword) or "." in keyword or + isinstance(value, (dict, list)) or value is None or + not any( + (name == function or name.endswith("." + function)) and + _call_keyword_matches(node, keyword, value, constants) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-keyword check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, "keyword": keyword, + "value": value} + elif kind == "python_call_signature": + function = str(check.get("function") or "").strip() + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + if (not _DOTTED.fullmatch(function) or + not isinstance(arguments, list) or + not isinstance(keywords, dict) or + not isinstance(argument_expressions, list) or + not isinstance(keyword_expressions, dict) or + not (arguments or keywords or + argument_expressions or keyword_expressions or + assignment) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + isinstance(item.get("value"), dict) + for item in arguments) or + len({item["index"] for item in arguments}) != + len(arguments) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or isinstance(value, dict) + for name, value in keywords.items()) or + any(not isinstance(item, dict) or + not isinstance(item.get("index"), int) or + item.get("index") < 0 or + not _expression_fingerprint( + item.get("expression")) + for item in argument_expressions) or + len({item["index"] for item in + argument_expressions}) != + len(argument_expressions) or + ({item["index"] for item in arguments} & + {item["index"] for item in + argument_expressions}) or + any(not _DOTTED.fullmatch(str(name)) or + "." in str(name) or + not _expression_fingerprint(value) + for name, value in + keyword_expressions.items()) or + (set(keywords) & set(keyword_expressions)) or + (assignment is not None and ( + not isinstance(assignment, dict) or + not _DOTTED.fullmatch(str( + assignment.get("target") or "")) or + "." in str(assignment.get("target") or "") or + not _expression_fingerprint( + assignment.get("expression")))) or + not any( + (name == function or + name.endswith("." + function)) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, + keyword_expressions, assignment) + for name, node in call_nodes)): + raise ObjectiveEvaluatorError( + "Python call-signature check is invalid or fails reference content") + compiled = {"type": kind, "path": path, + "function": function, + "arguments": arguments, + "keywords": keywords, + "argument_expressions": argument_expressions, + "keyword_expressions": keyword_expressions, + "assignment": assignment} + else: + raise ObjectiveEvaluatorError("unsupported Python objective check") + if kind in {"python_call", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + targets = _objective_call_targets( + kind, compiled, resolved_calls, constants) + if len(targets) != 1: + raise ObjectiveEvaluatorError( + "Python call check has no unique canonical target") + compiled["target"] = next(iter(targets)) + checks.append({"id": f"python_{index:03d}_{check_index:03d}", + **compiled}) + else: + raw_checks = raw.get("checks") or [] + if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12: + raise ObjectiveEvaluatorError( + "shell deliverable requires 1-12 objective command checks") + checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax", + "path": path}) + reference_sequence = _shell_lines(content) + reference_lines = set(reference_sequence) + unconditional_lines = _shell_unconditional_lines(content) + command_checks = [] + for check in raw_checks: + value = " ".join(str(check.get("value") or "").strip().split()) + if (not isinstance(check, dict) or + str(check.get("type") or "").strip().casefold() != "shell_command" or + not value or value not in reference_lines): + raise ObjectiveEvaluatorError("unsupported shell objective check") + command_checks.append({"type": "shell_command", "path": path, + "value": value}) + if len({item["value"] for item in command_checks}) != len(command_checks): + raise ObjectiveEvaluatorError("shell objective checks must be unique") + command_checks.sort(key=lambda item: reference_sequence.index(item["value"])) + if not all(any(_shell_command_matches( + item["value"], line) for line in unconditional_lines) + for item in command_checks): + raise ObjectiveEvaluatorError( + "checked shell commands must be top-level and unconditional") + for check_index, check in enumerate(command_checks, 1): + checks.append({"id": f"shell_{index:03d}_{check_index:03d}", + **check}) + if len(command_checks) >= 2: + checks.append({ + "id": f"shell_{index:03d}_sequence", + "type": "shell_command_sequence", "path": path, + "values": [item["value"] for item in command_checks], + }) + checks.append({ + "id": f"shell_{index:03d}_unconditional", + "type": "shell_unconditional_commands", "path": path, + "values": [item["value"] for item in command_checks], + }) + # Preserve the reference's fail-fast behavior when accepting normal + # command-substitution/guard wrappers. Never turn `|| true` into a + # passing preflight simply because it contains the correct argv. + reference_calls = shell_invocations(content) + protected = [item["value"] for item in command_checks if any( + call["fail_fast"] and _shell_command_matches(item["value"], call["command"]) + for call in reference_calls)] + if protected: + checks.append({"id": f"shell_{index:03d}_failure_propagation", + "type": "shell_failure_propagation", "path": path, + "values": protected}) + # Candidate workspaces may also contain root-level public inputs and + # installed Skill packages. Deliverables use dedicated top-level output + # directories, so enforce an exact file set inside those namespaces while + # leaving the read-only environment outside them untouched. + output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path}) + if len(output_roots) == len({path.split("/", 1)[0] for path in paths}): + checks.insert(0, { + "id": "workspace_file_set", "type": "workspace_file_set", + "paths": sorted(paths), "roots": output_roots, + }) + return { + "type": WORKSPACE_EVALUATOR, + "version": WORKSPACE_EVALUATOR_VERSION, + "output_mode": "workspace", + "reference_files": reference_files, + "checks": checks, + } + + +def reference_bundle(evaluator): + if evaluator.get("type") != WORKSPACE_EVALUATOR: + raise ObjectiveEvaluatorError("not a workspace evaluator") + return {"files": [ + {"path": item["path"], "content": item["content"]} + for item in evaluator.get("reference_files") or [] + ]} + + +def hidden_workspace_values(evaluator): + """Return decisive package-owned values that public queries must not leak.""" + values = [] + for check in (evaluator or {}).get("checks") or []: + kind = check.get("type") + if kind in {"json_exact", "toml_exact"}: + values.extend(value for _, value in _flatten(check.get("expected"))) + elif kind in {"python_import", "python_call", "shell_command", + "python_constant", "python_call_literal", + "python_call_keyword_literal"}: + values.append(check.get("value")) + elif kind == "python_call_signature": + values.extend(value for _, value in _flatten({ + "arguments": [item.get("value") for item in + check.get("arguments") or []], + "keywords": check.get("keywords") or {}, + "argument_expressions": [item.get("expression") for item in + check.get("argument_expressions") or []], + "keyword_expressions": check.get("keyword_expressions") or {}, + "assignment": check.get("assignment"), + })) + return [value for value in values if value is not None] + + +def _flatten(value, path=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_flatten(item, path + (str(key),))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_flatten(item, path + (index,))) + return out + return [(path, value)] + + +def _bundle_rows(candidate): + if isinstance(candidate, str): + text = candidate.strip() + # Chat solvers often wrap the requested file bundle in a Markdown fence + # or append a duplicate FINAL_ANSWER object. Decode one complete JSON + # value at a time instead of requiring the entire response to be JSON; + # only an object carrying the explicit ``files`` transport field is + # eligible, so unrelated prose/objects are not silently accepted. + decoder = json.JSONDecoder() + candidate = None + for match in re.finditer(r"\{", text): + try: + parsed, _ = decoder.raw_decode(text, match.start()) + except json.JSONDecodeError: + continue + if isinstance(parsed, dict) and "files" in parsed: + candidate = parsed + break + if candidate is None: + raise ObjectiveEvaluatorError( + "workspace response contains no complete JSON file bundle") + if not isinstance(candidate, dict): + raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object") + files = candidate.get("files") + if isinstance(files, dict): + files = [{"path": path, "content": content} + for path, content in files.items()] + if not isinstance(files, list) or len(files) > 30: + raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list") + return files + + +def materialize_bundle(candidate, workspace): + root = Path(workspace).resolve() + root.mkdir(parents=True, exist_ok=True) + seen = set() + for item in _bundle_rows(candidate): + if not isinstance(item, dict): + raise ObjectiveEvaluatorError("candidate file entry is not an object") + relative = safe_relative_path(item.get("path")) + if relative in seen: + raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}") + seen.add(relative) + content = item.get("content") + if isinstance(content, (dict, list)): + content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000: + raise ObjectiveEvaluatorError("candidate file content is invalid or too large") + target = (root / relative).resolve() + if root not in target.parents: + raise ObjectiveEvaluatorError("candidate file escapes workspace") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return root + + +def evaluate_workspace(evaluator, workspace): + if (not isinstance(evaluator, dict) or + evaluator.get("type") != WORKSPACE_EVALUATOR or + int(evaluator.get("version") or 0) not in + SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS): + return False, {"error": "invalid workspace evaluator contract"} + root = Path(workspace).resolve() + results = [] + for check in evaluator.get("checks") or []: + kind = check.get("type") + relative, path = "", None + if kind != "workspace_file_set": + relative = safe_relative_path(check.get("path")) + path = (root / relative).resolve() + if root not in path.parents: + return False, {"error": "evaluator path escapes workspace"} + passed, detail = False, "" + try: + if kind == "workspace_file_set": + expected = {safe_relative_path(value) + for value in check.get("paths") or []} + roots = [safe_relative_path(value) + for value in check.get("roots") or []] + actual = set() + for relative_root in roots: + scan_root = (root / relative_root).resolve() + if root not in scan_root.parents: + raise ObjectiveEvaluatorError( + "workspace file-set root escapes workspace") + if not scan_root.exists(): + continue + for candidate in scan_root.rglob("*"): + if candidate.is_file() or candidate.is_symlink(): + actual.add(candidate.relative_to(root).as_posix()) + passed = bool(expected) and actual == expected + detail = ("exact deliverable file set" if passed else + f"expected_files={sorted(expected)}; " + f"actual_files={sorted(actual)}") + elif kind == "file_exists": + passed = path.is_file() + detail = "present" if passed else "missing" + elif kind == "json_exact": + from r9_json import parse_file, strict_equal + actual = parse_file(path) + passed = strict_equal(actual, check.get("expected")) + detail = "semantic JSON match" if passed else "JSON value mismatch" + elif kind == "toml_exact": + actual = tomllib.loads(path.read_text(encoding="utf-8")) + passed = _canonical(actual) == _canonical(check.get("expected")) + detail = "semantic TOML match" if passed else "TOML value mismatch" + elif kind in {"python_syntax", "python_bound_calls", + "python_import", "python_call", + "python_constant", "python_call_literal", + "python_call_keyword_literal", + "python_call_signature"}: + source = path.read_text(encoding="utf-8") + imports, calls, constants, call_nodes = _python_semantics(source) + resolved_calls = _python_resolved_call_nodes(source) + if kind == "python_syntax": + passed, detail = True, "valid Python syntax" + elif kind == "python_bound_calls": + unbound = python_unbound_call_roots( + path.read_text(encoding="utf-8")) + passed = not unbound + detail = ("all call roots are statically bound" if passed else + "unbound call roots=" + repr(unbound)) + elif kind == "python_import": + expected = str(check.get("value") or "") + passed = expected in imports or any( + value == expected or value.startswith(expected + ".") + for value in imports) + detail = f"imports={sorted(imports)}" + elif kind == "python_call": + expected = str(check.get("value") or "") + target = str(check.get("target") or "") + passed = (any( + canonical == target + for _, canonical, _ in resolved_calls) + if target else expected in calls or any( + value.endswith("." + expected) + for value in calls)) + detail = f"calls={sorted(calls)}" + elif kind == "python_constant": + name, expected = str(check.get("name") or ""), check.get("value") + actual = constants.get(name, _UNRESOLVED) + passed = actual is not _UNRESOLVED and actual == expected + detail = f"constant {name}={actual!r}" + elif kind == "python_call_literal": + function, expected = (str(check.get("function") or ""), + check.get("value")) + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _node_contains_literal(node, expected, constants) + for name, canonical, node in source_calls) + detail = f"call={function} literal={expected!r}" + elif kind == "python_call_keyword_literal": + function = str(check.get("function") or "") + keyword = str(check.get("keyword") or "") + expected = check.get("value") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_keyword_matches(node, keyword, expected, constants) + for name, canonical, node in source_calls) + detail = (f"call={function} keyword={keyword} " + f"literal={expected!r}") + else: + function = str(check.get("function") or "") + arguments = check.get("arguments") or [] + keywords = check.get("keywords") or {} + argument_expressions = check.get( + "argument_expressions") or [] + keyword_expressions = check.get( + "keyword_expressions") or {} + assignment = check.get("assignment") + target = str(check.get("target") or "") + source_calls = (resolved_calls if target else + [(name, "", node) for name, node in call_nodes]) + passed = any( + (bool(target) or _call_name_matches(name, function)) and + (not target or canonical == target) and + _call_signature_matches( + node, arguments, keywords, constants, + argument_expressions, keyword_expressions, + assignment) + for name, canonical, node in source_calls) + detail = (f"call={function} arguments={arguments!r} " + f"keywords={keywords!r} " + f"argument_expressions={argument_expressions!r} " + f"keyword_expressions={keyword_expressions!r} " + f"assignment={assignment!r}") + elif kind == "shell_syntax": + completed = subprocess.run( + ["bash", "-n", str(path)], capture_output=True, text=True, + timeout=5, check=False) + passed = completed.returncode == 0 + detail = ("valid shell syntax" if passed else + (completed.stderr or "invalid shell syntax").strip()) + elif kind == "shell_command": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = " ".join(str(check.get("value") or "").split()) + passed = any(_shell_command_matches(expected, line) for line in lines) + detail = f"executable_lines={lines[:30]}" + elif kind == "shell_command_sequence": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (len(expected) >= 2 and + _shell_command_sequence_matches(expected, lines)) + detail = f"expected_sequence={expected}; executable_lines={lines[:30]}" + elif kind == "shell_unconditional_commands": + source = path.read_text(encoding="utf-8") + lines = ([call["command"] for call in shell_invocations(source)] + if int(evaluator.get("version", 0)) >= 15 + else _shell_unconditional_lines(source)) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = (bool(expected) and all( + any(_shell_command_matches(command, line) for line in lines) + for command in expected)) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_failure_propagation": + calls = shell_invocations(path.read_text(encoding="utf-8")) + expected = [" ".join(str(value).split()) + for value in check.get("values") or []] + passed = bool(expected) and all(any( + call["fail_fast"] and _shell_command_matches(command, call["command"]) + for call in calls) for command in expected) + detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}" + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + detail = ("all executable lines are top-level" if passed else + "shell contains conditional, loop, case, or function") + else: + detail = f"unsupported check: {kind}" + except (OSError, ValueError, SyntaxError, subprocess.SubprocessError, + json.JSONDecodeError, + tomllib.TOMLDecodeError) as exc: + detail = str(exc) + results.append({"id": check.get("id"), "type": kind, + "path": relative, "passed": bool(passed), + "detail": detail[:1000]}) + return bool(results) and all(item["passed"] for item in results), { + "type": WORKSPACE_EVALUATOR, + "assertions_passed": sum(item["passed"] for item in results), + "assertions_total": len(results), + "assertions": results, + } + + +def evaluate_candidate(evaluator, candidate): + if isinstance(candidate, os.PathLike): + try: + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + except (OSError, ValueError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + if isinstance(candidate, str): + # A chat file-bundle can be much longer than a filesystem path. Avoid + # passing arbitrary model output to stat(), which can raise ENAMETOOLONG. + stripped = candidate.strip() + if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped + and not stripped.startswith(("{", "[", "```"))): + try: + if Path(stripped).is_dir(): + return evaluate_workspace(evaluator, stripped) + except (OSError, ValueError): + # Python/platform versions differ on ENAMETOOLONG and invalid + # path errors. It is still candidate text: parse it unchanged. + pass + try: + with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp: + materialize_bundle(candidate, temp) + return evaluate_workspace(evaluator, temp) + except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc: + return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)} + + +def self_test_workspace_evaluator(evaluator): + correct = reference_bundle(evaluator) + ok_correct, correct_detail = evaluate_candidate(evaluator, correct) + rows = list(correct.get("files") or []) + perturbed = {"files": rows[1:] if len(rows) > 1 else []} + ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed) + mutations = [] + # Exact JSON fields must each matter, not merely the file's existence. + for check in evaluator.get("checks") or []: + if check.get("type") != "json_exact": + continue + for path, value in _flatten(check.get("expected")): + candidate = copy.deepcopy(correct) + file_row = next(row for row in candidate["files"] + if row["path"] == check["path"]) + data = json.loads(file_row["content"]) + replacement = (not value if isinstance(value, bool) else + value + 1 if isinstance(value, (int, float)) else + str(value) + "__mutation__") + if not path: + data = replacement + else: + container = data + for key in path[:-1]: + container = container[key] + container[path[-1]] = replacement + file_row["content"] = json.dumps(data) + passed, _ = evaluate_candidate(evaluator, candidate) + mutations.append({"path": check["path"], "field": list(path), + "rejected": not passed}) + return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), { + "correct": correct_detail, + "perturbed": wrong_detail, + "scalar_mutations": mutations, + } diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..b84dc8f2b2af4bebe2eb4c48e55c3aeaef091cad --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,229 @@ +"""A deliberately bounded, non-executing shell structure recognizer. + +Supports simple commands, literal scalar assignments, one command substitution +on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards. +It does not interpret shell code or credit commands in branch bodies/functions. +Pipelines, command lists, substitutions within substitutions, and swallowed +failures are outside this grammar. bash -n remains a separate required check. +""" +import re +import shlex + + +def _statements(text): + out, current = [], [] + quote, escaped, comment, depth = None, False, False, 0 + for ch in str(text): + if comment: + if ch == '\n': + comment = False + else: + continue + if escaped: + if ch != '\n': + current.extend(('\\', ch)) + escaped = False + continue + if ch == '\\' and quote != "'": + escaped = True + continue + if quote: + current.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + current.append(ch) + elif ch == '#' and (not current or current[-1].isspace()): + comment = True + elif ch == '(': + depth += 1 + current.append(ch) + elif ch == ')': + depth -= 1 + if depth < 0: + return [] + current.append(ch) + elif ch in '\n;' and depth == 0: + value = ''.join(current).strip() + if value: + out.append(value) + current = [] + else: + current.append(ch) + if quote or escaped or depth: + return [] + if ''.join(current).strip(): + out.append(''.join(current).strip()) + expanded = [] + for statement in out: + inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S) + expanded.extend(['then', inline_then.group(1)] if inline_then else [statement]) + return expanded + + +def _simple_argv(text): + if '$(' in text or '`' in text: + return None + try: + lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()') + lexer.whitespace_split = True + tokens = list(lexer) + except ValueError: + return None + argv, index = [], 0 + redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'} + while index < len(tokens): + token = tokens[index] + if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects: + index += 1 + token = tokens[index] + if token in redirects: + if index + 1 >= len(tokens): + return None + target = tokens[index + 1] + if (not target or any(c in target for c in '$`;&|<>()') + or target in ('{', '}')): + return None + index += 2 + continue + if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'): + return None + argv.append(token) + index += 1 + return argv or None + + +def _invocation(text): + substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text) + if substitution: + inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3) + argv = _simple_argv(inner) + return (argv, 'assignment_substitution') if argv else (None, None) + return _simple_argv(text), 'simple' + + +def _guard_end(statements, start): + depth = 1 + for index in range(start + 1, len(statements)): + item = statements[index] + if re.match(r'^if\s', item): + depth += 1 + elif item == 'fi': + depth -= 1 + if depth == 0: + return index + return None + + +def _nonzero_exit_body(statements): + """Only literal logging followed by a final unconditional nonzero exit.""" + if not statements: + return False + for index, statement in enumerate(statements): + argv = _simple_argv(statement) + if not argv: + return False + if argv[0] == 'exit': + return (index == len(statements) - 1 and len(argv) == 2 + and argv[1].isdigit() and 1 <= int(argv[1]) <= 255) + if argv[0] not in ('echo', 'printf'): + return False + return False + + +def shell_invocations(text): + """Return ordered, actually evaluated invocation nodes in the supported subset. + + fail_fast is a structural proof: a simple command/assignment runs under + errexit, or a negated test exits nonzero on failure. This is not a complete + shell interpreter, and unsupported syntax earns no invocation credit. + """ + statements = _statements(text) + # Function definitions or dynamic shell mutation can shadow the command or + # `exit` itself. They are outside this objective subset, even if uncalled. + if any(re.match(r'^(?:function\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?|[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\))\s*\{', s) + or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s) + for s in statements): + return [] + constants, result, index, errexit = {}, [], 0, False + assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$") + variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while index < len(statements): + statement = statements[index] + literal = assignment.fullmatch(statement) + if literal: + constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None) + index += 1 + continue + statement = variable.sub(lambda m: constants.get(m.group(1) or m.group(2), m.group(0)), statement) + setting = _simple_argv(statement) + if setting and setting[0] == 'set': + flag_index = 1 + while flag_index < len(setting): + flag = setting[flag_index] + if flag == '--' or not flag.startswith(('-', '+')): + break # Remaining words set positional parameters. + if not re.fullmatch(r'[-+][eufxEo]+', flag): + return [] # e.g. `set -n` suppresses execution entirely. + if 'e' in flag[1:]: + errexit = flag[0] == '-' + if 'o' in flag[1:]: + if flag_index + 1 >= len(setting): + return [] + option = setting[flag_index + 1] + if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'): + return [] + if option == 'errexit': + errexit = flag[0] == '-' + flag_index += 1 + flag_index += 1 + index += 1 + continue + if re.match(r'^if\s', statement): + end = _guard_end(statements, index) + if end is None: + return [] + negated = re.fullmatch(r'if\s+!\s+(.+)', statement) + if (negated and index + 1 < end + and statements[index + 1] == 'then' + and _nonzero_exit_body(statements[index + 2:end])): + argv, kind = _invocation(negated.group(1).strip()) + if argv: + if argv[0] == 'false': + break + result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind, + 'fail_fast': True, 'statement_index': index}) + else: + return [] + else: + # Arbitrary conditions may terminate the script or shadow its + # commands. Do not infer a reachable suffix through them. + return [] + # Bodies are never credited and may have assigned local variables. + constants.clear() + index = end + 1 + continue + if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{': + # Unsupported compounds are not searched for command substrings. + return [] + argv, kind = _invocation(statement) + if not argv: + # An unparsed statement may change control flow or shell state. + # Skipping it would incorrectly credit an unreachable suffix. + return [] + if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare', + 'typeset', 'local', 'read', 'mapfile', 'readarray', + 'unset', 'readonly', '[', '[[', 'test'): + return [] + if argv[0] == 'exit' or (argv[0] == 'false' and errexit): + break + if kind == 'assignment_substitution': + assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement) + if assigned: + constants.pop(assigned.group(1), None) + result.append({'command': shlex.join(argv), 'kind': kind, + 'fail_fast': errexit, 'statement_index': index}) + index += 1 + return result diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}} +if [[ -z "$candidate" ]]; then + echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2 + exit 64 +fi +python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate" diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..c6290e83629e9f84ece58ae2c4cfd0f5b3f932e2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,525 @@ +"""Verifier execution engine and fail-closed self-tests. + +New verified tasks use atomic_json (complete shape plus scalar assertions). +Legacy verifier types remain readable so historical runs can still be audited. +自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。 +""" +import json +import logging +import os +import re + +try: + from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) +except ImportError: # portable task copies these modules beside each other + from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate, + reference_bundle, + self_test_workspace_evaluator) + +log = logging.getLogger("pipeline") + + +def _norm(s): + return str(s).strip().lower() + + +def _json_value(value): + """Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return value + text = str(value).strip() + match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S) + if match: + text = match.group(1).strip() + text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) + text = re.sub(r"\s*```$", "", text) + start_obj, start_arr = text.find("{"), text.find("[") + starts = [x for x in (start_obj, start_arr) if x >= 0] + if starts: + start = min(starts) + closing = "}" if text[start] == "{" else "]" + end = text.rfind(closing) + if end >= start: + text = text[start:end + 1] + try:return json.loads(text) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + + +from r9_json import parse_single as _r9_parse_single +_json_value = _r9_parse_single + + +def _canonical_json(value): + if isinstance(value, dict): + return {key: _canonical_json(value[key]) for key in sorted(value)} + if isinstance(value, list): + values = [_canonical_json(item) for item in value] + return sorted(values, key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return value + + +def _atomic_prepare(value, list_order): + if isinstance(value, dict): + return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)} + if isinstance(value, list): + values = [_atomic_prepare(item, list_order) for item in value] + if list_order == "unordered": + values.sort(key=lambda item: json.dumps( + item, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return values + return value + + +def _atomic_shape(value): + if isinstance(value, dict): + return {"type": "object", "keys": { + key: _atomic_shape(item) for key, item in value.items()}} + if isinstance(value, list): + return {"type": "array", "length": len(value), + "items": [_atomic_shape(item) for item in value]} + if isinstance(value, bool): + return {"type": "boolean"} + if value is None: + return {"type": "null"} + if isinstance(value, (int, float)): + return {"type": "number"} + return {"type": "string"} + + +def _atomic_leaves(value, path="$", tokens=()): + if isinstance(value, dict): + out = [] + for key, item in value.items(): + out.extend(_atomic_leaves( + item, path + "." + key, tokens + (key,))) + return out + if isinstance(value, list): + out = [] + for index, item in enumerate(value): + out.extend(_atomic_leaves( + item, f"{path}[{index}]", tokens + (index,))) + return out + return [(path, tokens, value)] + + +def _normalize_path_equivalence_tokens(values): + """Freeze a stable set of scalar JSON paths allowed to ignore a final slash.""" + normalized = [] + for tokens in values or []: + if (not isinstance(tokens, (list, tuple)) or not tokens or + any(not isinstance(token, (str, int)) for token in tokens)): + raise ValueError("path equivalence tokens must be non-empty JSON paths") + item = list(tokens) + if item not in normalized: + normalized.append(item) + return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False)) + + +def _path_value(value): + """Normalize only portable path spelling, not general answer text.""" + if not isinstance(value, str): + return None + text = value.strip().replace("\\", "/") + if text != "/": + text = text.rstrip("/") + return text + + +def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01, + path_equivalence_tokens=None): + """Freeze a complete JSON shape plus one assertion for every scalar leaf.""" + if list_order not in {"ordered", "unordered"}: + raise ValueError(f"unsupported atomic list_order: {list_order}") + tolerance = float(float_tolerance) + prepared = _atomic_prepare(_json_value(expected), list_order) + path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens) + assertions = [] + for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1): + assertion = {"id": f"leaf_{index:03d}", "path": path, + "tokens": list(tokens), "operator": "eq", "expected": value} + if isinstance(value, float): + assertion.update({"operator": "abs_diff", "tolerance": tolerance}) + elif list(tokens) in path_tokens: + if not isinstance(value, str): + raise ValueError("path equivalence can only target string leaves") + assertion["operator"] = "path_eq" + assertions.append(assertion) + compiled = { + "type": "atomic_json", "version": 2 if path_tokens else 1, + "list_order": list_order, + "float_tolerance": tolerance, + "completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)}, + "assertions": assertions, + } + if path_tokens: + compiled["path_equivalence_tokens"] = path_tokens + return compiled + + +def _shape_differences(expected, actual, path="$"): + if not isinstance(actual, dict) or actual.get("type") != expected.get("type"): + return [f"{path}: expected {expected.get('type')}, got " + f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"] + kind = expected.get("type") + if kind == "object": + expected_keys = set((expected.get("keys") or {})) + actual_keys = set((actual.get("keys") or {})) + differences = [f"{path}: missing key {key}" for key in sorted( + expected_keys - actual_keys)] + differences.extend(f"{path}: extra key {key}" for key in sorted( + actual_keys - expected_keys)) + for key in sorted(expected_keys & actual_keys): + differences.extend(_shape_differences( + expected["keys"][key], actual["keys"][key], path + "." + key)) + return differences + if kind == "array": + differences = [] + if actual.get("length") != expected.get("length"): + differences.append( + f"{path}: expected length {expected.get('length')}, got {actual.get('length')}") + for index, (expected_item, actual_item) in enumerate(zip( + expected.get("items") or [], actual.get("items") or [])): + differences.extend(_shape_differences( + expected_item, actual_item, f"{path}[{index}]")) + return differences + return [] + + +def _atomic_get(value, tokens): + current = value + for token in tokens: + current = current[token] + return current + + +def _int_values(value): + if isinstance(value, (list, tuple)): + out = [] + for item in value: + out.extend(_int_values(item)) + return out + if isinstance(value, int) and not isinstance(value, bool): + return [value] + return [int(number) for number in re.findall(r"\d+", str(value or ""))] + + +def _finding_type(value): + text = str(value or "").lower().replace("-", "_") + if "duplicate" in text: + return "duplicate_rows" + if ("none" in text or "null" in text) and "check" in text: + return "none_check" + if "missing" in text or "empty" in text or "null" in text: + return "missing" + if "outlier" in text or "large" in text or ">=" in text or "greater" in text: + return "outlier" + if "invalid" in text and "config" in text: + return "invalid_config" + if "off" in text and "one" in text: + return "off_by_one" + return text.strip().replace(" ", "_") + + +def _normalized_findings(value, family): + obj = _json_value(value) + findings = obj.get("findings") if isinstance(obj, dict) else None + if not isinstance(findings, list): + raise ValueError("answer must contain a findings array") + normalized = set() + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("each finding must be an object") + # The public contract uses type/function. Accept common semantically + # equivalent aliases as a robustness layer, while still comparing the + # normalized values and exact locations against generator-owned GT. + kind = _finding_type(finding.get("type", finding.get( + "defect_type", finding.get("defect")))) + if family == "csv": + if kind == "duplicate_rows": + rows = _int_values(finding.get("rows", finding.get("row"))) + if len(rows) != 2: + raise ValueError("duplicate finding requires exactly two row numbers") + normalized.add((kind, *sorted(rows))) + elif kind in {"missing", "outlier"}: + rows = _int_values(finding.get("row")) + column = str(finding.get("column") or "").strip().lower() + if len(rows) != 1 or not column: + raise ValueError(f"{kind} requires one row and column") + normalized.add((kind, rows[0], column)) + else: + raise ValueError(f"unsupported CSV finding type: {kind}") + elif family == "config": + if kind != "invalid_config": + raise ValueError(f"unsupported config finding type: {kind}") + normalized.add((kind, str(finding.get("path") or "").lower(), + json.dumps(finding.get("value"), sort_keys=True), + str(finding.get("expected") or "").lower())) + elif family == "code": + if kind not in {"off_by_one", "none_check"}: + raise ValueError(f"unsupported code finding type: {kind}") + function = finding.get("function", finding.get("function_name")) + function = str(function or "").strip().lower() + if not function: + raise ValueError(f"{kind} requires a function") + normalized.add((kind, function)) + else: + raise ValueError(f"unsupported findings family: {family}") + return normalized + + +def _normalized_facts(value): + obj = _json_value(value) + facts = obj.get("facts") if isinstance(obj, dict) else None + if not isinstance(facts, list): + raise ValueError("answer must contain a facts array") + def textual(item): + # The document generator serializes scalar values as visible text. JSON + # has no way to infer whether the source token "30" was authored from an + # integer or a string, so facts_match compares that surface text. Nested + # values retain structural JSON comparison. + if isinstance(item, (dict, list)): + return json.dumps(item, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + if item is None: + return "None" + return str(item) + return {(str(fact.get("key") or ""), textual(fact.get("value"))) + for fact in facts if isinstance(fact, dict)} + + +def verify(verifier, gt_answer, solver_output, material_paths=None): + """执行 verifier。返回 (passed, detail)。""" + vtype = verifier.get("type") + try: + if vtype == WORKSPACE_EVALUATOR: + return evaluate_candidate(verifier, solver_output) + + if vtype == "json_exact": + pred = _canonical_json(_json_value(solver_output)) + gold = _canonical_json(_json_value(gt_answer)) + ok = pred == gold + return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}" + + if vtype == "atomic_json": + try: + pred = _atomic_prepare(_json_value(solver_output), + verifier.get("list_order", "ordered")) + pred_shape = _atomic_shape(pred) + except RecursionError: + return False, "candidate JSON nesting is too deep" + compiled = compile_atomic_verifier( + gt_answer, verifier.get("list_order", "ordered"), + verifier.get("float_tolerance", 0.01), + verifier.get("path_equivalence_tokens")) + frozen = {key: verifier.get(key) for key in + ("type", "version", "list_order", "float_tolerance", + "completeness", "assertions", "path_equivalence_tokens")} + expected_frozen = {key: compiled.get(key) for key in frozen} + if frozen != expected_frozen: + return False, {"error": "atomic verifier does not match ground truth"} + shape_failures = _shape_differences( + verifier["completeness"]["shape"], pred_shape) + assertion_results = [] + for assertion in verifier.get("assertions") or []: + try: + actual = _atomic_get(pred, assertion["tokens"]) + if assertion["operator"] == "abs_diff": + passed = abs(float(actual) - float(assertion["expected"])) <= float( + assertion.get("tolerance", 0.0)) + elif assertion["operator"] == "path_eq": + passed = (_path_value(actual) is not None and + _path_value(actual) == _path_value(assertion["expected"])) + else: + passed = (actual is assertion["expected"] if + isinstance(assertion["expected"], bool) else + actual == assertion["expected"]) + message = "" if passed else ( + f"actual={actual!r} expected={assertion['expected']!r}") + except (KeyError, IndexError, TypeError, ValueError) as exc: + actual, passed, message = None, False, f"lookup/compare failed: {exc}" + assertion_results.append({ + "id": assertion["id"], "path": assertion["path"], + "operator": assertion["operator"], "expected": assertion["expected"], + "actual": actual, "passed": passed, "message": message}) + passed_count = sum(item["passed"] for item in assertion_results) + ok = not shape_failures and passed_count == len(assertion_results) + return ok, { + "type": "atomic_json", "completeness_passed": not shape_failures, + "completeness_failures": shape_failures, + "assertions_passed": passed_count, + "assertions_total": len(assertion_results), + "assertion_pass_rate": (passed_count / len(assertion_results) + if assertion_results else 1.0), + "assertions": assertion_results, + } + + if vtype == "findings_match": + family = verifier.get("family") + pred = _normalized_findings(solver_output, family) + gold = _normalized_findings(gt_answer, family) + ok = pred == gold + return ok, ("findings_match: pass" if ok else + f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "facts_match": + pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer) + ok = pred == gold + return ok, ("facts_match: pass" if ok else + f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}") + + if vtype == "exact_match": + ok = _norm(solver_output) == _norm(gt_answer) + return ok, f"exact_match: {'pass' if ok else 'mismatch'}" + + if vtype == "numeric": + tol = verifier.get("tolerance") or 1e-6 + pred = float(str(solver_output).strip().split()[0]) + gold = float(gt_answer) + ok = abs(pred - gold) <= tol + return ok, f"numeric: pred={pred} gold={gold} tol={tol}" + + if vtype == "set_match": + pred = set(_as_list(solver_output)) + gold = set(_as_list(gt_answer)) + ok = pred == gold + return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}" + + if vtype == "structured_match": + pred = _json_value(solver_output) + gold = _json_value(gt_answer) + if not isinstance(pred, dict) or not isinstance(gold, dict): + return False, "structured_match requires JSON objects" + missing = [f for f in verifier.get("required_fields", []) if f not in pred] + wrong = [f for f in verifier.get("required_fields", []) + if f in pred and f in gold and pred[f] != gold[f]] + ok = not missing and not wrong + return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}" + + if vtype == "execution": + return False, "execution verifier is disabled in verified-first v2" + + if vtype == "constraint": + fails = _check_constraints(verifier.get("criteria", []), solver_output) + return not fails, f"constraint: failed={fails[:5]}" + + if vtype == "file_inspection": + fails = _inspect_files(verifier.get("expected_files", []), material_paths or []) + return not fails, f"file_inspection: failed={fails[:5]}" + + return False, f"unknown verifier type: {vtype}" + except Exception as e: + return False, f"verifier error: {e}" + + +def _as_list(x): + if isinstance(x, list): + return [_norm(i) for i in x] + # 逗号/换行分隔的字符串 + return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()] + + +def _check_constraints(criteria, solver_output): + """criteria: ["must contain X", "must be valid json", "length <= 500"]""" + fails = [] + text = str(solver_output) + for c in criteria: + cl = c.lower() + if cl.startswith("must contain "): + needle = c[len("must contain "):] + if needle.lower() not in text.lower(): + fails.append(c) + elif "valid json" in cl: + try: + json.loads(text) + except Exception: + fails.append(c) + elif cl.startswith("length <="): + limit = int(cl.split("<=")[1].strip()) + if len(text) > limit: + fails.append(c) + else: + # Deterministic verifier DSL is closed-world: unknown checks fail. + fails.append(f"unsupported criterion: {c}") + return fails + + +def _inspect_files(expected, material_paths): + fails = [] + paths = set(material_paths or []) + for e in expected: + fname = e.get("filename") if isinstance(e, dict) else str(e) + if not any(os.path.basename(p) == os.path.basename(fname) for p in paths): + fails.append(f"missing file: {fname}") + return fails + + +# ---------------- 自测 ---------------- + +def build_correct_solution(verifier, gt_answer, planted_info): + """由埋点/ground truth 直接构造正确解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + return reference_bundle(verifier) + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric", + "set_match", "structured_match"): + return gt_answer + if vtype == "constraint": + parts = [c[len("must contain "):] for c in verifier.get("criteria", []) + if c.lower().startswith("must contain ")] + return " ".join(parts) if parts else str(gt_answer) + # execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造 + return None + + +def build_perturbed_solution(verifier, gt_answer, planted_info): + """破坏埋点构造扰动解。""" + vtype = verifier.get("type") + if vtype == WORKSPACE_EVALUATOR: + files = list(reference_bundle(verifier).get("files") or []) + return {"files": files[1:] if len(files) > 1 else []} + if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"): + gold = _json_value(gt_answer) + if isinstance(gold, dict): + perturbed = dict(gold) + key = next(iter(perturbed), "__missing__") + if key in perturbed: + perturbed.pop(key) + else: + perturbed["__wrong__"] = True + return perturbed + if isinstance(gold, list): + return gold[:-1] if gold else ["__wrong__"] + return "__wrong__" + if vtype in ("exact_match", "numeric"): + return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER" + if vtype == "set_match": + gold = _as_list(gt_answer) + return gold[: max(0, len(gold) - 1)] + ["perturbed_item"] + if vtype == "structured_match": + fields = verifier.get("required_fields", []) + return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段 + if vtype == "constraint": + return "perturbed output lacking required content" + return None + + +def self_test(verifier, gt_answer, planted_info, material_paths): + """返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。 + + 之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier + 可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。 + """ + if verifier.get("type") == WORKSPACE_EVALUATOR: + return self_test_workspace_evaluator(verifier) + correct = build_correct_solution(verifier, gt_answer, planted_info) + perturbed = build_perturbed_solution(verifier, gt_answer, planted_info) + if correct is None or perturbed is None: + return False, (f"cannot self-test verifier type {verifier.get('type')} " + "(execution/file_inspection need real correct/perturbed solutions)") + ok1, d1 = verify(verifier, gt_answer, correct, material_paths) + ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths) + passed = ok1 and not ok2 + return passed, {"correct": d1, "perturbed": d2} diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/r9_json.py b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/r9_json.py new file mode 100644 index 0000000000000000000000000000000000000000..9038b5dcda483f3b1fb11794bb030669af07eccb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/evaluator/r9_json.py @@ -0,0 +1,74 @@ +"""JSON wire parsing and native-type equality for the R9 task copies. + +No expected answers are defined here. Single complete JSON fences are accepted +only as a transport wrapper when requested by the calling task. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json +import math +import re + + +def no_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError('duplicate JSON key') + result[key] = value + return result + + +def _finite_tree(value): + if isinstance(value, float) and not math.isfinite(value): + raise ValueError('non-finite JSON number') + if isinstance(value, dict): + for item in value.values(): + _finite_tree(item) + elif isinstance(value, list): + for item in value: + _finite_tree(item) + return value + + +def parse_single(value, allow_fence=True): + """Parse the entire response; no prefix/suffix or duplicate keys allowed.""" + if isinstance(value, (dict, list, int, float, bool)) or value is None: + return _finite_tree(value) + if isinstance(value, bytes): + value = value.decode('utf-8-sig') + text = str(value).lstrip('\ufeff').strip() + if allow_fence and text.startswith('```'): + match = re.fullmatch(r'```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```', text, re.I) + if match is None: + raise ValueError('not one complete JSON fence') + text = match.group(1) + return _finite_tree(json.loads( + text, object_pairs_hook=no_duplicates, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError('non-finite JSON number')))) + + +def parse_file(path): + """Files must contain raw JSON; Markdown fences are not JSON file bytes.""" + with open(path, 'r', encoding='utf-8-sig') as stream: + return parse_single(stream.read(), allow_fence=False) + + +def strict_equal(actual, expected, number_equivalence=False): + """Preserve keys, order and every native type; booleans never equal numbers. + + Set number_equivalence only if the public contract says a generic number + rather than an integer. It accepts finite integral numeric equivalents. + """ + if type(actual) is not type(expected): + if number_equivalence and type(actual) in (int, float) and type(expected) in (int, float): + return math.isfinite(actual) and math.isfinite(expected) and actual == expected + return False + if isinstance(expected, dict): + return set(actual) == set(expected) and all( + strict_equal(actual[key], value, number_equivalence) for key, value in expected.items()) + if isinstance(expected, list): + return len(actual) == len(expected) and all( + strict_equal(left, right, number_equivalence) for left, right in zip(actual, expected)) + if isinstance(expected, float) and not (math.isfinite(actual) and math.isfinite(expected)): + return False + return actual == expected diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..02078e537f5808ce43fb7c2b1a26043a33126484 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/grading/verified_config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19b54eb6c511d60e990a0c9fc81d6ccb514ded9c1b2e1ec17ef2a6cdf4724ea0 +size 4081 diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5c887cd8e0fed1eafd43677a38380603f086e08 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/instruction.md @@ -0,0 +1 @@ +I'm extending our UX review checklist and hit a blocker: I need to confirm which bundled reference file each symptom category routes to, using the paths exactly as declared. Two questions: which reference file does the checklist route touch-target sizing issues to, and which one does it route response time and loading feedback issues to? Answer with exactly one JSON object matching {"answers":{"q1":"string","q2":"string"}}, replacing each placeholder with the bare project-defined path value. diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/README.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2d3e6039c820b03d68e9194dd7528fe55ebb0e6c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/README.md @@ -0,0 +1,26 @@ +# audit-ux-laws + +Building or auditing UI against the 30 Laws of UX — Fitts's, Hick's, Miller's, Jakob's, Gestalt, choice overload, or cognitive load. + +**Category:** Audit (read-only inspection) + +## Install + +**As a plugin (easy install / uninstall via `/plugin`):** + +``` +/plugin marketplace add yigitkonur/skills-by-yigitkonur +/plugin install audit-ux-laws@yigitkonur +``` + +**Or with the `skills` CLI — this skill only:** + +```bash +npx -y skills add -y -g yigitkonur/skills-by-yigitkonur/skills/audit-ux-laws +``` + +**Or the full pack:** + +```bash +npx -y skills add -y -g yigitkonur/skills-by-yigitkonur +``` diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..4fb5132a113ead8e77a83bdea1b865424820c4d4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/SKILL.md @@ -0,0 +1,120 @@ +--- +name: audit-ux-laws +description: "Use if building or auditing UI against the 30 Laws of UX (Fitts, Hick, Gestalt, cognitive load)." +--- + +# Audit UX Laws + +Self-contained reference for the **30 Laws of UX** (based on lawsofux.com by Jon Yablonski), tuned for an agent to find the relevant law, apply it to real code, and flag violations by severity. No live fetch — all law content is bundled in `references/`. + +This skill does two jobs: **proactive design** (pick the right law while building UI) and **review** (audit an interface and report violations as CRITICAL / MINOR with concrete fixes). It works on UI only — components, layouts, navigation, forms, interactions, perceived performance. It is not a visual/CSS-correctness pass and it does not redesign brand or content. + +The agent owns one decision: *which laws are relevant to the thing in front of me?* Everything downstream — the takeaway, the code pattern, the severity threshold — lives in the routed reference file. Read the router, open the **one** category file you need, apply it. + +## When to Use + +Trigger on phrases and contexts like: + +- *"is this good UX?"*, *"review this interface"*, *"what's wrong with this design?"* +- building or editing components, pages, layouts, navigation, menus, dropdowns, forms +- *"too many options"*, *"this feels overwhelming"*, decision points, pricing tiers +- touch-target sizing, click areas, spacing, visual grouping, hierarchy, what stands out +- loading states, response time, perceived performance, animation timing +- any named law: Fitts's, Hick's, Miller's, Jakob's, Doherty Threshold, Gestalt, Von Restorff, choice overload, chunking, cognitive load, Tesler's, Postel's, Pareto, Occam's, Zeigarnik, peak-end, goal-gradient, serial position + +### Do NOT use when + +- The work is backend / API / data-layer with no user-facing surface. +- The ask is pure visual polish (exact colors, shadows, brand) — that is a CSS/design-system pass. +- You need a full persona-driven usability audit with saved findings → use `audit-ux-and-save-files`. +- You need a visual UI bug audit across pages with screenshots → use `audit-ui-and-save-files`. + +## Step 1 — Route the symptom to a law + +Match what you see to a row; open only the reference file in the last column. + +| What you're checking | Laws | Reference file | +|---|---|---| +| **Too many options** (menus, dropdowns, nav, plans) | Hick's Law, Choice Overload | `references/heuristics.md` | +| **Touch targets** too small / far apart / hard to hit | Fitts's Law | `references/heuristics.md` | +| **Beautiful-but-is-it-usable** / first-impression trust | Aesthetic-Usability Effect | `references/heuristics.md` | +| **Too much info on screen** / dense forms / long lists | Miller's Law, Cognitive Load, Chunking, Working Memory | `references/cognitive.md` | +| **What stands out** / CTA emphasis / scanning order | Von Restorff, Serial Position, Selective Attention | `references/cognitive.md` | +| **Onboarding / first-time users skip instructions** | Paradox of the Active User, Cognitive Bias, Flow | `references/cognitive.md` | +| **Grouping / spacing / layout relationships** | Proximity, Similarity, Common Region, Uniform Connectedness, Prägnanz | `references/gestalt.md` | +| **Users confused by an unfamiliar pattern** | Jakob's Law, Mental Model | `references/gestalt.md` (Mental Model), `references/principles.md` (Jakob's) | +| **Response time / loading / perceived speed** | Doherty Threshold | `references/principles.md` | +| **Forms too long / complexity** | Tesler's Law, Parkinson's Law, Occam's Razor, Pareto | `references/principles.md` | +| **Input handling / error tolerance** | Postel's Law | `references/principles.md` | +| **Motivation / progress / completion / memorable ending** | Goal-Gradient, Zeigarnik, Peak-End Rule | `references/principles.md` | + +If more than one row matches, open each named file once and apply every relevant law. + +## Step 2 — Apply or review + +**Designing (proactive):** read the law's *Key Takeaways* + *Frontend Code Implications*, then build to them. + +**Reviewing (audit):** walk the law's *Review Criteria*, classify each violation, and report it with the fix. Severity scale: + +- **CRITICAL** — breaks usability, accessibility, or trust. Fix before ship. (e.g. touch target <44×44px mobile; >7 ungrouped options; primary CTA indistinguishable from secondary; no loading feedback >400ms; required cross-screen memorization.) +- **MINOR** — polish / optimization. (e.g. >6 colors, inconsistent spacing, missing smart default, no progress indicator, suboptimal CTA placement.) + +Always connect the finding to the *why* (the psychological principle) and give a **concrete, actionable fix** — code pattern or specific change, never "improve the UX." + +## Step 3 — Follow Related links when warranted + +Each law entry ends with **Related** pointers (e.g. Choice Overload → Hick's Law → Doherty Threshold). Follow them only when the current law's fix creates a new question the related law answers. + +## Quick Reference — all 30 laws + +| Law | Category | One-liner | Related | +|---|---|---|---| +| Aesthetic-Usability Effect | Heuristic | Beautiful design is perceived as more usable | Von Restorff, Jakob's | +| Choice Overload | Heuristic | Too many options cause decision paralysis | Hick's, Doherty | +| Fitts's Law | Heuristic | Larger, closer targets are faster to hit | Doherty, Choice Overload | +| Hick's Law | Heuristic | Decision time grows with number of choices | Choice Overload, Miller's | +| Chunking | Cognitive | Group info into meaningful units | Miller's, Cognitive Load | +| Cognitive Bias | Cognitive | Systematic thinking errors shape decisions | Selective Attention, Peak-End | +| Cognitive Load | Cognitive | Minimize mental effort to use the interface | Miller's, Tesler's | +| Miller's Law | Cognitive | Working memory holds ~7±2 items | Chunking, Working Memory | +| Working Memory | Cognitive | Don't force recall across steps/screens | Miller's, Chunking | +| Selective Attention | Cognitive | Users filter to goal-relevant stimuli | Von Restorff, Cognitive Bias | +| Serial Position Effect | Cognitive | First and last items remembered best | Von Restorff, Peak-End | +| Von Restorff Effect | Cognitive | The distinct item stands out — use for CTAs | Serial Position, Selective Attention | +| Flow | Cognitive | Balance challenge & skill; remove friction | Doherty, Goal-Gradient | +| Paradox of the Active User | Cognitive | Users skip manuals and learn by doing | Jakob's, Mental Model | +| Law of Proximity | Gestalt | Near elements are perceived as grouped | Common Region, Similarity | +| Law of Similarity | Gestalt | Similar-looking elements are seen as related | Proximity, Uniform Connectedness | +| Law of Common Region | Gestalt | A shared boundary groups elements | Proximity, Uniform Connectedness | +| Law of Uniform Connectedness | Gestalt | Visually connected elements are most related | Common Region, Similarity | +| Law of Prägnanz | Gestalt | Users read complex shapes in their simplest form | Occam's, Similarity | +| Mental Model | Gestalt | Users carry prebuilt expectations from other products | Jakob's, Paradox of Active User | +| Jakob's Law | Principle | Users expect your site to work like the others they know | Mental Model, Prägnanz | +| Doherty Threshold | Principle | Keep response <400ms to hold attention & flow | Flow, Fitts's | +| Goal-Gradient Effect | Principle | Motivation rises as the goal nears — show progress | Zeigarnik, Flow | +| Zeigarnik Effect | Principle | Incomplete tasks are remembered — use progress cues | Goal-Gradient, Peak-End | +| Peak-End Rule | Principle | Experiences are judged by their peak and ending | Serial Position, Zeigarnik | +| Postel's Law | Principle | Be liberal in what you accept, strict in what you output | Jakob's, Tesler's | +| Tesler's Law | Principle | Irreducible complexity must live in design, not the user | Cognitive Load, Occam's | +| Occam's Razor | Principle | Remove elements until you can't without breaking function | Tesler's, Prägnanz, Pareto | +| Pareto Principle | Principle | ~80% of effects come from ~20% of causes | Occam's, Tesler's | +| Parkinson's Law | Principle | Work expands to fill available time/space — constrain it | Doherty, Goal-Gradient | + +## Reference routing + +Load only the file for the category you routed to in Step 1. + +| File | Read when | +|---|---| +| `references/heuristics.md` | Decision time, target acquisition, choice volume, aesthetic trust. | +| `references/cognitive.md` | Memory limits, attention, scanning, learning, biases. | +| `references/gestalt.md` | Visual grouping, layout relationships, shape simplification, expectations. | +| `references/principles.md` | Trade-offs, simplicity, response time, input handling, motivation, conventions. | + +## Guardrails + +- Self-contained: never fetch lawsofux.com at runtime; bundled references are the source of truth. +- Don't load all four category files for every request — route, then apply only what's relevant. +- Every review finding needs a severity (CRITICAL/MINOR), a *why* (the law), and a concrete fix. +- Don't invent thresholds; use the numbers in the reference files. +- Severity numbers are usability heuristics, not a substitute for WCAG accessibility testing. diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/cognitive.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/cognitive.md new file mode 100644 index 0000000000000000000000000000000000000000..948d6ef12d04f992c4047d71e7035c36e0595a30 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/cognitive.md @@ -0,0 +1,211 @@ +# Cognitive + +Memory limits, attention, scanning, learning, biases. Each entry: principle → takeaways → frontend code → review criteria (CRITICAL/MINOR) → related. + +--- + +## Miller's Law + +**Principle:** The average person holds ~7 (±2) items in working memory. Organize content into small, meaningful chunks rather than long unstructured lists. + +**Key takeaways** +- Don't weaponize "7±2" to justify arbitrary limits — it's about chunking, not a hard cap. +- Capacity varies with prior knowledge and context. + +**Frontend code implications** +- Nav grouped into ~5–9 top-level categories; overflow into sub/mega-menus, not more top links. +- Group related fields with `
`/``; break long forms into multi-step wizards with a progress indicator. +- Paginate / "load more" for long result sets; add category headers when showing many rows. +- Tab bars and segmented controls: 3–5 items; overflow into a "More" menu. + +**Review criteria** +- CRITICAL: required cross-screen memorization (user must recall data from a prior step with no carry-over); >9 ungrouped top-level nav items. +- MINOR: long form with no grouping/steps; unformatted long data sequences. + +**Related:** Chunking, Working Memory + +--- + +## Chunking + +**Principle:** Break information into grouped, meaningful units so users can scan, process, and memorize more efficiently. + +**Key takeaways** +- Visually distinct groups with clear hierarchy match how people evaluate digital content. +- Chunking also communicates relationships (what belongs with what). + +**Frontend code implications** +- Format sequences: phone `(XXX) XXX-XXXX`, card `XXXX XXXX XXXX XXXX`, date `MM/DD/YYYY`; use `inputmode`/`pattern`. +- Group form fields in `
`; separate groups with `margin-bottom: 24–32px` or dividers. +- Break long lists into chunks of 3–5 with grid/flex `gap`; use `

/

` + whitespace for content hierarchy. +- Tables: alternating row backgrounds (`tr:nth-child(even)`), ``, separators between logical sections. + +**Review criteria** +- CRITICAL: long sequences (phone/card/account) shown as raw unbroken strings; unrelated fields visually merged with no separation. +- MINOR: wall-of-text content with no subheads/whitespace; lists >5–7 with no sub-grouping. + +**Related:** Miller's Law, Cognitive Load + +--- + +## Cognitive Load + +**Principle:** The total mental effort required to use an interface. Minimize *extraneous* load so users spend effort on their goal, not the UI. + +**Key takeaways** +- Remove, defer, or offload anything not essential to the current task. +- Reuse familiar patterns so users don't relearn (ties to Jakob's Law). + +**Frontend code implications** +- Eliminate redundant inputs; prefill known data; use smart defaults. +- Defer secondary settings behind progressive disclosure; show contextual help inline, not in a manual. +- Avoid jargon; one clear primary action per view. + +**Review criteria** +- CRITICAL: user forced to compute/convert/remember something the system could do for them; competing primary actions with no clear priority. +- MINOR: redundant fields; unexplained jargon; help buried away from the point of need. + +**Related:** Miller's Law, Tesler's Law + +--- + +## Working Memory + +**Principle:** Temporary cognitive storage for the active task is limited and fragile. Don't force users to hold information across steps or screens. + +**Key takeaways** +- Carry context forward; show, don't make them recall. +- Interruptions wipe working memory — preserve state. + +**Frontend code implications** +- Persist entered data across steps and on back-navigation; show a summary/review step before submit. +- Keep reference info visible while it's needed (e.g. order summary beside the form). +- Autosave drafts; restore on return. + +**Review criteria** +- CRITICAL: data lost on back/refresh; user must memorize a code/value from one screen to use on another. +- MINOR: needed reference info hidden behind a tab/modal during a task. + +**Related:** Miller's Law, Chunking + +--- + +## Selective Attention + +**Principle:** Users focus on a subset of stimuli — usually goal-relevant — and miss the rest (including, often, ads and unexpected changes). + +**Key takeaways** +- Clear hierarchy guides the eye; don't bury critical info in visual noise. +- "Banner blindness": important things that look like ads get ignored. + +**Frontend code implications** +- Give each screen one obvious focal point; use size/color/position to create attention flow. +- Don't style critical messages like promo banners; place them in the primary content path. +- De-emphasize or remove decorative noise around key actions. + +**Review criteria** +- CRITICAL: essential info (errors, required steps) hidden in low-contrast or ad-like placement. +- MINOR: no clear focal point; decorative elements competing with the primary action. + +**Related:** Von Restorff Effect, Cognitive Bias + +--- + +## Serial Position Effect + +**Principle:** Users best remember the first and last items in a series (primacy and recency). + +**Key takeaways** +- Place the most important/least-related actions at the start and end of lists and nav. +- Middle items are weakest — don't bury anything critical there. + +**Frontend code implications** +- Put key nav items first and last; least important in the middle. +- In action rows, anchor primary/destructive actions at the ends deliberately. + +**Review criteria** +- CRITICAL: the single most important action buried in the middle of a long list/menu. +- MINOR: suboptimal ordering with no primacy/recency consideration. + +**Related:** Von Restorff Effect, Peak-End Rule + +--- + +## Von Restorff Effect (Isolation Effect) + +**Principle:** When multiple similar objects are present, the one that differs is most likely to be noticed and remembered. + +**Key takeaways** +- Make the primary CTA visually distinct — but distinction must be scarce to work. +- Don't rely on color alone (accessibility); pair with weight/size/shape. + +**Frontend code implications** +- One dominant CTA per view; secondary actions visually quieter (ghost/outline). +- Highlight important info with contrast + a non-color cue (icon, weight). + +**Review criteria** +- CRITICAL: primary CTA indistinguishable from secondary actions; "everything emphasized" so nothing stands out. +- MINOR: 3+ elements competing to stand out; emphasis carried by color alone. + +**Related:** Serial Position Effect, Selective Attention + +--- + +## Flow + +**Principle:** The state of focused, immersive engagement that emerges when challenge and skill are balanced and friction is removed. + +**Key takeaways** +- Remove interruptions and latency that break immersion (ties to Doherty Threshold). +- Match difficulty to user skill; provide clear goals and immediate feedback. + +**Frontend code implications** +- Keep responses fast (<400ms perceived) and feedback immediate; avoid modal interruptions mid-task. +- Preserve context across actions; minimize context switches and reloads. + +**Review criteria** +- CRITICAL: frequent blocking interruptions (modals, full reloads) during a focused task. +- MINOR: small latency or feedback gaps that nibble at immersion. + +**Related:** Doherty Threshold, Goal-Gradient Effect + +--- + +## Paradox of the Active User + +**Principle:** Users don't read manuals — they jump straight in and learn by doing, even when reading first would be faster. + +**Key takeaways** +- Design for exploration: make the product teach itself in context. +- Front-load value; defer documentation to the moment of need. + +**Frontend code implications** +- Inline, contextual hints and empty-state guidance instead of upfront tutorials. +- Sensible defaults so a user who reads nothing still succeeds; forgiving, reversible actions (undo). + +**Review criteria** +- CRITICAL: core flow unusable without reading docs first; no guidance in empty/first-run states. +- MINOR: help exists but isn't surfaced at the point of need. + +**Related:** Jakob's Law, Mental Model + +--- + +## Cognitive Bias + +**Principle:** Systematic errors in thinking shape how users perceive interfaces and make decisions. + +**Key takeaways** +- Anchoring, framing, loss aversion, social proof, etc. quietly steer choices — design honestly. +- Use biases to *help* users decide, not to manipulate (avoid dark patterns). + +**Frontend code implications** +- Framing: present the option you genuinely recommend as the default/highlighted choice. +- Social proof: show real usage/ratings near decisions; never fabricate urgency or scarcity. +- Anchoring: order pricing so the intended reference point comes first. + +**Review criteria** +- CRITICAL: dark patterns — fake scarcity/urgency, manipulative framing, hidden costs revealed late. +- MINOR: missed honest opportunity to reduce decision effort (no recommended default, no social proof where genuine). + +**Related:** Selective Attention, Peak-End Rule diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/gestalt.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/gestalt.md new file mode 100644 index 0000000000000000000000000000000000000000..762a0e3c5a9e74ccdb06093933819c0c5ce92a8c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/gestalt.md @@ -0,0 +1,123 @@ +# Gestalt & Mental Models + +Visual grouping, layout relationships, shape simplification, expectations. Each entry: principle → takeaways → frontend code → review criteria (CRITICAL/MINOR) → related. + +--- + +## Law of Proximity + +**Principle:** Objects near each other are perceived as a group. + +**Key takeaways** +- Spacing communicates relationship more strongly than borders or color. +- The gap *between* groups must exceed the gap *within* a group. + +**Frontend code implications** +- Tighten spacing within a group, widen it between groups (e.g. `gap: 8px` inside, `32px` between). +- Keep labels close to their inputs; keep an action close to the object it acts on. + +**Review criteria** +- CRITICAL: a label/control or item/action so far apart users can't tell what belongs to what; uniform spacing that erases all grouping. +- MINOR: within-group gap nearly equal to between-group gap (weak grouping signal). + +**Related:** Common Region, Similarity + +--- + +## Law of Similarity + +**Principle:** Elements that look alike (color, shape, size) are perceived as related, even when separated. + +**Key takeaways** +- Consistent styling signals "same kind/role"; differing style signals "different role." +- Make links/buttons look like links/buttons everywhere. + +**Frontend code implications** +- One consistent visual language per element role (all primary buttons identical; all links styled the same). +- Don't style a non-interactive element like an interactive one (false affordance). + +**Review criteria** +- CRITICAL: interactive and static elements share identical styling (users can't tell what's clickable). +- MINOR: same-role elements styled inconsistently across views. + +**Related:** Proximity, Uniform Connectedness + +--- + +## Law of Common Region + +**Principle:** Elements within a shared boundary (a container/background) are perceived as grouped. + +**Key takeaways** +- A card, panel, or background block is a strong grouping device — stronger than proximity alone. +- Use it to separate logically distinct sections. + +**Frontend code implications** +- Wrap related content in a card (`background`, `border`, `border-radius`, padding) to bind it. +- Separate sections with distinct background regions rather than relying on spacing only. + +**Review criteria** +- CRITICAL: a container visually encloses unrelated items, implying a false relationship. +- MINOR: related items would read more clearly inside a shared region but aren't. + +**Related:** Proximity, Uniform Connectedness + +--- + +## Law of Uniform Connectedness + +**Principle:** Elements visually connected (by a line, shared color region, or container) are perceived as more related than elements merely near or similar. + +**Key takeaways** +- The strongest Gestalt grouping cue — explicit connection beats proximity and similarity. +- Use connectors for steps, relationships, and flows. + +**Frontend code implications** +- Connect stepper/wizard nodes with a line; group toolbar actions in a connected segmented control. +- Use a shared header band or connecting element to bind a control to its content. + +**Review criteria** +- CRITICAL: a connecting line/region links items that aren't actually related. +- MINOR: a sequence/flow shown as loose items where a connector would clarify order. + +**Related:** Common Region, Similarity + +--- + +## Law of Prägnanz (Simplicity) + +**Principle:** People interpret ambiguous or complex images in the simplest form possible, because it takes the least cognitive effort. + +**Key takeaways** +- Favor simple, clean shapes and layouts the eye resolves instantly. +- Complex or irregular forms increase processing effort and error. + +**Frontend code implications** +- Prefer simple geometric shapes and regular grids; avoid gratuitously complex layouts. +- Reduce visual clutter so structure is read at a glance. + +**Review criteria** +- CRITICAL: layout so visually complex/irregular that structure is unreadable at a glance. +- MINOR: ornamental complexity that adds processing cost without function. + +**Related:** Occam's Razor, Similarity + +--- + +## Mental Model + +**Principle:** Users come with a prebuilt belief — from prior products and the real world — about how your system should work. Friction comes from a mismatch between their model and yours. + +**Key takeaways** +- Meet existing expectations; align labels, icons, and flows with what users already know. +- When you must break a convention, signal it clearly and explain. + +**Frontend code implications** +- Use conventional icons/labels (cart, gear = settings, magnifier = search) for their conventional meaning. +- Match real-world metaphors (folders, trash) where they fit; don't repurpose familiar icons for new meanings. + +**Review criteria** +- CRITICAL: a familiar pattern/icon repurposed for an unexpected action (violates the user's model). +- MINOR: novel pattern used where a conventional one would be understood instantly. + +**Related:** Jakob's Law, Paradox of the Active User diff --git a/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/heuristics.md b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/heuristics.md new file mode 100644 index 0000000000000000000000000000000000000000..ac7d4c9816c5256fdd1be1d5193cea26aeedf6ba --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/903718834b4c9bd4_q1/skill/references/heuristics.md @@ -0,0 +1,89 @@ +# Heuristics + +Decision time, target acquisition, choice volume, aesthetic trust. Each entry: principle → takeaways → frontend code → review criteria (CRITICAL/MINOR) → related. + +--- + +## Aesthetic-Usability Effect + +**Principle:** Users perceive aesthetically pleasing design as more usable, and forgive minor usability issues when an interface looks good. + +**Key takeaways** +- Visual polish builds trust and buys tolerance for small friction. +- It can also *mask* real usability problems in testing — don't let "it looks nice" end a review. + +**Frontend code implications** +- Establish clear visual hierarchy: deliberate size/weight steps, 4–6 font sizes, 2–3 font families, a constrained palette (3–5 intentional colors). +- Consistent system tokens for shadow, radius, spacing, hover/focus states — inconsistency reads as "broken" regardless of beauty. + +**Review criteria** +- CRITICAL: no visual hierarchy (all elements same weight); >3 font families or >8 font sizes; missing focus/hover states on interactive elements. +- MINOR: >6 colors without purpose; inconsistent spacing or radii; uneven shadow language. + +**Related:** Von Restorff Effect, Jakob's Law + +--- + +## Choice Overload + +**Principle:** Too many options overwhelm users, causing decision paralysis and lower satisfaction (a.k.a. paradox of choice; "overchoice," Toffler 1970). + +**Key takeaways** +- Reducing and organizing choices improves both decisions and how the whole experience is felt. +- When comparison is genuinely needed, enable side-by-side comparison rather than removing options. +- Prioritize what's shown at any moment (featured/recommended) and give upfront narrowing tools (search, filter). + +**Frontend code implications** +- For >5–7 items, replace a plain `