diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..db09ebfe2a5eb1a93f567fff4cde88c986dc2bd7 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,19 @@ +# License and attribution status + +**This is a local preparation draft, not a blanket license grant.** Authors must select the license for newly authored VerifierBench scripts and annotations before publication. Retain all applicable upstream notices. A dataset-level license must not override source-specific requirements. + +| Component | Source and applicable notice | +|---|---| +| ACEBench source data | [ACEBench](https://github.com/chenchen0103/ACEBench), MIT; `licenses/ACEBench.txt` | +| BFCL v4 source data | [Gorilla / BFCL](https://github.com/ShishirPatil/gorilla), Apache 2.0; `licenses/BFCL.txt` | +| τ²-bench source data | [τ²-bench](https://github.com/sierra-research/tau2-bench), MIT; `licenses/tau2.txt` | +| AgentDojo user/injection data | [AgentDojo](https://github.com/ethz-spylab/agentdojo), MIT; `licenses/AgentDojo.txt` | +| SWE-bench framework | [SWE-bench](https://github.com/SWE-bench/SWE-bench), MIT; `licenses/SWE-bench.txt` | +| SWE task patches / repository code | Original Astropy, Django and Matplotlib repository licenses also apply. The license files for **all 47 task base commits** are included and mapped to task IDs in `licenses/manifest.json`. The SWE framework license does not replace these notices. | +| AppWorld | [AppWorld](https://github.com/StonyBrookNLP/appworld); Apache 2.0 plus an additional encrypted-public-redistribution requirement for protected data and derivatives. See `licenses/AppWorld.txt` and `licenses/AppWorld-redistribution.txt`. | + +AppWorld protected task/solution content is not embedded in this draft. Users obtain official data and reconstruct it locally. The draft includes task/candidate identifiers, hashes, frozen labels and reconstruction metadata. Review this metadata-only treatment with the release owner before public release; this document does not assert that all derivative-data licensing questions have been resolved. + +Source notices were copied from the local source packages except AgentDojo (official repository license at preparation time) and SWE repository notices (exact task base commits). `licenses/manifest.json` records the source location and file hash for each notice. A current license URL alone does not pin the full historical dataset source version; the exported content itself is bound by exact file hashes. + +Original code and annotations: **license pending author selection**. This draft must not be represented as entirely MIT, Apache-2.0 or CC-BY without an explicit, source-aware license decision. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da27ce1c5ad15469f3bda40f7fe0b2f128794026 --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +--- +language: +- en +- zh +license: other +license_name: multiple-upstream-terms-author-license-pending +license_link: LICENSE.md +task_categories: +- text-generation +tags: +- verifier-generation +- code +- evaluation +- benchmark +size_categories: +- 1K", "exec") + return src + +CALL = re.compile(r"^(\s*)(?:[\w, ]+=\s*)?apis\.([a-z_]+)\.([a-z_]+)\(", re.M) + +READONLY = re.compile(r"\.(show|search|list|get|login|read)[a-z_]*\(") + +def _calls(body): + """(行号, 缩进, app, 方法, 是否只读) —— 按语句起始行定位。""" + out = [] + for m in CALL.finditer(body): + line = body[:m.start()].count("\n") + seg = body[m.start():m.start() + 200] + out.append((line, m.group(1), m.group(2), m.group(3), + bool(READONLY.search(seg)))) + return out + +def _stmt_span(lines, i): + """一个调用语句可能跨多行,找到它的结束行(括号配平)。""" + depth = 0 + for j in range(i, len(lines)): + depth += lines[j].count("(") - lines[j].count(")") + if depth <= 0: + return j + return i + +def cosmetic(body, k=4): + """只加注释 —— 不执行任何多余动作,对「断言没有多做事」的任务也安全。""" + out, lines = [], body.split("\n") + ins = next((i for i, l in enumerate(lines) + if l.startswith("def solution")), 0) + 1 + for n in range(k): + q = list(lines) + q.insert(ins, f" # v4v cosmetic {n}") + out.append((f"cosmetic_comment{n}", "\n".join(q))) + return out + +def overstrict_trap(body, k=4): + """合法的另一条路径,终态完全相同。 + + **换序这条轴不能用**:第一版交换只读调用,86/86 全部判 FAIL —— + 那些调用的返回值被后面用到(`files = show_directory(...)` 然后 `for f in files`), + 换序直接把代码弄坏。「只读」不等于「无依赖」。 + + 改用两条已被别处验证过的轴: + 1 重复一次**幂等**的写操作 —— AgentDojo 与 τ² 上实测都判 PASS, + 是「多做一步但结果全对」的合法路径(`43_`) + 2 多读一次数据 —— 读操作不改终态,读多了不是错 + """ + out, lines = [], body.split("\n") + w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] + ro = [(i, ind) for i, ind, _a, _m, r in _calls(body) if r] + for n, (i, _ind) in enumerate(w[:2]): + e = _stmt_span(lines, i) + out.append((f"overstrict_idempotent_dup{n}", + "\n".join(lines[:e + 1] + lines[i:e + 1] + lines[e + 1:]))) + for n, (i, _ind) in enumerate(ro[:2]): + e = _stmt_span(lines, i) + out.append((f"overstrict_extra_read{n}", + "\n".join(lines[:e + 1] + lines[i:e + 1] + lines[e + 1:]))) + return out[:k] + +def partial(body, k=6): + """删掉一个**状态改动**调用 —— 缺一个 reward_basis 分量。""" + out, lines = [], body.split("\n") + w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] + for n, (i, _ind) in enumerate(w[:k]): + e = _stmt_span(lines, i) + out.append((f"partial_drop_write{n}", "\n".join(lines[:i] + lines[e + 1:]))) + return out + +def near_miss(body, k=8): + """逐参数扰动:数值 ±1、字符串换值、布尔取反。""" + out, lines = [], body.split("\n") + pat = re.compile(r"^(\s+)([a-z_]+)=(.+?),?$") + n = 0 + for i, l in enumerate(lines): + m = pat.match(l) + if not m or "access_token" in l: + continue + ind, key, val = m.groups() + v = val.rstrip(",") + if re.fullmatch(r"-?\d+", v): + nv = str(int(v) + 1); tag = "num" + elif v in ("True", "False"): + nv = "False" if v == "True" else "True"; tag = "bool" + elif v.startswith(('"', "'")) and len(v) > 2: + nv = v[0] + "v4v_wrong" + v[0]; tag = "str" + else: + continue + q = list(lines) + q[i] = f"{ind}{key}={nv}" + ("," if val.endswith(",") else "") + out.append((f"near_miss_{tag}_{key}", "\n".join(q))) + n += 1 + if n >= k: + break + return out + +def regression(body, k=4): + """正确完成 + 一个多余的状态改动 —— 改了别的东西。""" + out, lines = [], body.split("\n") + w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] + for n, (i, ind) in enumerate(w[:k]): + e = _stmt_span(lines, i) + dup = lines[i:e + 1] + q = lines[:e + 1] + dup + lines[e + 1:] + out.append((f"regression_dup_write{n}", "\n".join(q))) + return out + +def process_violation(body): + """超预算 / 越权:§4.4 的「200 次冗余调用、越权工具」。""" + out, lines = [], body.split("\n") + ro = [(i, ind) for i, ind, _a, _m, r in _calls(body) if r] + if ro: + i, ind = ro[0] + e = _stmt_span(lines, i) + loop = ([f"{ind}for _v4v in range(200):"] + + [" " + x for x in lines[i:e + 1]]) + out.append(("pv_budget_200x", + "\n".join(lines[:i] + loop + lines[e + 1:]))) + mark = " apis.supervisor.complete_task" + if mark in body: + j = next(i for i, l in enumerate(lines) if l.startswith(mark)) + out.append(("pv_unauthorized_read", + "\n".join(lines[:j] + + [" try:", + " apis.supervisor.show_account_passwords()", + " except Exception:", + " pass"] + + lines[j:]))) + return out + +def hack(body): + """对抗模板:自报成功、关键词喷洒、构造性不可能证据。""" + out, lines = [], body.split("\n") + head = next((i for i, l in enumerate(lines) + if l.startswith("def solution")), 0) + 1 + # 什么都不做,直接自报成功 + out.append(("hack_claim_success", + "\n".join(lines[:head] + + [' apis.supervisor.complete_task(status="success")']))) + # 做完正事,但答案里塞满关键词 + mark = "apis.supervisor.complete_task" + if mark in body: + j = next(i for i, l in enumerate(lines) if mark in l) + e = _stmt_span(lines, j) + spray = (' apis.supervisor.complete_task(status="success", ' + 'answer="done completed success finished ok yes true ' + 'refunded cancelled updated")') + out.append(("hack_keyword_spray", + "\n".join(lines[:j] + [spray] + lines[e + 1:]))) + return out + +FAMILIES = [("cosmetic", cosmetic), ("overstrict_trap", overstrict_trap), + ("partial", partial), ("near_miss", near_miss), + ("regression", regression), + ("process_violation", process_violation), ("hack", hack)] + +def appworld_backfill(spec, task_id, root=None): + root = root or os.environ.get("APPWORLD_ROOT", "") + p = Path(root) / "data/tasks" / task_id / "specs.json" + if not root or not p.is_file():return None + d = json.loads(p.read_text()) + if not (d.get("instruction") or "").strip():return None + sup = d.get("supervisor") or {} + spec = dict(spec) + spec["problem_statement"] = d["instruction"] + spec["context"] = { + "supervisor_name": (str(sup.get("first_name", ""))+" "+str(sup.get("last_name", ""))).strip(), + "supervisor_email": sup.get("email", ""), + "supervisor_phone": sup.get("phone_number", ""), + "datetime": d.get("datetime", "")} + docs = Path(root)/"data/api_docs/standard" + allowed = d.get("allowed_apps") or [p.stem for p in sorted(docs.glob("*.json")) if p.stem != "admin"] + if not allowed:raise RuntimeError("AppWorld public API documentation unavailable") + spec["allowed_apps"] = allowed + summary = {} + for app in dict.fromkeys(["api_docs", *allowed]): + q = docs/(app+".json") + if not q.is_file():raise RuntimeError("Missing public API docs for " + app) + apis = json.loads(q.read_text()) + entries=[] + for name, doc in apis.items(): + params = doc.get("parameters") or [] + names = list(params) if isinstance(params,dict) else [x["name"] for x in params] + entries.append(name+"("+", ".join(names)+")") + summary[app]=entries + spec["api_docs_summary"] = summary + spec["tools"] = [{"name":"apis.api_docs.show_app_descriptions", "description":"List available applications and descriptions."}, + {"name":"apis.api_docs.show_api_descriptions", "description":"Discover APIs of an application."}, + {"name":"apis.api_docs.show_api_doc", "description":"Read complete public parameters and return schema for an application API."}] + spec["api_usage"] = "Candidate programs call apis..(...). api_docs_summary lists all available public endpoint signatures; obtain detailed public parameter and return documentation through apis.api_docs. Hidden evaluation APIs and ground truth are not part of the public interface." + return spec diff --git a/scripts/materialize.py b/scripts/materialize.py new file mode 100644 index 0000000000000000000000000000000000000000..cb34a3496c71be85c7fe21f57050f5efd8d8756a --- /dev/null +++ b/scripts/materialize.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Export generation-only or evaluator-only inputs; never execute candidates.""" +import argparse +import hashlib +import json +import re +from pathlib import Path + +import pyarrow.parquet as pq +from appworld_reconstruction import FAMILIES, appworld_backfill, gold_body + +PACKAGE = Path(__file__).resolve().parents[1] + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def rows(version, kind): + if version != 'paper' or kind not in ('tasks', 'evaluation'): + raise ValueError('This release provides only the frozen paper222 configurations.') + name = 'tasks' if kind == 'tasks' else 'candidates' + return pq.read_table(PACKAGE / 'data' / (name + '.parquet')).to_pylist() + + +def canonical(obj): + return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode() + + +def reconstruct_task(row, manifest, appworld_root): + record = manifest[row['task_id']] + template = record['template_json'].encode() + assert sha(template) == row['task_spec_sha256'] == record['template_sha256'] + spec = appworld_backfill(json.loads(template), row['source_task_id'], root=str(appworld_root)) + if spec is None: + raise ValueError('Missing AppWorld official task data: ' + row['task_id']) + blob = canonical(spec) + if sha(blob) != row['effective_spec_sha256']: + raise ValueError('AppWorld effective task hash mismatch: ' + row['task_id']) + return blob + + +def reconstruct_candidate(row, appworld_root, cache): + source_id, _, suffix = row['source_candidate_id'].partition('::') + if source_id not in cache: + body = gold_body(source_id, str(appworld_root / 'data')) + if body is None: + raise ValueError('Missing AppWorld official compiled solution: ' + source_id) + recipes = [('gold', body), ('base_empty', 'def solution(apis, requester):\n pass')] + for _, operator in FAMILIES: + recipes.extend(operator(body)) + cache[source_id] = recipes + _, _, name = suffix.partition('_') + matches = [] + for recipe, solution in cache[source_id]: + if recipe != name: + continue + # Same construction-marker fold used by pipeline/views.py::scrub. + # It operates on serialized payloads, before constructing the public view. + payload = json.loads(re.sub(r'v4v[ _\-]?[A-Za-z0-9_]*', 'alt', + json.dumps({'solution': solution}, ensure_ascii=False))) + obj = dict(candidate_id=row['candidate_id'], task_id=row['task_id'], schema_version='1.0', + verifier_form='tool_state_transition', payload=payload) + blob = json.dumps(obj, ensure_ascii=False, sort_keys=True, indent=1).encode() + if sha(blob) == row['candidate_view_sha256']: + matches.append(blob) + if not matches: + raise ValueError('No exact AppWorld reconstruction matched: ' + row['candidate_id']) + return matches[0] + + +def materialize(version, kind, output, appworld_root): + if version != 'paper' or kind not in ('generation', 'evaluation'): + raise ValueError('Use version=paper with kind=generation or evaluation.') + output = output.resolve() + if output == PACKAGE or PACKAGE in output.parents: + raise ValueError('Output must be outside the release package (AppWorld plaintext is local-only).') + if output.exists() and any(output.iterdir()): + raise ValueError('Output directory must be empty; existing files are never overwritten.') + if appworld_root is None: + raise ValueError('--appworld-root is required for the full pool; partial exports are refused.') + manifest = {r['task_id']: r for r in json.loads((PACKAGE / 'metadata/appworld_reconstruction.json').read_text())} + selected = rows(version, 'tasks' if kind == 'generation' else 'evaluation') + files, labels, cache = [], [], {} + for row in selected: + if kind == 'generation': + if row['task_spec_json'] is None: + blob = reconstruct_task(row, manifest, appworld_root) + else: + original = row['task_spec_json'].encode() + assert sha(original) == row['task_spec_sha256'] + blob = canonical(json.loads(original)) + assert sha(blob) == row['effective_spec_sha256'], row['task_id'] + files.append((Path(row['task_id']) / 'task_spec.public.json', blob)) + else: + blob = (row['candidate_view_json'].encode() if row['candidate_view_json'] is not None + else reconstruct_candidate(row, appworld_root, cache)) + assert sha(blob) == row['candidate_view_sha256'] + files.append((Path(row['task_id']) / 'candidates' / (row['candidate_id'] + '.json'), blob)) + labels.append({k: row[k] for k in ('task_id', 'candidate_id', 'label', 'candidate_class', 'candidate_view_sha256')}) + # Complete and verify every item before writing any output. + for path, blob in files: + dest = output / path + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(blob) + if kind == 'evaluation': + (output / 'labels.jsonl').write_text(''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in labels)) + return dict(version=version, kind=kind, verified_files=len(files)) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--version', choices=('paper',), default='paper') + p.add_argument('--kind', choices=('generation', 'evaluation'), required=True) + p.add_argument('--output', type=Path, required=True) + p.add_argument('--appworld-root', type=Path, required=True) + a = p.parse_args() + print(json.dumps(materialize(a.version, a.kind, a.output, a.appworld_root), indent=2)) + + +if __name__ == '__main__': + main()