diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/instruction.md b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4497261d98e27a9ec4317916770d27cc0cf4bf4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/instruction.md @@ -0,0 +1,7 @@ +You are triaging CI failures offline. Three failed GitHub Actions run logs are provided in the inputs. For each log, classify the failure using this decision procedure: (1) if the log contains 'npm ERR! Could not resolve dependency', 'Module not found', or 'Cannot find module', classify as 'dependency' with the dependency fix from the frozen CI Failure Fix Patterns reference; (2) if it contains 'Snapshot mismatch' or 'received value does not match', classify as 'snapshot' with the snapshot fix from that frozen reference; (3) if it contains 'eslint' or 'Formatting issues', classify as 'lint' with action 'eslint --fix + push'; (4) if it contains 'Unauthorized', '401', 'token expired', or 'GITHUB_TOKEN', classify as 'auth' with action 'REPORT ONLY (human needed)'; (5) if it contains 'exceeded the maximum execution time', classify as 'timeout' with action 'REPORT ONLY (human needed)'; (6) otherwise classify as 'unknown' with action 'REPORT ONLY with diagnosis'. Patterns are checked in that priority order and the first match wins. Write a Python 3 script (standard library only) at triage.py that reads each log file passed as command-line arguments and writes a JSON array to triage_report.. Each element must have keys: 'log' (the file path as given), 'pattern' (one of dependency/snapshot/lint/auth/timeout/unknown), and 'action'. For dependency/snapshot, serialize the frozen reference's repair command followed by ` + push`, omitting cd/git-add/git-commit scaffolding. For all other categories use the exact action strings above. Then run it on all three logs so triage_report. exists in the working directory. +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/aba6991804c4279544487710/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..886ba3a357fa655c298542d40bfa29f526077b28 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/SKILL.md @@ -0,0 +1,78 @@ +--- +name: ci-failure-fixer +description: Monitor GitHub Actions CI pipelines for failures and automatically fix common issues. Use when asked to watch CI, fix build failures, monitor GitHub Actions, set up CI auto-repair, or diagnose failed builds. Detects failures via `gh` CLI, reads build logs, matches against known fix patterns (dependency issues, snapshot mismatches, lint errors, E2E failures), applies fixes automatically, and reports unfixable issues with diagnosis. Works as a cron job or on-demand. Requires `gh` CLI authenticated with GitHub. +--- + +# CI Failure Fixer + +Monitor GitHub Actions for failures. Auto-fix what's fixable, report what's not. + +## How It Works + +1. `scripts/check-ci-failures.sh` polls repos for new failed runs +2. If failures found → read build logs via `gh run view --log` +3. Match error against known patterns → auto-fix if safe +4. Push fix → wait 90s → verify build passes +5. Report results (fixed or diagnosis-only) + +## Quick Start + +### On-demand +```bash +bash scripts/check-ci-failures.sh +``` + +Output: `OK` (no failures) or `FAILURES` with details. + +### As Cron Job (OpenClaw) + +Set up a cron that runs every 30 minutes: +- **Script:** `bash scripts/check-ci-failures.sh` +- **Model:** Haiku (cheap, sufficient) +- **On failure:** Read logs, attempt auto-fix, report + +## Configuration + +Environment variables: +- `GITHUB_OWNER` — GitHub username (auto-detected from `gh` if not set) +- `CI_REPOS` — Space-separated repo names (auto-discovers all repos if not set) +- `CI_STATE_FILE` — Path to state JSON (tracks last check time) + +## Auto-Fixable Patterns + +| Pattern | Detection | Fix | +|---------|-----------|-----| +| Dependency issues | `npm ERR! Could not resolve` | `npm install` + push | +| Test snapshots | `Snapshot mismatch` | `npm test -- --update` + push | +| Lint errors | `eslint`, `Formatting` | `eslint --fix` + push | +| E2E snapshots | Playwright snapshot diff | `playwright --update-snapshots` + push | + +## Report-Only (Human Needed) + +- Token/auth errors (secrets rotation) +- TypeScript errors (complex type issues) +- Build timeouts (resource/loop issues) +- Unknown errors + +## Fix Patterns Reference + +Read `references/fix-patterns.md` for detailed decision tree, log reading commands, and all known patterns with fix scripts. + +## Reading Logs + +```bash +# Latest failed run logs +gh run view --repo OWNER/REPO --log 2>&1 | tail -50 + +# Filter for errors +gh run view --repo OWNER/REPO --log 2>&1 | grep -A5 "error\|FAIL" +``` + +## After Fixing + +Always verify the fix worked: +```bash +sleep 90 # Wait for new CI run +gh run list --repo OWNER/REPO --limit 1 --json conclusion -q '.[0].conclusion' +# Should be "success" +``` diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/_export_skill_meta.json b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/_export_skill_meta.json new file mode 100644 index 0000000000000000000000000000000000000000..6e36ef483c60ac9ced09e2be1ac1742043a65db0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/_export_skill_meta.json @@ -0,0 +1,20 @@ +{ + "slug": "ci-failure-fixer", + "displayName": "Ci Failure Fixer", + "sourceRef": "public-clawhub", + "version": "1.0.0", + "createdAt": 1774357146234, + "updatedAt": 1779078822481, + "stats": { + "comments": 0, + "downloads": 612, + "installsAllTime": 16, + "installsCurrent": 0, + "stars": 0, + "versions": 1 + }, + "owner": { + "handle": "danielgrobelny", + "displayName": "DanielGrobelny" + } +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/references/fix-patterns.md b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/references/fix-patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..0c9da2720084d35d923e8080bafee499a85a8f05 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/references/fix-patterns.md @@ -0,0 +1,119 @@ +# CI Failure Fix Patterns + +Common GitHub Actions failure patterns and how to auto-fix them. + +## Pattern 1: Dependency Issues + +**Symptoms:** `npm ERR! Could not resolve dependency`, `Module not found`, `Cannot find module` + +**Fix:** +```bash +cd +npm install +git add package-lock.json +git commit -m "fix: resolve dependency issue" +git push +``` + +## Pattern 2: Test Snapshot Mismatch + +**Symptoms:** `Snapshot mismatch`, `toMatchSnapshot`, `received value does not match` + +**Fix:** +```bash +cd +npm test -- --update +git add -A +git commit -m "fix: update test snapshots" +git push +``` + +## Pattern 3: TypeScript Errors + +**Symptoms:** `TS2xxx`, `Type error`, `Property does not exist on type` + +**Fix:** Read the error, fix the type issue in source code. Usually requires understanding the code — not auto-fixable for complex cases. + +**Auto-fixable cases:** +- Missing `@ts-ignore` → add comment +- Unused imports → remove them +- Missing type exports → add `export type` + +## Pattern 4: ESLint / Prettier Errors + +**Symptoms:** `Lint errors`, `Formatting issues`, `eslint` + +**Fix:** +```bash +cd +npx eslint --fix . +npx prettier --write . +git add -A +git commit -m "fix: resolve lint errors" +git push +``` + +## Pattern 5: Environment Variable / Token Issues + +**Symptoms:** `Unauthorized`, `401`, `VERCEL_TOKEN`, `GITHUB_TOKEN`, `token expired` + +**Fix:** Cannot auto-fix — requires human to rotate/update secrets. Report to user with diagnosis. + +## Pattern 6: Build Timeout + +**Symptoms:** `The job running on runner has exceeded the maximum execution time` + +**Fix:** Usually indicates infinite loop or resource exhaustion. Read logs, identify the stuck step. Not auto-fixable. + +## Pattern 7: E2E Test Failures (Playwright) + +**Symptoms:** `browserType.launch`, `Timeout exceeded`, `locator.click` + +**Fix:** +```bash +cd +npx playwright install +npx playwright test --update-snapshots +git add -A +git commit -m "fix: update E2E snapshots" +git push +``` + +## Decision Tree + +``` +Failure detected +├── Dependency error? → npm install + push +├── Snapshot mismatch? → npm test --update + push +├── Lint error? → eslint --fix + push +├── E2E snapshot? → playwright --update-snapshots + push +├── Token/Auth error? → REPORT ONLY (human needed) +├── Type error (simple)? → TRY fix, push if confident +└── Unknown? → REPORT ONLY with diagnosis +``` + +## Reading Build Logs + +```bash +# Get the latest failed run's logs +gh run view --repo OWNER/REPO --log 2>&1 | tail -50 + +# Get specific run by ID +gh run view --repo OWNER/REPO --log 2>&1 | grep -A5 "error\|Error\|FAIL" +``` + +## Cron Integration + +Set up as an OpenClaw cron job: +``` +Schedule: every 30m +Model: haiku (cheap, sufficient for script + log reading) +Script: scripts/check-ci-failures.sh +``` + +When failures detected, the agent should: +1. Read build logs (`gh run view --log`) +2. Match against known patterns above +3. Auto-fix if pattern is recognized and safe +4. Report to user with diagnosis if unknown +5. After fix: wait 90s, re-check if build passed diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/scripts/check-ci-failures.sh b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/scripts/check-ci-failures.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba90d98885b32132ca79f948ed210dcc8395f6ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/scripts/check-ci-failures.sh @@ -0,0 +1,57 @@ +#!/bin/bash +# Check GitHub repos for failed CI runs and report new failures. +# +# Usage: ./check-ci-failures.sh [--repos "repo1 repo2"] [--owner "GitHubUser"] +# +# Requires: gh CLI (authenticated) +# Output: "OK" if no failures, "FAILURES\n❌ repo: details" if failures found. +# Tracks last check time in a state file to only report NEW failures. + +OWNER="${GITHUB_OWNER:-$(gh api user -q .login 2>/dev/null)}" +STATE_FILE="${CI_STATE_FILE:-$HOME/.openclaw/workspace/memory/ci-check-state.json}" + +# Auto-discover repos if not provided +if [ -n "$1" ] && [ "$1" = "--repos" ]; then + REPOS="$2" +elif [ -n "$CI_REPOS" ]; then + REPOS="$CI_REPOS" +else + # Auto-discover: all repos with GitHub Actions + REPOS=$(gh repo list "$OWNER" --limit 50 --json name,hasWiki \ + -q '.[].name' 2>/dev/null | tr '\n' ' ') +fi + +# Initialize state file if missing +if [ ! -f "$STATE_FILE" ]; then + mkdir -p "$(dirname "$STATE_FILE")" + echo '{"lastCheck":"2026-01-01T00:00:00Z"}' > "$STATE_FILE" +fi + +LAST_CHECK=$(python3 -c "import json; print(json.load(open('$STATE_FILE'))['lastCheck'])" 2>/dev/null || echo "2026-01-01T00:00:00Z") +NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ") +FAILURES="" +CHECKED=0 + +for REPO in $REPOS; do + CHECKED=$((CHECKED + 1)) + + # Get failed runs since last check + FAILED=$(gh run list --repo "$OWNER/$REPO" --status failure --json databaseId,createdAt \ + -q "[.[] | select(.createdAt > \"$LAST_CHECK\")] | length" 2>/dev/null) + + if [ "$FAILED" != "" ] && [ "$FAILED" != "0" ]; then + DETAIL=$(gh run list --repo "$OWNER/$REPO" --status failure --limit 1 --json name,headBranch,url \ + -q '.[0] | "\(.name) on \(.headBranch)"' 2>/dev/null) + URL=$(gh run list --repo "$OWNER/$REPO" --status failure --limit 1 --json url -q '.[0].url' 2>/dev/null) + FAILURES="$FAILURES\n❌ $REPO: $DETAIL ($FAILED new) $URL" + fi +done + +# Update last check time +python3 -c "import json; json.dump({'lastCheck':'$NOW'}, open('$STATE_FILE','w'))" 2>/dev/null + +if [ -n "$FAILURES" ]; then + echo -e "FAILURES ($CHECKED repos checked)$FAILURES" +else + echo "OK" +fi diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/skill-card.md b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/skill-card.md new file mode 100644 index 0000000000000000000000000000000000000000..9abd856cde23a24363b8c6fd612c224f88ddb887 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/skill-card.md @@ -0,0 +1,41 @@ +## Description:
+Monitor GitHub Actions CI pipelines for failures and automatically fix common issues.
+ +This skill is ready for commercial/non-commercial use.
+ +## Publisher:
+[danielgrobelny](https://clawhub.ai/user/danielgrobelny)
+ +### License/Terms of Use:
+MIT-0
+ + +## Use Case:
+Developers and engineers use this skill to monitor GitHub Actions failures, inspect logs, apply common CI fixes, and report issues that require human intervention.
+ +### Deployment Geography for Use:
+Global
+ +## Known Risks and Mitigations:
+Risk: The skill can drive recurring automated repository changes and pushes using the user's GitHub access.
+Mitigation: Set CI_REPOS explicitly, use a least-privilege GitHub token, run the skill on demand before enabling cron, and require human approval or pull request review before any commit or push.
+Risk: The skill reads GitHub Actions logs, which may expose sensitive build details.
+Mitigation: Install only where access to GitHub Actions logs is acceptable, and scope credentials to the repositories that need CI monitoring.
+ + +## Reference(s):
+- [CI Failure Fix Patterns](references/fix-patterns.md)
+- [ClawHub Skill Page](https://clawhub.ai/danielgrobelny/ci-failure-fixer)
+ + +## Skill Output:
+**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]
+**Output Format:** [Markdown with inline bash commands and diagnosis text]
+**Output Parameters:** [1D]
+**Other Properties Related to Output:** [Requires an authenticated GitHub CLI and may read GitHub Actions logs or propose repository changes.]
+ +## Skill Version(s):
+1.0.0 (source: server release metadata)
+ +## Ethical Considerations:
+Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.
diff --git a/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/task.json b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5047120e4847196d96d50a139a5bac7bcb267d62 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/task.json @@ -0,0 +1,86 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "aba6991804c4279544487710", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "aba6991804c4279544487710", + "outputs": [ + "triage.py", + "triage_report." + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "f6066978de15659025c9d81d0bf8754c3ab5224173e8f94f7ebca4fe99aab5e6", + "files": { + "SKILL.md": "b7bf0fb1ff16c9c8bb52b0f2b426b81a012ee61448f154124a5f924e44cc5ee8", + "_export_skill_meta.json": "9b1a1b6a2e3e52cdeac316f7b9d1696d55b27322b1c62d1f83d57e5c1179e821", + "references/fix-patterns.md": "d1db37bf7ca6cfec74f6117190a522338e8304108eea1644d295229e49fe0daa", + "scripts/check-ci-failures.sh": "53077b4c0ce1deeb1d4c50bf4bdad595a6643b75b5b1165474a54d61c498cf9d", + "skill-card.md": "3b20c3a903329bc322d8781a9b8b5ae310d90ae8d5354072e480afe318f9bf76" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/logs/run-4821-webapp.log", + "workspace_target": "logs/run-4821-webapp.log", + "sha256": "eb92ffb4b509cfd47012abc7103fb51868e03401ab51c3b8a0bb7ff50583e29a" + }, + { + "source": "inputs/logs/run-4822-api.log", + "workspace_target": "logs/run-4822-api.log", + "sha256": "2201f178ef8a582bfbc71f46b08c82e7afca449cd86ea93b2f048cf728b747dd" + }, + { + "source": "inputs/logs/run-4823-deploy.log", + "workspace_target": "logs/run-4823-deploy.log", + "sha256": "1c9cd1a0ab31ee6fad9ea97783f557ecd7f96e47f7974d17a42b313814a9208d" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "f6066978de15659025c9d81d0bf8754c3ab5224173e8f94f7ebca4fe99aab5e6" + } + ] + }, + "autograde_runtime_contract": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60 + }, + "automatic_evaluation_runtime": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/ac993ee8a71a4ab4726c1662/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/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/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..bc69f81e085c631459f91368df8f1efe32cafb5f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.json @@ -0,0 +1,16 @@ +{ + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/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/ac993ee8a71a4ab4726c1662/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/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(' lib/util/format.js\', \'lib/data/repo.js -> lib/analyzer/summary.js\']\nMUST_NOT_VIOLATE = [\'lib/analyzer/summary.js -> lib/util/format.js\', \'lib/analyzer/summary.js -> lib/model/store.js\', \'bin/main.js -> lib/data/repo.js\', \'bin/main.js -> lib/util/format.js\', \'lib/data/repo.js -> lib/model/store.js\']\nKNOWN = set(FILES)\n\ndef rel_ok(p):\n if not isinstance(p, str) or not p or \'\\\\\' in p or p.startswith(\'/\') or (\'..\' in p.split(\'/\')):\n return False\n return p in KNOWN\n\ndef find_candidate():\n for c in (_repair_os.environ.get(\'MYBENCH_CANDIDATE\', \'/candidate\') + \'/analyze.py\', _repair_os.environ.get(\'MYBENCH_CANDIDATE\', \'/candidate\') + \'/analyze.py/analyze.py\'):\n if os.path.isfile(c):\n return c\n if os.path.isfile(\'/answer.txt\'):\n return \'/answer.txt\'\n return None\n\ndef main():\n checks = [None] * 6\n tmp = tempfile.mkdtemp(dir=\'/tmp\')\n try:\n for rel, content in FILES.items():\n full = os.path.join(tmp, rel)\n os.makedirs(os.path.dirname(full), exist_ok=True)\n with open(full, \'w\') as f:\n f.write(content)\n src = find_candidate()\n report = None\n if src is None:\n checks[0] = (False, \'no analyze.py found in /candidate or /answer.txt\')\n else:\n try:\n shutil.copy(src, os.path.join(tmp, \'analyze.py\'))\n except Exception as e:\n checks[0] = (False, \'could not stage analyze.py: %s\' % e)\n src = None\n if src is not None and checks[0] is None:\n try:\n r = subprocess.run([sys.executable, \'analyze.py\'], cwd=tmp, capture_output=True, text=True, timeout=60)\n rp = os.path.join(tmp, \'report.\')\n if not os.path.isfile(rp):\n checks[0] = (False, "analyze.py ran (rc=%d) but did not write \'report.\'" % r.returncode)\n else:\n try:\n report = json.load(open(rp))\n checks[0] = (r.returncode == 0, \'analyze.py must exit0 and write a parseable fresh report.\')\n except Exception as e:\n checks[0] = (False, \'report. is not valid JSON: %s\' % e)\n except subprocess.TimeoutExpired:\n checks[0] = (False, \'analyze.py timed out\')\n except Exception as e:\n checks[0] = (False, \'failed to run analyze.py: %s\' % e)\n if report is None:\n for i in range(1, 6):\n checks[i] = (False, \'no valid report. produced\')\n else:\n edges = report.get(\'edges\')\n got = set()\n edges_ok = isinstance(edges, list)\n if edges_ok:\n for e in edges:\n if isinstance(e, dict) and rel_ok(e.get(\'from\')) and rel_ok(e.get(\'to\')):\n got.add((e[\'from\'], e[\'to\']))\n else:\n edges_ok = False\n missing = EXPECTED_EDGES - got\n checks[1] = (edges_ok and got == EXPECTED_EDGES and (len(edges) == len(got)) and ([(e[\'from\'], e[\'to\']) for e in edges] == sorted(got)), \'all 7 expected edges present\' if edges_ok and (not missing) else \'missing/malformed edges: %s\' % sorted(missing) if edges_ok else \'edges malformed\')\n cycles = report.get(\'cycles\')\n found = False\n if isinstance(cycles, list):\n for c in cycles:\n if isinstance(c, list) and len(c) >= 2:\n s = [x for x in c if isinstance(x, str)]\n if \'lib/data/repo.js\' in s and \'lib/analyzer/summary.js\' in s:\n found = True\n valid_cycles = isinstance(cycles, list) and bool(cycles)\n signatures = []\n if valid_cycles:\n for c in cycles:\n if not isinstance(c, list) or not all((isinstance(x, str) for x in c)):\n valid_cycles = False\n break\n v = c[:-1] if len(c) > 1 and c[0] == c[-1] else c\n if len(v) < 2 or len(set(v)) != len(v) or any(((a, b) not in EXPECTED_EDGES for a, b in zip(v, v[1:] + v[:1]))):\n valid_cycles = False\n break\n signatures.append(tuple(sorted(v)))\n valid_cycles = valid_cycles and len(signatures) == len(set(signatures))\n checks[2] = (found and valid_cycles, \'cycle between repo.js and summary.js reported\' if found else \'expected repo<->summary cycle not found in cycles\')\n viols = report.get(\'violations\')\n vlist = viols if isinstance(viols, list) else []\n vstrs = [v for v in vlist if isinstance(v, str)]\n miss_v = [m for m in MUST_VIOLATE if not any((m in v for v in vstrs))]\n bad_v = [m for m in MUST_NOT_VIOLATE if any((m in v for v in vstrs))]\n true_pairs = {(\'lib/data/repo.js\', \'lib/util/format.js\'), (\'lib/data/repo.js\', \'lib/analyzer/summary.js\'), (\'lib/analyzer/summary.js\', \'lib/data/repo.js\')}\n pairs = []\n for v in vstrs:\n m = re.fullmatch(\'VIOLATION:\\\\s*(\\\\S+)\\\\s*->\\\\s*(\\\\S+)\\\\s*\\\\((.+)\\\\)\', v)\n if m:\n pairs.append((m[1], m[2]))\n ok = isinstance(viols, list) and len(viols) == 3 and (len(pairs) == 3) and (set(pairs) == true_pairs) and (vlist == sorted(vlist))\n reason = \'violations correct\' if ok else (\'missing violations: %s; \' % miss_v if miss_v else \'\') + (\'wrongly flagged: %s\' % bad_v if bad_v else \'\' if ok else \'violations malformed\')\n checks[3] = (ok, reason)\n imp = report.get(\'impact\')\n ok = isinstance(imp, dict)\n detail = \'impact malformed\'\n if ok:\n direct = imp.get(\'direct\')\n trans = imp.get(\'transitive\')\n total = imp.get(\'total\')\n exp_direct = {\'bin/main.js\', \'lib/analyzer/summary.js\', \'lib/data/repo.js\'}\n ok = imp.get(\'target\') == \'lib/util/format.js\' and isinstance(direct, list) and (direct == sorted(exp_direct)) and isinstance(trans, list) and (len(trans) == 0) and (total == 3)\n detail = \'impact correct\' if ok else \'impact wrong: target=%r direct=%r transitive=%r total=%r\' % (imp.get(\'target\'), direct, trans, total)\n checks[4] = (ok, detail)\n paths = []\n if isinstance(edges, list):\n for e in edges:\n if isinstance(e, dict):\n paths += [e.get(\'from\'), e.get(\'to\')]\n if isinstance(cycles, list):\n for c in cycles:\n if isinstance(c, list):\n paths += c\n if isinstance(imp, dict):\n paths += [imp.get(\'target\')]\n for k in (\'direct\', \'transitive\'):\n v = imp.get(k)\n if isinstance(v, list):\n paths += v\n bad = [p for p in paths if not rel_ok(p)]\n checks[5] = (not bad, \'all paths relative, forward-slash, matching layout\' if not bad else \'bad paths: %s\' % bad)\n finally:\n shutil.rmtree(tmp, ignore_errors=True)\n print(json.dumps({\'checks\': [{\'id\': str(i), \'passed\': bool(p), \'reason\': r} for i, (p, r) in enumerate(checks)]}))\n\ndef _repair_verify_import_syntaxes():\n import contextlib, io, copy\n global FILES\n original_files = copy.deepcopy(FILES)\n pattern = re.compile(\'\\\\bimport\\\\s+(?:[^;\\\\n]*?\\\\s+from\\\\s+)?(["\\\'])([^"\\\']+)\\\\1\\\\s*;?\')\n required_files = {}\n converted = 0\n for name, source in original_files.items():\n converted_source, count = pattern.subn(lambda match: \'require(\' + json.dumps(match.group(2)) + \');\', source)\n required_files[name] = converted_source\n converted += count\n if not converted:\n raise RuntimeError(\'grader CommonJS panel conversion produced no imports\')\n results = []\n try:\n for panel in [original_files, required_files]:\n FILES = panel\n capture = io.StringIO()\n with contextlib.redirect_stdout(capture):\n main()\n values = []\n for line in capture.getvalue().splitlines():\n try:\n obj = json.loads(line)\n except ValueError:\n continue\n if isinstance(obj, dict) and isinstance(obj.get(\'checks\'), list):\n values.append(obj)\n if len(values) != 1:\n raise RuntimeError(\'grader did not emit one check object per syntax panel\')\n results.append(values[0])\n finally:\n FILES = original_files\n output = results[0]\n by = {str(item[\'id\']): item for item in results[1][\'checks\']}\n for item in output[\'checks\']:\n other = by.get(str(item[\'id\']))\n item[\'passed\'] = bool(item.get(\'passed\') and other is not None and other.get(\'passed\'))\n if other is None or not other.get(\'passed\'):\n item[\'reason\'] = str(item.get(\'reason\', \'\')) + \'; CommonJS panel: \' + str(other.get(\'reason\', \'missing check\') if other else \'missing check\')\n output[\'syntax_panels\'] = [\'ES imports\', \'CommonJS require\']\n print(json.dumps(output))\nif __name__ == \'__main__\':\n _repair_verify_import_syntaxes()\n' +IDS = ['0', '1', '2', '3', '4', '5'] +DELIVERY_IDS = {'0', '5', '1', '4', '3', '2'} +import io, json, contextlib, builtins, subprocess, tempfile, shutil, os +_ORIGINAL_APIS = (builtins.open, io.open, subprocess.run, tempfile.mkdtemp, tempfile.TemporaryDirectory, shutil.rmtree, shutil.copytree, shutil.copy) + +def _restore(): + builtins.open, io.open, subprocess.run, tempfile.mkdtemp, tempfile.TemporaryDirectory, shutil.rmtree, shutil.copytree, shutil.copy = _ORIGINAL_APIS + +def _grade(delivery): + _restore() + _buffer = io.StringIO() + _problem = None + try: + with contextlib.redirect_stdout(_buffer): + exec(compile(BODY, __file__, 'exec'), {'__file__': __file__, '__name__': '__main__', '_REPAIR_DELIVERY_MODE': delivery}) + except SystemExit: + pass + except Exception as e: + _problem = type(e).__name__ + ': ' + str(e) + finally: + _restore() + result = None + for line in reversed(_buffer.getvalue().splitlines()): + try: + x = json.loads(line) + if isinstance(x, dict) and isinstance(x.get('checks'), list): + result = x + break + except Exception: + pass + if result is None or _problem is not None: + result = {'checks': [{'id': i, 'passed': False, 'reason': 'evaluation failed: ' + str(_problem or 'missing valid checks JSON')} for i in IDS]} + return result +fresh = _grade(False) +from graph_probe import verify as _graph_verify +_graph_flags=_graph_verify() +for _item in fresh['checks']: + _idx=int(_item['id']);_item['passed']=bool(_item.get('passed') and _graph_flags[_idx]);_item['reason']+='; independent nested/index/nonempty-transitive graph panel='+str(_graph_flags[_idx]) +if DELIVERY_IDS and os.environ.get('MYBENCH_FIXTURE_MATERIALIZE') != '1': + submitted = _grade(True) + by = {str(c['id']): c for c in submitted['checks']} + for c in fresh['checks']: + if str(c['id']) in DELIVERY_IDS: + b = by.get(str(c['id']), {}) + c['passed'] = bool(c['passed'] and b.get('passed', False)) + if not b.get('passed', False): + c['reason'] += '; original public deliverable: ' + str(b.get('reason', 'missing semantic check')) +for _r10_row in fresh['checks']: + if str(_r10_row['id'])=='0':_r10_row['passed']=combine([_r10_row['passed'],dependency('analyze.py')]);_r10_row['reason']+='; complete local standard-library closure' +fresh['scoreable']=all(c['passed']is not None for c in fresh['checks']) +print(json.dumps(fresh, ensure_ascii=False)) diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/graph_probe.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/graph_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..587b91b8d5d494e83afb68ea6efa34cdc605d41c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/graph_probe.py @@ -0,0 +1,54 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,re,shutil,subprocess,sys,tempfile,os +from pathlib import Path +FILES={ +'lib/util/format.js':'export const fmt=1;\n', +'lib/model/store.js':"import { fmt } from '../util/format'; export const Store=fmt;\n", +'lib/model/index.js':"import { Store } from './store'; export { Store };\n", +'lib/data/repo.js':"const model=require('../model'); import { summary } from '../analyzer/summary.js';\n", +'lib/analyzer/summary.js':"import { repo } from '../data/repo';\n", +'bin/main.js':"import { summary } from '../lib/analyzer/summary';\n", +'bin/helpers/deep.js':"const repo=require('../../lib/data/repo');\n"} +EDGES={('lib/model/store.js','lib/util/format.js'),('lib/model/index.js','lib/model/store.js'),('lib/data/repo.js','lib/model/index.js'),('lib/data/repo.js','lib/analyzer/summary.js'),('lib/analyzer/summary.js','lib/data/repo.js'),('bin/main.js','lib/analyzer/summary.js'),('bin/helpers/deep.js','lib/data/repo.js')} +VIOLATIONS={('lib/model/store.js','lib/util/format.js'),('lib/data/repo.js','lib/analyzer/summary.js'),('lib/analyzer/summary.js','lib/data/repo.js')} +def verify(): + candidate=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'));root=Path('/workspace')if os.environ.get('MYBENCH_EPHEMERAL_WORKSPACE')=='1'else Path(tempfile.mkdtemp()) + root.mkdir(exist_ok=True) + for p in list(root.iterdir()): + if p.is_dir()and not p.is_symlink():shutil.rmtree(p) + else:p.unlink() + shutil.copytree(candidate,root,dirs_exist_ok=True,symlinks=True) + for name in ['lib','bin']: + p=root/name + if p.exists():shutil.rmtree(p) + for name,value in FILES.items():p=root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(value) + p=root/'report.' + if p.is_symlink()or p.is_file():p.unlink() + elif p.is_dir():shutil.rmtree(p) + try:r=subprocess.run([sys.executable,'analyze.py'],cwd=root,capture_output=True,text=True,timeout=60) + except subprocess.TimeoutExpired:return[False]*6 + except(OSError,subprocess.SubprocessError)as error:raise RuntimeError('Graph probe launcher infrastructure failure')from error + try: + if not p.is_file():return[False]*6 + doc=json.loads(p.read_text()) + except(OSError,ValueError,UnicodeError,RecursionError):return[False]*6 + flags=[r.returncode==0 and isinstance(doc,dict)]*6 + if not isinstance(doc,dict):return[False]*6 + edges=doc.get('edges');got=[(e.get('from'),e.get('to'))for e in edges if isinstance(e,dict)]if isinstance(edges,list)else[] + flags[1]=got==sorted(EDGES) + cycles=doc.get('cycles');seen=[];valid=isinstance(cycles,list)and bool(cycles) + for cycle in cycles if isinstance(cycles,list)else []: + if not isinstance(cycle,list)or not all(isinstance(x,str)for x in cycle):valid=False;continue + c=cycle[:-1]if len(cycle)>1 and cycle[0]==cycle[-1]else cycle + valid=valid and len(c)==len(set(c))and all((a,b)in EDGES for a,b in zip(c,c[1:]+c[:1]));seen.append(set(c)) + flags[2]=valid and len(seen)==1 and seen[0]=={'lib/data/repo.js','lib/analyzer/summary.js'} + violations=doc.get('violations');pairs=[] + for v in violations if isinstance(violations,list)else []: + m=re.fullmatch(r'VIOLATION:\s*(\S+)\s*->\s*(\S+)\s*\((.+)\)',v)if isinstance(v,str)else None + if m:pairs.append((m[1],m[2])) + flags[3]=isinstance(violations,list)and all(isinstance(v,str)for v in violations)and violations==sorted(violations)and len(pairs)==3 and set(pairs)==VIOLATIONS + impact=doc.get('impact');direct=['lib/model/store.js'];trans=sorted(set(FILES)-{'lib/util/format.js',*direct}) + flags[4]=impact=={'target':'lib/util/format.js','direct':direct,'transitive':trans,'total':6} + paths=[v for edge in got for v in edge]+[x for c in (cycles if isinstance(cycles,list)else [])if isinstance(c,list)for x in c] + flags[5]=all(isinstance(x,str)and x in FILES and not x.startswith('/')and'..'not in Path(x).parts for x in paths) + return flags diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/original_check.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/original_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b0c155fafc97e8867503490060539e60eaf1f6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/original_check.py @@ -0,0 +1,148 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json, os, shutil, subprocess, sys, tempfile + +FILES = { +"lib/model/store.js": "// model layer: no dependencies on other layers\nexport class Store {\n constructor() { this.items = []; }\n add(item) { this.items.push(item); }\n all() { return this.items; }\n}\n", +"lib/util/format.js": "export function fmt(n) { return n.toFixed(2); }\nexport function label(s) { return '[' + s + ']'; }\n", +"lib/data/repo.js": "import { Store } from '../model/store.js';\nimport { fmt } from '../util/format.js';\nimport { summarize } from '../analyzer/summary.js';\n\nconst store = new Store();\nexport function put(x) { store.add(x); }\nexport function report() { return summarize(store.all()) + ' avg=' + fmt(1); }\n", +"lib/analyzer/summary.js": "import { fmt } from '../util/format.js';\nimport { report } from '../data/repo.js';\n\nexport function summarize(items) {\n if (!items.length) return 'empty';\n return 'count=' + items.length;\n}\nexport function full() { return report(); }\n", +"bin/main.js": "// entry point: may import from lib only\nimport { put, report } from '../lib/data/repo.js';\nimport { label } from '../lib/util/format.js';\n\nput(3);\nconsole.log(label(report()));\n", +} + +EXPECTED_EDGES = { + ("lib/data/repo.js","lib/model/store.js"), + ("lib/data/repo.js","lib/util/format.js"), + ("lib/data/repo.js","lib/analyzer/summary.js"), + ("lib/analyzer/summary.js","lib/util/format.js"), + ("lib/analyzer/summary.js","lib/data/repo.js"), + ("bin/main.js","lib/data/repo.js"), + ("bin/main.js","lib/util/format.js"), +} + +MUST_VIOLATE = ["lib/data/repo.js -> lib/util/format.js", "lib/data/repo.js -> lib/analyzer/summary.js"] +MUST_NOT_VIOLATE = ["lib/analyzer/summary.js -> lib/util/format.js", "lib/analyzer/summary.js -> lib/model/store.js", "bin/main.js -> lib/data/repo.js", "bin/main.js -> lib/util/format.js", "lib/data/repo.js -> lib/model/store.js"] + +KNOWN = set(FILES) + +def rel_ok(p): + if not isinstance(p, str) or not p or "\\" in p or p.startswith("/") or ".." in p.split("/"): + return False + return p in KNOWN + +def find_candidate(): + for c in ("/candidate/analyze.py", "/candidate/analyze.py/analyze.py"): + if os.path.isfile(c): + return c + if os.path.isfile("/answer.txt"): + return "/answer.txt" + return None + +def main(): + checks = [None]*6 + tmp = tempfile.mkdtemp(dir="/tmp") + try: + for rel, content in FILES.items(): + full = os.path.join(tmp, rel) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w") as f: + f.write(content) + src = find_candidate() + report = None + if src is None: + checks[0] = (False, "no analyze.py found in /candidate or /answer.txt") + else: + try: + shutil.copy(src, os.path.join(tmp, "analyze.py")) + except Exception as e: + checks[0] = (False, "could not stage analyze.py: %s" % e) + src = None + if src is not None and checks[0] is None: + try: + r = subprocess.run([sys.executable, "analyze.py"], cwd=tmp, + capture_output=True, text=True, timeout=60) + rp = os.path.join(tmp, "report.") + if not os.path.isfile(rp): + checks[0] = (False, "analyze.py ran (rc=%d) but did not write 'report.'" % r.returncode) + else: + try: + report = json.load(open(rp)) + checks[0] = (True, "analyze.py ran and wrote a parseable report.") + except Exception as e: + checks[0] = (False, "report. is not valid JSON: %s" % e) + except subprocess.TimeoutExpired: + checks[0] = (False, "analyze.py timed out") + except Exception as e: + checks[0] = (False, "failed to run analyze.py: %s" % e) + + if report is None: + for i in range(1, 6): + checks[i] = (False, "no valid report. produced") + else: + edges = report.get("edges") + got = set() + edges_ok = isinstance(edges, list) + if edges_ok: + for e in edges: + if isinstance(e, dict) and rel_ok(e.get("from")) and rel_ok(e.get("to")): + got.add((e["from"], e["to"])) + else: + edges_ok = False + missing = EXPECTED_EDGES - got + checks[1] = (edges_ok and not missing, + "all 7 expected edges present" if (edges_ok and not missing) + else "missing/malformed edges: %s" % sorted(missing) if edges_ok else "edges malformed") + + cycles = report.get("cycles") + found = False + if isinstance(cycles, list): + for c in cycles: + if isinstance(c, list) and len(c) >= 2: + s = [x for x in c if isinstance(x, str)] + if "lib/data/repo.js" in s and "lib/analyzer/summary.js" in s: + found = True + checks[2] = (found, "cycle between repo.js and summary.js reported" if found else "expected repo<->summary cycle not found in cycles") + + viols = report.get("violations") + vlist = viols if isinstance(viols, list) else [] + vstrs = [v for v in vlist if isinstance(v, str)] + miss_v = [m for m in MUST_VIOLATE if not any(m in v for v in vstrs)] + bad_v = [m for m in MUST_NOT_VIOLATE if any(m in v for v in vstrs)] + ok = isinstance(viols, list) and not miss_v and not bad_v + reason = "violations correct" if ok else ("missing violations: %s; " % miss_v if miss_v else "") + ("wrongly flagged: %s" % bad_v if bad_v else "" if ok else "violations malformed") + checks[3] = (ok, reason) + + imp = report.get("impact") + ok = isinstance(imp, dict) + detail = "impact malformed" + if ok: + direct = imp.get("direct"); trans = imp.get("transitive"); total = imp.get("total") + exp_direct = {"bin/main.js", "lib/analyzer/summary.js", "lib/data/repo.js"} + ok = (imp.get("target") == "lib/util/format.js" + and isinstance(direct, list) and set(direct) == exp_direct and len(direct) == 3 + and isinstance(trans, list) and len(trans) == 0 + and total == 3) + detail = "impact correct" if ok else "impact wrong: target=%r direct=%r transitive=%r total=%r" % (imp.get("target"), direct, trans, total) + checks[4] = (ok, detail) + + paths = [] + if isinstance(edges, list): + for e in edges: + if isinstance(e, dict): + paths += [e.get("from"), e.get("to")] + if isinstance(cycles, list): + for c in cycles: + if isinstance(c, list): paths += c + if isinstance(imp, dict): + paths += [imp.get("target")] + for k in ("direct", "transitive"): + v = imp.get(k) + if isinstance(v, list): paths += v + bad = [p for p in paths if not rel_ok(p)] + checks[5] = (not bad, "all paths relative, forward-slash, matching layout" if not bad else "bad paths: %s" % bad) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + print(json.dumps({"checks": [{"id": str(i), "passed": bool(p), "reason": r} for i, (p, r) in enumerate(checks)]})) + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/r10_support.py b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/r10_support.py new file mode 100644 index 0000000000000000000000000000000000000000..0709a48fdbd10e98f7beaea2bc598f7568372ef5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/r10_support.py @@ -0,0 +1,107 @@ +"""R10 evaluator helpers. Candidate programs are only run by the Docker harness.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import ast, contextlib, io, json, os, pathlib, shutil, sys, tokenize + +def combine(values): + values=list(values) + return False if any(v is False for v in values)else None if any(v is None for v in values)else True + +def candidate_root(): + return pathlib.Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_ROOT','/candidate'))) + +def copy_program(destination,skip=()): + root=candidate_root();destination=pathlib.Path(destination);destination.mkdir(parents=True,exist_ok=True) + skip=set(skip) + def ignored(directory,names): + relative=pathlib.Path(directory).relative_to(root) + return [n for n in names if n in ('__pycache__','.git','.venv')or str(relative/n)in skip] + shutil.copytree(root,destination,dirs_exist_ok=True,symlinks=True,ignore=ignored) + return destination + +def install_copy(skip=()): + original=shutil.copy + def copied(source,destination,*args,**kwargs): + source=pathlib.Path(source) + try:source.resolve().relative_to(candidate_root().resolve());local=True + except ValueError:local=False + if local and source.suffix=='.py': + target=pathlib.Path(destination) + if not target.is_dir():target=target.parent + copy_program(target,skip) + return original(source,destination,*args,**kwargs) + shutil.copy=copied + +def _constant(node,constants): + if isinstance(node,ast.Constant):return node.value + if isinstance(node,ast.Name):return constants.get(node.id) + if isinstance(node,(ast.List,ast.Tuple)): + values=[_constant(n,constants)for n in node.elts] + return values if all(v is not None for v in values)else None + if isinstance(node,ast.BinOp)and isinstance(node.op,ast.Add): + a,b=_constant(node.left,constants),_constant(node.right,constants) + return a+b if isinstance(a,str)and isinstance(b,str)else None + if isinstance(node,ast.Call)and isinstance(node.func,ast.Attribute)and node.func.attr=='join'and len(node.args)==1: + separator=_constant(node.func.value,constants);values=_constant(node.args[0],constants) + return separator.join(values)if isinstance(separator,str)and isinstance(values,list)and all(isinstance(v,str)for v in values)else None + if isinstance(node,ast.JoinedStr): + values=[_constant(n.value,constants)if isinstance(n,ast.FormattedValue)else _constant(n,constants)for n in node.values] + return ''.join(map(str,values))if all(v is not None for v in values)else None + return None + +def scan_stdlib(root,entries,banned=()): + return True, [], 'Deferred to public bounded runtime policy; no whole-source inference' + +def dependency(entry,banned=()): + return True + +def strict_json(text): + def unique(pairs): + result={} + for k,v in pairs: + if k in result:raise ValueError('duplicate JSON member: '+k) + result[k]=v + return result + return json.loads(text,object_pairs_hook=unique,parse_constant=lambda value:(_ for _ in()).throw(ValueError(value))) + +def strict_response(text): + import re + match=re.fullmatch(r'\s*```(?:json)?\s*\n(.*?)\n```\s*',text,re.S|re.I) + return strict_json(match[1]if match else text) + +def trusted_stdout(query_id): + import hashlib + path=pathlib.Path(os.environ.get('MYBENCH_TRUSTED_TRACE','/tool_trajectory.json')) + expected=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256') + try: + path.resolve().relative_to(candidate_root().resolve()) + return None + except ValueError:pass + try: + raw=path.read_bytes() + if not expected or hashlib.sha256(raw).hexdigest()!=expected:return None + trace=json.loads(raw) + metadata=json.loads(pathlib.Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text()) + binding=metadata.get('trusted_trace_binding',metadata.get('derived',{}).get('trusted_trace_binding',{})) + if binding.get('query_id')!=query_id or binding.get('trajectory_sha256')!=expected:return None + hashes=binding.get('candidate_file_sha256') + if not isinstance(hashes,dict)or not hashes:return None + for relative,digest in hashes.items(): + if pathlib.PurePosixPath(relative).is_absolute()or'..'in pathlib.PurePosixPath(relative).parts:return None + if hashlib.sha256((candidate_root()/relative).read_bytes()).hexdigest()!=digest:return None + except (OSError,ValueError):return None + if not isinstance(trace,dict)or not isinstance(trace.get('steps'),list):return None + outputs=[] + for step in trace['steps']: + observation=step.get('observation',{}) + results=observation.get('results',[])if isinstance(observation,dict)else[] + calls={str(c.get('tool_call_id')):c for c in step.get('tool_calls',[])if isinstance(c,dict)and c.get('function_name')in ('bash','exec_command','shell','terminal','run_shell_command')} + for result in results: + if isinstance(result,dict)and str(result.get('source_call_id'))in calls and result.get('content')is not None:outputs.append(str(result['content'])) + # A later successful printing may replace an earlier trial. Candidate + # formal answers and strings in tool arguments never enter this channel. + summaries=[output for output in outputs if re_search_summary(output)] + return summaries[-1]if summaries else '' + +def re_search_summary(output): + import re + return bool(re.search(r'(?m)^G\d+:\s*(?:platformer|grid_logic|tower_defense|top_down|ui_heavy)\s*$',output)) diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6b3edeb246b2ea18ad6385edf28bfec6bc0666d8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/grading/verified_config.json @@ -0,0 +1,86 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "ac993ee8a71a4ab4726c1662", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "graph_probe.py": "489c27f14aaa05bb6450fc7f87296022d4dbe8ddcefcf7f66c083fb0be63774e", + "original_check.py": "e1618214a64955e7dfcd211cd757fc13fcf9dba797b4e6c993b202a37852788e", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f245803a06b801617e2ec10e3bf5d2705663cbbcecbb21fff72555eaa9796161", + "r10_support.py": "40d42ef87dc72d111ac18afe6e413f07e8acbf342aac9d089b51e2c0a3dcefa6", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "48e25d5b56963e0e094fe22b59ddf1cd203a221ade0af78b97850b65ef5bda80", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + }, + "runtime_requirements": { + "family": "verified2_repaired_workspace", + "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "read_only_mounts": [ + "task:/source", + "task:/task", + "evaluator:/grader", + "candidate:/candidate", + "answer:/answer.txt" + ], + "writable_tmpfs": [ + "/app", + "/workspace", + "/tmp" + ], + "copy_completed_candidate_children_to_app_before_grader": true, + "entrypoint": [ + "python3", + "/grader/check.py" + ], + "working_directory": "/candidate", + "environment": { + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_CANDIDATE_PATH": "/candidate", + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1" + }, + "environment_names_detected": [ + "MYBENCH_CANDIDATE", + "MYBENCH_EPHEMERAL_WORKSPACE", + "MYBENCH_FIXTURE_MATERIALIZE" + ], + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_count": 6, + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "actual_original_success_criteria_count": 6, + "original_task_metadata_must_not_define_override_criterion_count": false, + "requires_external_actual_native_trace": false, + "requires_external_trusted_snapshot_binding": false, + "fresh_native_binding_must_not_require_historical_run_id": true, + "checker_can_execute_candidate_subprocesses": true, + "host_execution_forbidden": true, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "docker_image_payload_in_source_tree": false, + "runtime_missing": [], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "grader_timeout_seconds": 600 + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/bin/main.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/bin/main.js new file mode 100644 index 0000000000000000000000000000000000000000..159e548131d3ec87cc24ee2bae66f3227a04cfaa --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/bin/main.js @@ -0,0 +1,6 @@ +// entry point: may import from lib only +import { put, report } from '../lib/data/repo.js'; +import { label } from '../lib/util/format.js'; + +put(3); +console.log(label(report())); diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/analyzer/summary.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/analyzer/summary.js new file mode 100644 index 0000000000000000000000000000000000000000..a1a71922da62074d6a7558fdf7e3b71fa5fcbb9a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/analyzer/summary.js @@ -0,0 +1,8 @@ +import { fmt } from '../util/format.js'; +import { report } from '../data/repo.js'; + +export function summarize(items) { + if (!items.length) return 'empty'; + return 'count=' + items.length; +} +export function full() { return report(); } diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/data/repo.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/data/repo.js new file mode 100644 index 0000000000000000000000000000000000000000..8afb57eaaf82af15502a9e0124619dbeb5496376 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/data/repo.js @@ -0,0 +1,7 @@ +import { Store } from '../model/store.js'; +import { fmt } from '../util/format.js'; +import { summarize } from '../analyzer/summary.js'; + +const store = new Store(); +export function put(x) { store.add(x); } +export function report() { return summarize(store.all()) + ' avg=' + fmt(1); } diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/model/store.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/model/store.js new file mode 100644 index 0000000000000000000000000000000000000000..d6b464c90487f9ef31a00117c85fc53a4bc24a16 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/model/store.js @@ -0,0 +1,6 @@ +// model layer: no dependencies on other layers +export class Store { + constructor() { this.items = []; } + add(item) { this.items.push(item); } + all() { return this.items; } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/util/format.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/util/format.js new file mode 100644 index 0000000000000000000000000000000000000000..13cc1a0a741672fab8c3e3baa72227ea2a5db9b1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/util/format.js @@ -0,0 +1,2 @@ +export function fmt(n) { return n.toFixed(2); } +export function label(s) { return '[' + s + ']'; } diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/instruction.md b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ede3612f77c79de0ec7d5515e1a694e06535ae4c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/instruction.md @@ -0,0 +1,7 @@ +A small JavaScript project is provided under the workspace with a layered layout: lib/model/, lib/data/, lib/analyzer/, lib/util/, and bin/. Write a Python 3 script (standard library only) called analyze.py that: (1) recursively collects all .js files under lib/ and bin/; (2) extracts every import/require specifier using regexes for both ES module syntax (import ... from '...') and CommonJS (require('...')); (3) resolves relative specifiers to actual files, trying the exact path and then extensions .js, .ts, /index.js, /index.ts, and keeps only edges whose target is a collected project file; (4) builds a directed import graph and its reverse graph; (5) detects circular dependencies with a DFS and reports each cycle as a path of relative file paths; (6) enforces these layer rules and reports each violation as 'VIOLATION: -> ()': files in lib/model must not import from any other layer; for lib/data, lib/analyzer and lib/util apply the frozen Dart-package Skill Layer separation rules to the same-named JavaScript directories, allowing within-layer imports; files in bin/ may import only from lib/; (7) performs change-impact analysis for lib/util/format.js: using BFS on the reverse graph, list direct dependents and transitive dependents (relative paths, sorted) and a total affected count; (8) writes a JSON report to report. with keys: "edges" (list of {from,to} relative paths, sorted), "cycles" (list of cycles, each a list of relative paths), "violations" (sorted list of the violation strings), "impact" ({"target":"lib/util/format.js","direct":[...],"transitive":[...],"total":N}). Run the script and produce report.. +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/ac993ee8a71a4ab4726c1662/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ba0a0fbae2e3be4c89215ebb267b8c02e139bbdc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/SKILL.md @@ -0,0 +1,3 @@ +# Multi-skill source bundle + +Private source bundle wrapper. The original skills are in members/. diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M000/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M000/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c099c940d90f0d6a1e63ad7ba14bbe6ced0ba3f9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M000/SKILL.md @@ -0,0 +1,56 @@ +--- +name: validate-architecture +description: Verify architectural consistency and dependency rules +trigger: when the user asks about architecture, rules, conventions, or dependency validation +--- + +# Validate Architecture + +When invoked: + +1. Detect project structure: + - Analyze `lib/` directory layout. + - Identify internal packages and subdirectories (`analyzer/`, `data/`, `model/`, `util/`). + - Note the `bin/` entry point. + +2. Analyze dependencies between modules: + - Map which `lib/` subdirectories import from which others. + - Track imports across package boundaries. + +3. Verify architecture rules for Dart packages: + + ### Package boundaries + - Public API should be minimal and intentional. + - Internal implementation details should not be exposed. + - Files outside `lib/` (e.g., `bin/`, `test/`) should not be imported by `lib/`. + + ### Layer separation + - `lib/model/` should have minimal dependencies (ideally none on other layers). + - `lib/data/` may depend on `model/` but not on `analyzer/` or `util/`. + - `lib/analyzer/` may depend on `model/` and `util/`. + - `lib/util/` should be independent of other layers. + - `bin/main.dart` should only depend on the public API entry point. + +4. Detect: + + ### Violations + - Cyclic dependencies between packages/modules. + - Forbidden dependencies (e.g., data layer importing analyzer). + - Unused modules or files. + - Internal implementation leaks (private files imported externally). + + ### Warnings + - Overly broad exports. + - Files with too many dependencies. + - Modules with unclear responsibilities. + +5. Produce a report with: + + ### Violations + Critical issues that break architectural rules. + + ### Warnings + Potential issues or code smells. + + ### Recommendations + Suggested improvements for the module structure and dependency graph. diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ecc44dbf8881268bbb550e48997c4afe4dfd782a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/SKILL.md @@ -0,0 +1,152 @@ +--- +name: dependency-analyzer +display-name: Dependency Analyzer +description: 依赖分析技能 - 导入图构建、变更影响分析、CVE可达性、循环依赖检测 +version: 1.0.0 +category: analysis +user-invocable: true +tags: [dependency, import, graph, impact, circular, vulnerability, license] +capabilities: + [ + import-graph, + impact-analysis, + circular-detection, + vulnerability-reachability, + license-check, + ] +tools: + - file_reader + - code_analyzer +handler: ./handler.js +instructions: | + Use this skill when the user needs to understand module dependencies, analyze the + impact of code changes, detect circular dependencies, or check dependency vulnerabilities. + Build import/require graphs from source code and npm/pip/maven dependency trees. + Provide change impact analysis: given a file modification, enumerate all affected + downstream consumers. For security, perform reachability analysis to determine if + CVEs in dependencies actually affect the application. +examples: + - input: "/dependency-analyzer src/main/llm/session-manager.js --impact" + output: "Impact analysis: 14 files depend on session-manager. Changes affect: conversation-ipc, manus-optimizations, context-engineering..." + - input: "/dependency-analyzer --circular src/main/" + output: "Found 2 circular dependencies: llm/→hooks/→llm/ and browser/→actions/→browser/" + - input: "/dependency-analyzer package-lock.json --vulnerabilities" + output: "12 CVEs found, 3 reachable from application code, 9 in unused code paths" +os: [win32, darwin, linux] +author: ChainlessChain +--- + +# 依赖分析技能 + +## 描述 + +构建代码库的模块导入图和包依赖树。提供变更影响分析、循环依赖检测、CVE 可达性分析和许可证兼容性检查。 + +## 使用方法 + +``` +/dependency-analyzer [目标] [选项] +``` + +## 分析类型 + +### 导入图构建 + +``` +/dependency-analyzer src/main/ --graph +``` + +解析所有 `import`/`require` 语句,构建模块依赖图: + +- 直接依赖和传递依赖 +- 导出/导入的具体符号 +- Mermaid 图表输出 + +### 变更影响分析 + +``` +/dependency-analyzer src/main/llm/session-manager.js --impact +``` + +给定一个文件修改,追踪所有受影响的下游消费者: + +- 直接导入者 +- 传递依赖者 +- 受影响的 IPC 处理器 +- 受影响的测试文件 + +### 循环依赖检测 + +``` +/dependency-analyzer --circular src/main/ +``` + +使用拓扑排序检测循环依赖: + +- 列出所有循环路径 +- 建议解耦方案 +- 影响严重度评估 + +### CVE 可达性分析 + +``` +/dependency-analyzer package-lock.json --vulnerabilities +``` + +不仅列出 CVE,还追踪漏洞是否可达: + +- 运行 `npm audit` 获取 CVE 列表 +- 追踪漏洞函数是否被应用代码调用 +- 标记"可达"(需修复)vs "不可达"(低优先级) +- 修复建议(版本升级、替代包) + +### 许可证检查 + +``` +/dependency-analyzer --licenses +``` + +扫描所有依赖的许可证: + +- 许可证类型汇总 (MIT, Apache, GPL, BSD 等) +- 兼容性矩阵 +- GPL 传染风险警告 + +## 输出格式 + +### 影响分析报告 + +``` +Impact Analysis: session-manager.js +==================================== +Direct dependents: 6 files + → conversation-ipc.js (imports: SessionManager) + → manus-optimizations.js (imports: SessionManager) + → context-engineering.js (imports: SessionManager) + ... + +Transitive dependents: 8 additional files +Affected IPC handlers: 12 +Affected tests: 5 test files +Risk level: HIGH (core module) +``` + +## 示例 + +分析影响范围: + +``` +/dependency-analyzer src/main/database.js --impact +``` + +检测循环依赖: + +``` +/dependency-analyzer --circular src/main/ +``` + +漏洞可达性分析: + +``` +/dependency-analyzer package-lock.json --vulnerabilities --reachability +``` diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/handler.js b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/handler.js new file mode 100644 index 0000000000000000000000000000000000000000..6c1bebda040718952162d35f05d9c458769f2c4f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/handler.js @@ -0,0 +1,511 @@ +/** + * Dependency Analyzer Skill Handler + * + * Builds import/require graphs, detects circular dependencies, + * performs change impact analysis, and checks npm audit vulnerabilities. + */ + +const fs = require("fs"); +const path = require("path"); +const { execSync } = require("child_process"); +const { logger } = require("../../../../../utils/logger.js"); + +const IGNORE_DIRS = new Set([ + "node_modules", + ".git", + "dist", + "build", + "coverage", + ".cache", +]); +const CODE_EXTS = new Set(["js", "mjs", "ts", "tsx", "jsx", "vue"]); + +module.exports = { + async init(skill) { + logger.info("[DependencyAnalyzer] Handler initialized"); + }, + + async execute(task, context = {}, skill) { + const input = task.input || task.args || ""; + const { action, options } = parseInput(input, context); + + logger.info(`[DependencyAnalyzer] Action: ${action}`, { options }); + + try { + switch (action) { + case "impact": + return await handleImpact(options.targetPath, options.targetDir); + case "circular": + return await handleCircular(options.targetDir); + case "vulnerabilities": + return await handleVulnerabilities(options.targetDir); + case "licenses": + return await handleLicenses(options.targetDir); + default: + return await handleGraph(options.targetDir); + } + } catch (error) { + logger.error(`[DependencyAnalyzer] Error: ${error.message}`); + return { + success: false, + error: error.message, + message: `Dependency analysis failed: ${error.message}`, + }; + } + }, +}; + +function parseInput(input, context) { + const parts = (input || "").trim().split(/\s+/); + const options = { + targetDir: context.workspacePath || process.cwd(), + targetPath: null, + }; + let action = "graph"; + + for (let i = 0; i < parts.length; i++) { + const p = parts[i]; + if (p === "--impact") { + action = "impact"; + } else if (p === "--circular") { + action = "circular"; + } else if (p === "--graph") { + action = "graph"; + } else if (p === "--vulnerabilities") { + action = "vulnerabilities"; + } else if (p === "--licenses") { + action = "licenses"; + } else if (p && !p.startsWith("-")) { + const resolved = path.resolve(options.targetDir, p); + if (fs.existsSync(resolved)) { + const stat = fs.statSync(resolved); + if (stat.isDirectory()) { + options.targetDir = resolved; + } else { + options.targetPath = resolved; + } + } + } + } + + return { action, options }; +} + +function collectFiles(dir, maxDepth = 6, depth = 0) { + const files = []; + if (depth > maxDepth || !fs.existsSync(dir)) { + return files; + } + + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return files; + } + + for (const entry of entries) { + if ( + entry.isDirectory() && + !IGNORE_DIRS.has(entry.name) && + !entry.name.startsWith(".") + ) { + files.push( + ...collectFiles(path.join(dir, entry.name), maxDepth, depth + 1), + ); + } else if (entry.isFile()) { + const ext = path.extname(entry.name).slice(1); + if (CODE_EXTS.has(ext)) { + files.push(path.join(dir, entry.name)); + } + if (files.length >= 500) { + return files; + } + } + } + return files; +} + +function extractImports(filePath) { + let content; + try { + content = fs.readFileSync(filePath, "utf-8"); + } catch { + return []; + } + + const imports = []; + + // ES6 imports: import ... from '...' + const esRe = /import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g; + let m; + while ((m = esRe.exec(content)) !== null) { + imports.push(m[1]); + } + + // CommonJS require: require('...') + const cjsRe = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g; + while ((m = cjsRe.exec(content)) !== null) { + imports.push(m[1]); + } + + return imports; +} + +function resolveImport(importPath, fromFile, baseDir) { + if (!importPath.startsWith(".") && !importPath.startsWith("/")) { + return null; + } // npm package + + const fromDir = path.dirname(fromFile); + const resolved = path.resolve(fromDir, importPath); + + // Try extensions + const exts = [ + ".js", + ".ts", + ".mjs", + ".jsx", + ".tsx", + ".vue", + "/index.js", + "/index.ts", + ]; + if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) { + return resolved; + } + for (const ext of exts) { + if (fs.existsSync(resolved + ext)) { + return resolved + ext; + } + } + return null; +} + +function buildImportGraph(files, baseDir) { + const graph = new Map(); // file -> [imported files] + const reverseGraph = new Map(); // file -> [files that import it] + + for (const file of files) { + const imports = extractImports(file); + const resolvedImports = []; + + for (const imp of imports) { + const resolved = resolveImport(imp, file, baseDir); + if (resolved && files.includes(resolved)) { + resolvedImports.push(resolved); + if (!reverseGraph.has(resolved)) { + reverseGraph.set(resolved, []); + } + reverseGraph.get(resolved).push(file); + } + } + + graph.set(file, resolvedImports); + } + + return { graph, reverseGraph }; +} + +async function handleGraph(targetDir) { + const files = collectFiles(targetDir); + const { graph } = buildImportGraph(files, targetDir); + + const edges = []; + for (const [file, imports] of graph) { + for (const imp of imports) { + edges.push({ + from: path.relative(targetDir, file), + to: path.relative(targetDir, imp), + }); + } + } + + const fileCount = files.length; + const edgeCount = edges.length; + + // Top files by import count + const importCounts = {}; + for (const edge of edges) { + importCounts[edge.to] = (importCounts[edge.to] || 0) + 1; + } + + const topImported = Object.entries(importCounts) + .sort(([, a], [, b]) => b - a) + .slice(0, 15); + + const report = + `Dependency Graph\n${"=".repeat(25)}\n` + + `Files: ${fileCount}, Edges: ${edgeCount}\n\n` + + `Most imported files:\n` + + topImported + .map(([file, count]) => ` ${file} (imported by ${count} files)`) + .join("\n"); + + return { + success: true, + result: { fileCount, edgeCount, topImported, edges: edges.slice(0, 100) }, + message: report, + }; +} + +async function handleImpact(targetPath, targetDir) { + if (!targetPath) { + return { success: false, message: "Usage: --impact " }; + } + + const files = collectFiles(targetDir); + const { reverseGraph } = buildImportGraph(files, targetDir); + + // BFS for transitive dependents + const visited = new Set(); + const queue = [targetPath]; + const directDeps = []; + const transitiveDeps = []; + let level = 0; + + while (queue.length > 0) { + const size = queue.length; + for (let i = 0; i < size; i++) { + const current = queue.shift(); + if (visited.has(current)) { + continue; + } + visited.add(current); + + const dependents = reverseGraph.get(current) || []; + for (const dep of dependents) { + if (!visited.has(dep)) { + if (level === 0) { + directDeps.push(dep); + } else { + transitiveDeps.push(dep); + } + queue.push(dep); + } + } + } + level++; + if (level > 10) { + break; + } // prevent infinite loops + } + + const relTarget = path.relative(targetDir, targetPath); + const report = + `Impact Analysis: ${relTarget}\n${"=".repeat(40)}\n\n` + + `Direct dependents: ${directDeps.length} files\n` + + directDeps.map((f) => ` -> ${path.relative(targetDir, f)}`).join("\n") + + `\n\nTransitive dependents: ${transitiveDeps.length} files\n` + + transitiveDeps + .slice(0, 20) + .map((f) => ` -> ${path.relative(targetDir, f)}`) + .join("\n") + + `\n\nTotal affected: ${directDeps.length + transitiveDeps.length} files` + + `\nRisk level: ${directDeps.length > 10 ? "HIGH" : directDeps.length > 5 ? "MEDIUM" : "LOW"}`; + + return { + success: true, + result: { + target: relTarget, + directDeps: directDeps.length, + transitiveDeps: transitiveDeps.length, + }, + message: report, + }; +} + +async function handleCircular(targetDir) { + const files = collectFiles(targetDir); + const { graph } = buildImportGraph(files, targetDir); + + // Detect cycles using DFS + const cycles = []; + const visited = new Set(); + const inStack = new Set(); + const stackPath = []; + + function dfs(node) { + if (inStack.has(node)) { + const cycleStart = stackPath.indexOf(node); + if (cycleStart >= 0) { + const cycle = stackPath + .slice(cycleStart) + .map((f) => path.relative(targetDir, f)); + cycles.push(cycle); + } + return; + } + if (visited.has(node)) { + return; + } + + visited.add(node); + inStack.add(node); + stackPath.push(node); + + const deps = graph.get(node) || []; + for (const dep of deps) { + dfs(dep); + } + + inStack.delete(node); + stackPath.pop(); + } + + for (const file of files) { + if (!visited.has(file)) { + dfs(file); + } + } + + const report = + cycles.length > 0 + ? `Circular Dependencies Found: ${cycles.length}\n${"=".repeat(40)}\n\n` + + cycles + .slice(0, 10) + .map((cycle, i) => `${i + 1}. ${cycle.join(" -> ")} -> ${cycle[0]}`) + .join("\n\n") + : `No circular dependencies found in ${files.length} files.`; + + return { + success: true, + result: { cycles: cycles.slice(0, 20), fileCount: files.length }, + message: report, + }; +} + +async function handleVulnerabilities(targetDir) { + let auditOutput; + try { + auditOutput = execSync("npm audit --json 2>/dev/null", { + encoding: "utf-8", + cwd: targetDir, + timeout: 30000, + stdio: ["pipe", "pipe", "pipe"], + }); + } catch (err) { + // npm audit returns non-zero when vulnerabilities exist + auditOutput = err.stdout || ""; + } + + if (!auditOutput) { + return { + success: true, + result: { vulnerabilities: [] }, + message: "npm audit returned no data. Ensure package-lock.json exists.", + }; + } + + let audit; + try { + audit = JSON.parse(auditOutput); + } catch { + return { + success: true, + result: {}, + message: "Could not parse npm audit output.", + }; + } + + const vulns = audit.vulnerabilities || {}; + const summary = audit.metadata || {}; + + const vulnList = Object.entries(vulns).map(([pkg, info]) => ({ + package: pkg, + severity: info.severity, + via: Array.isArray(info.via) + ? info.via.filter((v) => typeof v === "string") + : [], + fixAvailable: !!info.fixAvailable, + })); + + const bySeverity = { critical: 0, high: 0, moderate: 0, low: 0 }; + for (const v of vulnList) { + if (bySeverity[v.severity] !== undefined) { + bySeverity[v.severity]++; + } + } + + const report = + `Vulnerability Report\n${"=".repeat(25)}\n` + + `Total: ${vulnList.length} vulnerable packages\n` + + `Critical: ${bySeverity.critical}, High: ${bySeverity.high}, Moderate: ${bySeverity.moderate}, Low: ${bySeverity.low}\n\n` + + vulnList + .sort((a, b) => { + const order = { critical: 0, high: 1, moderate: 2, low: 3 }; + return (order[a.severity] || 4) - (order[b.severity] || 4); + }) + .slice(0, 30) + .map( + (v) => + ` ${v.severity.toUpperCase()} ${v.package}${v.fixAvailable ? " (fix available)" : ""}`, + ) + .join("\n"); + + return { + success: true, + result: { vulnerabilities: vulnList, bySeverity }, + message: report, + }; +} + +async function handleLicenses(targetDir) { + const pkgLockPath = path.join(targetDir, "node_modules"); + if (!fs.existsSync(pkgLockPath)) { + return { + success: false, + message: "node_modules not found. Run npm install first.", + }; + } + + const licenses = {}; + let entries; + try { + entries = fs.readdirSync(pkgLockPath, { withFileTypes: true }); + } catch { + return { success: false, message: "Cannot read node_modules." }; + } + + let scanned = 0; + for (const entry of entries) { + if (!entry.isDirectory() || entry.name.startsWith(".")) { + continue; + } + const pkgJsonPath = path.join(pkgLockPath, entry.name, "package.json"); + if (!fs.existsSync(pkgJsonPath)) { + continue; + } + + try { + const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8")); + const license = pkg.license || "UNKNOWN"; + licenses[license] = (licenses[license] || 0) + 1; + scanned++; + } catch { + /* skip */ + } + + if (scanned >= 500) { + break; + } + } + + const sorted = Object.entries(licenses).sort(([, a], [, b]) => b - a); + const gplWarnings = sorted.filter( + ([lic]) => /GPL/i.test(lic) && !/LGPL/i.test(lic), + ); + + const report = + `License Report\n${"=".repeat(20)}\nPackages scanned: ${scanned}\n\n` + + sorted.map(([lic, count]) => ` ${lic}: ${count} packages`).join("\n") + + (gplWarnings.length > 0 + ? `\n\n GPL Warning: ${gplWarnings.map(([lic, count]) => `${lic} (${count})`).join(", ")} - may have copyleft requirements` + : ""); + + return { + success: true, + result: { licenses, scanned, gplWarnings: gplWarnings.map(([lic]) => lic) }, + message: report, + }; +} diff --git a/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/task.json b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/task.json new file mode 100644 index 0000000000000000000000000000000000000000..44e9a9d7b84c47401c9ec6c3c30a772ff9fcedee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/task.json @@ -0,0 +1,155 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "ac993ee8a71a4ab4726c1662", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "ac993ee8a71a4ab4726c1662", + "outputs": [ + "analyze.py", + "report." + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "450202932be3f6ef368e619c323fb1120ab2ae1940ec76c2d793ded0b6686460", + "files": { + "SKILL.md": "c026851d0b60cc1e9687b03a24dfadf626b1e352c79c1d0b3ee85fc61ff4766c", + "members/M000/SKILL.md": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50", + "members/M001/SKILL.md": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49", + "members/M001/handler.js": "23e720a63e968b5129569f915f1227fe7ff745d35d664450bab6a257c419aa27" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/lib/model/store.js", + "workspace_target": "lib/model/store.js", + "sha256": "a3f6d8663d055e39d6b6747b69580c5c6e7b1e6581b692ee8ad91c1a32999d1c" + }, + { + "source": "inputs/lib/util/format.js", + "workspace_target": "lib/util/format.js", + "sha256": "2f7d90b4f059ee5c8276db9bf0ef95084e2871d3d3165117bf0e95e7c3c54591" + }, + { + "source": "inputs/lib/data/repo.js", + "workspace_target": "lib/data/repo.js", + "sha256": "bbe2f1ceccc8dde7061f90b315045309e7ae5bb45cd670fbc3f6f99d22f94aff" + }, + { + "source": "inputs/lib/analyzer/summary.js", + "workspace_target": "lib/analyzer/summary.js", + "sha256": "62aba452b46669556b461718d0b09f93d7a4b1f0799911f9eb81a59d240195ba" + }, + { + "source": "inputs/bin/main.js", + "workspace_target": "bin/main.js", + "sha256": "25370136857dfdb033d21fd56ff6e62e77024b8474cc87cd3ccabb2d27c65749" + } + ], + "skill_packages": [ + { + "package_path": "skill/members/M000", + "content_hash": "4d1d5042054ac7ac2f427041b67bfb2238573c0b909b162a9612d7621fb88424", + "member_id": "M000" + }, + { + "package_path": "skill/members/M001", + "content_hash": "771b1f7265a1bfd8972019b920aafaf6dc891f3be2ad43bd74c101f1c1fff5a4", + "member_id": "M001" + } + ] + }, + "source_group": { + "schema_version": "multi-skill-source-v1", + "group_id": "48067dafeda4b985974ccc55", + "members": [ + { + "skill_id": "skill-5663c6660ebc397463aed38b", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/56/skill-5663c6660ebc397463aed38b", + "snapshot": { + "sha256": "4d1d5042054ac7ac2f427041b67bfb2238573c0b909b162a9612d7621fb88424", + "files": { + "SKILL.md": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50" + }, + "bytes": 1846 + }, + "skill_md_sha256": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50", + "member_id": "M000", + "package_path": "members/M000" + }, + { + "skill_id": "skill-9e3d94e0234104258cb84843", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/9e/skill-9e3d94e0234104258cb84843", + "snapshot": { + "sha256": "771b1f7265a1bfd8972019b920aafaf6dc891f3be2ad43bd74c101f1c1fff5a4", + "files": { + "SKILL.md": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49", + "handler.js": "23e720a63e968b5129569f915f1227fe7ff745d35d664450bab6a257c419aa27" + }, + "bytes": 16979 + }, + "skill_md_sha256": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49", + "member_id": "M001", + "package_path": "members/M001" + } + ] + }, + "label_scope": { + "comparison": "none_vs_all_members", + "unit": "skill_group", + "individual_member_necessity_tested": false + }, + "member_contributions": [ + { + "member_id": "M000", + "contribution": "Layered architecture rules (model independent, data may depend only on model, analyzer on model/util, util independent, bin only on lib) and the violation-report format used to classify forbidden dependency edges", + "relationship": "Supplies the rule set the import graph is validated against; violations are edges found by the other member's graph construction" + }, + { + "member_id": "M001", + "contribution": "Import extraction regexes for ES modules and CommonJS, relative-path resolution with extension/index fallback, graph + reverse graph construction, DFS cycle detection, and BFS transitive impact analysis", + "relationship": "Builds the dependency graph and impact/cycle analyses that the layer rules are evaluated over, producing the report contents" + } + ], + "autograde_runtime_contract": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60 + }, + "automatic_evaluation_runtime": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/acf457a314e435c5_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_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/acf457a314e435c5_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_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/acf457a314e435c5_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_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/acf457a314e435c5_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/acf457a314e435c5_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/acf457a314e435c5_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_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/acf457a314e435c5_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..400da41145f3344c7a6d6d3b24a9810e6c6f59cb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,554 @@ +"""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 math +import posixpath +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 _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + try: + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + except RecursionError as error: + raise ValueError('Candidate JSON nesting is too deep') from error + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + try:is_finite=finite(result) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + if not is_finite:raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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(_strict_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_equal(actual, 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/acf457a314e435c5_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..d0d8500514ebff6eb05e099b84e723a9a07d9220 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "acf457a314e435c5_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "1df3b6f6e233d6567cc9c93efc5dd176cb098c6d9f383a9f1d6c80501ddfaa19", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9bc4f00d562acbc2de227208de50bf43bb479502 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/instruction.md @@ -0,0 +1 @@ +We're drafting org-level sync and visibility policies for Engram and need the canonical rule wording. Four questions: what remains the default mental model for data handling in Engram; where do org-wide security controls belong; which Engram control defines what the organization currently allows; and when a policy blocks sync, how should the system behave instead of dropping data silently? 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/acf457a314e435c5_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..99922bc938048612e0ed07844aee60125011d2df --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/skill/SKILL.md @@ -0,0 +1,36 @@ +--- +name: engram-business-rules +description: > + Product and business-rule guardrails for Engram. Trigger: Any change that + affects sync behavior, project controls, permissions, or memory semantics. +license: Apache-2.0 +metadata: + author: gentleman-programming + version: "1.0" +--- + +## When to Use + +Use this skill when: +- Changing enrollment, sync, auth, admin controls, or cloud behavior +- Implementing project-level or org-level policy +- Adjusting what data appears locally vs remotely + +--- + +## Product Rules + +1. Local-first remains the default mental model. +2. Org-wide security controls belong in cloud, not only in local clients. +3. Project sync policy must be enforceable server-side if it is meant for admins. +4. UI controls must map to real business rules, never fake toggles. +5. Data visibility and sync permissions must be deterministic and testable. + +--- + +## Sync Rules + +- Enrollment controls what may sync from local. +- Cloud pause controls what the organization currently allows. +- When a policy blocks sync, fail loudly rather than dropping data silently. +- Preserve auditability whenever admin policy changes behavior. diff --git a/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/task.json b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..65fe34600d5d2e9154dcb82444f6b4a0e5c123db --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "acf457a314e435c5", + "query_id": "acf457a314e435c5_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "e682803f9137854a0cb35dcdb4525331708770b70c2fcfc095c3bbb78f206acb", + "name": "engram-business-rules", + "package_path": "skill", + "install_name": "engram-business-rules-463e1031" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "e682803f9137854a0cb35dcdb4525331708770b70c2fcfc095c3bbb78f206acb", + "files": { + "SKILL.md": "0832c148a3f12da6b59142b07ae3b3c6967389945ddc567ed8df5e7bfb3f738f" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "463e1031f1a05eb823497dda24d993dea5f775fad5be1be6d61a53d766c0396b" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_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/adc122d50c75da6b_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_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/adc122d50c75da6b_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_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/adc122d50c75da6b_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..7df3731ee96483e805072e7a024bebc9031ece0e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1291 @@ +"""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 math +import os +import re +import shlex +import subprocess +import tempfile +import tomllib +from pathlib import Path, PurePosixPath + + +WORKSPACE_EVALUATOR = "workspace_objective" +WORKSPACE_EVALUATOR_VERSION = 14 +SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14} +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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], + }) + # 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 = (_same_native_json_types(actual, check.get("expected")) and + _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": + lines = _shell_lines(path.read_text(encoding="utf-8")) + 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": + lines = _shell_lines(path.read_text(encoding="utf-8")) + 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": + lines = _shell_unconditional_lines( + path.read_text(encoding="utf-8")) + 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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + detail = (f"expected_unconditional={expected}; " + f"top_level_lines={lines[:30]}") + elif kind == "shell_straight_line": + source = path.read_text(encoding="utf-8") + passed = _shell_is_straight_line(source) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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): + return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else ( + False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"}) + 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 not stripped.startswith(("{", "[")) and + Path(stripped).is_dir()): + return evaluate_workspace(evaluator, stripped) + 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/adc122d50c75da6b_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_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/adc122d50c75da6b_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..400da41145f3344c7a6d6d3b24a9810e6c6f59cb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,554 @@ +"""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 math +import posixpath +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 _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + try: + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + except RecursionError as error: + raise ValueError('Candidate JSON nesting is too deep') from error + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + try:is_finite=finite(result) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + if not is_finite:raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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(_strict_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_equal(actual, 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/adc122d50c75da6b_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..27d5ec0a4d6d82af74b95bb7bcf950f7712d9542 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/grading/verified_config.json @@ -0,0 +1,98 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "adc122d50c75da6b_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "b3201595d67321c122f2f5585b515cb020470bc94ffd9d788c0c676091442284", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "5d8c0a66324bf53fe772cc22324dbb99955402294896750eda8cbeb0a5902432", + "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e84eccb1e8fd9aebf6d48011300deff5c54e666f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/instruction.md @@ -0,0 +1 @@ +We're booting our Godot authoritative host with --headless for a dedicated_server run and need to harden it before wiring up ENet networking. Two release questions: which script file is mandatory for detecting and initializing dedicated server logic on --headless / dedicated_server runs, and which script file must run before any untrusted get_var call to guard against RCE? Give each file name. Return one JSON object like {"answers":{"q1":"string","q2":"string"}}, replacing the placeholders with the bare file names. diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3b4f3f942f7e83b7a08d4338dc8d94e7c3638bdf --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/SKILL.md @@ -0,0 +1,143 @@ +--- +name: godot-server-architecture +description: "Expert blueprint for dedicated / headless multiplayer hosts: ENet/DTLS, authority validation, safe packet decode, matchmaker handoff, and health telemetry. Use when building authoritative servers, --headless hosts, or hardening host networking. Keywords: dedicated server, headless, ENet, DTLS, authority, safe_packet_decoder, multiplayer host, WebSocketMultiplayerPeer." +--- + +## Skill boundary (Do NOT Load) + +| Use **this skill** for | Use **godot-multiplayer-networking** for | +| :--- | :--- | +| `--headless` / dedicated export boot | Lobby UI, matchmaking UX, friend invites | +| ENet/DTLS host peer + safe decode | RPC signatures, `@rpc` gameplay handlers | +| Authority validation on privileged ops | MultiplayerSynchronizer / scene replication | +| Kick, health telemetry, matchmaker handoff | Client prediction, lag compensation | + +**Do NOT Load** lobby/RPC tutorial scripts from multiplayer-networking when only booting a host — follow Host Golden Path here first. + +## Host Golden Path (MANDATORY) + +1. **Headless detect/init** — **MANDATORY** [headless_init_manager.gd](scripts/headless_init_manager.gd) (`--headless` / `dedicated_server` feature). +2. **Safe decode** — **MANDATORY** [safe_packet_decoder.gd](scripts/safe_packet_decoder.gd) before any untrusted `get_var`. +3. **Host peer** — [enet_optimized_host.gd](scripts/enet_optimized_host.gd); add [dtls_secure_server.gd](scripts/dtls_secure_server.gd) when encrypting UDP. +4. **Authority** — [server_authority_validator.gd](scripts/server_authority_validator.gd) on every privileged RPC. +5. **Ops** — [peer_kick_manager.gd](scripts/peer_kick_manager.gd), [server_health_exporter.gd](scripts/server_health_exporter.gd); matchmaker handoff via [server_matchmaker_client.gd](scripts/server_matchmaker_client.gd). + +## Available Scripts + +### [headless_init_manager.gd](scripts/headless_init_manager.gd) +Detect/initialize dedicated server logic for `--headless` / `dedicated_server`. + +### [headless_manager.gd](scripts/headless_manager.gd) +Headless runtime manager companion patterns. + +### [enet_optimized_host.gd](scripts/enet_optimized_host.gd) +High-performance ENet UDP hosts with bandwidth/client limits. + +### [dtls_secure_server.gd](scripts/dtls_secure_server.gd) +DTLS + X509 hardening for ENet UDP. + +### [safe_packet_decoder.gd](scripts/safe_packet_decoder.gd) +Forbid object decoding on untrusted packets (RCE guard). + +### [manual_network_poll.gd](scripts/manual_network_poll.gd) +Manual `multiplayer.poll()` when auto-poll is disabled. + +### [isolated_multiplayer_api.gd](scripts/isolated_multiplayer_api.gd) +Isolated MultiplayerAPI instances (client+server in one process). + +### [server_authority_validator.gd](scripts/server_authority_validator.gd) +`get_remote_sender_id()` gates for authoritative requests. + +### [websocket_server_compat.gd](scripts/websocket_server_compat.gd) +HTML5-compatible `WebSocketMultiplayerPeer` hosts. + +### [peer_kick_manager.gd](scripts/peer_kick_manager.gd) +Graceful peer termination with reason propagation. + +### [server_matchmaker_client.gd](scripts/server_matchmaker_client.gd) +Load-balancer / matchmaker handoff to game hosts. + +### [server_health_exporter.gd](scripts/server_health_exporter.gd) +Headless telemetry for monitoring stacks. + +### [physics_server_direct.gd](scripts/physics_server_direct.gd) / [rid_performance_server.gd](scripts/rid_performance_server.gd) +Optional host-side RID sim — **only when** node physics cannot hold tick budget: > ~200 active bodies per tick, or headless host CPU > 70% on physics step with nodes. Criteria: profile first; if SceneTree bodies dominate, prefer [godot-performance-optimization](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md). **Do NOT Load** RID scripts for ≤64 entity lobbies. + +## NEVER Do in Server Architecture (Host) + +- **NEVER trust the client** — Validate state, purchases, and damage on the authoritative host. +- **NEVER use `TRANSFER_MODE_RELIABLE` for continuous streams** — Prefer unreliable for high-rate transforms. +- **NEVER use `get_var(true)` on untrusted packets** — Object decode = RCE. **MANDATORY** safe_packet_decoder. +- **NEVER use TCP for fast-paced action** — Prefer ENet UDP (or WebSocket for HTML5 constraints). +- **NEVER run a dedicated server without stripping visuals** — Dedicated Server export / dummy drivers. +- **NEVER expect RPCs before `connected_to_server` / peer ready**. +- **NEVER assume `UNRELIABLE` packets arrive in order**. +- **NEVER leave `SceneTree.multiplayer_poll` false without manual `poll()`**. +- **NEVER mix incompatible engine/multiplayer protocol versions across peers**. +- **NEVER forget `free_rid` on server-created RIDs** if the host uses Physics/RenderingServer pools. + +## Host Patterns + +### Interest management +Large worlds: `MultiplayerSynchronizer.public_visibility = false` + visibility filters (AABB / grid) so the host does not sync the entire world to every peer. + +```gdscript +# Hook on synchronizer — filter peers by grid cell / AABB (no full tutorial) +func _visibility_filter(for_peer: int, node: Node) -> bool: + return _interest_grid.is_visible_to_peer(for_peer, node.global_position) +# Assign: synchronizer.set_visibility_filter(_visibility_filter) +``` + +### Health metrics +Watch host FPS, static memory (RID leaks), and orphan counts via [server_health_exporter.gd](scripts/server_health_exporter.gd). + +## Deep recipes (on demand) + +> LLM-ignorance rule: if a general agent would not know it before reading, it lives here or in `scripts/` — never delete, only move. + +| Topic | Reference | +|-------|-----------| +| RID canvas/physics cookbook | [rendering-physics-server-cookbook.md](references/rendering-physics-server-cookbook.md) | + +## Reference + +> Progressive disclosure: open Official Documentation links only when researching a specific API; load Related Skills when routing to a peer domain — do not preload the whole lattice. + +### Official Documentation +- [Using Servers](https://docs.godotengine.org/en/stable/tutorials/performance/using_servers.html) — RID-based RenderingServer/PhysicsServer/NavigationServer workflow when SceneTree nodes are too slow. +- [RenderingServer](https://docs.godotengine.org/en/stable/classes/class_renderingserver.html) — `canvas_item_*` / `instance_*` / `free_rid` for procedural draw and mesh swarms without MeshInstance nodes. +- [PhysicsServer3D](https://docs.godotengine.org/en/stable/classes/class_physicsserver3d.html) — `body_create`, space binding, and direct-state queries for headless authoritative simulation. +- [PhysicsServer2D](https://docs.godotengine.org/en/stable/classes/class_physicsserver2d.html) — 2D body/shape RIDs mirroring the same SceneTree-bypass pattern. +- [RID](https://docs.godotengine.org/en/stable/classes/class_rid.html) — opaque server handles; every `*_create()` needs a matching `free_rid` to avoid leaks. +- [High-level multiplayer](https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html) — authority, RPCs, and peer lifecycle for dedicated hosts and isolated MultiplayerAPI branches. +- [ENetMultiplayerPeer](https://docs.godotengine.org/en/stable/classes/class_enetmultiplayerpeer.html) — UDP host creation, channels/bandwidth limits, and DTLS host setup on `peer.host`. +- [WebSocket multiplayer](https://docs.godotengine.org/en/stable/tutorials/networking/websocket.html) — browser-compatible peer path when ENet UDP is unavailable (HTML5 clients). +- [Exporting for dedicated servers](https://docs.godotengine.org/en/stable/tutorials/export/exporting_for_dedicated_servers.html) — dedicated-server export presets and stripping visuals/audio for production hosts. +- [Command line tutorial](https://docs.godotengine.org/en/stable/tutorials/editor/command_line_tutorial.html) — `--headless` and CLI flags used by headless init/managers. +- [Binary serialization API](https://docs.godotengine.org/en/stable/tutorials/io/binary_serialization_api.html) — `get_var(false)` / object-decoding rules that block RCE on untrusted packets. +- [DTLSServer](https://docs.godotengine.org/en/stable/classes/class_dtlsserver.html) — DTLS accept path complementary to ENet `dtls_server_setup` with X509/TLSOptions. + +### Related Skills + +#### Prerequisites +- [godot-project-foundations](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-project-foundations/SKILL.md) — project layout, Autoloads, and feature tags that dedicated-server and headless launches depend on. +- [godot-gdscript-mastery](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-gdscript-mastery/SKILL.md) — typed RID arrays, `@rpc` annotations, and safe Variant decoding patterns used across server scripts. +- [godot-physics-3d](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-physics-3d/SKILL.md) — node-level PhysicsBody3D/space concepts before bypassing them with PhysicsServer3D RIDs. + +#### Complements +- [godot-multiplayer-networking](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md) — lobby/RPC/synchronizer toolkit that sits on the headless ENet/WebSocket hosts this skill scaffolds. +- [godot-adapt-single-to-multiplayer](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-adapt-single-to-multiplayer/SKILL.md) — authority split and prediction shells before wiring dedicated-server validation and interest filters. +- [godot-export-builds](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-export-builds/SKILL.md) — dedicated-server export presets and CLI packaging for real multi-instance host tests. +- [godot-2d-physics](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-2d-physics/SKILL.md) — PhysicsServer2D body/shape patterns for 2D authoritative swarms without SceneTree bodies. +- [godot-navigation-pathfinding](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-navigation-pathfinding/SKILL.md) — NavigationServer RIDs and bake updates when AI agents share the same low-level server path. +- [godot-performance-optimization](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md) — budgets and profiling that decide when RID servers beat nodes under peer/object load. +- [godot-debugging-profiling](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-debugging-profiling/SKILL.md) — Performance monitors and remote debug habits for headless FPS/memory/orphan telemetry. +- [godot-platform-web](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-platform-web/SKILL.md) — HTML5 client constraints that force WebSocketMultiplayerPeer instead of ENet. + +#### Downstream / consumers +- [godot-procedural-generation](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-procedural-generation/SKILL.md) — mass object/voxel spawners that consume RenderingServer/PhysicsServer RID pools. +- [godot-monte-carlo-balancer](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-monte-carlo-balancer/SKILL.md) — retune economy/TTK after authoritative server tick rates or validation change effective combat windows. +- [godot-genre-battle-royale](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-genre-battle-royale/SKILL.md) — large-peer dedicated hosts that need interest grids, kick/health exporters, and RID-scale sim. + +#### Master +- [godot-master](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-master/SKILL.md) — library router and mirrored module entry; open when discovering which Domain Skill owns a cross-cutting server concern. diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/migration-notes.md b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/migration-notes.md new file mode 100644 index 0000000000000000000000000000000000000000..37c68fc17408c7950ea484281438b203f08f977a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/migration-notes.md @@ -0,0 +1,50 @@ +# Migration notes: godot-server-architecture + +Incremental upgrade for topics this skill covers. Apply **one hop**, stabilize/test, then next. Never skip hops. + +If the project is **< 4.0**, follow [godot-version-migration](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-version-migration/SKILL.md) era bridges (legacy → 3→4) until 4.0, then these hops. Official 3→4: [Upgrading from Godot 3 to Godot 4](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.html). + +## 4.0 → 4.1 + +Official: [Upgrading to Godot 4.1](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.1.html) + +- `WebRTCPeerConnectionExtension._create_data_channel()` return type is `WebRTCDataChannel`. + +## 4.1 → 4.2 + +Official: [Upgrading to Godot 4.2](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.2.html) + +*No skill-relevant breaking changes for this hop.* + +## 4.2 → 4.3 + +Official: [Upgrading to Godot 4.3](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.3.html) + +- `SceneMultiplayer` protocol break — dedicated server and clients must share the same minor version. + +## 4.3 → 4.4 + +Official: [Upgrading to Godot 4.4](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.4.html) + +*No skill-relevant breaking changes for this hop.* + +## 4.4 → 4.5 + +Official: [Upgrading to Godot 4.5](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.5.html) + +- `Node.get_rpc_config()` → **`get_node_rpc_config()`**. +- `JSONRPC.set_scope()` → **`set_method()`**. +- `Resource.duplicate(true)` deep-copies **internal** resources only — use `duplicate_deep(DEEP_DUPLICATE_ALL)` when cloning authoritative server state graphs. + +## 4.5 → 4.6 + +Official: [Upgrading to Godot 4.6](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.6.html) + +- `StreamPeerTCP` → **`StreamPeerSocket`**; migrate custom TCP gate/login servers. + +## 4.6 → 4.7 + +Official: [Upgrading to Godot 4.7](https://docs.godotengine.org/en/stable/tutorials/migrating/upgrading_to_godot_4.7.html) + +- Packed array element assignment no longer triggers whole-property setter — audit replicated state bags using typed arrays. +- Typed-return overrides must explicitly `return` — fix headless server GDScript that relied on implicit null. diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/rendering-physics-server-cookbook.md b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/rendering-physics-server-cookbook.md new file mode 100644 index 0000000000000000000000000000000000000000..285492c6b8e088fbf0f956f6d47de6d8418bcc7e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/references/rendering-physics-server-cookbook.md @@ -0,0 +1,34 @@ +# RenderingServer / PhysicsServer cookbook + +Use when SceneTree nodes cannot meet tick budget — pair with [physics_server_direct.gd](../scripts/physics_server_direct.gd). + +## RenderingServer canvas item (2D) + +```gdscript +var canvas_item := RenderingServer.canvas_item_create() +RenderingServer.canvas_item_set_parent(canvas_item, get_canvas_item()) +var texture_rid := load("res://icon.png").get_rid() +RenderingServer.canvas_item_add_texture_rect( + canvas_item, Rect2(0, 0, 64, 64), texture_rid) +``` + +## PhysicsServer2D body + +```gdscript +var body_rid := PhysicsServer2D.body_create() +PhysicsServer2D.body_set_mode(body_rid, PhysicsServer2D.BODY_MODE_RIGID) +var shape_rid := PhysicsServer2D.circle_shape_create() +PhysicsServer2D.shape_set_data(shape_rid, 16.0) +PhysicsServer2D.body_add_shape(body_rid, shape_rid) +``` + +> [!CAUTION] +> Every `*_create()` needs matching `free_rid()` on dedicated hosts. + +## When to use servers vs nodes + +| Servers | Nodes | +|---------|-------| +| Procedural swarms, voxels, mass particles | Gameplay actors, UI, prototyping | + +Interest management: `MultiplayerSynchronizer.public_visibility = false` + visibility filter — see Host Patterns in SKILL.md. diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/dtls_secure_server.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/dtls_secure_server.gd new file mode 100644 index 0000000000000000000000000000000000000000..60ff7f2018844e522ad60ee7c609744af6eae2cc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/dtls_secure_server.gd @@ -0,0 +1,30 @@ +# dtls_secure_server.gd +# Encrypting ENet traffic using DTLS and certificates +extends Node + +# EXPERT NOTE: DTLS provides encryption over UDP, +# preventing man-in-the-middle attacks on sensitive data. + +func secure_server(crypto_key: CryptoKey, cert: X509Certificate): + var peer := ENetMultiplayerPeer.new() + peer.create_server(7000) + + # Setting up the TLS/DTLS options for the host + var server_options := TLSOptions.server(crypto_key, cert) + peer.host.dtls_server_setup(server_options) + + multiplayer.multiplayer_peer = peer + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_enetmultiplayerpeer.html +# - https://docs.godotengine.org/en/stable/classes/class_dtlsserver.html +# - https://docs.godotengine.org/en/stable/classes/class_tlsoptions.html +# - https://docs.godotengine.org/en/stable/classes/class_x509certificate.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/ssl_certificates.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — secure transport before RPC game traffic +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-export-builds/SKILL.md — ship cert/key assets with dedicated-server builds +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/enet_optimized_host.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/enet_optimized_host.gd new file mode 100644 index 0000000000000000000000000000000000000000..edc9bd9272cbc228d9ffc62ef33d804562a6611e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/enet_optimized_host.gd @@ -0,0 +1,29 @@ +# enet_optimized_host.gd +# Configuring high-performance UDP hosts for Godot servers +extends Node + +# EXPERT NOTE: ENet is the preferred protocol for action games. +# Defining precise bandwidth and client limits is vital for stability. + +func setup_enet_server(port: int, max_clients: int): + var peer := ENetMultiplayerPeer.new() + # Port, Max Clients, Channels (0 for default), In/Out Bandwidth (0 for unlimited) + var err := peer.create_server(port, max_clients, 0, 0, 0) + + if err == OK: + multiplayer.multiplayer_peer = peer + print("Server listening on port ", port) + else: + push_error("ENet Server Setup Failed: ", err) + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_enetmultiplayerpeer.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerapi.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — ENet channel/bandwidth tuning beyond create_server +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-adapt-single-to-multiplayer/SKILL.md — wire host peer into authority split +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_init_manager.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_init_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..41ab4b7e1d94c4311b0f1c5a6585ca94df70c93b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_init_manager.gd @@ -0,0 +1,27 @@ +# headless_init_manager.gd +# Detecting and initializing dedicated server environments +extends Node + +# EXPERT NOTE: DisplayServer.get_name() returns "headless" +# only if the binary was launched with the --headless argument. + +func _ready(): + if DisplayServer.get_name() == "headless" or OS.has_feature("dedicated_server"): + print_rich("[color=green]DEDICATED SERVER DETECTED[/color]") + _start_server_logic() + +func _start_server_logic(): + # Configure server-specific singletons or physics speeds + Engine.max_fps = 60 # Servers don't need high FPS, but need stability + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/editor/command_line_tutorial.html +# - https://docs.godotengine.org/en/stable/tutorials/export/exporting_for_dedicated_servers.html +# - https://docs.godotengine.org/en/stable/classes/class_displayserver.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-export-builds/SKILL.md — dedicated-server export presets for headless hosts +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — start multiplayer peer after headless detect +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_manager.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..c15fa7863a6a3cebfbfbd701bfbecaf2a19f732e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/headless_manager.gd @@ -0,0 +1,63 @@ +# skills/server-architecture/scripts/headless_manager.gd +extends Node + +## Headless Server Manager Expert Pattern +## Manages headless state, arguments, and optimizations for dedicated servers. + +class_name HeadlessManager + +signal server_ready +signal server_shutdown + +func _ready() -> void: + # 1. Detect Headless Mode + if DisplayServer.get_name() == "headless": + print("[HeadlessManager] Running in Headless Mode") + _configure_headless() + else: + print("[HeadlessManager] Running in Graphical Mode") + + # 2. Parse Arguments + _parse_cmdline_args() + +func _configure_headless() -> void: + # Disable visual-only processing if necessary + # Note: Godot 4 headless automatically disables rendering, but we can save more + + # Limit physics if not needed, or lock FPS + Engine.max_fps = 60 # Server tick rate + + # Lower audio bus volume or disable + AudioServer.set_bus_mute(0, true) + +func _parse_cmdline_args() -> void: + var args = OS.get_cmdline_user_args() + for arg in args: + if arg.begins_with("--port="): + var port = arg.split("=")[1].to_int() + print("[HeadlessManager] Override Port: ", port) + # NetworkManager.start_server(port) + +func _notification(what: int) -> void: + if what == NOTIFICATION_WM_CLOSE_REQUEST: + print("[HeadlessManager] Shutdown Requested") + server_shutdown.emit() + # Perform cleanup + # Save state + get_tree().quit() + +## EXPERT USAGE: +## Add as AutoLoad. Call using standard --headless -- --port=7777 + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/editor/command_line_tutorial.html +# - https://docs.godotengine.org/en/stable/tutorials/export/feature_tags.html +# - https://docs.godotengine.org/en/stable/classes/class_os.html +# - https://docs.godotengine.org/en/stable/classes/class_displayserver.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-export-builds/SKILL.md — headless/dedicated export and CLI packaging +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-autoload-architecture/SKILL.md — Autoload host lifecycle for HeadlessManager +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/isolated_multiplayer_api.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/isolated_multiplayer_api.gd new file mode 100644 index 0000000000000000000000000000000000000000..4a9198452fe3934e8c4a58bae4355dc9a546f592 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/isolated_multiplayer_api.gd @@ -0,0 +1,25 @@ +# isolated_multiplayer_api.gd +# Running Client and Server instances in a single Godot run +extends Node + +# EXPERT NOTE: Use for Local Hosting where the same instance +# needs to act as both authoritative server and local client. + +func split_branches(): + var server_api = MultiplayerAPI.create_default_interface() + # Isolate the /root/Server branch to its own MultiplayerAPI root + get_tree().set_multiplayer(server_api, ^"/root/Server") + + print("Network branches isolated: Client and Server now run independently.") + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerapi.html +# - https://docs.godotengine.org/en/stable/classes/class_scenemultiplayer.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — SceneMultiplayer roots for host+client-in-one +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-scene-management/SKILL.md — /root/Server branch layout for isolated APIs +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/manual_network_poll.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/manual_network_poll.gd new file mode 100644 index 0000000000000000000000000000000000000000..3581d15d6abc09e8b988bc9433f235a80503a90d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/manual_network_poll.gd @@ -0,0 +1,27 @@ +# manual_network_poll.gd +# Running networking on a separate thread via manual polling +extends Node + +# EXPERT NOTE: Disabling SceneTree.multiplayer_poll allows +# you to control exactly when network packets are processed. + +func _ready(): + # Stop the engine from automatically polling networking + get_tree().multiplayer_poll = false + +func _physics_process(_delta): + # Manual pumping of the network stack, usually inside a Mutex lock + if multiplayer.has_multiplayer_peer(): + multiplayer.poll() + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerapi.html +# - https://docs.godotengine.org/en/stable/classes/class_scenemultiplayer.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — poll timing with transfer modes and sync Hz +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md — off-main-thread poll vs frame budget +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/peer_kick_manager.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/peer_kick_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..c8a83c333d9f2a5b7889046cfbc19242ccda414f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/peer_kick_manager.gd @@ -0,0 +1,30 @@ +# peer_kick_manager.gd +# Gracefully terminating peer connections +extends Node + +# EXPERT NOTE: Disconnecting peers forcefully (disconnect_peer) +# is cleaner than just erasing them from a list. + +func remove_player(peer_id: int, reason: String): + # Notify the peer first if possible + _on_kicked.rpc_id(peer_id, reason) + + # Drop connection + multiplayer.disconnect_peer(peer_id) + print("Kicked peer ", peer_id, " for: ", reason) + +@rpc("authority", "call_remote", "reliable") +func _on_kicked(reason: String): + print("Disconnected by server: ", reason) + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerapi.html +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerpeer.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — disconnect/kick with lobby state cleanup +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-signal-architecture/SKILL.md — local kicked/disconnected events off transport +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/physics_server_direct.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/physics_server_direct.gd new file mode 100644 index 0000000000000000000000000000000000000000..5ae3bb7734b369104ef7e164b29857ed26e317d2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/physics_server_direct.gd @@ -0,0 +1,34 @@ +# physics_server_direct.gd +# Bypassing SceneTree overhead for high-density simulations +extends Node3D + +# EXPERT NOTE: For MMO-scale logic, Nodes are too expensive. +# Create bodies directly on the PhysicsServer3D and manage RIDs. + +var server_bodies: Array[RID] = [] + +func spawn_server_body(xform: Transform3D) -> RID: + var body_rid := PhysicsServer3D.body_create() + PhysicsServer3D.body_set_mode(body_rid, PhysicsServer3D.BODY_MODE_KINEMATIC) + # Link to the 3D world's physics space + PhysicsServer3D.body_set_space(body_rid, get_world_3d().space) + PhysicsServer3D.body_set_state(body_rid, PhysicsServer3D.BODY_STATE_TRANSFORM, xform) + + server_bodies.append(body_rid) + return body_rid + +func _exit_tree(): + for rid in server_bodies: + PhysicsServer3D.free_rid(rid) + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/performance/using_servers.html +# - https://docs.godotengine.org/en/stable/classes/class_physicsserver3d.html +# - https://docs.godotengine.org/en/stable/classes/class_rid.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-physics-3d/SKILL.md — node physics baseline before RID body_create +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md — when SceneTree bodies become too expensive +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/rid_performance_server.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/rid_performance_server.gd new file mode 100644 index 0000000000000000000000000000000000000000..ca67dc8c67683d395e35c6c623936ec15faaabf4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/rid_performance_server.gd @@ -0,0 +1,70 @@ +# skills/server-architecture/code/rid_performance_server.gd +extends Node + +## Server Architecture Expert Pattern +## Implements High-Performance RID Management (Scene Tree Bypass). + +var _instance_rids: Array[RID] = [] +var _mesh_rid: RID +var _material_rid: RID + +func _enter_tree() -> void: + # 1. Resource ID (RID) Mastery + # Expert logic: Manually manage drawing without MeshInstance3D nodes. + _mesh_rid = RenderingServer.mesh_create() + # Assume a pre-loaded mesh resource for brevity + # RenderingServer.mesh_add_surface_from_arrays(_mesh_rid, RenderingServer.PRIMITIVE_TRIANGLES, arrays) + + _material_rid = RenderingServer.material_create() + +func spawn_instances(count: int, area_size: float) -> void: + # 2. Direct RenderingServer Calls + # This bypasses the overhead of 10,000 Node3D objects. + for i in range(count): + var instance = RenderingServer.instance_create() + RenderingServer.instance_set_base(instance, _mesh_rid) + RenderingServer.instance_set_scenario(instance, get_world_3d().scenario) + + var xform = Transform3D(Basis(), Vector3( + randf_range(-area_size, area_size), + 0, + randf_range(-area_size, area_size) + )) + RenderingServer.instance_set_transform(instance, xform) + _instance_rids.append(instance) + +func query_physics_direct(origin: Vector3, direction: Vector3) -> Dictionary: + # 3. Direct PhysicsServer Queries + # Professional pattern: Query the server directly instead of using RayCast3D node. + var space_state = PhysicsServer3D.space_get_direct_state(get_world_3d().space) + var query = PhysicsRayQueryParameters3D.create(origin, origin + direction * 100.0) + + return space_state.intersect_ray(query) + +func _exit_tree() -> void: + # CRITICAL: Manual cleanup of RIDs is mandatory to prevent memory leaks. + for rid in _instance_rids: + RenderingServer.free_rid(rid) + RenderingServer.free_rid(_mesh_rid) + RenderingServer.free_rid(_material_rid) + +## EXPERT NOTE: +## Use 'WorkerThreadPool Batching': For 1 million+ calculations, split +## the loop across cores: 'WorkerThreadPool.add_native_group_task(self, "_proc", count)'. +## For 'Headless Simulation', run Godot with '--headless' to disable +## the OS window and Vulkan/OpenGL context for pure low-latency servers. +## NEVER instantiate Nodes for pure data or invisible calculation; +## use RIDs or plain Objects to save 90% memory overhead. + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/performance/using_servers.html +# - https://docs.godotengine.org/en/stable/classes/class_renderingserver.html +# - https://docs.godotengine.org/en/stable/classes/class_physicsserver3d.html +# - https://docs.godotengine.org/en/stable/classes/class_rid.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md — RID instance pools vs MultiMesh/node budgets +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-procedural-generation/SKILL.md — consumer of mass RID spawn/despawn +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/safe_packet_decoder.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/safe_packet_decoder.gd new file mode 100644 index 0000000000000000000000000000000000000000..e9578744247f18453a7722a745a8114a2418b42e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/safe_packet_decoder.gd @@ -0,0 +1,26 @@ +# safe_packet_decoder.gd +# Preventing RCE vulnerabilities in network serialization +extends Node + +# EXPERT NOTE: NEVER pass true to get_var/set_var on untrusted data. +# Object decoding allows a client to trigger arbitrary code. + +func process_untrusted_packet(packet_peer: PacketPeerUDP): + if packet_peer.get_available_packet_count() > 0: + # EXPERT: Passing 'false' forbids Object decoding, preventing RCE. + var data: Variant = packet_peer.get_var(false) + _handle_data(data) + +func _handle_data(data: Variant): pass + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/io/binary_serialization_api.html +# - https://docs.godotengine.org/en/stable/classes/class_packetpeer.html +# - https://docs.godotengine.org/en/stable/classes/class_packetpeerudp.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — apply same no-object-decode rule to custom RPCs +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-adapt-single-to-multiplayer/SKILL.md — validate untrusted client payloads at authority +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_authority_validator.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_authority_validator.gd new file mode 100644 index 0000000000000000000000000000000000000000..1893e06b62165fa10f3b2248ecc5f158a4d49c28 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_authority_validator.gd @@ -0,0 +1,34 @@ +# server_authority_validator.gd +# Validating client requests at the entry point +extends Node + +# EXPERT NOTE: RPC authority checks are the first line of defense. +# Use get_remote_sender_id() to identify and validate peers. + +@rpc("any_peer", "call_local", "reliable") +func commit_transaction(item_id: String, amount: int): + if not multiplayer.is_server(): return + + var peer_id = multiplayer.get_remote_sender_id() + if _can_afford(peer_id, amount): + _apply_transaction(peer_id, item_id, amount) + else: + _notify_error.rpc_id(peer_id, "Insufficient funds") + +@rpc("authority", "call_remote", "reliable") +func _notify_error(msg: String): pass + +func _can_afford(id, amt): return true +func _apply_transaction(id, item, amt): pass + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# - https://docs.godotengine.org/en/stable/classes/class_multiplayerapi.html +# - https://docs.godotengine.org/en/stable/classes/class_node.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — authority/RPC patterns for validated actions +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-monte-carlo-balancer/SKILL.md — economy checks after authority rules change TTK +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_health_exporter.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_health_exporter.gd new file mode 100644 index 0000000000000000000000000000000000000000..a554c8d4059f18015b90b1f9b10fcaa0293ebb58 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_health_exporter.gd @@ -0,0 +1,64 @@ +class_name ServerHealthExporter +extends Node + +## Exports server telemetry and performance metrics for external monitoring (Prometheus/Grafana). +## Runs automatically in headless/dedicated server mode. + +@export var export_interval: float = 10.0 # Seconds + +func _ready() -> void: + # Only run on dedicated/headless servers to save client resources + if DisplayServer.get_name() != "headless": + queue_free() + return + + var timer = Timer.new() + timer.wait_time = export_interval + timer.autostart = true + timer.timeout.connect(_export_metrics) + add_child(timer) + +func _export_metrics() -> void: + var metrics = { + "timestamp": Time.get_unix_time_from_system(), + "performance": { + "fps": Performance.get_monitor(Performance.TIME_FPS), + "process": Performance.get_monitor(Performance.TIME_PROCESS), + "physics_process": Performance.get_monitor(Performance.TIME_PHYSICS_PROCESS), + "static_memory": Performance.get_monitor(Performance.MEMORY_STATIC), + "objects": Performance.get_monitor(Performance.OBJECT_COUNT), + "nodes": Performance.get_monitor(Performance.OBJECT_NODE_COUNT), + "orphan_nodes": Performance.get_monitor(Performance.OBJECT_ORPHAN_NODE_COUNT) + }, + "network": { + "peers": multiplayer.get_peers().size(), + "bandwidth_in": _get_enet_bandwidth_in(), + "bandwidth_out": _get_enet_bandwidth_out() + } + } + + # Print to standard output in JSON format for scraping tools like Filebeat or Promtail + print("METRICS_DUMP:" + JSON.stringify(metrics)) + +func _get_enet_bandwidth_in() -> float: + var peer = multiplayer.multiplayer_peer + if peer is ENetMultiplayerPeer: + # Note: ENet doesn't expose raw bandwidth easily in high-level API, + # but you can track it via custom packet counting. + return 0.0 + return 0.0 + +func _get_enet_bandwidth_out() -> float: + return 0.0 + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/classes/class_performance.html +# - https://docs.godotengine.org/en/stable/classes/class_displayserver.html +# - https://docs.godotengine.org/en/stable/classes/class_enetmultiplayerpeer.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-debugging-profiling/SKILL.md — Performance monitors and headless telemetry habits +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md — act on FPS/memory/orphan signals from exporters +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_matchmaker_client.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_matchmaker_client.gd new file mode 100644 index 0000000000000000000000000000000000000000..de91ea0448a434393a651a53d9fa9c8f48ed53c4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/server_matchmaker_client.gd @@ -0,0 +1,56 @@ +class_name ServerMatchmakerClient +extends Node + +## Client-side logic for connecting to a central Load Balancer/Matchmaker. +## Uses HTTP to receive a dedicated server IP/Port handoff. + +@export var matchmaker_url: String = "https://api.game.com/v1/match" +@export var auth_token: String = "" + +signal match_found(ip: String, port: int) +signal match_failed(reason: String) + +var _http: HTTPRequest + +func _ready() -> void: + _http = HTTPRequest.new() + add_child(_http) + _http.request_completed.connect(_on_request_completed) + +## Requests a server assignment from the Load Balancer. +func request_match(region: String = "us-east") -> void: + var headers = ["Content-Type: application/json"] + if not auth_token.is_empty(): + headers.append("Authorization: Bearer " + auth_token) + + var body = JSON.stringify({"region": region}) + _http.request(matchmaker_url, headers, HTTPClient.METHOD_POST, body) + +func _on_request_completed(result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray) -> void: + if result != HTTPRequest.RESULT_SUCCESS or response_code != 200: + match_failed.emit("HTTP Error: %d" % response_code) + return + + var json = JSON.new() + var err = json.parse(body.get_string_from_utf8()) + if err != OK: + match_failed.emit("JSON Parse Error") + return + + var data = json.get_data() + if data.has("ip") and data.has("port"): + match_found.emit(data.ip, int(data.port)) + else: + match_failed.emit("Malformed matchmaker response") + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/networking/http_client_class.html +# - https://docs.godotengine.org/en/stable/classes/class_httprequest.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/ssl_certificates.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — connect ENet/WebSocket after matchmaker handoff +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-platform-web/SKILL.md — HTTPS matchmaker from browser builds +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/websocket_server_compat.gd b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/websocket_server_compat.gd new file mode 100644 index 0000000000000000000000000000000000000000..014976ce5ea60e6035196a7defd7e750b689e1da --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/skill/scripts/websocket_server_compat.gd @@ -0,0 +1,25 @@ +# websocket_server_compat.gd +# WebSocket implementation for HTML5/Web browser servers +extends Node + +# EXPERT NOTE: ENet is UDP-only and unsupported in browsers. +# WebSocketMultiplayerPeer is required for web compatibility. + +func start_web_server(port: int): + var peer := WebSocketMultiplayerPeer.new() + var err = peer.create_server(port) + if err == OK: + multiplayer.multiplayer_peer = peer + print("WebSocket Server active on port ", port) + +# ============================================================================= +# GDSkills research links (agents) — does not affect runtime +# Official docs: +# - https://docs.godotengine.org/en/stable/tutorials/networking/websocket.html +# - https://docs.godotengine.org/en/stable/classes/class_websocketmultiplayerpeer.html +# - https://docs.godotengine.org/en/stable/tutorials/networking/high_level_multiplayer.html +# Related skills: +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-platform-web/SKILL.md — HTML5 client constraints requiring WebSocket peers +# - https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-multiplayer-networking/SKILL.md — shared high-level API over WebSocket transport +# Parent skill: https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-server-architecture/SKILL.md +# ============================================================================= diff --git a/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/task.json b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3933eb57acc6eb74831f9f695ecbf416232afd22 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/task.json @@ -0,0 +1,62 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "adc122d50c75da6b", + "query_id": "adc122d50c75da6b_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "3f279dc27904337eca624c5f4a76701d87cfd4eccb635873ac7db13d35e90646", + "name": "godot-server-architecture", + "package_path": "skill", + "install_name": "godot-server-architecture-47c57af9" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "3f279dc27904337eca624c5f4a76701d87cfd4eccb635873ac7db13d35e90646", + "files": { + "SKILL.md": "f61ff706768c2f7544cf2f2c1599ebc42b8154dc29735b8a49041a458c9379b5", + "references/migration-notes.md": "0b1fe9d2e1b4c4771e2ef117acae31006b604399f80f7a624794df26398c7d97", + "references/rendering-physics-server-cookbook.md": "57b0f238047fb3793dfc55bcd2045652dfbaa199059f7130da508cbc9427c6dc", + "scripts/dtls_secure_server.gd": "18775a53382d5b1cc1c4196babb0134b5154884ea56fe968ee8adbd335048644", + "scripts/enet_optimized_host.gd": "5356d578bd039a46afcda0da612be966ef6b5473ba37d64d246e96b1bfc337f4", + "scripts/headless_init_manager.gd": "70e76db33b32845cfd6be7d539e7ad78bcfedf22bb3d428010d893badde1e094", + "scripts/headless_manager.gd": "851d13801ee16f3a7c00642e8af59ece50ef32cf9d60ca5b5b15fd398f4e81db", + "scripts/isolated_multiplayer_api.gd": "cacb538f11ea2e45991fab0653daf8c2e5fc61139688f2e35a36b9c084468c9c", + "scripts/manual_network_poll.gd": "c4b32a6c8d980a32a48abe6176d5804395ae7b68da1dda3152adee8f6abbb391", + "scripts/peer_kick_manager.gd": "3ddaa278f0269ae3f322be34d3afb9d6882858ff51afd51653c4ebb4f826a82a", + "scripts/physics_server_direct.gd": "24c80d4a7c30767c14022c88f4d265941d6c37d82d041a0dff7319a48adb35b1", + "scripts/rid_performance_server.gd": "4f4306e52045ac549d12288b8a61ddc982c7d84db3680016e882c64f30f76271", + "scripts/safe_packet_decoder.gd": "7e411ee3569b0f5c514d570ddf7f759061855623c26fced85b73e3529d0f1497", + "scripts/server_authority_validator.gd": "7a33205ee058b633de63af18f4f84a4ca68cdfd2ab341d8c1e1ad20a9e3bb002", + "scripts/server_health_exporter.gd": "dae352a0381608575fae66f7af2faeb9ef09d44f43d371e079ab52529008418f", + "scripts/server_matchmaker_client.gd": "672da355e6d1b50cf6e03658a1d661381e76c8aa044a4c9d7f88b8f70050b8f4", + "scripts/websocket_server_compat.gd": "c78f6267b5c3b46c840b10ecd2f921489229b64b709cf066cd9caa86f8f496f2" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "47c57af9d58d07a68dcdc8279a138b37b61ea3cf6952f2934153617e7a3d950c" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..8a3aa71df49f5fc1a8e4375567cd0a92e2cc23a9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_contract.json @@ -0,0 +1,24 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/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/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..3dc9a412ce0ebac378f2c6aed84f1d09c38dfe57 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy.json @@ -0,0 +1,16 @@ +{ + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 30, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/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/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/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('=0]);return values +def main(): + actual=[] + for name in('summary.','summary'): + path=Path('/candidate')/name + if not path.is_file():continue + try:report=json.loads(path.read_text()) + except(OSError,ValueError,UnicodeError,RecursionError):report=None + actual.append(assess(report,BASE)) + flags=[tri(row[i]for row in actual)for i in range(9)]if actual else[False]*9 + script=entry() + if script is None:flags[0]=False;return flags + dep,mods,why=scan_stdlib('/candidate',[script]);flags[0]=tri([flags[0],None if why.startswith('unknown:')else dep]) + novel='\n'.join([ + 'Apr 21 11:00:00 host worker: started unit; Bash and Write and Edit', + 'Apr 21 11:00:01 host worker: ERROR TELEGRAM_BOT_TOKEN not set', + 'Apr 21 11:00:02 host worker: fatal Cannot find module xyz', + 'Apr 21 11:00:03 host worker: panic ENOENT settings.', + 'Apr 21 11:00:04 host worker: unhandled start request repeated too quickly', + 'Apr 21 11:00:05 host worker: ERROR session expired', + 'Apr 21 11:00:06 host worker: FAIL connect ECONNREFUSED', + 'Apr 21 11:00:07 host worker: exit code 7 arbitrary new unknown issue', + 'Apr 21 11:00:08 host worker: status=2/STOP', + 'Apr 21 11:00:08 host worker: exit code -3 signed nonzero', + 'Apr 21 11:00:08 host worker: status=-2 signed nonzero', + 'Apr 21 11:00:09 host worker: activated unit; Write Bash', + 'Apr 21 11:00:10 host worker: Main process exited, status=0/SUCCESS', + 'Apr 21 11:00:11 host worker: info exit code 0', + 'Apr 21 11:00:12 host worker: info 401 ECONNREFUSED Cannot find module', + ])+'\n' + for log in (BASE,novel,'May 02 00:00:00 host: Everything ordinary\n',''): + values=fresh(log,script) + for i,v in enumerate(values):flags[i]=tri([flags[i],v]) + return flags +try: + flags=main();result={'checks':[dict(id=str(i),passed=v,reason='Complete actual and fresh error eligibility/mapping/Unknown/timestamps, exact restarts, first-occurrence tools; mapping text alone not error and zero exit not error')for i,v in enumerate(flags)]} + result['scoreable']=all(value is not None for value in flags) + print(json.dumps(result)) +except Exception as exc:raise RuntimeError('Trusted diagnostic grader failed')from exc diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..87ec5351b24ead4f9ba0067fdaf328a3c1f0e1a3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/dependency_scan.py @@ -0,0 +1,14 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + return True, [], 'Deferred to public bounded runtime policy; no whole-source inference' diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/finite_interpretation_resolution.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/finite_interpretation_resolution.json new file mode 100644 index 0000000000000000000000000000000000000000..186fb7365fb6e81315e69c41118faca15228d489 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/finite_interpretation_resolution.json @@ -0,0 +1,14 @@ +{ + "resolution": "Finite complete literal/casefold accepted sets per error/restart family; supersedes earlier cannot_repair judgement without deleting its evidence.", + "basis": "Public marker casing unspecified, but both complete literal and complete casefold interpretations are explicitly definable from unchanged source. No arbitrary subset or incomplete mixed inventory accepted.", + "canonical_owners": { + "2": "MCP mappings", + "3": "Auth mappings", + "4": "Other table mappings/Unknown (includes Crash loop when eligible)", + "5": "Complete count+timestamp restart family", + "6": "Complete restart timestamps", + "8": "Complete eligible errors and explicit matched field" + }, + "historical_scores_seen": false, + "candidate_executed_locally": false +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..527cfc954a2044a3a9e40b10b1bb6feddeb472ed --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/repair_manifest.json @@ -0,0 +1,52 @@ +{ + "query_id": "ae5ae2fe1c2b1030e2ea4133", + "sample_index": 665, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ], + "original_count": 9, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ], + "root_cause": "The prose output punctuation admits the original narrow summary/summary. aliases; stale or conflicting aliases cannot bypass fresh evidence.", + "public_semantics": "Read every actual and fresh report at the two original-supported narrow names and clean both before replay, preserving complete finite casing families and independent owners.", + "source_hashes": { + "instruction.md": "4aa3090c02258ad8686e2b2501599ddd99a51ae5b75635dbdb5be13999f198cb", + "task.json": "ece7d91a623fe6cd32627af4b73f7304d2468b68fd9a0448c9cd82546e48af8b", + "evaluator/check.py": "57f073cce3f3da0dc9686aa43987bb0115c96479c4619cef2244414f7297fb29", + "skill/SKILL.md": "bad32ca0781aa44d20ebf377e3c9bb5d2d532db7fd966e6c8b499001836ad7e5", + "inputs/logs/clerk-scout.log": "6ac00fbb2288f68698d64fe0d1a689b21113dcd2d6fc6e1c1e070bf85fe62bf9" + }, + "required_historical_artifacts": [], + "checker_sha256": "c4b1ec91f1ffaf578f1e7d78bebbeba076fac832185a7aaa798ed447a09f7eb4", + "all_logic_sha256": { + "check.py": "c4b1ec91f1ffaf578f1e7d78bebbeba076fac832185a7aaa798ed447a09f7eb4", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": [ + "Focused a FULL filename delta: summary-no-dot positive, stale summary-no-dot negative, conflicting actual/fresh aliases only7False. Prior full source/family/control review inherited. Main and all new fixture code AST parsed, unchanged intentional invalid-unused and latin1 fixture bodies preserved. No execution/history." + ], + "repair_scope": "grader_only_second_round", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..92b57ae29e6fd3e02487af3d613d7dccb07e08bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6583b3b1b7d09a41bd0f6711360e29a5e8a86a0b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/grading/verified_config.json @@ -0,0 +1,46 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "ae5ae2fe1c2b1030e2ea4133", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8" + ], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3", + "finite_interpretation_resolution.json": "ed2fe103075b2b1f2958d4cd3431b7f9865ab5bfd7d88e38474028140d2b2866", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "fff5148a948b979fd6e1d011f010b0641d12fa6480547d45106d0382c4121559", + "repair_manifest.json": "4b15c81401a40f265ab84cf86e2141dce4cdf1831a7b1acdf8bc0d6ab6ad669c", + "dependency_scan.py": "aff23360095bcb8289ad65e861c5fe29ae8b9c355ae7cab23f306d1e20c81f67", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "539875ed48f4b0fcfa5a193fcfaa3474819f4b66c1e2876b109c180d5db05c74", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "8dc6e7de4a36a0468deac0c67a7fbb75f2a6b38b2f43aa4329458f6cdd37b7f7" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/inputs/logs/clerk-scout.log b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/inputs/logs/clerk-scout.log new file mode 100644 index 0000000000000000000000000000000000000000..845d0b3107d77c297376a6ff8745205805ec6a82 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/inputs/logs/clerk-scout.log @@ -0,0 +1,13 @@ +Mar 10 08:00:01 host systemd[1200]: Started clerk-scout.service. +Mar 10 08:00:03 host clerk-scout[5521]: using tool Bash: git status +Mar 10 08:00:05 host clerk-scout[5521]: ERROR: connect ECONNREFUSED 127.0.0.1:9222 +Mar 10 08:00:06 host clerk-scout[5521]: retrying MCP connection +Mar 10 08:00:12 host clerk-scout[5521]: using tool Edit: notes.md +Mar 10 08:00:14 host systemd[1200]: clerk-scout.service: Main process exited, code=exited, status=1/FAILURE +Mar 10 08:00:14 host systemd[1200]: clerk-scout.service: Failed with result 'exit-code'. +Mar 10 08:00:30 host systemd[1200]: Started clerk-scout.service. +Mar 10 08:00:31 host clerk-scout[5540]: ERROR: Telegram error 401: session expired +Mar 10 08:00:33 host clerk-scout[5540]: using tool Write: report.txt +Mar 10 08:00:34 host clerk-scout[5540]: using tool Bash: ls -la +Mar 10 08:00:40 host systemd[1200]: clerk-scout.service: Start request repeated too quickly. +Mar 10 08:00:41 host clerk-scout[5541]: info: shutdown complete, exit code 0 diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/instruction.md b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ed7ea388d67fa6ffbb47e6cfda476f40619c040 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/instruction.md @@ -0,0 +1,11 @@ +You are given a journal log extract for a user service at logs/clerk-scout.log (content below in the workspace). Write a Python 3 script (standard library only) that reads that file and writes a diagnostic summary to summary. applying these rules: (1) Errors: detect error lines with the marker set in the frozen clerk-logs Skill Step 3 Errors guidance; for each, map it to a likely cause and suggested fix using this table: 'TELEGRAM_BOT_TOKEN not set' -> cause 'Bot token unresolved from vault', fix 'clerk vault list — check token is stored'; 'ECONNREFUSED' -> 'MCP server not running', 'Start the MCP server'; '401' or 'session expired' -> 'Claude API auth expired', 'clerk auth login'; 'Cannot find module' -> 'Node dependency missing', 'npm install in agent dir'; 'start request repeated too quickly' -> 'Crash loop', 'Fix underlying error; systemctl --user reset-failed'; 'ENOENT settings.' -> 'Agent not fully scaffolded', 'clerk agent reconcile'. Unmatched error lines get cause 'Unknown' and fix 'Investigate manually'. (2) Restarts: count the restart-marker lines defined in that frozen Skill Step 3 Restarts guidance and report the count and the timestamps of those lines. (3) Tool use: list, in order of first appearance and without duplicates, the three example tool names from that frozen Skill Step 3 Tool use guidance. Write summary. with structure {"errors": [{"timestamp":..., "matched":..., "cause":..., "fix":...}], "restarts": {"count": N, "timestamps": [...]}, "tools": [...]}. Run your script and produce summary.. +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. + +Submit the entry point as diagnose_logs.py. Each invocation has a30-second completion budget. Error eligibility and restart-marker recognition may use either consistent literal case-sensitive matching or consistent case-insensitive matching across the complete input; do not mix policies per line. The cause/fix table matches case-insensitively in its listed order. A non-zero exit notation means a decimal integer different from zero following exit code or status=; zero is not an error. Timestamp is the first15 characters. summary. must be produced by running this entry point; guessed script filenames and historical tool calls are not scored. + +Execution budget: every grader-launched candidate Python invocation must complete within 30 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 30 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. + +The errors[].matched field contains the first matching cause/fix table pattern as a string, or null when no table pattern matches; another table pattern present on that same source line with the same cause/fix is also accepted. For compatibility, matched may instead contain the complete original log line or that line with its first 16 characters removed. A boolean match flag is not this field's format. diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..5c8b6098dc909ddbd20eedc9483420a76c0c90dc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/skill/SKILL.md @@ -0,0 +1,69 @@ +--- +name: clerk-logs +description: Fetches recent log output and errors from agent journals. Use when the user asks for logs, errors, 'what happened', 'why did it crash', 'show me what went wrong', debug output, failure details, 'check the logs', or 'show me the recent logs'. +--- + +# Agent Logs + +When the user asks for logs, wants to see what an agent did, or is debugging a problem — fetch and display recent journal output. + +## Step 1 — Identify the agent + +If the user named an agent, use that. Otherwise, ask: "Which agent's logs do you want?" Then list options: + +```bash +clerk agent list 2>/dev/null || ls ~/.clerk/agents/ +``` + +## Step 2 — Fetch logs + +Try clerk CLI first, fall back to journalctl: + +```bash +clerk agent logs --lines 50 2>/dev/null \ + || journalctl --user -u "clerk-" -n 50 --no-pager 2>/dev/null \ + || journalctl --user -u "clerk-.service" -n 50 --no-pager 2>/dev/null \ + || echo "No logs found for clerk-" +``` + +## Step 3 — Display with highlights + +Show the log output in a code block. While presenting, call out: + +**Errors** (lines with ERROR, FAIL, fatal, panic, unhandled, exit code non-zero): +- Summarize what went wrong +- Suggest a fix if the error is recognizable (see table below) + +**Restarts** (lines mentioning "started", "activated", "Main process exited"): +- Note how many restarts occurred and when + +**Tool use** (lines mentioning tool names like Bash, Edit, Write): +- Shows what the agent was doing + +## Common errors and fixes + +| Error pattern | Likely cause | Fix | +|---|---|---| +| `TELEGRAM_BOT_TOKEN` not set / empty | Bot token unresolved from vault | `clerk vault list` — check token is stored | +| `connect ECONNREFUSED` | MCP server not running (Hindsight, etc.) | Start the MCP server | +| `session expired` / `401` | Claude API auth expired | `clerk auth login` | +| `Cannot find module` | Node dependency missing | `npm install` in agent dir | +| `systemd[...]: start request repeated too quickly` | Crash loop | Fix underlying error; `systemctl --user reset-failed clerk-` | +| `ENOENT settings.json` | Agent not fully scaffolded | `clerk agent reconcile ` | + +## Step 4 — Offer more + +After showing 50 lines, offer: +- "Want to see more? (`journalctl --user -u clerk- -n 200 --no-pager`)" +- "Want logs since a specific time? (`journalctl --user -u clerk- --since '1 hour ago'`)" +- "Want to follow live? (`journalctl --user -u clerk- -f`)" — note: live follow isn't possible via Telegram, but user can run it locally + +## Cron task logs + +For scheduled task failures, logs are in separate units: + +```bash +journalctl --user -u "clerk--cron-.service" -n 20 --no-pager +``` + +If the user asks "why didn't my morning briefing run", check cron service logs. diff --git a/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/task.json b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/task.json new file mode 100644 index 0000000000000000000000000000000000000000..81de85abe907f35fdcd3c3a6c8b75053464aeff7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae5ae2fe1c2b1030e2ea4133/task.json @@ -0,0 +1,72 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "ae5ae2fe1c2b1030e2ea4133", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "ae5ae2fe1c2b1030e2ea4133", + "outputs": [ + "summary." + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "bd392416039d860bbace7205fbee027b5bbf9929081f2ff1c7e9d318964c458e", + "files": { + "SKILL.md": "bad32ca0781aa44d20ebf377e3c9bb5d2d532db7fd966e6c8b499001836ad7e5" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/logs/clerk-scout.log", + "workspace_target": "logs/clerk-scout.log", + "sha256": "6ac00fbb2288f68698d64fe0d1a689b21113dcd2d6fc6e1c1e070bf85fe62bf9" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "bd392416039d860bbace7205fbee027b5bbf9929081f2ff1c7e9d318964c458e" + } + ] + }, + "autograde_runtime_contract": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 30 + }, + "autograde_canonical_entry": "diagnose_logs.py", + "automatic_evaluation_runtime": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 30, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 30 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/ae7d03369d9bf344_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_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/ae7d03369d9bf344_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_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/ae7d03369d9bf344_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_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/ae7d03369d9bf344_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/ae7d03369d9bf344_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/ae7d03369d9bf344_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_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/ae7d03369d9bf344_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..400da41145f3344c7a6d6d3b24a9810e6c6f59cb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,554 @@ +"""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 math +import posixpath +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 _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + try: + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + except RecursionError as error: + raise ValueError('Candidate JSON nesting is too deep') from error + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + try:is_finite=finite(result) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + if not is_finite:raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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(_strict_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_equal(actual, 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/ae7d03369d9bf344_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..fc6c61a208720d9e3ce3414a664bc83285a51e44 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "ae7d03369d9bf344_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "3aadebbb2821ec47161606624f0d39202adcc999da39cd6aec671996fd74ddd6", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44d6667deca6d6cb0654286c7f1375d59ccd28d9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/instruction.md @@ -0,0 +1 @@ +Our QA lead wants the payment-validation module triaged before sprint review — it's the biggest coverage gap we have (40 uncovered lines and 10 branches out of 50 total lines) and it handles authentication-sensitive input validation, so it sits in our highest sensitivity tier. Using our project's standard coverage-gap risk calculation (not a generic substitute), compute the complexity-weighted risk score for this gap with missing_lines=40, complexity_factor=0.2, and sensitivity_multiplier=3, rounding to 2 decimal places. Return only the computed numeric value, not the formula or a citation, as exactly one JSON object matching this schema: {"result":"number"} diff --git a/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..efc4915736226fa709afabfaf2b25e23c6a38e9f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/skill/SKILL.md @@ -0,0 +1,229 @@ +--- +name: test-architect +description: >- + Test strategy, coverage analysis, edge case identification, flaky test + diagnosis. Use when designing test suites. NOT for running tests + (devops-engineer), TDD, or code review (review). +argument-hint: " [target]" +model: opus +license: MIT +metadata: + author: wyattowalsh + version: "1.0.0" +--- + +# Test Architect + +Design test strategies, analyze coverage gaps, identify edge cases, diagnose flaky tests, and audit test suite architecture. + +**Scope:** Test design and analysis only. NOT for running tests or CI/CD (devops-engineer), code review (review), or TDD workflow. + +## Dispatch + +| $ARGUMENTS | Action | +|------------|--------| +| `design ` | Design test strategy and pyramid for a feature or module | +| `generate ` | Generate test cases (strategy text or actual test code based on context) | +| `gaps` | Analyze coverage gaps from coverage reports | +| `edge-cases ` | Systematic edge case identification for a function | +| `flaky` | Diagnose flaky tests from logs and code | +| `review` | Audit test suite architecture | +| Empty | Show mode menu with examples | + +## Canonical Vocabulary + +Use these terms exactly throughout all modes: + +| Term | Definition | +|------|------------| +| **test pyramid** | Layered test distribution: unit (base), integration (middle), e2e (top) | +| **coverage gap** | Code path with no test coverage, weighted by complexity risk | +| **edge case** | Input at boundary conditions, null/empty, type coercion, overflow, unicode, concurrent | +| **flaky test** | Test with non-deterministic pass/fail behavior across identical runs | +| **mutation score** | Percentage of injected mutations detected by the test suite | +| **test strategy** | Document defining what to test, how, at what layer, with what tools | +| **property-based test** | Test asserting invariants over generated inputs (Hypothesis/fast-check) | +| **test isolation** | Guarantee that tests do not share mutable state or execution order dependencies | +| **fixture** | Reusable test setup/teardown providing controlled state | +| **test surface** | Set of public interfaces, code paths, and states requiring test coverage | + +## Mode 1: Design + +`/test-architect design ` + +### Surface Analysis + +1. Read the feature/module code. Map the test surface: public API, internal paths, state transitions, error conditions. +2. Classify complexity: simple (pure functions), moderate (I/O, state), complex (distributed, concurrent, multi-service). + +### Pyramid Design + +3. Design test pyramid: + - **Unit layer:** Pure logic, transformations, validators. Target: 70-80% of tests. + - **Integration layer:** Database, API, file I/O, service boundaries. Target: 15-25%. + - **E2E layer:** Critical user flows only. Target: 5-10%. +4. For each layer, list specific test cases with: description, input, expected output, rationale. +5. Recommend framework and tooling based on language/ecosystem. +6. Output: structured strategy document with pyramid diagram, case list, and priority order. + +Reference: read references/test-pyramid.md for layer guidance. + +## Mode 2: Generate + +`/test-architect generate ` + +1. Read the target file/function. Identify signature, dependencies, side effects. +2. Determine output format: + - If test file exists for target: generate actual test code matching existing patterns. + - If no test file exists: generate test strategy text with case descriptions. + - If user specifies `--code`: always generate test code. +3. Generate test cases covering: + - Happy path (expected inputs and outputs) + - Error path (invalid inputs, exceptions, timeouts) + - Edge cases (run edge-case-generator.py if function has typed parameters) + - Boundary conditions (min/max values, empty collections, null) +4. Follow framework conventions: read references/framework-patterns.md for pytest/jest/vitest patterns. +5. Output: test cases or test code with clear section headers per category. + +## Mode 3: Gaps + +`/test-architect gaps` + +1. Locate coverage reports. Search for: + - `coverage.json`, `coverage.xml`, `.coverage` (Python/coverage.py) + - `lcov.info`, `coverage/lcov.info` (JS/lcov) + - `htmlcov/`, `coverage/` directories +2. Run coverage analyzer: + ``` + uv run python skills/test-architect/scripts/coverage-analyzer.py + ``` +3. Parse JSON output. Rank gaps by complexity-weighted risk. +4. For each gap, assess: + - What code is untested and why it matters + - Complexity score (cyclomatic complexity proxy) + - Recommended test type (unit/integration/e2e) + - Priority (P0: security/auth, P1: core logic, P2: utilities, P3: cosmetic) +5. Render dashboard if 10+ gaps: + ``` + Copy templates/dashboard.html to a temporary file + Inject gap data JSON into +
+ + + diff --git a/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/task.json b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ad58d481591feeba5c3e4ca11e9eaa746d022fe8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ae7d03369d9bf344_q1/task.json @@ -0,0 +1,75 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "ae7d03369d9bf344", + "query_id": "ae7d03369d9bf344_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "adf2e778c4d77213ee345a3c2463b02fb369b74532b3cd13a57cfb88a61d14de", + "name": "test-architect", + "package_path": "skill", + "install_name": "test-architect-5bcf3d8c" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "adf2e778c4d77213ee345a3c2463b02fb369b74532b3cd13a57cfb88a61d14de", + "files": { + "SKILL.md": "89d8d5c87f8b3ded1a53570d1013c7feeb7447074bb893f966fd2e3a8b2c8bb3", + "data/edge-case-heuristics.json": "b2162ac3cf54a3b889b30a15eb335652f10b581afd50b85a4785b8aca9c97236", + "data/test-framework-patterns.json": "3e859513fb601de45223a9348293bdeedf4db8a4e1cd484f18af85c756f1f09a", + "evals/coverage-gaps.json": "9ed8cc8312af6e4294e2abebc90f8b4e457f2657927102970c9e21b02682a8eb", + "evals/design-strategy.json": "ef8d1dda47435f8d572b882e3054fc7fd8d0f99f900dccc9ed3250ec9eb98e11", + "evals/edge-cases.json": "8c669f1795eadca0748ce9a51f850577d12921c4d96499f29e789ea52cc6c899", + "evals/evals.json": "5ea764ccba8707c4174e061c73161d46dc3d4b6c64a9158149a3479673a6bd1c", + "evals/implicit-trigger.json": "6883dd99f72f37d1a1bbf70d338cd4b2700592a448e9f873663cac0aab2651a5", + "evals/negative-control.json": "b88025f73aae5f8235f5858e48fdfb98f9834e92abaae0e191f193fe167a750d", + "evals/test-design.json": "19209882d8dba4513cf04039d0345457735525a34489e2c9298932ebc8f72cc5", + "references/coverage-analysis.md": "a083d2c86546c73e32e5d66214a3ac7c26cbc1f06198781d483641a07758bf47", + "references/edge-case-heuristics.md": "426a5b2422e004320783461f2895cccd1bede7a1eaa80670fc1bcba4b4db207e", + "references/flaky-diagnosis.md": "68aed602ad91f0357dbd16a7878f33c6b6f71273cd10d6ec909050e845e437c4", + "references/framework-patterns.md": "f7a51c20a16cec602c09cb7cdf89696c36d02d8c7c3ae5894093c93c99decd93", + "references/mutation-testing.md": "b9cca351c5127e2437b8e1067c76c7ec5428de36aa22c82defea2a775eb94e5f", + "references/property-testing.md": "947c1df4e4baae365219e18100c7830fec951fa283083eab26832d3861dd4c76", + "references/test-pyramid.md": "99ca1631cb4c42ceb6754916e372c2f05696650841f385163a5ff5d2f4172338", + "references/test-suite-audit.md": "6a653fc484465f6711d78a9856330a661d9ae24beb936d5db528cefb65df6243", + "scripts/asset_toolkit/__init__.py": "5677c08900c4ab91213459982ce78a740ccc8508f6b50e0059698793c2b437ed", + "scripts/asset_toolkit/_shared.py": "d157c48daf798467f342a94a4bc65487099a8d4e400f89b55b516d27209c49e8", + "scripts/asset_toolkit/common.py": "2fc82278cfbf6b7329b80ef2f16bfe43e3e2229479ec32d177884866e62f40da", + "scripts/asset_toolkit/package.py": "3defa28eafaa04f6fc98f24958b0506d0fc2b0065e9a5c7fe2c4f071252a5153", + "scripts/asset_toolkit/validate_evals.py": "ba16c342d0bdbe9710c0991addd25e03c963bc70867c65816e024f0f9075dfa0", + "scripts/asset_toolkit/validate_hooks.py": "52d41e99c5b0193b55a8b26845c6a3f69f8ffae1c8b07feb32fd6927a1aa71eb", + "scripts/asset_toolkit/validate_skill.py": "c03b9a43806399cf6ccbeab93d42690cdbe97449973ff5937d6b4629faf847b7", + "scripts/check.py": "55eff436d1dbd6eb1f7129bfeea1910482db7695aae2a1da2aeac2a004d7bb2f", + "scripts/coverage-analyzer.py": "90a83f0af7519276a936a5757118f2bd38728fe9d10d5ec9635e6a0a97334d47", + "scripts/edge-case-generator.py": "294534c4794130b1474d005a827b87fb40e0881d67ebe03382fda1e623db8951", + "scripts/flaky-test-analyzer.py": "42ba7418aa349f83fbc6ab9c1b1a892125abbe3ff738a8d63f10daa09dc41421", + "templates/dashboard.html": "1acba3ce637800cd93c5922516b1a58dcd084850aa30728f7bb8e1cc27a51899" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "5bcf3d8cec8259f1a58430a6898db3ffe83096a209085aef2a20ec5a145f370e" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/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/aed26083404e28ca4473d673/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..bc69f81e085c631459f91368df8f1efe32cafb5f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_policy.json @@ -0,0 +1,16 @@ +{ + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/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/aed26083404e28ca4473d673/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/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(' exit 2 + rc0, _, _ = run(tmp, []) + checks.append({"id": "5", "passed": rc0 == 2, "reason": "exit 2 on usage error" if rc0 == 2 else "expected exit 2 with no arguments, got %s" % rc0}) + # 6: inner frontmatter preferred over outer + rc_i, out_i, _ = run(tmp, ["articles/inner-pref-skill-source.md"]) + iss_i = issue_lines(out_i, "inner-pref-skill-source.md") + mismatch = has(iss_i,'skill_name','match',codes=('NAME_MISMATCH',)) + p6 = (rc_i == 1) and mismatch and (rc_all == 0) + checks.append({"id": "6", "passed": p6, "reason": "inner frontmatter preferred (mismatch detected despite matching outer name); outer-only fallback still passes" if p6 else "inner frontmatter not preferred over outer, or outer fallback broken"}) + enum_name='invalid-enum-skill-source.md' + long_name='long-name-skill-source.md' + for fname,text in [(enum_name,VALID_OUTER.replace('skill: enabled','skill: maybe')),(long_name,VALID_OUTER.replace('outer-only','a'*65))]: + with open(os.path.join(tmp,'articles',fname),'w') as f:f.write(text) + enum_rc,enum_out,enum_err=run(tmp,['articles/'+enum_name]) + long_rc,long_out,long_err=run(tmp,['articles/'+long_name]) + enum_issues=issue_lines(enum_out,enum_name) + long_issues=issue_lines(long_out,long_name) + checks[1]['passed']=bool(checks[1]['passed'] and enum_rc==1 and has(enum_issues,'skill',codes=('TAG_SKILL',)) and long_rc==1 and has(long_issues,'skill_name',codes=('SKILL_NAME_SYNTAX',))) + checks[1]['reason']+='; explicit illegal skill enum and >64-character name boundaries' + required_ok=True + for key,correct,wrong in [('type','skill','note'),('kind','skill-source','document'),('skill_ref','outer-only','')]: + for missing in [False,True]: + tag=key+': '+correct+'\n';body=VALID_OUTER.replace(tag,'' if missing else key+': '+wrong+'\n',1) + filename='required-'+key+('-missing' if missing else '-wrong')+'-skill-source.md' + with open(os.path.join(tmp,'articles',filename),'w') as f:f.write(body) + rr,oo,ee=run(tmp,['articles/'+filename]);issues=issue_lines(oo,filename) + required_ok=required_ok and rr==1 and has(issues,key,codes=('TAG_'+key.upper(),)) + checks[1]['passed']=bool(checks[1]['passed'] and required_ok) + checks[1]['reason']+='; type/kind/skill_ref are independently required and exact' + # Isolate the kebab grammar from the original case/name mismatch, and + # protect the inclusive 64-character upper boundary with a valid example. + kebab_ok=True + for number,name in enumerate(['bad_name','-start','end-','two--dashes','a'*64]): + filename='grammar-'+str(number)+'.md';body=VALID_OUTER.replace('outer-only',name) + with open(os.path.join(tmp,'articles',filename),'w')as stream:stream.write(body) + rc_g,out_g,err_g=run(tmp,['articles/'+filename]) + if number==4:kebab_ok=kebab_ok and rc_g==0 and filename+': PASS'in out_g + else:kebab_ok=kebab_ok and rc_g==1 and has(issue_lines(out_g,filename),'skill_name',codes=('SKILL_NAME_SYNTAX',)) + checks[1]['passed']=checks[1]['passed']and kebab_ok + checks[1]['reason']+='; isolated underscore/leading/trailing/doubled hyphens and valid length64' + for _r10_row in checks: + if str(_r10_row["id"])=='0':_r10_row["passed"]=combine([_r10_row["passed"],dependency('validate_skills.py')]) + print(json.dumps({"checks": checks})) + +main() diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/r10_support.py b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/r10_support.py new file mode 100644 index 0000000000000000000000000000000000000000..0709a48fdbd10e98f7beaea2bc598f7568372ef5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/evaluator/r10_support.py @@ -0,0 +1,107 @@ +"""R10 evaluator helpers. Candidate programs are only run by the Docker harness.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import ast, contextlib, io, json, os, pathlib, shutil, sys, tokenize + +def combine(values): + values=list(values) + return False if any(v is False for v in values)else None if any(v is None for v in values)else True + +def candidate_root(): + return pathlib.Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_ROOT','/candidate'))) + +def copy_program(destination,skip=()): + root=candidate_root();destination=pathlib.Path(destination);destination.mkdir(parents=True,exist_ok=True) + skip=set(skip) + def ignored(directory,names): + relative=pathlib.Path(directory).relative_to(root) + return [n for n in names if n in ('__pycache__','.git','.venv')or str(relative/n)in skip] + shutil.copytree(root,destination,dirs_exist_ok=True,symlinks=True,ignore=ignored) + return destination + +def install_copy(skip=()): + original=shutil.copy + def copied(source,destination,*args,**kwargs): + source=pathlib.Path(source) + try:source.resolve().relative_to(candidate_root().resolve());local=True + except ValueError:local=False + if local and source.suffix=='.py': + target=pathlib.Path(destination) + if not target.is_dir():target=target.parent + copy_program(target,skip) + return original(source,destination,*args,**kwargs) + shutil.copy=copied + +def _constant(node,constants): + if isinstance(node,ast.Constant):return node.value + if isinstance(node,ast.Name):return constants.get(node.id) + if isinstance(node,(ast.List,ast.Tuple)): + values=[_constant(n,constants)for n in node.elts] + return values if all(v is not None for v in values)else None + if isinstance(node,ast.BinOp)and isinstance(node.op,ast.Add): + a,b=_constant(node.left,constants),_constant(node.right,constants) + return a+b if isinstance(a,str)and isinstance(b,str)else None + if isinstance(node,ast.Call)and isinstance(node.func,ast.Attribute)and node.func.attr=='join'and len(node.args)==1: + separator=_constant(node.func.value,constants);values=_constant(node.args[0],constants) + return separator.join(values)if isinstance(separator,str)and isinstance(values,list)and all(isinstance(v,str)for v in values)else None + if isinstance(node,ast.JoinedStr): + values=[_constant(n.value,constants)if isinstance(n,ast.FormattedValue)else _constant(n,constants)for n in node.values] + return ''.join(map(str,values))if all(v is not None for v in values)else None + return None + +def scan_stdlib(root,entries,banned=()): + return True, [], 'Deferred to public bounded runtime policy; no whole-source inference' + +def dependency(entry,banned=()): + return True + +def strict_json(text): + def unique(pairs): + result={} + for k,v in pairs: + if k in result:raise ValueError('duplicate JSON member: '+k) + result[k]=v + return result + return json.loads(text,object_pairs_hook=unique,parse_constant=lambda value:(_ for _ in()).throw(ValueError(value))) + +def strict_response(text): + import re + match=re.fullmatch(r'\s*```(?:json)?\s*\n(.*?)\n```\s*',text,re.S|re.I) + return strict_json(match[1]if match else text) + +def trusted_stdout(query_id): + import hashlib + path=pathlib.Path(os.environ.get('MYBENCH_TRUSTED_TRACE','/tool_trajectory.json')) + expected=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256') + try: + path.resolve().relative_to(candidate_root().resolve()) + return None + except ValueError:pass + try: + raw=path.read_bytes() + if not expected or hashlib.sha256(raw).hexdigest()!=expected:return None + trace=json.loads(raw) + metadata=json.loads(pathlib.Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text()) + binding=metadata.get('trusted_trace_binding',metadata.get('derived',{}).get('trusted_trace_binding',{})) + if binding.get('query_id')!=query_id or binding.get('trajectory_sha256')!=expected:return None + hashes=binding.get('candidate_file_sha256') + if not isinstance(hashes,dict)or not hashes:return None + for relative,digest in hashes.items(): + if pathlib.PurePosixPath(relative).is_absolute()or'..'in pathlib.PurePosixPath(relative).parts:return None + if hashlib.sha256((candidate_root()/relative).read_bytes()).hexdigest()!=digest:return None + except (OSError,ValueError):return None + if not isinstance(trace,dict)or not isinstance(trace.get('steps'),list):return None + outputs=[] + for step in trace['steps']: + observation=step.get('observation',{}) + results=observation.get('results',[])if isinstance(observation,dict)else[] + calls={str(c.get('tool_call_id')):c for c in step.get('tool_calls',[])if isinstance(c,dict)and c.get('function_name')in ('bash','exec_command','shell','terminal','run_shell_command')} + for result in results: + if isinstance(result,dict)and str(result.get('source_call_id'))in calls and result.get('content')is not None:outputs.append(str(result['content'])) + # A later successful printing may replace an earlier trial. Candidate + # formal answers and strings in tool arguments never enter this channel. + summaries=[output for output in outputs if re_search_summary(output)] + return summaries[-1]if summaries else '' + +def re_search_summary(output): + import re + return bool(re.search(r'(?m)^G\d+:\s*(?:platformer|grid_logic|tower_defense|top_down|ui_heavy)\s*$',output)) diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..46b86c956eb0a635341f16ed4848bef2c64275c5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/grading/verified_config.json @@ -0,0 +1,106 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "aed26083404e28ca4473d673", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f245803a06b801617e2ec10e3bf5d2705663cbbcecbb21fff72555eaa9796161", + "r10_support.py": "40d42ef87dc72d111ac18afe6e413f07e8acbf342aac9d089b51e2c0a3dcefa6", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a3238d7272abc9e16f8a3da06872356a6401eb790ed42fbe4d28b0c3f11f36b4", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": false, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "cpu_memory_basis": "source_runtime_container_limits", + "cpus": 2, + "disk_mib": 10240, + "memory_mib": 4096, + "timeout_disk_basis": "advisory_not_measured_or_enforced", + "timeout_sec": 1200 + }, + "oracle": { + "basis": "advisory_reference_copy", + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": 60, + "max_steps": 16 + }, + "verifier": { + "basis": "original_python_evaluator_enforced_limits", + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 60, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/backup-tool-skill-source.md b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/backup-tool-skill-source.md new file mode 100644 index 0000000000000000000000000000000000000000..7cc91799d19f5b206f9cabc68c7cc5acede3f7f7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/backup-tool-skill-source.md @@ -0,0 +1,17 @@ +--- +type: skill +kind: skill-source +skill: enabled +skill_ref: backup-tool +skill_name: backup-tool +audience: agent +format: agent-skill +source: user +status: stable +--- +--- +name: backup-tool +description: Creates timestamped backups of project directories +--- + +You create backups. Copy files into a timestamped directory and verify sizes. diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/code-review-helper-skill-source.md b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/code-review-helper-skill-source.md new file mode 100644 index 0000000000000000000000000000000000000000..36365044e31aaf2b20d0f7a6013623c385e406c3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/code-review-helper-skill-source.md @@ -0,0 +1,16 @@ +--- +type: skill +kind: skill-source +skill: enabled +skill_ref: code-review-helper +skill_name: CodeReviewHelper +audience: agent +format: agent-skill +source: user +--- +--- +name: code-review-helper +description: Reviews diffs for common mistakes +--- + +Review the diff and flag issues. diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/note-taker-skill-source.md b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/note-taker-skill-source.md new file mode 100644 index 0000000000000000000000000000000000000000..e58dd919f3f0971235e0e9065b1c4c48bbc441a7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/inputs/articles/note-taker-skill-source.md @@ -0,0 +1,10 @@ +--- +type: skill +kind: skill-source +skill: disabled +skill_ref: note-taker +skill_name: note-taker +audience: agent +format: agent-skill +source: user +--- diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/instruction.md b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28b56b5ae0ef32ecdcb4bac07df236d9a1992d2b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/instruction.md @@ -0,0 +1,10 @@ +I maintain a knowledge base of skill articles stored as markdown files with tag lines. Write a Python 3 script `validate_skills.py` (standard library only) that validates skill-source articles against the required tag schema and reports issues. The script takes one or more article file paths as command-line arguments. Each article file is markdown whose first block is frontmatter delimited by `---` lines, containing `key: value` tag lines. Apply the frozen knowledge-base-skills Skill Tag schema reference, Skill metadata (name + description) precedence, and Hard requirements validation checklist. This adapter intentionally accepts both enabled and disabled as valid skill-tag values (disabled affects installation, not article validity); evaluate only the six original hard categories: source identity/status tags, nonempty skill_ref/skill_name, skill_name syntax/length, name agreement, nonempty description, nonempty body. The inner metadata block, if present, is the second --- delimited block after the outer one, with name: and description: lines; everything after the frontmatter block(s) is body. Do not add the Skill's recommended audience/format/source/status/project tags as hard failures. The script must print one line per article: `: PASS` if all hard requirements hold, otherwise `: FAIL` followed by one indented line per distinct issue found (e.g. ` missing tag: skill_ref`, ` skill_name does not match name`, ` empty body`). It must exit with status 0 if all articles pass, 1 if any fail, and 2 on usage error (no arguments). Run it against the three provided articles and include the exact output in your response. + +Automatic diagnostic adapter: An article header may use its basename or the same article's command-line relative/absolute path; these identify the same article. For language-independent category checking, each issue may start with one stable code in square brackets: [TAG_TYPE], [TAG_KIND], [TAG_SKILL], [TAG_SKILL_REF], [TAG_SKILL_NAME], [SKILL_NAME_SYNTAX], [NAME_MISMATCH], [EMPTY_DESCRIPTION], or [EMPTY_BODY]. Use the matching tag code for a missing/invalid corresponding outer tag, SKILL_NAME_SYNTAX for the delegated syntax/length failure, NAME_MISMATCH for metadata name disagreement, and the two EMPTY codes for missing/empty description or body. Text after a code is free display prose in any language and its wording is not scored. The code declares the category, not the correct business value: obtain the validation rules from the frozen Skill and the adapters above. For compatibility, the previously shown English diagnostics (including missing/invalid tag with its field name, skill_name mismatch/name syntax messages, and body/description messages) remain accepted without codes. Distinct diagnostics within an article may appear in any order. The response must still reproduce the actual issue text, ignoring only article path spelling and within-article issue order. + +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/aed26083404e28ca4473d673/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..eea061fb53d5767edac4bb9f9a7bc89b8fe96c80 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/skill/SKILL.md @@ -0,0 +1,191 @@ +--- +name: knowledge-base-skills +description: Manages knowledge-base-backed pi skills — create skills stored as KB articles and explicitly install them to project or global pi skill directories. +--- + +You are an expert in the knowledge-base-skills pi extension. You know how to save skills as KB articles, materialize them into project-local `.pi/skills/`, and validate skill-source articles. + +## Two-article model + +Each skill is represented by **two linked KB articles** sharing a `skill_ref`: + +| Article | Type | Purpose | +|---------|------|---------| +| **Skill-source article** | `type:skill`, `kind:skill-source`, `skill:enabled` or `skill:disabled` | Machine-oriented — contains the raw SKILL.md body with embedded frontmatter (`name`, `description`). | +| **Documentation article** | `type:guide`, `kind:skill-doc` | Human-oriented — explains what the skill does, when to use it, examples, and links to the skill source. | + +> **Design principle:** Skills are **explicitly installed**, not auto-loaded. Save a skill to the KB with `kb_save_skill`, then install it to your project or user scope with `kb_install_skill`. + +## Tools + +### `kb_save_skill` — Save a skill into the KB + +Creates both linked articles automatically. Defaults to **local KB scope** (`./knowledge-base/`). + +Required parameters: +- `skillName` — Lowercase kebab-case name (e.g. `debug-with-screenshots`) +- `skillContent` — Full SKILL.md with embedded frontmatter containing `name` (matches skillName) and `description` + +Optional parameters: +- `docTitle` / `docContent` — Customize the companion documentation article +- `scope` — `"local"` (default, project KB) or `"global"` (`~/.pi/knowledge-base/`) +- `tags` — Additional comma-separated `key:value` pairs +- `enabled` — Set to `false` to create a disabled skill (saved to KB but not flagged for install) + +**Example:** +``` +kb_save_skill + skillName: "my-analyzer" + skillContent: "---\nname: my-analyzer\ndescription: Analyzes code structure\n---\n\nYou analyze code..." + scope: local + tags: "domain:code-analysis,tool:read" +``` + +### `kb_install_skill` — Install a KB skill to a pi skill directory + +Takes a skill-source article slug and writes `SKILL.md` + `SOURCE.json` into the target directory. +Default: **local** (project `.pi/skills/`). Use `scope:global` for user-wide (`~/.pi/agent/skills/`). + +Required parameters: +- `articleSlug` — Slug of the skill-source article in the KB + +Optional parameters: +- `scope` — `"local"` (default, project `.pi/skills/`) or `"global"` (`~/.pi/agent/skills/`) + +**Example:** +``` +kb_install_skill + articleSlug: "my-analyzer-skill-source" + scope: local +``` + +### `kb_list_skills` — List skill-source articles in the KB + +Scans the knowledge base for skill-source articles and shows their status, description, and validation issues. + +Optional parameters: +- `scope` — `"local"` | `"global"` | `"all"` (default: `"all"`) +- `status` — `"enabled"` | `"disabled"` | `"all"` (default: `"all"`) +- `verbose` — Show detailed validation issues per skill (default: `false`) + +**Example:** +``` +kb_list_skills + scope: global + status: enabled + verbose: true +``` + +### `kb_fix_skill` — Validate and repair a skill-source article + +Checks a skill-source article for missing required tags and broken frontmatter, then repairs them automatically. Can also enable disabled skills and fix name/description mismatches. + +Required parameters: +- `articleSlug` — Slug of the skill-source article to fix + +Optional parameters: +- `fixTags` — Add missing required tags (type, kind, skill_ref, skill_name, audience, format, source). Default: `true` +- `fixFrontmatter` — Add or repair inner embedded frontmatter (name, description). Default: `true` +- `enable` — Change `skill:disabled` → `skill:enabled` +- `name` — Override skill name (updates both tag:skill_name and inner frontmatter) +- `description` — Override description (updates inner frontmatter description) +- `source` — Override source tag value (default: `"user"`) + +**Example (fix a broken skill and enable it):** +``` +kb_fix_skill + articleSlug: "my-broken-skill-source" + fixTags: true + fixFrontmatter: true + enable: true + name: "my-fixed-skill" + description: "A repaired skill" +``` + +**Example (preview issues):** +``` +kb_list_skills + scope: global + verbose: true +``` +See validation issues before fixing anything, then apply `kb_fix_skill` as needed. + +## Install targets + +| Scope | Directory | +|-------|-----------| +| `local` (default) | `/.pi/skills//` | +| `global` | `~/.pi/agent/skills//` | + +## Tag schema reference + +### Required tags for skill-source article + +| Tag | Value | Purpose | +|-----|-------|---------| +| `type` | `skill` | Identifies as a skill definition | +| `kind` | `skill-source` | Distinguishes from doc articles | +| `skill` | `enabled` or `disabled` | Opt-in flag; only `enabled` loads | +| `skill_ref` | `` | Shared identifier linking source + doc | +| `skill_name` | `` | Runtime name for cache dir and SKILL.md | +| `audience` | `agent` | Marks as machine-oriented | +| `format` | `agent-skill` | Content format | +| `source` | `user` | Origin tracking | + +### Required tags for documentation article + +| Tag | Value | Purpose | +|-----|-------|---------| +| `type` | `guide` | Identifies as guidance content | +| `kind` | `skill-doc` | Distinguishes from source articles | +| `skill_ref` | `` | Links to the skill-source article | +| `skill_name` | `` | Reference to the skill name | +| `audience` | `human` | Marks as human-readable | + +### Skill metadata (name + description) + +The loader accepts `name` and `description` from two places: + +1. **Inner frontmatter** (preferred) — an embedded `---` block within the article body: + ```markdown + --- + name: my-skill + description: Does X + --- + Body content... + ``` +2. **Outer article frontmatter** (fallback) — `name` and `description` fields in the article's own frontmatter, used when no inner frontmatter is present + +## Validation checklist + +When creating or editing a skill-source article, verify: + +### Hard requirements (skip if missing) +- `type:skill`, `kind:skill-source`, `skill:enabled` tags present +- `skill_ref` and `skill_name` tags are non-empty +- `skill_name` matches `/^[a-z0-9]+(-[a-z0-9]+)*$/` (max 64 chars) +- Skill `name` (inner or outer) matches `skill_name` tag exactly +- `description` is non-empty +- Body content is non-empty + +### Recommended +- `status:stable` or `status:draft` for lifecycle tracking +- `project:knowledge-base-skills` tag +- `domain:` tags for discovery +- `tool:` tags for related tools + +## Troubleshooting + +### "description is required" or skill not loading + +If pi shows this error after installing: +1. Check `//SKILL.md` — does it have `name:` and `description:` in frontmatter? +2. If not, the KB article lacks these fields — ensure the article has `name` and `description` either as inner frontmatter or as outer frontmatter fields +3. Clean the stale copy and re-install: `rm -rf ./pi/agent/skills/` and run `kb_install_skill` again + +### Skill not found after install + +1. Verify the KB article has tags: `type:skill`, `kind:skill-source` +2. Ensure you used the correct `articleSlug` +3. Run `/reload` in pi to re-discover installed skills +4. Check `KB_SKILLS_KB_PATH` env var if the KB is at a custom path diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/skill/SOURCE.json b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/skill/SOURCE.json new file mode 100644 index 0000000000000000000000000000000000000000..86c8011149ee9a862fb22f1e666cbbc6d4065c97 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/skill/SOURCE.json @@ -0,0 +1,6 @@ +{ + "skillName": "knowledge-base-skills", + "skillRef": "knowledge-base-skills", + "articleSlug": "knowledge-base-skills-skill-source", + "articlePath": "articles/knowledge-base-skills-skill-source/ARTICLE.md" +} diff --git a/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/task.json b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5594ce3f245ddf4dfe4bfa6665242acd9f6ae78d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aed26083404e28ca4473d673/task.json @@ -0,0 +1,82 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "aed26083404e28ca4473d673", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "aed26083404e28ca4473d673", + "outputs": [ + "validate_skills.py" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "229f8fcddfa22496e2110676da56c78e078cf34747f675dbbe282644c87518be", + "files": { + "SKILL.md": "6e277a5c0b04c07d01ff5503c319ce741cb4e31c0e906539dd9450f93be5755a", + "SOURCE.json": "d0977911ac156f8df43e13582c3541b12c870b67dd3aa96ba22abfd032c627c4" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/articles/backup-tool-skill-source.md", + "workspace_target": "articles/backup-tool-skill-source.md", + "sha256": "dabf5929969d7c0e3d055d3976a13b3042cb519892d55aef18e8c0ef63ac793e" + }, + { + "source": "inputs/articles/code-review-helper-skill-source.md", + "workspace_target": "articles/code-review-helper-skill-source.md", + "sha256": "c1a94e843bcee4e050dbc028b5bf37c2d0bf7eb3c5a5bdc206afbfebf87f8606" + }, + { + "source": "inputs/articles/note-taker-skill-source.md", + "workspace_target": "articles/note-taker-skill-source.md", + "sha256": "024dedc6904631b9177cb2e7df3a954de34cb517364f6a7b5c8ce31a2df2afff" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "229f8fcddfa22496e2110676da56c78e078cf34747f675dbbe282644c87518be" + } + ] + }, + "autograde_runtime_contract": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60 + }, + "automatic_evaluation_runtime": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/aee86167b6632164dcf30121/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..27a58f3c3d272ec8f5617b77eb33dcce4f07532c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_contract.json @@ -0,0 +1,22 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/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/aee86167b6632164dcf30121/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..bc69f81e085c631459f91368df8f1efe32cafb5f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_policy.json @@ -0,0 +1,16 @@ +{ + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/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/aee86167b6632164dcf30121/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/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('not\s+)?(?:expected|required)(?:\s+(?:to\s+be|to|is)|\s*:)?|(?:must|should))\s+(?Pnot\s+)?(?:be\s+)?(?Ppresent|absent|appear|occur)\b' + for match in re.finditer(grammar,prose): + presence=match['state']in('present','appear','occur') + if match['outer']:presence=not presence + if match['neg']:presence=not presence + claims.append(presence) + if re.search(r'(?=0 +def main(): + flags=[True]*5;cand=Path('/candidate') + try:actual=json.loads((cand/'report.json').read_text())if(cand/'report.json').is_file()else None + except(OSError,ValueError,UnicodeError,RecursionError):actual=None + flags[2]=report_ok(actual,oracle(CRITERIA,LOG)) + if not(cand/'verify_dod.py').is_file():return [False]*5 + good,mods,reason=scan_stdlib(cand,['verify_dod.py']);flags[0]=None if reason.startswith('unknown:')else good + criteria=[dict(id='K-z',description='literal punctuation must stay literal',check=dict(type='log_contains',pattern='a.b')),dict(id='K-a',description='forbidden marker absent',check=dict(type='log_not_contains',pattern='panic[')),dict(id='K-x',description='line bounds and duplicate hits',check=dict(type='log_contains',pattern='READY'))] + panels=[(CRITERIA,LOG,True),(criteria,'aXb\nREADY READY\n\nREADY\npanic[ repeated\n',False),(criteria,'a.b\nREADY\na.b\nREADY\n',True),(criteria,'nothing matches\n',False),([], '',False)] + for cs,log,wrapped in panels: + reports,shape,protocol,ran=fresh(cs,log,wrapped);flags[0]=tri([flags[0],ran]);flags[1]=tri([flags[1],reports]);flags[2]=tri([flags[2],shape]);flags[3]=tri([flags[3],protocol]) + if cs==CRITERIA: + flags[2]=tri([flags[2],reports]);flags[4]=tri([flags[4],reports,protocol]) + return flags +try: + flags=main();print(json.dumps({'scoreable':all(v is not None for v in flags),'checks':[dict(id=str(i),passed=v,reason='Source report2 and independently changed literal match/evidence1, typed schema2, exact blocker exit/stdout3 and original all-pass witness4. Plain DONE whitespace and id-followed-pattern separators accepted. Contradictory expected presence/absence fails3; required pass/passed native-Boolean report schema. Scoped dependencies and complete mirrored resources.')for i,v in enumerate(flags)]})) +except Exception as exc:raise RuntimeError('Trusted definition-of-done grader failed')from exc diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/hardening_contract.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/hardening_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..5b8b0435bf1bdcf3e57147f3a0124182ac44cf04 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/hardening_contract.json @@ -0,0 +1,14 @@ +{ + "query_id": "aee86167b6632164dcf30121", + "append_check_ids": [ + "5", + "6", + "7" + ], + "skill_anchors": [ + "skill/SKILL.md:36-53", + "skill/SKILL.md:55-77", + "skill/SKILL.md:103-115" + ], + "public_mode": "--journal attempts.json" +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..1b1712a46884a8d7cea4b5c3feddfa376da33cba --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/repair_manifest.json @@ -0,0 +1,48 @@ +{ + "query_id": "aee86167b6632164dcf30121", + "sample_index": 669, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4" + ], + "original_count": 5, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4" + ], + "root_cause": "Private evidence colon and DONE whitespace constraints rejected equivalents; reverse presence/absence was keyword-accepted; global pending/bool coercion fabricated report failures and temp/scanner layout rejected aliases/resources. Explicit expectation polarity previously confused must not be present with must be present.", + "public_semantics": "EVIDENCE id follows by pattern with harmless separators, explicit wrong expected polarity fails3; DONE outer whitespace accepted. Unknown Boolean/report representation remains relevant1/2/4None independent of known bad decision3False. Changed match truth1 and schema/sample2 retain separate diagnostics, explicit exit protocol3 unchanged.", + "source_hashes": { + "instruction.md": "9a65e0ff33bae1316a7ecfce843075848adcab5d2212f8769ac18394f3f37116", + "task.json": "3a85201c04557f7f6ed90481d22c745e78bf6601400d1854437d5092275d86ac", + "evaluator/check.py": "8b0eca945268d6eb15ef633582ef0861fcc2ddbdf854213a0af989b2d343cc56", + "skill/SKILL.md": "c782347b31cca1f9253e554b8717ec8ae5fdff755f16c92f459af788e632b85a", + "inputs/criteria.json": "6612262795f9284e6e362a80aa005064e3845d5a60542ec5a01b2888857a701b", + "inputs/runtime.log": "0784daafa2454e25b49e07bb7350aaeed2267426cc872f27d71a19e475cdd376" + }, + "required_historical_artifacts": [], + "checker_sha256": "262248ae5fc3e9b50309bc551f833038e8aacc8b9e04012d4a1806478c233305", + "all_logic_sha256": { + "check.py": "262248ae5fc3e9b50309bc551f833038e8aacc8b9e04012d4a1806478c233305", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": [ + "Read complete public/old/current/relevant skill/inputs/reference/script/report/answer and all unique controls. Full typed unknown+knownfalse, dash/polarity/whitespace, app/resource/computed0None controls added. Reused exact reviewed589 helpers; AST only; no solver/candidate/grader execution or historical rescoring.", + "Same-owner report truth aggregates every row rather than early-return on unsupported Boolean key; added unknown-first-row plus definite wrong later description2False control.", + "Manifest-only integration repair: remove candidate-output filenames/dotted source metadata selector from required_historical_artifacts, which expects normalized replay-row external path keys. Actual artifacts are graded by checker;607 missing trusted date trace is already per-ID3None. No checker or fixture changes in this seal.", + "Owned stdout expectation grammar now binds present/absent/appear/occur and exact modal negation, including must not be absent; no arbitrary proximity. Added same-grammar positive/reverse and unrelated-negation controls. No local candidate execution." + ], + "repair_scope": "grader_only_second_round", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..92b57ae29e6fd3e02487af3d613d7dccb07e08bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..af7f58b98229e1ada5d408141fb019dce60ad48d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/grading/verified_config.json @@ -0,0 +1,46 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "aee86167b6632164dcf30121", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7" + ], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3", + "hard_previous.py": "f6f6cf5e7bd1061a1032493c8c5f5a844702851db7671466509207aa59466796", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f245803a06b801617e2ec10e3bf5d2705663cbbcecbb21fff72555eaa9796161", + "hardening_contract.json": "b76a913f4675a2191d97853f8268d35fc406052c5ba38910560462b7ac553368", + "repair_manifest.json": "fea5c11aafa069f6416c4673d385c9cadb72e7670c651ffe9f7e62182fa2f987", + "dependency_scan.py": "aff23360095bcb8289ad65e861c5fe29ae8b9c355ae7cab23f306d1e20c81f67", + "hard_journal.py": "2999f88b10cc89fae644c8ef9000d65237ec6f36c24b51dace88660fb1b31ce0", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a89aa6d2e36dff9459af4e1053065567275ad070e54ba9e9142a81d491dddbff", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "1973ab59d6c798839dc76976e2cf6ec72facd1f60b833ebabefed0e297a7ccd7" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/attempts.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/attempts.json new file mode 100644 index 0000000000000000000000000000000000000000..ed6e8627e77fb83d1f11a153db4f36cd5da6ce6c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/attempts.json @@ -0,0 +1,18 @@ +{ + "issue_status": "ready", + "execution_gate": "allowed", + "attempts": [ + { + "id": "initial", + "log": "GET /health 200 ok\nprovider failed before payment creation\n" + }, + { + "id": "fixed", + "log": "GET /health 200 ok\npayment_url=https://pay.example/dev/42\n" + }, + { + "id": "later_unprocessed", + "log": "Traceback (most recent call last)\n" + } + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/criteria.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/criteria.json new file mode 100644 index 0000000000000000000000000000000000000000..32aaaf4b2f257d2877dd41f496b780823c0d150b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/criteria.json @@ -0,0 +1,19 @@ +{ + "criteria": [ + { + "id": "AC-1", + "description": "health endpoint returned 200 in dev", + "check": { "type": "log_contains", "pattern": "GET /health 200" } + }, + { + "id": "AC-2", + "description": "no unhandled exceptions during smoke test", + "check": { "type": "log_not_contains", "pattern": "Traceback (most recent call last)" } + }, + { + "id": "AC-3", + "description": "payment URL was generated", + "check": { "type": "log_contains", "pattern": "payment_url=" } + } + ] +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/runtime.log b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/runtime.log new file mode 100644 index 0000000000000000000000000000000000000000..2173d9f22f80f92d4de8544b72c3a9ecb8f0a593 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/inputs/runtime.log @@ -0,0 +1,4 @@ +2026-03-12T10:00:01Z INFO starting dev deploy +2026-03-12T10:00:04Z INFO GET /health 200 ok +2026-03-12T10:00:05Z INFO payment_url=https://pay.example.dev/inv_42 +2026-03-12T10:00:06Z INFO smoke test finished diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/instruction.md b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d4d4b7d5fe9035df75d3b01a8e72ae4dc9089ae --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/instruction.md @@ -0,0 +1,22 @@ +Write a Python 3 script `verify_dod.py` (standard library only) that performs a closed-loop Definition-of-Done verification for a small service task. It must read `criteria.json` and `runtime.log` (captured dev-deploy runtime output). The criteria input is either a list or an object with a `criteria` field containing that list; both are supported input adapters, including in journal mode. Each criterion has an `id`, `description`, and `check` object specifying a `type` of either "log_contains" or "log_not_contains" plus a `pattern` string. For each criterion, evaluate the check against the log contents using substring matching on each log line, and write `report.json` containing: for every criterion its id, description, pass/fail boolean, and the matching log line number(s) as evidence (line numbers are 1-based; for "log_not_contains" criteria, evidence is the empty list when passing). The script must exit with code 0 only if ALL criteria pass, otherwise exit code 1. When any criterion fails, the script must additionally print a blocker report to stdout with exactly four sections in this order: `PASSED:` (comma-separated ids of passing criteria or `none`), `FAILED:` (comma-separated ids of failing criteria), `EVIDENCE:` (for each failed criterion, its id followed by the pattern that was expected to be present or absent), and `DECISION:` (the single smallest decision needed, which is `fix implementation and re-run verification` when at least one criterion failed). When all criteria pass, print only `DONE` to stdout. Verify correctness by running the script against the provided sample inputs and checking `report.json` and the exit code. + +Also support an offline multi-round replay mode: `python3 verify_dod.py --journal attempts.json`. The original no-argument mode and every original output/exit requirement remain unchanged. Journal mode reads the same criteria.json and an attempts document with `issue_status` (`ready` or `draft`), `execution_gate` (`allowed` or `blocked`), optional positive-integer `max_rounds` (use the frozen closed-loop-delivery Skill Required Inputs default when absent), and `attempts` in chronological order. Each attempt has a unique `id`, complete `log` text for that round, optional boolean `conflict` (default false), and optional `external_blocker` (null/empty or a nonempty string). Inputs in this mode are well-formed; this task requires no real deployment, issue tracker, sleeps, or network calls. + +Journal decision rules (first applicable stop wins): +- Before processing any round, a draft issue or blocked execution gate yields BLOCKED / issue_gate; process zero rounds and do not infer acceptance from logs. +- Process at most max_rounds. A round with conflict=true stops BLOCKED / conflicting_instructions. Otherwise a nonempty external_blocker stops BLOCKED / external_dependency, even if its log looks successful. Such a stopped round counts as processed and has results []. +- For each ordinary round, independently evaluate EVERY criterion against that round's log using the original substring/line-number rules. Never accumulate passing criteria or evidence across rounds. The first round where all criteria pass stops DONE / all_criteria_passed, ignoring every later attempt. +- If max_rounds ordinary failing rounds have been processed, stop ESCALATE / max_rounds and ignore later attempts. If supplied evidence runs out before the budget and no earlier stop applied, stop BLOCKED / evidence_exhausted. An empty attempts list is evidence_exhausted, never DONE. + +Write journal_report.json with exactly these fields: decision, reason, rounds_processed, rounds, blocking_detail, smallest_decision. rounds preserves processed attempt order; each element is {"id": , "results": [{"id": , "description": , "passed": , "evidence": }]} with criteria in input order. blocking_detail is the exact external_blocker string only for external_dependency, otherwise null. smallest_decision is: `none` for DONE; `make issue ready and execution allowed` for issue_gate; `resolve conflicting review instructions` for conflicting_instructions; `resolve external dependency` for external_dependency; `fix implementation and re-run verification` for max_rounds; and `provide next runtime evidence` for evidence_exhausted. rounds_processed equals len(rounds). Print only the decision token and a newline; exit 0 for DONE, 1 for ESCALATE, or 2 for BLOCKED. + +The journal requirement is a runnable program interface: journal_report.json must be produced when --journal is invoked. A pre-generated journal report in the submitted workspace is optional; the original explicit sample verification remains required. + +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. + +Deterministic ordinary-mode report schema: report.json is either an array of criterion-result objects or an object containing exactly one array-valued field with those result objects (other non-array metadata is allowed). Every result must contain id, description, evidence (array of native JSON integer line numbers), and at least one of pass or passed as a native JSON boolean; if both are present they must agree. Alternative boolean-field names, numeric0/1 and ambiguous multiple-result arrays are invalid outputs. This schema clarification applies to ordinary verification mode; journal-mode protocol and all journal behavior remain as specified. + + +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/aee86167b6632164dcf30121/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..0de9f2aa844da318d1faeea38fe23d71ce3dd089 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/skill/SKILL.md @@ -0,0 +1,124 @@ +--- +name: closed-loop-delivery +description: >- + Use when a coding task must be completed against explicit acceptance criteria with minimal user re-intervention across implementation, review feedback, deployment, and runtime verification. +license: CC-BY-4.0 +metadata: + category: workflow + source: + repository: 'https://github.com/sickn33/antigravity-awesome-skills' + path: skills/closed-loop-delivery + license_path: LICENSE-CONTENT + original_metadata: + risk: 'safe' + source: 'community' + date_added: '2026-03-12' +--- +# Closed-Loop Delivery + +## Overview + +Treat each task as incomplete until acceptance criteria are verified in evidence, not until code is merely changed. + +Core rule: **deliver against DoD (Definition of Done), not against code diff size.** + +## When to Use +Use this skill when: +- user gives a coding/fix task and expects end-to-end completion +- task spans code + tests + PR comments + dev deploy + runtime checks +- repeated manual prompts like "now test", "now deploy", "now re-check PR" should be avoided + +Do not use this skill for: +- pure Q&A/explanations +- prod deploy requests without explicit human approval +- tasks blocked by missing secrets/account access that cannot be inferred + +## Required Inputs + +Before execution, define these once: +- task goal +- acceptance criteria (DoD) +- target environment (`dev` by default) +- max iteration rounds (default `2`) + +If acceptance criteria are missing, request them once. If user does not provide, propose a concrete default and proceed. + +## Issue Gate Dependency + +Before execution, prefer using `create-issue-gate`. + +- If issue status is `ready` and execution gate is `allowed`, continue. +- If issue status is `draft`, do not execute implementation/deploy/review loops. +- Require user-provided, testable acceptance criteria before starting execution. + +## Default Workflow + +1. **Define DoD** + - Convert request into testable criteria. + - Example: checkout task DoD = "checkout endpoint returns a valid, openable third-party payment URL in dev". + +2. **Implement minimal change** + - Keep scope tight to task goal. + +3. **Verify locally** + - Run focused tests first, then broader checks if needed. + +4. **Review loop** + - Fetch PR comments/reviews. + - Classify valid vs non-actionable. + - Fix valid items, re-run verification. + +5. **Dev deploy + runtime verification** + - Deploy to `dev` when runtime behavior matters. + - Verify via real API/Lambda/log evidence against DoD. + +6. **Completion decision** + - Only report "done" when all DoD checks pass. + - Otherwise continue loop until pass or stop condition. + +## PR Comment Polling Policy + +Avoid noisy short polling by default. Use batched windows: + +- **Round 1:** wait `3m`, collect delta comments/reviews +- **Round 2:** wait `6m`, collect delta again +- **Final round:** wait `10m`, collect all remaining visible comments/reviews + +At each round: +- process all new comments in one batch +- avoid immediate re-poll after each single comment +- after the `10m` round, stop waiting and proceed with all comments visible at that point + +If CI is still running, align polling to check completion boundaries instead of fixed rapid polling. + +## Human Gate Rules (Must Ask) + +Require explicit user confirmation for: +- production/staging deploy beyond agreed scope +- destructive operations (history rewrite, force push, data-destructive ops) +- actions with billing/security posture changes +- secret values not available in repo/runtime +- ambiguous DoD that materially changes outcome + +## Iteration/Stop Conditions + +Stop and escalate with a concise blocker report when: +- DoD still fails after max rounds (`2` default) +- external dependency blocks progress (provider outage, missing creds, account permission) +- conflicting review instructions cannot both be satisfied + +Escalation report must include: +- what passed +- what failed +- evidence (commands/logs/API result) +- smallest decision needed from user + +## Output Contract + +When claiming completion, always include: +- acceptance criteria checklist with pass/fail +- commands/tests run +- runtime evidence (endpoint/Lambda/log key lines) +- PR status (new actionable comments count) + +Do not claim success without evidence. diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/skill/SOURCE_METADATA.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/skill/SOURCE_METADATA.json new file mode 100644 index 0000000000000000000000000000000000000000..b6e8eb550715d4f99a02667a7796b219706688ab --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/skill/SOURCE_METADATA.json @@ -0,0 +1,26 @@ +{ + "id": "closed-loop-delivery", + "upstream_path": "skills/closed-loop-delivery", + "category": "workflow", + "description": "Use when a coding task must be completed against explicit acceptance criteria with minimal user re-intervention across implementation, review feedback, deployment, and runtime verification.", + "risk": "safe", + "source": "community", + "date_added": "2026-03-12", + "plugin": { + "targets": { + "codex": "supported", + "claude": "supported" + }, + "setup": { + "type": "none", + "summary": "", + "docs": null + }, + "reasons": [] + }, + "conversion": { + "mode": "skip", + "copied_files": 1, + "rewritten_frontmatter": true + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/task.json b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6ebd75cd6ebbf3f24047c094ae26333843d2a230 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/aee86167b6632164dcf30121/task.json @@ -0,0 +1,87 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "aee86167b6632164dcf30121", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "aee86167b6632164dcf30121", + "outputs": [ + "verify_dod.py", + "report.json" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "kind_ignore": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "308f371f9f50d4fbe27fd32570a022b7b3edf40e149c4aa569f33ba45971fab1", + "files": { + "SKILL.md": "c782347b31cca1f9253e554b8717ec8ae5fdff755f16c92f459af788e632b85a", + "SOURCE_METADATA.json": "11376ff3d872c27fa528f918ae02934e78c1696b57fadb6ecb34da5fdb01aba5" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/criteria.json", + "workspace_target": "criteria.json", + "sha256": "6612262795f9284e6e362a80aa005064e3845d5a60542ec5a01b2888857a701b" + }, + { + "source": "inputs/runtime.log", + "workspace_target": "runtime.log", + "sha256": "0784daafa2454e25b49e07bb7350aaeed2267426cc872f27d71a19e475cdd376" + }, + { + "source": "inputs/attempts.json", + "workspace_target": "attempts.json", + "sha256": "28334f4d74e88c64cc9ebce32ff1c04235d7b4082972945cc50092caffa16439" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "308f371f9f50d4fbe27fd32570a022b7b3edf40e149c4aa569f33ba45971fab1" + } + ] + }, + "generated_outputs_on_invocation": [ + "journal_report.json" + ], + "autograde_runtime_contract": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60 + }, + "automatic_evaluation_runtime": { + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "owner_ids": [ + "0" + ], + "require_execution": true, + "scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.", + "execution_budget_seconds": 60, + "runtime_owner_ids": [ + "0" + ], + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/af4438bc4d445682_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_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/af4438bc4d445682_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_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/af4438bc4d445682_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_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/af4438bc4d445682_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/af4438bc4d445682_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..c03f64348caa714a2797a7d6488d9a515c65d380 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,455 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i&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/af4438bc4d445682_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..400da41145f3344c7a6d6d3b24a9810e6c6f59cb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,554 @@ +"""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 math +import posixpath +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 _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + try: + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + except RecursionError as error: + raise ValueError('Candidate JSON nesting is too deep') from error + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + try:is_finite=finite(result) + except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error + if not is_finite:raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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(_strict_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_equal(actual, 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/af4438bc4d445682_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..22bdb4df05c8e0e71b92b559a241072fd46cace3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_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/af4438bc4d445682_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..02e1c3b693a0508f8fd24e5527f6dfff8766f736 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "engine": "portable_verified_v1", + "grader_file_sha256": { + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "d44e27583fb5e2fa2790cc2129b8c7bcb344eee41925d3c7ba1338a5182dc51f", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b", + "repair_equivalences.py": "bb8e82984f5e10c54f739b955e6fa91f1c3615acfb73bcab071f8ff69e05e0a6" + }, + "query_id": "af4438bc4d445682_q1", + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "criterion_weights": { + "0": 1 + }, + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "grader_timeout_seconds": 600, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ] + }, + "schema": "audited-verified-grader-v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703" +} diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e967e860edf92842ce314b10f1f33672dbd2b04e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/instruction.md @@ -0,0 +1 @@ +We just finished configuring OAuth2 PKCE user-context credentials for our X API v2 integration and bound them to the API host. Before we let our automation start running timeline and bookmark workflows, I want one straight-line shell script at output/verify_x_setup.sh that we can run to sanity-check the whole setup. It needs to do three things, in order, as top-level commands with no control flow: first, confirm that our OpenAPI-backed CLI for the X API is linked/present in this environment; second, verify that the user-context auth binding is actually attached to the https://api.x.com/2 host; and third, perform a single read of the authenticated user's own profile (the current-user account endpoint) as a smoke test. If any command fails, the script must stop immediately and exit nonzero — no continuing past a failure and no suppressing errors. Please create the script at exactly output/verify_x_setup.sh following our repo's conventions for these scripts. diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b6b85422f0462a3f70d765f82ce423457c8eb54d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/SKILL.md @@ -0,0 +1,162 @@ +--- +name: x-openapi-skill +description: Operate X API v2 through UXC with the official OpenAPI schema, OAuth2 PKCE user-context auth, app-only bearer guidance, and read-first guardrails for timeline/bookmark/post workflows. +--- + +# X API Skill + +Use this skill to run X API v2 operations through `uxc` + OpenAPI. + +Reuse the `uxc` skill for shared execution, auth, and error-handling guidance. + +## Prerequisites + +- `uxc` is installed and available in `PATH`. +- Network access to `https://api.x.com`. +- Access to the official OpenAPI schema URL: + - `https://api.x.com/2/openapi.json` +- An X developer app with OAuth2 enabled. + +## Authentication + +### Preferred Path: OAuth2 Authorization Code + PKCE (User Context) + +This path is required for user-context operations such as bookmarks, home timeline, posting, replying, and DM actions. + +1. Start OAuth2 login: + +```bash +uxc auth oauth start x-api-user \ + --endpoint https://api.x.com/2 \ + --client-id M3VseG9xOXZXZVREZnNqWk9jN1I6MTpjaQ \ + --redirect-uri http://127.0.0.1:11111/callback \ + --scope users.read \ + --scope tweet.read \ + --scope tweet.write \ + --scope tweet.moderate.write \ + --scope media.write \ + --scope like.read \ + --scope like.write \ + --scope follows.read \ + --scope follows.write \ + --scope list.read \ + --scope list.write \ + --scope timeline.read \ + --scope space.read \ + --scope mute.read \ + --scope mute.write \ + --scope block.read \ + --scope block.write \ + --scope bookmark.read \ + --scope bookmark.write \ + --scope dm.read \ + --scope dm.write \ + --authorization-endpoint https://x.com/i/oauth2/authorize \ + --token-endpoint https://api.x.com/2/oauth2/token +``` + +This default example intentionally includes the full OAuth2 user scope set exposed by the current X OpenAPI surface, excluding `offline.access` to avoid refresh-token compatibility failures observed on some X app configurations. Add `--scope offline.access` only when you explicitly need long-lived refresh behavior and have verified token refresh works for your app. + +2. Open the returned authorization URL in browser and finish consent. +3. Complete login with the callback URL: + +```bash +uxc auth oauth complete x-api-user \ + --session-id \ + --authorization-response '' +``` + +4. Bind credential to X API: + +```bash +uxc auth binding add \ + --id x-api-user \ + --host api.x.com \ + --path-prefix /2 \ + --scheme https \ + --credential x-api-user \ + --priority 100 +``` + +5. Verify binding: + +```bash +uxc auth binding match https://api.x.com/2 +``` + +### Optional Path: App-only Bearer Token (Public Reads) + +App-only bearer auth is useful for selected public read endpoints. + +Do not embed bearer tokens in this skill or repository. Configure local credentials only. + +```bash +uxc auth credential set x-api-app \ + --auth-type bearer \ + --secret-env X_API_BEARER_TOKEN + +uxc auth binding add \ + --id x-api-app \ + --host api.x.com \ + --path-prefix /2 \ + --scheme https \ + --credential x-api-app \ + --priority 90 +``` + +Use `--auth x-api-app` when you intentionally want app-only requests. + +## Core Workflow + +1. Use fixed link command by default: + - `command -v x-openapi-cli` + - If missing, create it: + `uxc link x-openapi-cli https://api.x.com --schema-url https://api.x.com/2/openapi.json` + - `x-openapi-cli -h` + +2. Inspect operation schema first: + - `x-openapi-cli get:/2/users/me -h` + - `x-openapi-cli get:/2/users/{id}/bookmarks -h` + - `x-openapi-cli post:/2/tweets -h` + +3. Execute reads before writes: + - `x-openapi-cli get:/2/users/me` + - `x-openapi-cli get:/2/users/{id}/bookmarks id= max_results=20` + - `x-openapi-cli get:/2/users/{id}/timelines/reverse_chronological id= max_results=20` + +4. Execute writes with explicit user confirmation: + - key/value: + `x-openapi-cli post:/2/tweets text='hello from uxc'` + - positional JSON: + `x-openapi-cli post:/2/tweets '{"text":"hello from uxc"}'` + +## Subscribe / Stream Status + +X stream endpoints are HTTP streaming routes and can be used with `uxc subscribe` raw HTTP stream mode. + +Example: + +```bash +uxc subscribe start https://api.x.com/2/tweets/search/stream \ + --auth x-api-app \ + --sink file:$HOME/.uxc/subscriptions/x-search-stream.ndjson +``` + +Use the relevant stream rule-management endpoints before starting stream consumers. + +## Guardrails + +- Keep automation on JSON output envelope; do not use `--text`. +- Parse stable fields first: `ok`, `kind`, `protocol`, `data`, `error`. +- `x-openapi-cli ...` is equivalent to + `uxc https://api.x.com --schema-url https://api.x.com/2/openapi.json ...`. +- OAuth2 PKCE is the default path for user-context operations. +- Do not commit or hardcode bearer tokens, client secrets, or refresh tokens. +- Treat `post:/2/tweets`, DM endpoints, bookmark write endpoints, and stream rule mutation endpoints as write/high-risk operations; require explicit user confirmation before execution. + +## References + +- Usage patterns: `references/usage-patterns.md` +- X API OpenAPI schema: `https://api.x.com/2/openapi.json` +- X OAuth2 authorization code with PKCE: `https://docs.x.com/fundamentals/authentication/oauth-2-0/authorization-code` +- X OAuth2 app-only bearer auth: `https://docs.x.com/fundamentals/authentication/oauth-2-0/application-only` diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/agents/openai.yaml b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3248631a162d1f11383015ad8da88c95d6700038 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "X API v2" + short_description: "Operate X API v2 via UXC + official OpenAPI schema with OAuth2 PKCE and stream-capable workflows" + default_prompt: "Use $x-openapi-skill to discover and execute X API v2 operations through UXC with OAuth2 PKCE user-context auth, optional app-only bearer reads, and read-first/write-confirmed guardrails." diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/references/usage-patterns.md b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/references/usage-patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..eae28d0a5e577623a3e29582316fd5c2eb1f9668 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/references/usage-patterns.md @@ -0,0 +1,133 @@ +# X API Skill - Usage Patterns + +## Link Setup + +```bash +command -v x-openapi-cli +uxc link x-openapi-cli https://api.x.com \ + --schema-url https://api.x.com/2/openapi.json +x-openapi-cli -h +``` + +## OAuth2 PKCE Setup (User Context) + +```bash +uxc auth oauth start x-api-user \ + --endpoint https://api.x.com/2 \ + --client-id M3VseG9xOXZXZVREZnNqWk9jN1I6MTpjaQ \ + --redirect-uri http://127.0.0.1:11111/callback \ + --scope users.read \ + --scope tweet.read \ + --scope tweet.write \ + --scope tweet.moderate.write \ + --scope media.write \ + --scope like.read \ + --scope like.write \ + --scope follows.read \ + --scope follows.write \ + --scope list.read \ + --scope list.write \ + --scope timeline.read \ + --scope space.read \ + --scope mute.read \ + --scope mute.write \ + --scope block.read \ + --scope block.write \ + --scope bookmark.read \ + --scope bookmark.write \ + --scope dm.read \ + --scope dm.write \ + --authorization-endpoint https://x.com/i/oauth2/authorize \ + --token-endpoint https://api.x.com/2/oauth2/token +``` + +Default flow uses the full OAuth2 user scope set except `offline.access`; drop unneeded scopes for least-privilege access when your workflow is narrower. Add `--scope offline.access` only when you need refresh tokens and your X app supports token refresh for this client. + +After browser consent: + +```bash +uxc auth oauth complete x-api-user \ + --session-id \ + --authorization-response '' +``` + +Bind and verify: + +```bash +uxc auth binding add \ + --id x-api-user \ + --host api.x.com \ + --path-prefix /2 \ + --scheme https \ + --credential x-api-user \ + --priority 100 + +uxc auth binding match https://api.x.com/2 +``` + +## App-only Bearer Setup (Optional) + +```bash +uxc auth credential set x-api-app \ + --auth-type bearer \ + --secret-env X_API_BEARER_TOKEN + +uxc auth binding add \ + --id x-api-app \ + --host api.x.com \ + --path-prefix /2 \ + --scheme https \ + --credential x-api-app \ + --priority 90 +``` + +## Read Examples + +```bash +x-openapi-cli get:/2/users/me + +x-openapi-cli get:/2/users/{id}/bookmarks \ + id= \ + max_results=20 + +x-openapi-cli get:/2/users/{id}/timelines/reverse_chronological \ + id= \ + max_results=20 +``` + +Incremental reads with `since_id`: + +```bash +x-openapi-cli get:/2/users/{id}/timelines/reverse_chronological \ + id= \ + since_id= \ + max_results=20 +``` + +## Write Examples (Confirm Before Running) + +```bash +x-openapi-cli post:/2/tweets text='hello from uxc' + +x-openapi-cli post:/2/tweets '{"text":"hello from uxc"}' +``` + +Reply: + +```bash +x-openapi-cli post:/2/tweets \ + '{"text":"reply from uxc","reply":{"in_reply_to_tweet_id":""}}' +``` + +## Stream Subscribe Example + +```bash +uxc subscribe start https://api.x.com/2/tweets/search/stream \ + --auth x-api-app \ + --sink file:$HOME/.uxc/subscriptions/x-search-stream.ndjson +``` + +## Fallback Equivalence + +- `x-openapi-cli ...` is equivalent to + `uxc https://api.x.com --schema-url https://api.x.com/2/openapi.json ...`. diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/scripts/validate.sh b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/scripts/validate.sh new file mode 100644 index 0000000000000000000000000000000000000000..d174518bac70bad132dd201dbe2b5f4496cab545 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/skill/scripts/validate.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +SKILL_DIR="${ROOT_DIR}/skills/x-openapi-skill" +SKILL_FILE="${SKILL_DIR}/SKILL.md" +OPENAI_FILE="${SKILL_DIR}/agents/openai.yaml" +USAGE_FILE="${SKILL_DIR}/references/usage-patterns.md" + +fail() { + printf '[validate] error: %s\n' "$*" >&2 + exit 1 +} + +need_cmd() { + command -v "$1" >/dev/null 2>&1 || fail "required command not found: $1" +} + +need_cmd rg + +for file in "${SKILL_FILE}" "${OPENAI_FILE}" "${USAGE_FILE}"; do + [[ -f "${file}" ]] || fail "missing required file: ${file}" +done + +rg -q '^name:\s*x-openapi-skill\s*$' "${SKILL_FILE}" || fail 'invalid skill name' +rg -q '^description:\s*.+' "${SKILL_FILE}" || fail 'missing description' + +rg -q 'command -v x-openapi-cli' "${SKILL_FILE}" || fail 'missing link-first command check' +rg -q 'uxc link x-openapi-cli https://api.x.com --schema-url https://api.x.com/2/openapi.json' "${SKILL_FILE}" || fail 'missing fixed link create command with schema-url' +rg -q 'x-openapi-cli -h' "${SKILL_FILE}" || fail 'missing help-first host discovery example' +rg -q 'x-openapi-cli get:/2/users/me -h' "${SKILL_FILE}" || fail 'missing operation-level help example' + +rg -q 'uxc auth oauth start x-api-user' "${SKILL_FILE}" || fail 'missing oauth start flow' +rg -q -- '--client-id ' "${SKILL_FILE}" "${USAGE_FILE}" || fail 'missing oauth client-id guidance' +rg -q 'http://127.0.0.1:11111/callback' "${SKILL_FILE}" "${USAGE_FILE}" || fail 'missing redirect-uri guidance' +rg -q 'uxc auth binding match https://api.x.com/2' "${SKILL_FILE}" "${USAGE_FILE}" || fail 'missing binding match check' +rg -q 'Do not embed bearer tokens' "${SKILL_FILE}" || fail 'missing no-embedded-token guardrail' +rg -q 'positional JSON' "${SKILL_FILE}" || fail 'missing positional JSON guidance' + +if rg -q -- "--args\\s+'\\{" "${SKILL_FILE}" "${USAGE_FILE}"; then + fail 'found banned legacy JSON argument pattern' +fi + +rg -q '^\s*display_name:\s*"X API v2"\s*$' "${OPENAI_FILE}" || fail 'missing display_name' +rg -q '^\s*short_description:\s*".+"\s*$' "${OPENAI_FILE}" || fail 'missing short_description' +rg -q '^\s*default_prompt:\s*".*\$x-openapi-skill.*"\s*$' "${OPENAI_FILE}" || fail 'default_prompt must mention $x-openapi-skill' + +echo "skills/x-openapi-skill validation passed" diff --git a/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/task.json b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a7f57f184365b3ab9881789487e2230a8f473c8d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af4438bc4d445682_q1/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "af4438bc4d445682", + "query_id": "af4438bc4d445682_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/verify_x_setup.sh" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "7f2a0626624b1a8271039f7898211cd0261dc6a913628a8a840501bef99e4256", + "name": "x-openapi-skill", + "package_path": "skill", + "install_name": "x-openapi-skill-acc9636f" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "7f2a0626624b1a8271039f7898211cd0261dc6a913628a8a840501bef99e4256", + "files": { + "SKILL.md": "87c2a5f81d5e7107e20f99e1b5baa79fbc33a6c36528cc9485073dbd58167f0c", + "agents/openai.yaml": "5aa9779612863260cccd4eb4eec6cde61df70c0cf8c11162ad7fbe5397c2000d", + "references/usage-patterns.md": "3c6d8888d9d37440244884b5a59df21c3168c0a53168cbd53a26ecc2eb70e569", + "scripts/validate.sh": "c83065412075486d60fb93f90ba27f98fcb3235e5c427f08c38edcc9d73432e8" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "acc9636f92b7eddf73d5cf465f8a21612adc475adb1b82ad643e54ada54395a2" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/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/af9ed7786fd271a970e929f4/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..f2a331b07ad5792aa0fde5003054ed9d0f1554e3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_policy.json @@ -0,0 +1,14 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": false, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": false, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "purpose": "candidate timeout/result attribution only; no purity/resource restriction", + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/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/af9ed7786fd271a970e929f4/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/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('3 else None + forbidden='\n'.join(conf[:3]+conf[4:])+(frozen/'missing_output.txt').read_text()+(frozen/'check_output.txt').read_text() + special={'1':bool(good),'2':bool(uri_good),'4':bool(good and secret and secret not in forbidden)} + except Exception:special={'1':False,'2':False,'4':False} + checks=[] + for c in bchecks: + cid=str(c['id']); dc=dchecks.get(cid,{}) + ok=combine([c.get('passed'),dc.get('passed')]) + if cid in special:ok=combine([ok,special[cid]]) + if cid in CONFIG.get('presence_check_ids',[]):ok=combine([ok,not missing and not absent_wrong and not invalid_required]) + checks.append(dict(c,passed=ok,reason='behavior: %s; submitted delivery: %s%s'%(c.get('reason',''),dc.get('reason','missing check'),'; missing='+repr(missing) if missing else '; forbidden state='+repr(absent_wrong) if absent_wrong else ''))) + if set(dchecks)!={str(c['id']) for c in bchecks}:raise RuntimeError('check ID schema changed between views') + print(json.dumps({'scoreable':all(c.get('passed')is not None for c in checks),'checks':checks})) + except Exception as e: + print(json.dumps({'scoreable':False,'checks':[{'id':str(cid),'passed':None,'reason':'independent delivery evaluation failed: %s'%e} for cid in CONFIG['check_ids']]})) + +if __name__=='__main__':main() diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/original_check.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/original_check.py new file mode 100644 index 0000000000000000000000000000000000000000..77f411bf3b883a29842b4cf3ea1a478a8c40ef40 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/original_check.py @@ -0,0 +1,172 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from r10_support import install_copy,dependency,combine +install_copy(('reports.md', 'report_summary.')) +import json, os, re, shutil, subprocess, sys, tempfile + +REPORTS_MD = '''# Agent PR Performance Reports + +## Performance Report - PR-101 +- Image pull: 30s +- Container start: 20s +- Service ready: 40s +- Total: 2m + +## Performance Report - PR-102 +- Image pull: 1m 15s +- Container start: 25s +- Service ready: 2m 10s + +## Performance Report - PR-103 +- Image pull: 45s +- Container start: 20s +- Service ready: 50s +- Total: 95s +''' + +def find_script(root): + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if d not in ('.git', 'node_modules', '__pycache__')] + for f in filenames: + if f == 'check_reports.py': + return os.path.join(dirpath, f) + return None + +def load_summary(workdir): + for name in ('report_summary.',): + p = os.path.join(workdir, name) + if os.path.isfile(p): + try: + with open(p) as f:return json.load(f) + except (OSError,ValueError,UnicodeError,RecursionError):return None + return None + + +def numeric(value): + return type(value)in(int,float) and (not isinstance(value,float)or __import__('math').isfinite(value)) + +def typed_report(row): + return isinstance(row,dict) and isinstance(row.get('phases'),dict) and all(numeric(v)for v in row['phases'].values()) and numeric(row.get('total_seconds')) and type(row.get('meets_target'))is bool + +def missing_phase_panel(script): + text=REPORTS_MD.replace('- Image pull: 30s\n','').replace('- Container start: 25s\n','').replace('- Service ready: 50s\n','') + expected=[ + {'name':'PR-101','phases':{'image_pull':0,'container_start':20,'service_ready':40},'total_seconds':60,'meets_target':True}, + {'name':'PR-102','phases':{'image_pull':75,'container_start':0,'service_ready':130},'total_seconds':205,'meets_target':False}, + {'name':'PR-103','phases':{'image_pull':45,'container_start':20,'service_ready':0},'total_seconds':65,'meets_target':True} + ] + workdir=tempfile.mkdtemp() + try: + open(os.path.join(workdir,'reports.md'),'w').write(text) + shutil.copy(script,os.path.join(workdir,'check_reports.py')) + proc=subprocess.run([sys.executable,'check_reports.py'],cwd=workdir,capture_output=True,text=True,timeout=60) + summary=load_summary(workdir) + if proc.returncode!=0 or not isinstance(summary,dict) or not isinstance(summary.get('reports'),list) or len(summary['reports'])!=3:return [False]*3 + return [typed_report(got) and all(got.get(k)==v for k,v in want.items())for got,want in zip(summary['reports'],expected)] + except subprocess.TimeoutExpired:return [False]*3 + except OSError as error:raise RuntimeError('Trusted performance panel setup or launcher failed')from error + finally:shutil.rmtree(workdir,ignore_errors=True) + +def main(): + script = find_script('/candidate') + checks = [] + if not script: + for i in range(7): + checks.append({'id': str(i), 'passed': False, 'reason': 'check_reports.py not found in /candidate'}) + print(json.dumps({'checks': checks})) + return + workdir = tempfile.mkdtemp() + try: + with open(os.path.join(workdir, 'reports.md'), 'w') as f: + f.write(REPORTS_MD) + shutil.copy(script, os.path.join(workdir, 'check_reports.py')) + proc = subprocess.run([sys.executable, 'check_reports.py'], cwd=workdir, + capture_output=True, text=True, timeout=60) + summary = load_summary(workdir) + + def add(cid, passed, reason): + checks.append({'id': cid, 'passed': bool(passed), 'reason': reason}) + + # Check 0: script runs and produces report_summary. + if proc.returncode != 0: + add('0', False, 'check_reports.py exited with code %s: %s' % (proc.returncode, (proc.stderr or '')[:200])) + elif summary is None: + add('0', False, 'report_summary. (report_summary.json) was not produced') + else: + add('0', True, 'script ran and produced report_summary.') + + reports = None + if isinstance(summary, dict): + reports = summary.get('reports') + + # Check 1: 3 entries in file order + ok1 = (isinstance(reports, list) and len(reports) == 3 and + all(isinstance(r, dict) for r in reports) and + [r.get('name') for r in reports] == ['PR-101', 'PR-102', 'PR-103']) + add('1', ok1, 'reports list has exactly 3 entries in file order named PR-101, PR-102, PR-103' if ok1 + else 'reports list is missing, wrong length, or names/order are incorrect') + + def phase_check(idx, cid, expected_phases, expected_total, expected_target, note): + if not (isinstance(reports, list) and len(reports) == 3 and isinstance(reports[idx], dict)): + add(cid, False, 'cannot evaluate: reports entry missing or malformed') + return + r = reports[idx] + ph = r.get('phases') + ok_ph = (isinstance(ph, dict) and all(numeric(v)for v in ph.values()) and + {k: ph.get(k) for k in ('image_pull', 'container_start', 'service_ready')} == expected_phases) + ok_total = numeric(r.get('total_seconds')) and r.get('total_seconds') == expected_total + ok_target = r.get('meets_target') is expected_target + add(cid, ok_ph and ok_total and ok_target, + note if (ok_ph and ok_total and ok_target) else + 'phases/total_seconds/meets_target incorrect: got phases=%r total_seconds=%r meets_target=%r' % (ph, r.get('total_seconds'), r.get('meets_target'))) + + phase_check(0, '2', {'image_pull': 30, 'container_start': 20, 'service_ready': 40}, 90, True, + 'PR-101: phases 30/20/40, total_seconds=90, meets_target=true (Total: 2m line ignored)') + phase_check(1, '3', {'image_pull': 75, 'container_start': 25, 'service_ready': 130}, 230, False, + 'PR-102: 1m 15s=75s, 25s, 2m 10s=130s, total_seconds=230, meets_target=false') + phase_check(2, '4', {'image_pull': 45, 'container_start': 20, 'service_ready': 50}, 115, True, + 'PR-103: phases 45/20/50, total_seconds=115, meets_target=true (Total: 95s line ignored)') + + # Check 5: all_meet_target false + ok5 = isinstance(summary, dict) and summary.get('all_meet_target') is False + add('5', ok5, 'all_meet_target is false' if ok5 else 'all_meet_target is missing or not false') + + missing_ok=missing_phase_panel(script) + for check,ok in zip(checks[2:5],missing_ok): + check['passed']=check['passed'] and ok + if not ok:check['reason']+='; missing phase must contribute zero seconds' + # Check 6: phase keys exactly image_pull, container_start, service_ready with numeric values + ok6 = False + if isinstance(reports, list) and len(reports) == 3: + ok6 = True + for r in reports: + ph = r.get('phases') if isinstance(r, dict) else None + if not (isinstance(ph, dict) and set(ph.keys()) == {'image_pull', 'container_start', 'service_ready'} and + all(numeric(v)for v in ph.values())): + ok6 = False + break + add('6', ok6, 'phase keys are exactly image_pull, container_start, service_ready with numeric seconds' if ok6 + else 'phases objects have wrong keys or non-numeric values') + finally: + shutil.rmtree(workdir, ignore_errors=True) + boundary_ok=True;all_ok=True;names_ok=True;phase_shape_ok=True + for seconds in [(20,30,40),(60,60,60),(60,60,59)]: + name='Renamed-'+str(sum(seconds)) + body=('## Performance Report - '+name+'\n- Image pull: %ss\n- Container start: %ss\n- Service ready: %ss\n')%seconds + with tempfile.TemporaryDirectory() as td: + open(os.path.join(td,'reports.md'),'w').write(body);shutil.copy(script,os.path.join(td,'check_reports.py')) + pr=subprocess.run([sys.executable,'check_reports.py'],cwd=td,capture_output=True,text=True,timeout=60);summary=load_summary(td) + want=sum(seconds)<180;rows=summary.get('reports')if isinstance(summary,dict)else None + row=rows[0]if isinstance(rows,list)and len(rows)==1 and isinstance(rows[0],dict)else{} + names_ok=names_ok and row.get('name')==name + phases=row.get('phases') + phase_shape_ok=phase_shape_ok and isinstance(phases,dict)and set(phases)=={'image_pull','container_start','service_ready'}and all(numeric(v)for v in phases.values())and phases==dict(zip(('image_pull','container_start','service_ready'),seconds)) + boundary_ok=boundary_ok and pr.returncode==0 and isinstance(rows,list) and len(rows)==1 and numeric(row.get('total_seconds'))and row.get('total_seconds')==sum(seconds) and row.get('meets_target') is want + all_ok=all_ok and isinstance(summary,dict) and summary.get('all_meet_target') is want + for check in checks: + if check['id']in ['2','3','4']:check['passed']=bool(check['passed'] and boundary_ok) + if check['id']=='5':check['passed']=bool(check['passed'] and all_ok) + if check['id']=='1':check['passed']=bool(check['passed'] and names_ok) + if check['id']=='6':check['passed']=bool(check['passed'] and phase_shape_ok) + print(json.dumps({'checks': checks})) + +main() diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/r10_support.py b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/r10_support.py new file mode 100644 index 0000000000000000000000000000000000000000..38f19c77b5e97af6ec9040956008c8fa9c14da6e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/r10_support.py @@ -0,0 +1,192 @@ +"""R10 evaluator helpers. Candidate programs are only run by the Docker harness.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import ast, contextlib, io, json, os, pathlib, shutil, sys, tokenize + +def combine(values): + values=list(values) + return False if any(v is False for v in values)else None if any(v is None for v in values)else True + +def candidate_root(): + return pathlib.Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_ROOT','/candidate'))) + +def copy_program(destination,skip=()): + root=candidate_root();destination=pathlib.Path(destination);destination.mkdir(parents=True,exist_ok=True) + skip=set(skip) + def ignored(directory,names): + relative=pathlib.Path(directory).relative_to(root) + return [n for n in names if n in ('__pycache__','.git','.venv')or str(relative/n)in skip] + shutil.copytree(root,destination,dirs_exist_ok=True,symlinks=True,ignore=ignored) + return destination + +def install_copy(skip=()): + original=shutil.copy + def copied(source,destination,*args,**kwargs): + source=pathlib.Path(source) + try:source.resolve().relative_to(candidate_root().resolve());local=True + except ValueError:local=False + if local and source.suffix=='.py': + target=pathlib.Path(destination) + if not target.is_dir():target=target.parent + copy_program(target,skip) + return original(source,destination,*args,**kwargs) + shutil.copy=copied + +def _constant(node,constants): + if isinstance(node,ast.Constant):return node.value + if isinstance(node,ast.Name):return constants.get(node.id) + if isinstance(node,(ast.List,ast.Tuple)): + values=[_constant(n,constants)for n in node.elts] + return values if all(v is not None for v in values)else None + if isinstance(node,ast.BinOp)and isinstance(node.op,ast.Add): + a,b=_constant(node.left,constants),_constant(node.right,constants) + return a+b if isinstance(a,str)and isinstance(b,str)else None + if isinstance(node,ast.Call)and isinstance(node.func,ast.Attribute)and node.func.attr=='join'and len(node.args)==1: + separator=_constant(node.func.value,constants);values=_constant(node.args[0],constants) + return separator.join(values)if isinstance(separator,str)and isinstance(values,list)and all(isinstance(v,str)for v in values)else None + if isinstance(node,ast.JoinedStr): + values=[_constant(n.value,constants)if isinstance(n,ast.FormattedValue)else _constant(n,constants)for n in node.values] + return ''.join(map(str,values))if all(v is not None for v in values)else None + return None + +def scan_stdlib(root,entries,banned=()): + """Follow qualified/relative local modules, then dynamic literal imports. + + Unknown targets remain evidence missing, rather than proving a forbidden import. + Ordinary package initializers AND requested child modules are inspected. + """ + root=pathlib.Path(root);pending=[root/e for e in entries];seen=set();modules=set();unknown=[] + def local(name): + parts=name.split('.');paths=[] + for i in range(1,len(parts)+1): + package=root.joinpath(*parts[:i])/'__init__.py' + if package.is_file():paths.append(package) + file=root.joinpath(*parts).with_suffix('.py') + if file.is_file():paths.append(file) + namespace=root.joinpath(*parts).is_dir() + return paths,namespace + def consider(name): + if not isinstance(name,str)or not name:return + modules.add(name);paths,namespace=local(name) + if paths:pending.extend(paths) + elif namespace:pass + elif name.split('.')[0]in banned:raise ValueError('forbidden module: '+name) + elif name.split('.')[0]not in sys.stdlib_module_names and name!='__future__':raise ValueError('nonstdlib module: '+name) + if name.split('.')[0]in banned:raise ValueError('forbidden module: '+name) + try: + while pending: + path=pending.pop() + if path in seen:continue + seen.add(path) + if not path.is_file():return False,sorted(modules),'missing entry/helper: '+str(path) + try: + with tokenize.open(path)as stream:tree=ast.parse(stream.read()) + except (OSError,UnicodeError,SyntaxError)as exc:return False,sorted(modules),'invalid entry/helper: '+str(exc) + relative=path.relative_to(root);package=list(relative.parts[:-1]);aliases={};constants={} + assignments={};stores={} + for node in ast.walk(tree): + if isinstance(node,ast.Name)and isinstance(node.ctx,(ast.Store,ast.Del)):stores[node.id]=stores.get(node.id,0)+1 + if isinstance(node,ast.arg):stores[node.arg]=stores.get(node.arg,0)+1 + if isinstance(node,ast.Assign)and len(node.targets)==1 and isinstance(node.targets[0],ast.Name):assignments[node.targets[0].id]=node.value + for _ in range(len(assignments)+1): + for name,value in assignments.items(): + if stores.get(name)==1: + folded=_constant(value,constants) + if folded is not None:constants[name]=folded + # Resolve only immutable literal expressions, never execute candidate code. + for node in ast.walk(tree): + if isinstance(node,ast.Import): + for a in node.names:consider(a.name);aliases[a.asname or a.name.split('.')[0]]=a.name + elif isinstance(node,ast.ImportFrom): + if node.level: + base=package[:max(0,len(package)-node.level+1)]+((node.module or '').split('.')if node.module else[]) + name='.'.join(base) + else:name=node.module or '' + consider(name) + for a in node.names: + full=(name+'.'+a.name).strip('.');paths,namespace=local(full) + if paths or namespace:consider(full) + aliases[a.asname or a.name]=full + def qualified(node): + if isinstance(node,ast.Name):return aliases.get(node.id,node.id) + if isinstance(node,ast.Attribute):return qualified(node.value)+'.'+node.attr + return '' + for node in ast.walk(tree): + if not isinstance(node,ast.Call):continue + name=qualified(node.func) + if name in ('__import__','builtins.__import__','importlib.import_module'): + target=_constant(node.args[0],constants)if node.args else None + if isinstance(target,str)and not target.startswith('.'):consider(target) + else:unknown.append('computed dynamic import at '+str(relative)+':'+str(node.lineno)) + elif name in ('runpy.run_path','importlib.util.spec_from_file_location','importlib.machinery.SourceFileLoader','importlib.machinery.SourcelessFileLoader'): + argument=1 if name!='runpy.run_path'else 0 + target=_constant(node.args[argument],constants)if len(node.args)>argument else None + if isinstance(target,str): + path_=pathlib.Path(target) + for prefix in ('/app/','/workspace/','/candidate/'): + if target.startswith(prefix):path_=root/target[len(prefix):];break + if not path_.is_absolute():path_=root/path_ + try:path_.relative_to(root) + except ValueError:unknown.append('external run_path');continue + pending.append(path_) + else:unknown.append('computed run_path') + elif name in ('exec','eval','builtins.exec','builtins.eval'): + unknown.append('dynamic code execution at '+str(relative)+':'+str(node.lineno)) + except ValueError as exc:return False,sorted(modules),str(exc) + if unknown:return False,sorted(modules),'unknown: '+'; '.join(unknown) + return True,sorted(modules),'complete local stdlib closure' + +def dependency(entry,banned=()): + ok,modules,why=scan_stdlib(candidate_root(),[entry],banned) + return None if why.startswith('unknown:')else ok + +def strict_json(text): + def unique(pairs): + result={} + for k,v in pairs: + if k in result:raise ValueError('duplicate JSON member: '+k) + result[k]=v + return result + return json.loads(text,object_pairs_hook=unique,parse_constant=lambda value:(_ for _ in()).throw(ValueError(value))) + +def strict_response(text): + import re + match=re.fullmatch(r'\s*```(?:json)?\s*\n(.*?)\n```\s*',text,re.S|re.I) + return strict_json(match[1]if match else text) + +def trusted_stdout(query_id): + import hashlib + path=pathlib.Path(os.environ.get('MYBENCH_TRUSTED_TRACE','/tool_trajectory.json')) + expected=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256') + try: + path.resolve().relative_to(candidate_root().resolve()) + return None + except ValueError:pass + try: + raw=path.read_bytes() + if not expected or hashlib.sha256(raw).hexdigest()!=expected:return None + trace=json.loads(raw) + metadata=json.loads(pathlib.Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text()) + binding=metadata.get('trusted_trace_binding',metadata.get('derived',{}).get('trusted_trace_binding',{})) + if binding.get('query_id')!=query_id or binding.get('trajectory_sha256')!=expected:return None + hashes=binding.get('candidate_file_sha256') + if not isinstance(hashes,dict)or not hashes:return None + for relative,digest in hashes.items(): + if pathlib.PurePosixPath(relative).is_absolute()or'..'in pathlib.PurePosixPath(relative).parts:return None + if hashlib.sha256((candidate_root()/relative).read_bytes()).hexdigest()!=digest:return None + except (OSError,ValueError):return None + if not isinstance(trace,dict)or not isinstance(trace.get('steps'),list):return None + outputs=[] + for step in trace['steps']: + observation=step.get('observation',{}) + results=observation.get('results',[])if isinstance(observation,dict)else[] + calls={str(c.get('tool_call_id')):c for c in step.get('tool_calls',[])if isinstance(c,dict)and c.get('function_name')in ('bash','exec_command','shell','terminal','run_shell_command')} + for result in results: + if isinstance(result,dict)and str(result.get('source_call_id'))in calls and result.get('content')is not None:outputs.append(str(result['content'])) + # A later successful printing may replace an earlier trial. Candidate + # formal answers and strings in tool arguments never enter this channel. + summaries=[output for output in outputs if re_search_summary(output)] + return summaries[-1]if summaries else '' + +def re_search_summary(output): + import re + return bool(re.search(r'(?m)^G\d+:\s*(?:platformer|grid_logic|tower_defense|top_down|ui_heavy)\s*$',output)) diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/repair.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/repair.json new file mode 100644 index 0000000000000000000000000000000000000000..865fde0a6bf55176f0e5861493e4ce63bc119b26 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/evaluator/repair.json @@ -0,0 +1,35 @@ +{ + "query_id": "af9ed7786fd271a970e929f4", + "repair_kind": "independent_submitted_artifact_semantics", + "submitted_artifacts": [ + "report_summary." + ], + "fresh_artifacts": [], + "runs": { + "0": [ + { + "submitted": "report_summary.", + "generated": "report_summary." + } + ] + }, + "require_fresh_generated": true, + "check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "presence_check_ids": [ + "0" + ], + "timeout": 360, + "instruction_sha256": "0fd12a5cd608aaffb76e7f8e16e26f82f1b90f0c3a85472641e2c9d7f8968808", + "original_checker_sha256": "eb3e67d2e9d48ff3d09489b9bf0b7ffc570fd188129623118ec76ced9f33913a", + "public_delivery_contract": "A teammate pasted several 'Performance Report' blocks (in the format our agent PRs use) into reports.md. Write a Python script `check_reports.py` that reads reports.md, parses every report block, computes the total time for each report by summing its four phase times (image pull, container start, service ready, and any explicitly listed 'Total' line should be ignored in favor of the computed sum), and writes a summary to report_summary.. Each phase time is given like 'Image pull: 45s' or 'Service ready: 1m 30s' \u2014 parse both seconds-only and minutes+seconds formats. In report_summary., write a JSON object with key 'reports' (a list, in file order, of objects with fields: 'name' (the report's name from its '## Performance Report - NAME' heading), 'phases' (object mapping lowercase phase key to seconds: image_pull, container_start, service_ready), 'total_seconds' (computed sum), 'meets_target' (boolean, true if total_seconds < 180, per the < 3 minutes target)). Also include top-level key 'all_meet_target' (boolean). Handle missing phase lines by treating them as 0 seconds. Then run the script and make sure report_summary. is produced correctly.", + "preserve_ids_and_weights": true, + "no_condition_or_score_input": true +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..1a5bf3c3a30a51e5df725b27ee817e8013734ea0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/grading/verified_config.json @@ -0,0 +1,113 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "af9ed7786fd271a970e929f4", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "original_check.py": "47255056659a9340ec02dd1ddfb60f849a144387496da7f9eeb1686912dd8cf9", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "de36882a90b5542e5c3a0c2c6d154e51021531ab3befae4345f812bcc88f7911", + "r10_support.py": "fffaca73df4531fc7ef99fef08e5ecb05e744b55c0aa44e1160a3b0292a7968c", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "bfd2a7b5e02140d165581ad10830ffbbf54c10535ed6f5c18abf1a675b08313a", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "repair.json": "9065a17775064658a75d65dfea65258274925b60dc97e4d50663214890289887", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": false, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "cpu_memory_basis": "source_runtime_container_limits", + "cpus": 2, + "disk_mib": 10240, + "memory_mib": 4096, + "timeout_disk_basis": "advisory_not_measured_or_enforced", + "timeout_sec": 1200 + }, + "oracle": { + "basis": "advisory_reference_copy", + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": 60, + "max_steps": 16 + }, + "verifier": { + "basis": "original_python_evaluator_enforced_limits", + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 60, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_ANSWER", + "MYBENCH_CANDIDATE", + "MYBENCH_FROZEN", + "MYBENCH_VIEW" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/inputs/reports.md b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/inputs/reports.md new file mode 100644 index 0000000000000000000000000000000000000000..77502766160ed2c5129d786b0bffcc039427a82e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/inputs/reports.md @@ -0,0 +1,18 @@ +# Agent PR Performance Reports + +## Performance Report - PR-101 +- Image pull: 30s +- Container start: 20s +- Service ready: 40s +- Total: 2m + +## Performance Report - PR-102 +- Image pull: 1m 15s +- Container start: 25s +- Service ready: 2m 10s + +## Performance Report - PR-103 +- Image pull: 45s +- Container start: 20s +- Service ready: 50s +- Total: 95s diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/instruction.md b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eff046513fe79bb0401669305a1a04841099a1ba --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/instruction.md @@ -0,0 +1,5 @@ +A teammate pasted several 'Performance Report' blocks (in the format our agent PRs use) into reports.md. Write a Python script `check_reports.py` that reads reports.md, parses every report block, computes the total time for each report by summing its three phase times (image pull, container start, service ready, and any explicitly listed 'Total' line should be ignored in favor of the computed sum), and writes a summary to report_summary.. Each phase time is given like 'Image pull: 45s' or 'Service ready: 1m 30s' — parse both seconds-only and minutes+seconds formats. In report_summary., write a JSON object with key 'reports' (a list, in file order, of objects with fields: 'name' (the report's name from its '## Performance Report - NAME' heading), 'phases' (object mapping lowercase phase key to seconds: image_pull, container_start, service_ready), 'total_seconds' (computed sum), 'meets_target' (boolean, true exactly when the computed total satisfies the target in the bundled Skill's Monitoring / Performance Report template)). Also include top-level key 'all_meet_target' (boolean). Handle missing phase lines by treating them as 0 seconds. Then run the script and make sure report_summary. is produced correctly. +The grader evaluates the named Python program in finite fresh invocations (each existing per-case budget is at most90 seconds). Exceeding that budget or failing to produce the required result is a candidate execution failure; trusted fixture or instrumentation failures are separate infrastructure errors. This adds no library/import restriction. + + +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. 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/af9ed7786fd271a970e929f4/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ad94f865c1af1cc5c2bb510890fd6eb37d0c2635 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/skill/SKILL.md @@ -0,0 +1,213 @@ +--- +name: agent-automation-infrastructure +description: Current state of CI/CD automation infrastructure, pre-built Docker images, and performance optimization strategies. Use when dealing with slow builds, container timeouts, yarn install issues, or when you need to understand available pre-built images and automation tooling. +--- + +# Agent Automation Status & Recommendations + +## Current State (Updated 2026-01-04) + +### For Local Development ✅ +Agents can successfully test on local workstations where: +- Full network access available +- Docker and Node.js installed +- Can manually run `yarn install` and `docker compose up` +- Screenshots can be captured via browser + +### Pre-built Images Available 🚀 + +Three pre-built images are available via GitHub Container Registry: +- **Payload dev** (`ghcr.io/ynotradio/site/payload-dev:latest`) - Next.js + Payload CMS +- **PHP-FPM dev** (`ghcr.io/ynotradio/site/phpfpm-dev:latest`) - Legacy site backend +- **Postgres seeded** (`ghcr.io/ynotradio/site/postgres-seeded:latest`) - PostgreSQL with Payload schema + sample data + +### For CI/CD Automation ⚠️ + +**Infrastructure:** Complete and functional +**Blocker:** Performance (yarn install takes 5+ minutes in containers) + +After adding domains to firewall allowlist: +- ✅ `registry.hub.docker.com` - Docker Hub access working +- ✅ `registry.npmjs.org` - npm package downloads working +- ❌ **yarn install in Alpine containers: 5+ minutes** (timeout) + +## Performance Metrics + +| Operation | Current | With Pre-built | Status | +|-----------|---------|----------------|--------| +| Docker pull base images | ~2s | ~30s | ✅ | +| yarn install (Alpine) | 5+ min | N/A (pre-installed) | ✅ | +| Postgres startup (seeded) | ~3 min | ~10s | ✅ | +| Container startup | Blocked | ~20s | ✅ | +| Total time to ready | Timeout | ~1 min | ✅ | + +## Recommended Solutions + +### Option 1: Pre-Built Images (Recommended) ⭐ + +**Implementation:** +- GitHub Actions workflow builds images on every push to master +- Images pushed to GitHub Container Registry (ghcr.io) +- Agents pull pre-built images instead of building + +**Available images:** +1. **Payload dev** - Next.js + Payload CMS with dependencies pre-installed +2. **PHP-FPM dev** - Legacy site with PHP extensions and configuration +3. **Postgres seeded** - PostgreSQL 16 with Payload schema and sample data baked in + +**Benefits:** +- ✅ Startup time: 5+ minutes → ~20 seconds (15x faster) +- ✅ No network restrictions needed beyond image pull +- ✅ Consistent environments +- ✅ No yarn install timeouts +- ✅ Database comes pre-seeded with test data + +**Status:** ✅ Workflow ready in `.github/workflows/build-agent-images.yml` + +**Usage:** +```bash +# Pull and run pre-built images +docker pull ghcr.io/ynotradio/site/payload-dev:latest +docker pull ghcr.io/ynotradio/site/phpfpm-dev:latest +docker pull ghcr.io/ynotradio/site/postgres-seeded:latest + +# Or use docker-compose (configured to use pre-built images) +docker-compose up postgres # Pre-seeded Postgres ready in ~10s +``` + +**Image details:** +- `payload-dev`: Node.js 22 + yarn dependencies (~800 MB) +- `phpfpm-dev`: PHP 8.3-FPM + extensions (~450 MB) +- `postgres-seeded`: PostgreSQL 16 + seeded data (~400 MB) + +See `bin/docker/postgres/README.md` for Postgres image details. + +### Option 2: Playwright MCP Server + +**Implementation:** +- Add Playwright MCP server to agent tooling +- Point to existing staging/dev instances +- Agents navigate and screenshot directly + +**Benefits:** +- ✅ No local Docker needed +- ✅ Test against real data +- ✅ Instant access + +**Drawbacks:** +- ❌ Requires maintained staging environment +- ❌ Potential for environment conflicts +- ❌ Can't test isolated changes + +### Option 3: Optimized Containers + +**Improvements to current approach:** + +1. **Use Debian instead of Alpine** (faster yarn install) + ```dockerfile + FROM node:22 # Not -alpine + ``` + +2. **Layer caching** + ```dockerfile + COPY package*.json ./ + RUN npm ci --omit=dev + COPY . . + ``` + +3. **Use Yarn** (faster than npm) + ```dockerfile + RUN yarn install --frozen-lockfile + ``` + +**Expected improvement:** 5 min → 2-3 min (still slow for CI) + +## Recommendations + +### Immediate Action +1. ✅ Enable pre-built image workflow (already created) +2. Update agent documentation to use pre-built images +3. Add `ghcr.io` to firewall allowlist (if not already) + +### For Future PRs +Agents should: +1. **Check for pre-built images first** before building locally +2. **Report performance issues** when exceeding baselines +3. **Provide evidence or explain why not** (per testing checklist) +4. **Test locally** when CI automation unavailable + +## Usage Examples + +### With Pre-Built Images (Fast) +```bash +# Pull pre-built images +docker pull ghcr.io/ynotradio/site/payload-dev:latest +docker pull ghcr.io/ynotradio/site/phpfpm-dev:latest + +# Start services (uses pre-built images) +docker compose up -d + +# Seed databases with data +yarn seed:legacy # Legacy site with production data +yarn seed:payload # Payload with sample data + +# Ready in ~20 seconds (+ seed time) +``` + +### Building Locally (Slow) +```bash +# Build from scratch +docker compose up -d --build + +# Seed databases +yarn seed:legacy # Legacy site +yarn seed:payload # Payload + +# Takes 5+ minutes due to yarn install +``` + +### Database Seeding Notes + +**Why seed:** +- Empty applications are hard to verify +- Screenshots of empty dashboards don't prove functionality +- Real data helps test relationships and queries + +**Legacy site:** `yarn seed:legacy` +- Pulls production database snapshot +- Imports into MySQL container +- Site shows real content at http://localhost:8080 + +**Payload:** `yarn seed:payload` +- Creates sample collections and data +- Admin UI shows populated tables +- May need implementation if not yet available + +## Monitoring + +Track these metrics in agent PRs: + +```markdown +## Performance Report +- Image pull: [time] +- Container start: [time] +- Service ready: [time] +- Total: [time] + +Target: < 3 minutes total +``` + +## Future Improvements + +1. **Multi-stage builds** - Build dependencies in separate stage +2. **Volume caching** - Share node_modules between builds +3. **Lighter dependencies** - Audit and remove unnecessary packages +4. **Playwright MCP** - Add as complementary testing option + +## Conclusion + +**For immediate use:** Pre-built images solve the CI/CD automation blocker. + +**For local development:** Direct installation continues to work perfectly. + +All agent infrastructure is production-ready and documented. The only remaining step is enabling the pre-built image workflow. diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/skill/metadata.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/skill/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..7c25fd44ef56f5959ac25dfe186edad7c105bafe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/skill/metadata.json @@ -0,0 +1,26 @@ +{ + "name": "agent-automation-infrastructure", + "description": "Current state of CI/CD automation infrastructure, pre-built Docker images, and performance optimization strategies. Use when dealing with slow builds, container timeouts, yarn install issues, or when you need to understand available pre-built images and automation tooling.", + "category": "devops", + "canonical_category": "devops", + "repository": "majiayu000/claude-skill-registry-data", + "repository_url": "https://github.com/majiayu000/claude-skill-registry-data", + "author": "majiayu000", + "author_avatar": "https://github.com/majiayu000.png", + "file_path": "data/agent-automation-infrastructure/SKILL.md", + "source": "github_curated_repos", + "stars": 2, + "quality_score": 64, + "best_practices_score": 75, + "skill_level": 3, + "skill_level_label": "resources", + "has_scripts": true, + "has_extra_files": false, + "downloads": 0, + "content_hash": "c905e9ac120d75f984db121c43306a48a277bad35b4a0e9c42dc349ec142e3b3", + "indexed_at": "2026-02-27T02:55:46.325Z", + "synced_at": "2026-02-28T04:08:54.835Z", + "omni_registry_url": "https://omni-skill-registry.omniroute.online/#/skill/12b053cf7bed4049f2c0c4ebb5776230f61d0d87b861c6fc33237c254a27aa77", + "install_command": "mkdir -p .claude/skills/agent-automation-infrastructure && curl -sL \"https://raw.githubusercontent.com/majiayu000/claude-skill-registry-data/main/data/agent-automation-infrastructure/SKILL.md\" > .claude/skills/agent-automation-infrastructure/SKILL.md", + "raw_url": "https://raw.githubusercontent.com/majiayu000/claude-skill-registry-data/main/data/agent-automation-infrastructure/SKILL.md" +} diff --git a/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/task.json b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1294768769040adbb8ed76dc4a2fb9ede43529cb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/af9ed7786fd271a970e929f4/task.json @@ -0,0 +1,71 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "af9ed7786fd271a970e929f4", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "af9ed7786fd271a970e929f4", + "outputs": [ + "check_reports.py", + "report_summary." + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "ac6fd5d2f793b28b041cf7656f7c34a906d5d5c4eeba93a2b90ade896bbacfae", + "files": { + "SKILL.md": "beaf6a9505473cbdb7ca700a2e42ddc481f8c5d6f69b40ce2600ccafd098512f", + "metadata.json": "48e18ff7d9d4071ab749af643b21b2e0db15ececac367d823bcbd6ca67e3eebb" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/reports.md", + "workspace_target": "reports.md", + "sha256": "163e255372892e7b423f8f6e2b16bb25de2607be4d3b33191b35064087325aa9" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "ac6fd5d2f793b28b041cf7656f7c34a906d5d5c4eeba93a2b90ade896bbacfae" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": false, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": false, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "purpose": "candidate timeout/result attribution only; no purity/resource restriction" + }, + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": false, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": false, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "purpose": "candidate timeout/result attribution only; no purity/resource restriction", + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/afa3cae39fa70471ac8f9a3b/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/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/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/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/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/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('=needed else None if matching(possible,len(rows))>=needed else False) + return[shape,inventory,tri(details),noextra] + +def run(bundle,rules): + records=[] + with workspace(): + for root in[Path('/workspace'),Path('/app')]: + for where in[Path('/workspace'),Path('/app')]: + (where/'bundle.json').write_text(json.dumps(bundle));(where/'rules.json').write_text(json.dumps(rules));(where/'report.json').unlink(missing_ok=True) + try:proc=subprocess.run([sys.executable,'validate_mcode.py'],cwd=root,capture_output=True,text=True,errors='replace',timeout=35);rc=proc.returncode + except(OSError,subprocess.SubprocessError):rc=None + outputs=[where/'report.json'for where in[Path('/workspace'),Path('/app')]if(where/'report.json').is_file()] + for output in outputs or[None]: + try:report=json.loads(output.read_text())if output else None + except(OSError,ValueError,UnicodeError,RecursionError):report=None + records.append((rc,report)) + return records + +def main(): + # Only reports freshly produced from the independently supplied panels are + # assessed; an unused saved report must not affect replay or its error state. + flags=[True]*6 + panels=[(BUNDLE,RULES)] + rules={'profiles':{'fresh-profile':{'resourceType':'Observation','rules':[{'rule_id':'F-A','type':'fixed_code','element':'code','system':'urn:good','code':'alpha'},{'rule_id':'F-B','type':'required_element','element':'subject'},{'rule_id':'F-C','type':'allowed_systems','element':'method','systems':['urn:good']},{'rule_id':'F-D','type':'value_set','element':'valueCodeableConcept','value_set':'new-values'}]}},'value_sets':{'new-values':{'system':'urn:values','codes':['zero','one']}}} + base={'resourceType':'Observation','id':'fresh','meta':{'profile':['http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-fresh-profile']},'code':{'coding':[{'system':'urn:bad','code':'alpha'},{'system':'urn:good','code':'alpha'}]},'subject':{'reference':'Patient/fresh'},'method':{'coding':[{'system':'urn:bad-a','code':'a'},{'system':'urn:good','code':'b'},{'system':'urn:bad-b','code':'c'}]},'valueCodeableConcept':{'coding':[{'system':'urn:wrong-but-code-only-membership','code':'one'},{'system':'urn:values','code':'other'}]}} + for mode in ('mixed','all_clean','all_wrong','empty_string','empty_dict','empty_list','null','zero','false'): + res=copy.deepcopy(base);res['id']='changed-'+mode + if mode=='all_clean':res['method']['coding']=[{'system':'urn:good','code':'a'}] + if mode=='all_wrong':res['code']['coding'][1]['code']='wrong';res.pop('subject');res['valueCodeableConcept']['coding'][0]['code']='bad' + if mode in ('empty_string','empty_dict','empty_list','null','zero','false'):res['subject']={'empty_string':'','empty_dict':{},'empty_list':[],'null':None,'zero':0,'false':False}[mode] + panels.append(({'resourceType':'Bundle','entry':[{'resource':res}]},rules)) + changed=copy.deepcopy(rules);changed['profiles']['fresh-profile']['rules'][0]['code']='different';changed['profiles']['fresh-profile']['rules'][2]['systems']=['urn:bad-a','urn:bad-b'];changed['value_sets']['new-values']['codes']=['other'] + panels += [({'resourceType':'Bundle','entry':[{'resource':base}]},changed),({'resourceType':'Bundle','entry':[]},rules)] + # Coding membership and allowed-system checks must collect incomplete + # Coding objects independently of which keys each owning rule reads. + partial=copy.deepcopy(base);partial['id']='partial-codings' + partial['valueCodeableConcept']={'coding':[{'code':'one'}]} + partial['method']={'coding':[{'system':'urn:bad-no-code'}]} + panels.append(({'resourceType':'Bundle','entry':[{'resource':partial}]},rules)) + for panel_index,(bundle,rulesdoc)in enumerate(panels): + for rc,report in run(bundle,rulesdoc): + flags[0]=tri([flags[0],None if rc is None else rc==0]) + values=assess(report,bundle,rulesdoc)if rc is not None else[None]*4 + for i,value in enumerate(values,1):flags[i]=tri([flags[i],value]) + if panel_index>0:flags[5]=tri([flags[5],values[1],values[3]]) + std,mods,why=scan_stdlib('/candidate',['validate_mcode.py']);flags[0]=tri([flags[0],None if why.startswith('unknown:')else std]) + return{'scoreable':None not in flags,'checks':[dict(id=str(i),passed=v,reason='Six original independent owners: explicit exit0/stdlib0, array shape1, required finding presence2, reported field/source found/expected3, false positives4, changed-rule inventory5. Full roots, code-only membership, bad system without code, literal empty-list or normalized null found, typed numeric equivalence and local unknown expectation3 retained.')for i,v in enumerate(flags)]} +if __name__=='__main__': + try:print(json.dumps(main())) + except Exception as error:print(json.dumps({'scoreable':False,'checks':[dict(id=str(i),passed=None,reason='unresolved grader observation: '+type(error).__name__)for i in range(6)]})) diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..19d975e91023894f09ed5834ecca3b8b154f457d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/repair_manifest.json @@ -0,0 +1,47 @@ +{ + "query_id": "afa3cae39fa70471ac8f9a3b", + "sample_index": 672, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "original_count": 6, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "root_cause": "Fixture-only correction of actual import-shadow failure ownership and omitted mixed helper.", + "public_semantics": "Unknown dependency mixed case now contains its intended actual helper; no grader change or expectation relaxation. Shadow runtime failure has knownFalse0/1/2/3/5 but unknown4.", + "source_hashes": { + "instruction.md": "a8c055e56a12fbd39f83159eae2d61815f4e0ad538679f7353325a8b0627272f", + "task.json": "2736867d9652713cb3f738d3a39f40a816a3c6f36af5ef2fe5391e9e621e275f", + "evaluator/check.py": "454f85dd2eec7a5cef35a8a4a9af161a73fcbd36989a7c883a9217382f36bc65", + "skill/SKILL.md": "ff1b774f8450cc2c8e61e1b235fde8ec1d09fff1e7de4c3b30abd8cb7a267668", + "inputs/bundle.json": "eae0470685ef08fa1f2eeed8c821d5d9fa4ed73f2fa0e98c44f476efa68df17a", + "inputs/rules.json": "083f1757ca8437521d512f8953a6ff43d7945584e64b8347831b8f27c6a5bff9" + }, + "required_historical_artifacts": [], + "checker_sha256": "793f6ffe2c08fba3e0035cd78f65a936dc5427cc4b3d86c640a84ca16fbd26ca", + "all_logic_sha256": { + "check.py": "793f6ffe2c08fba3e0035cd78f65a936dc5427cc4b3d86c640a84ca16fbd26ca", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": [ + "Read safe control feedback and complete restored helper/source wrappers; original failed receipt preserved. No candidate execution/history." + ], + "repair_scope": "grader_only_second_round", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d23f87059c17c891c9c55dd74ccabfd662b7656 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..b0e890405be7842aece4e5766ee647dba8eb59de --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/grading/verified_config.json @@ -0,0 +1,39 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "afa3cae39fa70471ac8f9a3b", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "cd859930b7a46f578550df37bf228eaede9524cfb5a8d73a1d0d63ba3bd41ea4", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "35fd5ffffb5bf8dcdebcb756c86aa88048bc468a6f87bdef540e2f53d71e4242", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "773e9cb61308bb0485eeac24ab110c7971683e875869a89d906f464e1126a630", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/bundle.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..ebf70471c6842402362b16686683ca3e3f24722f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/bundle.json @@ -0,0 +1,76 @@ +{ + "resourceType": "Bundle", + "type": "collection", + "entry": [ + { + "resource": { + "resourceType": "Patient", + "id": "pat-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-cancer-patient"] }, + "gender": "female", + "birthDate": "1966-03-14" + } + }, + { + "resource": { + "resourceType": "Condition", + "id": "cond-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-primary-cancer-condition"] }, + "clinicalStatus": { "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-clinical", "code": "active" }] }, + "category": [{ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-category", "code": "problem-list-item" }] }], + "code": { "coding": [{ "system": "http://snomed.org/sct", "code": "408643008", "display": "Infiltrating duct carcinoma of breast" }] }, + "bodySite": [{ "coding": [{ "system": "http://snomed.info/sct", "code": "76752008", "display": "Breast structure" }] }], + "subject": { "reference": "Patient/pat-1" } + } + }, + { + "resource": { + "resourceType": "Observation", + "id": "obs-ecog-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-ecog-performance-status"] }, + "status": "final", + "code": { "coding": [{ "system": "http://loinc.org", "code": "89243-0", "display": "Karnofsky Performance Status score" }] }, + "subject": { "reference": "Patient/pat-1" }, + "valueInteger": 1 + } + }, + { + "resource": { + "resourceType": "Observation", + "id": "obs-status-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-cancer-disease-status"] }, + "status": "final", + "code": { "coding": [{ "system": "http://loinc.org", "code": "97509-4", "display": "Cancer disease status" }] }, + "subject": { "reference": "Patient/pat-1" }, + "focus": [{ "reference": "Condition/cond-1" }], + "valueCodeableConcept": { "coding": [{ "system": "http://snomed.info/sct", "code": "9999999", "display": "Patient status stable" }] } + } + }, + { + "resource": { + "resourceType": "Observation", + "id": "obs-stage-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-tnm-stage-group"] }, + "status": "final", + "code": { "coding": [{ "system": "http://snomed.info/sct", "code": "399537006", "display": "Clinical TNM stage grouping" }] }, + "subject": { "reference": "Patient/pat-1" }, + "valueCodeableConcept": { "coding": [{ "system": "http://cancerstaging.org", "code": "1229954002", "display": "American Joint Committee on Cancer stage IIB" }] }, + "method": { "coding": [{ "system": "http://snomed.info/sct", "code": "897275008", "display": "American Joint Committee on Cancer stage group 8th edition" }] } + } + }, + { + "resource": { + "resourceType": "Observation", + "id": "obs-size-1", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-tumor-size"] }, + "status": "final", + "code": { "coding": [{ "system": "http://loinc.org", "code": "21889-1", "display": "Size Tumor" }] }, + "subject": { "reference": "Patient/pat-1" }, + "component": [ + { "code": { "coding": [{ "system": "http://loinc.org", "code": "33728-7", "display": "Size.maximum dimension in Tumor" }] }, + "valueQuantity": { "value": 25, "unit": "mm[Hg]", "system": "http://unitsofmeasure.org", "code": "mm[Hg]" } } + ] + } + } + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/rules.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/rules.json new file mode 100644 index 0000000000000000000000000000000000000000..bea0dc0ea55b2225de3fe4fd6787da7ee3981855 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/inputs/rules.json @@ -0,0 +1,53 @@ +{ + "profiles": { + "primary-cancer-condition": { + "resourceType": "Condition", + "rules": [ + { "rule_id": "R1", "type": "allowed_systems", "element": "code", "systems": ["http://snomed.info/sct", "http://hl7.org/fhir/sid/icd-10-cm"] }, + { "rule_id": "R2", "type": "required_element", "element": "code" }, + { "rule_id": "R3", "type": "required_element", "element": "subject" }, + { "rule_id": "R4", "type": "required_element", "element": "clinicalStatus" } + ] + }, + "ecog-performance-status": { + "resourceType": "Observation", + "rules": [ + { "rule_id": "R5", "type": "fixed_code", "element": "code", "system": "http://loinc.org", "code": "89247-1" }, + { "rule_id": "R6", "type": "required_element", "element": "interpretation" }, + { "rule_id": "R7", "type": "required_element", "element": "subject" } + ] + }, + "cancer-disease-status": { + "resourceType": "Observation", + "rules": [ + { "rule_id": "R8", "type": "fixed_code", "element": "code", "system": "http://loinc.org", "code": "97509-4" }, + { "rule_id": "R9", "type": "value_set", "element": "valueCodeableConcept", "value_set": "ConditionStatusTrendVS" } + ] + }, + "tnm-stage-group": { + "resourceType": "Observation", + "rules": [ + { "rule_id": "R10", "type": "required_element", "element": "focus" }, + { "rule_id": "R11", "type": "required_element", "element": "method" }, + { "rule_id": "R12", "type": "allowed_systems", "element": "method", "systems": ["http://snomed.info/sct", "http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl"] } + ] + }, + "tumor-size": { + "resourceType": "Observation", + "rules": [ + { "rule_id": "R13", "type": "fixed_code", "element": "code", "system": "http://loinc.org", "code": "21889-1" }, + { "rule_id": "R14", "type": "value_set", "element": "component.valueQuantity", "value_set": "TumorSizeUnitsVS" } + ] + } + }, + "value_sets": { + "ConditionStatusTrendVS": { + "system": "http://snomed.info/sct", + "codes": ["268910001", "359746009", "271299001", "709137006"] + }, + "TumorSizeUnitsVS": { + "system": "http://unitsofmeasure.org", + "codes": ["mm", "cm"] + } + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/instruction.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a35e46b379451820da40b55f1a9f95a1b73e9ca5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/instruction.md @@ -0,0 +1,9 @@ +I have a FHIR R4 bundle of oncology resources and a machine-readable rules file describing mCODE profile requirements (fixed LOINC/SNOMED/NCIt codes for `.code`, allowed code-system URIs, required elements, and small enumerable value sets). Write a Python 3 program `validate_mcode.py` (standard library only) that reads `bundle.json` and `rules.json` from the working directory, validates every resource in the bundle against every applicable rule, and writes `report.json` — a JSON array of violation objects, each with keys: `resource` (the resource's `id`), `profile` (the mCODE profile name from rules, e.g. "ecog-performance-status"), `rule` (the rule id from rules.json), `path` (the failing element path in FHIR dot notation, e.g. "code.coding[0].system"), `found` (what was actually there, or null if missing), and `expected` (what the rule requires). Rules to implement: (1) `fixed_code` — the element at `element` must contain a coding whose system+code exactly matches the fixed pair; (2) `required_element` — the element at `element` must exist and be non-empty; (3) `allowed_systems` — every coding system under `element` must be one of the listed URIs; (4) `value_set` — for a CodeableConcept at `element`, at least one coding's code must appear in the named enumerated value set (value sets are given in rules.json). Clean resources must produce no violations. Run it with `python3 validate_mcode.py`; the program must exit 0 and create `report.json`. + +Deterministic report contract: `expected` is a JSON object, never prose. For `required_element` use exactly `{"required":true,"non_empty":true}`; for `fixed_code` use exactly `{"system":,"code":}`; for `allowed_systems` use exactly `{"allowed_systems":[]}`; for `value_set` use exactly `{"value_set":,"system":,"codes":[]}`. URI/code arrays are sets (order is irrelevant). Required values are empty only when null or an empty string, object, or list; false and zero are present non-empty values. The grader invokes the script freshly with the supplied files and changed-rule fixtures and evaluates those newly generated reports; a pre-generated report is optional and is not used as execution evidence. + + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/afa3cae39fa70471ac8f9a3b/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..da4e650d3fbe0ec1f6a5b548b58b4144df6349ac --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/SKILL.md @@ -0,0 +1,123 @@ +--- +name: fhir-mcode +description: FHIR R4 mCODE STU4 (4.0.0) oncology profile requirements, terminology bindings, and fixed codes. Use whenever building, validating, or reasoning about oncology FHIR data — cancer Condition/staging/TNM, tumor markers, genomic variants, radiotherapy, performance status (ECOG/Karnofsky), cancer-related medications, or any mCODE profile — even if the user says "oncology data" or "cancer FHIR" without naming mCODE. mCODE constrains US Core, so pair this with the fhir-us-core skill. +--- + +# FHIR R4 mCODE STU4 (4.0.0) Quick Reference + +mCODE™ (minimal Common Oncology Data Elements) is an HL7 FHIR R4 IG: 39 profiles + 14 extensions for oncology. **Every mCODE profile constrains a US Core or base R4 profile** — mCODE only *adds* oncology rules (codes, must-support, cardinality). So first satisfy the US Core base (see the `fhir-us-core` skill), then apply the mCODE constraints here. + +- FHIR version: **R4 (4.0.1)** · IG version: **STU4 / 4.0.0** +- Profile canonical: `http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-` +- ValueSet canonical: `http://hl7.org/fhir/us/mcode/ValueSet/` + +## Code System URIs + +mCODE leans on SNOMED CT heavily, plus several systems beyond the US Core set. The non-obvious ones (NCI Thesaurus, AJCC, ICD-O-3) trip people up — get them exact: + +```python +SYSTEM_URIS = { + "snomed": "http://snomed.info/sct", + "loinc": "http://loinc.org", + "rxnorm": "http://www.nlm.nih.gov/research/umls/rxnorm", + "icd10cm": "http://hl7.org/fhir/sid/icd-10-cm", + "icdo3": "http://terminology.hl7.org/CodeSystem/icd-o-3", + "ncit": "http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl", # NCI Thesaurus (codes like C167435) + "ajcc": "http://cancerstaging.org", # AJCC stage groups + "hgnc": "http://www.genenames.org/geneId", # gene symbols + "ucum": "http://unitsofmeasure.org", + "cpt": "http://www.ama-assn.org/go/cpt", + "v2_0487": "http://terminology.hl7.org/CodeSystem/v2-0487", # specimen type + "obs_cat": "http://terminology.hl7.org/CodeSystem/observation-category", +} +``` + +## Profile Quick Reference + +`.code` binding strength and value set per profile. **Pref. systems** = where to search when the binding isn't a fixed code. See "Fixed `.code` codes" below for profiles whose `.code` is pinned (skip terminology search entirely). + +| Profile (`mcode-…`) | FHIR / US Core base | `.code` binding | `.value[x]` binding | Pref. systems | +|---|---|---|---|---| +| primary-cancer-condition | Condition / us-core-condition-problems-health-concerns | extensible: PrimaryCancerDisorderVS | — | SNOMED, ICD-10-CM | +| secondary-cancer-condition | Condition / (same) | extensible: SecondaryCancerDisorderVS | — | SNOMED, ICD-10-CM | +| cancer-patient | Patient / us-core-patient | — | — | — | +| cancer-disease-status | Observation / (base) | **fixed** LOINC 97509-4 | preferred: ConditionStatusTrendVS | SNOMED | +| tnm-primary-tumor-category | Observation / mcode-tnm-category | preferred: T staging-type VS | preferred: TNMPrimaryTumorCategoryVS | SNOMED (AJCC) | +| tnm-regional-nodes-category | Observation / mcode-tnm-category | preferred: N staging-type VS | preferred: TNMRegionalNodesCategoryVS | SNOMED (AJCC) | +| tnm-distant-metastases-category | Observation / mcode-tnm-category | preferred: M staging-type VS | preferred: TNMDistantMetastasesCategoryVS | SNOMED (AJCC) | +| tnm-stage-group | Observation / mcode-cancer-stage | preferred: stage-group staging-type VS | preferred: TNMStageGroupVS | SNOMED, AJCC | +| cancer-stage | Observation / us-core-simple-observation | preferred: CancerStageTypeVS | preferred: CancerStageValueVS | SNOMED | +| lymphoma-stage | Observation / mcode-cancer-stage | **fixed** SNOMED 385388004 | required: LymphomaStageValueVS | SNOMED | +| tumor-marker-test | Observation / us-core-observation-lab | extensible: TumorMarkerTestVS | (Quantity/CC) | LOINC | +| histologic-behavior-and-type | Observation / us-core-observation-lab | **fixed** LOINC 31206-6 | extensible: HistologicBehaviorAndTypeVS | ICD-O-3 | +| histologic-grade | Observation / us-core-observation-lab | **fixed** NCIt C18000 | extensible: HistologicGradeVS | SNOMED | +| tumor-morphology | Observation / us-core-simple-observation | **fixed** LOINC 77753-2 | — | ICD-O-3, SNOMED | +| tumor-size | Observation / (base) | **fixed** LOINC 21889-1 | components in mm/cm | UCUM | +| tumor | BodyStructure | — (morphology+location) | — | SNOMED, ICD-O-3 | +| human-specimen | Specimen / us-core-specimen | type: extensible HumanSpecimenTypeVS | — | HL7 v2-0487 | +| ecog-performance-status | Observation / us-core-observation-clinical-result | **fixed** LOINC 89247-1 | (LOINC answer list LL529-9) | — | +| karnofsky-performance-status | Observation / (same) | **fixed** LOINC 89243-0 | (answer list LL4986-7) | — | +| lansky-play-performance-status | Observation / (same) | **fixed** NCIt C38144 | int 0–100 | — | +| comorbidities | Observation / us-core-simple-observation | **fixed** SNOMED 398192003 | — | SNOMED | +| genomic-variant | Observation / Genomics Reporting `variant` | **fixed** LOINC 69548-6 | (see genomics.md) | HGNC, LOINC | +| genomic-region-studied | Observation / `region-studied` | **fixed** LOINC 53041-0 | (components) | HGNC, LOINC | +| genomics-report | DiagnosticReport / Genomics `genomics-report` | preferred: report codes | — | LOINC | +| cancer-related-medication-request | MedicationRequest / us-core-medicationrequest | extensible: medication VS | — | RxNorm | +| cancer-related-medication-administration | MedicationAdministration / (base) | extensible: medication VS | — | RxNorm | +| cancer-related-surgical-procedure | Procedure / us-core-procedure | extensible: CancerRelatedSurgicalProcedureVS | — | SNOMED, CPT | +| radiotherapy-course-summary | Procedure / us-core-procedure | **fixed** SNOMED 1217123003 | — | SNOMED | + +> The full element-level tables (cardinality, must-support, every binding, slices, extensions) live in `references/`. Read the file for the domain you're working in — don't reconstruct constraints from memory. + +## Fixed `.code` codes (bypass terminology search) + +When `.code` is fixed, emit exactly this coding — do **not** search a terminology server: + +| Profile | system | code | display | +|---|---|---|---| +| cancer-disease-status | LOINC | 97509-4 | Cancer disease status | +| ecog-performance-status | LOINC | 89247-1 | ECOG performance status | +| karnofsky-performance-status | LOINC | 89243-0 | Karnofsky Performance Status score | +| lansky-play-performance-status | NCIt | C38144 | Lansky Play-Performance Status | +| histologic-behavior-and-type | LOINC | 31206-6 | Histology and behavior ICD-O-3 | +| histologic-grade | NCIt | C18000 | Grade | +| tumor-morphology | LOINC | 77753-2 | Tumor morphology | +| tumor-size | LOINC | 21889-1 | Size Tumor | +| comorbidities | SNOMED | 398192003 | Co-morbid conditions | +| deauville-scale | SNOMED | 708895006 | Deauville five point scale | +| lymphoma-stage | SNOMED | 385388004 | Lymphoma stage | +| body-surface-area | LOINC | 8277-6 | Body surface area | +| genomic-variant | LOINC | 69548-6 | Genetic variant assessment | +| genomic-region-studied | LOINC | 53041-0 | DNA region of interest panel | +| radiotherapy-course-summary | SNOMED | 1217123003 | Radiotherapy course of treatment | +| ALL-risk-assessment | NCIt | C167435 | Leukemia Finding | +| rhabdomyosarcoma-risk-assessment | NCIt | C148010 | IRSG Clinical Staging System | + +## Binding strength rules + +Same semantics as US Core. **Required** → SHALL use a code from the value set. **Extensible** → use the value set if an applicable concept exists; only go outside it if none fits. **Preferred** → encouraged but not enforced. mCODE's clinically-richest value sets (cancer disorders, body locations, tumor markers, ICD-O-3 morphology) are large/grammar-based and *not* enumerable here — bind by URL and resolve the specific code via terminology search. + +## Reference files (read the relevant one) + +- `references/disease.md` — CancerPatient, Primary/Secondary Cancer Condition, Cancer Disease Status, History of Metastatic Cancer +- `references/staging.md` — TNM categories + stage group, CancerStage, LymphomaStage, staging methods, AJCC value sets +- `references/treatment.md` — medication request/administration, radiotherapy course summary + extensions, surgical procedure, termination reasons, procedure intent +- `references/assessment.md` — ECOG / Karnofsky / Lansky, Comorbidities, risk assessments, Deauville +- `references/genomics.md` — GenomicVariant, GenomicRegionStudied, GenomicsReport (component slices) +- `references/specimen-tumor.md` — HumanSpecimen, Tumor, TumorSize, TumorMarkerTest, histologic behavior/grade, morphology + +## Worked example: Primary Cancer Condition + +```json +{ + "resourceType": "Condition", + "meta": { "profile": ["http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-primary-cancer-condition"] }, + "clinicalStatus": { "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-clinical", "code": "active" }] }, + "verificationStatus": { "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-ver-status", "code": "confirmed" }] }, + "category": [{ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-category", "code": "problem-list-item" }] }], + "code": { "coding": [{ "system": "http://snomed.info/sct", "code": "408643008", "display": "Infiltrating duct carcinoma of breast" }] }, + "bodySite": [{ "coding": [{ "system": "http://snomed.info/sct", "code": "76752008", "display": "Breast structure" }] }], + "subject": { "reference": "Patient/example" } +} +``` +Note: `code` binds extensibly to PrimaryCancerDisorderVS (resolve via SNOMED/ICD-10-CM), `bodySite` to CancerBodyLocationVS. Stage is linked via `Condition.stage.assessment` → TNMStageGroup/CancerStage Observations. diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/evals/evals.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/evals/evals.json new file mode 100644 index 0000000000000000000000000000000000000000..d6c91417223155bc7481fc0dbe47b445393f16e4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/evals/evals.json @@ -0,0 +1,26 @@ +{ + "skill_name": "fhir-mcode", + "evals": [ + { + "id": 0, + "name": "breast-cancer-staging-bundle", + "prompt": "I'm building a FHIR R4 bundle for an oncology app. Generate the FHIR resources for this patient: 58-year-old woman, newly diagnosed invasive ductal carcinoma of the left breast, clinically staged cT2 cN1 cM0, AJCC 8th edition stage group IIB. I need the primary cancer condition plus the TNM staging (the individual T/N/M categories and the overall stage group), wired together correctly. Output the JSON resources.", + "expected_output": "mCODE-conformant Condition (mcode-primary-cancer-condition) with SNOMED code + left breast bodySite, three TNM category Observations (cT/cN/cM with correct staging-type codes and category values), and a TNMStageGroup observation that references the cancer via focus and the categories via hasMember, method=AJCC 8th (897275008). Correct profile URLs and code-system URIs.", + "files": [] + }, + { + "id": 1, + "name": "ecog-and-disease-status", + "prompt": "For our cancer registry FHIR feed I need two Observations for patient James Lee: an ECOG performance status of 1, and a cancer disease status indicating the disease is stable. Give me the FHIR JSON conforming to the relevant oncology profiles.", + "expected_output": "Two Observations: ECOG (mcode-ecog-performance-status, fixed code LOINC 89247-1, grade 1 in interpretation/value) and Cancer Disease Status (mcode-cancer-disease-status, fixed code LOINC 97509-4, value = SNOMED 359746009 'Patient status stable' from ConditionStatusTrendVS). Correct fixed codes used verbatim, correct profile meta.", + "files": [] + }, + { + "id": 2, + "name": "egfr-genomic-variant", + "prompt": "Build a FHIR genomic variant Observation for an oncology genomics report: an EGFR L858R somatic point mutation found in a lung adenocarcinoma patient. Use the appropriate mCODE/genomics-reporting structure with the component slices for gene and the protein change. JSON please.", + "expected_output": "Observation conforming to mcode-genomic-variant: fixed code LOINC 69548-6, category laboratory, component slices with fixed LOINC codes for gene-studied (48018-6, EGFR via HGNC), amino-acid/protein change p.HGVS (48005-3, p.Leu858Arg), genomic source class (48002-0 = somatic). Correct component.code pinning and code systems.", + "files": [] + } + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/assessment.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/assessment.md new file mode 100644 index 0000000000000000000000000000000000000000..38d5e1e2539bf423564d288b27a6bb921afbe55b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/assessment.md @@ -0,0 +1,47 @@ +# mCODE Assessment Domain + +Performance status, comorbidities, and risk assessments. The performance-status profiles all derive from `us-core-observation-clinical-result`, pin `.code` to a fixed scale code, and bind `interpretation` to a LOINC answer list. + +## Performance status + +| Profile | `.code` (fixed) | value / interpretation | +|---|---|---| +| ecog-performance-status | LOINC 89247-1 | grade 0–5; `interpretation` **required** LOINC answer list LL529-9 | +| karnofsky-performance-status | LOINC 89243-0 | score 0–100; `interpretation` **required** LOINC answer list LL4986-7 | +| lansky-play-performance-status | NCIt C38144 | pediatric play score 0–100; `interpretation` extensible LanskyPlayPerformanceVS | + +Common shape (all): `status` 1..1 MS, `code` 1..1 MS (fixed above), `subject` 1..1 MS, `effective[x]` 0..1 MS, `value[x]` 0..1 MS, `dataAbsentReason` 0..1 MS, `interpretation` MS. + +ECOG/Karnofsky put the actual grade in `interpretation` (from the LOINC answer list) and may also carry the numeric in `value`. ECOG grades: 0 (fully active) → 5 (dead). Karnofsky: 100 (normal) → 0 (dead), in steps of 10. + +## Comorbidities (Observation → us-core-simple-observation) + +A structured roll-up of comorbid conditions relative to an index (primary) cancer condition. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: observation-status | +| code | 1..1 | ✓ | **fixed SNOMED 398192003** "Co-morbid conditions" | +| subject | 1..1 | ✓ | Patient | +| value[x] | 0..1 | ✓ | | + +Extensions (MS) carry the actual comorbidity data three ways: free-form list, a specified comorbidity category, or absent-comorbidity assertions — via the `comorbidities-elements` / `related-condition` extensions referencing Condition resources. + +## DeauvilleScale (Observation → us-core-observation-clinical-result) + +5-point PET response scale for Hodgkin / aggressive NHL. + +| Element | Card | MS | Binding | +|---|---|---|---| +| code | 1..1 | ✓ | **fixed SNOMED 708895006** "Deauville five point scale" | +| interpretation | 0..* | ✓ | extensible: DeauvilleScaleVS (the 1–5 score) | +| value[x], dataAbsentReason | 0..1 | ✓ | | + +## Risk assessments + +`CancerRiskAssessment` is the parent (Observation → us-core-simple-observation); `code` preferred RiskAssessmentTypeVS, `value[x]` example RiskAssessmentVS. Two disease-specific children pin the code: + +| Profile | `.code` (fixed) | `.value[x]` | +|---|---|---| +| ALL-risk-assessment | NCIt C167435 | extensible ALLRiskAssessmentVS: `C122457` standard risk, `C122458` high risk | +| rhabdomyosarcoma-risk-assessment | NCIt C148010 | required RhabdomyosarcomaAssessmentValueVS: `723505004` low, `C102402` intermediate, `723509005` high | diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/disease.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/disease.md new file mode 100644 index 0000000000000000000000000000000000000000..30e4a9fd79ff53be0945d20f71ae939bed5acc81 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/disease.md @@ -0,0 +1,69 @@ +# mCODE Disease Domain + +Patient, the cancer conditions, and disease status. All profiles constrain US Core — satisfy the US Core base first (`fhir-us-core` skill), then apply these mCODE additions. + +## CancerPatient (Patient → us-core-patient) + +No oncology-specific content — it is US Core Patient with the same must-support set (identifier, name, gender, birthDate, address, communication.language). Use it as the subject of every other mCODE resource. The only reason it exists is to mark the patient as in-scope for mCODE; conform to US Core Patient and reference this profile. + +## PrimaryCancerCondition (Condition → us-core-condition-problems-health-concerns) + +The original/first neoplasm. Records the cancer diagnosis and links to staging. + +| Element | Card | MS | Binding | +|---|---|---|---| +| clinicalStatus | 0..1 | ✓ | required: condition-clinical | +| verificationStatus | 0..1 | ✓ | required: condition-ver-status | +| category | 1..* | ✓ | required: us-core-problem-or-health-concern (+ condition-category) | +| code | 1..1 | ✓ | **extensible: PrimaryCancerDisorderVS** — resolve via SNOMED CT (preferred) or ICD-10-CM | +| bodySite | 0..* | ✓ | extensible: CancerBodyLocationVS (SNOMED); +laterality/location-qualifier extensions | +| subject | 1..1 | ✓ | Patient | +| onset[x], abatement[x], recordedDate | 0..1 | ✓ | | +| stage | 0..* | ✓ | `stage.assessment` → references TNMStageGroup / CancerStage Observations; `stage.type` extensible: CancerStagingMethodVS | +| evidence.code | 0..* | | required: CancerDiseaseStatusEvidenceTypeVS | + +Extensions (must-support): `histology-morphology-behavior` (ICD-O-3 morphology, links to a TumorMorphology Observation or codes inline), `assertedDate`, `condition-related`. + +`code` value set is large and grammar-based (SNOMED disorder hierarchy) — bind by URL, do **not** enumerate. Search terminology for the specific histology+site disorder code. + +## SecondaryCancerCondition (Condition → us-core-condition-problems-health-concerns) + +Metastases — cancer that has spread from the primary site. Same shape as PrimaryCancerCondition with two differences: + +- `code` binds **extensible: SecondaryCancerDisorderVS** (secondary/metastatic malignant neoplasm disorders). +- Adds the standard FHIR `condition-related` extension (`Condition.extension`, url fixed to `http://hl7.org/fhir/StructureDefinition/condition-related`) — point it at the PrimaryCancerCondition this metastasis derives from. + +`bodySite` (CancerBodyLocationVS) records the metastatic site(s). + +## CancerDiseaseStatus (Observation, base Observation) + +A clinician's qualitative judgment of the cancer's trend (stable / improving / worsening). Note: base R4 Observation, **not** US Core. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: observation-status | +| code | 1..1 | ✓ | **fixed LOINC 97509-4** "Cancer disease status" | +| subject | 1..1 | ✓ | Patient | +| focus | 0..* | ✓ | → the Condition this status is about | +| effective[x] | 0..1 | ✓ | | +| value[x] | 0..1 | ✓ | **preferred: ConditionStatusTrendVS** (CodeableConcept) | +| evidence type | | | via extension `cancer-disease-status-evidence-type` | + +**ConditionStatusTrendVS** (SNOMED, 4 codes — enumerable): +| code | display | +|---|---| +| 268910001 | Patient's condition improved | +| 359746009 | Patient status stable | +| 271299001 | Patient's condition worsened | +| 709137006 | Patient condition undetermined | + +## HistoryOfMetastaticCancer (Observation → us-core-simple-observation) + +Records that a past episode of metastatic cancer existed, for long-term tracking. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: observation-status | +| code | 1..1 | ✓ | extensible: HistoryOfMetastaticMalignantNeoplasmVS (SNOMED) | +| subject | 1..1 | ✓ | Patient | +| value[x] | 0..1 | ✓ | | diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/genomics.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/genomics.md new file mode 100644 index 0000000000000000000000000000000000000000..aa2e818861ebef09b0005b92d1e4e61c8f30bc51 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/genomics.md @@ -0,0 +1,53 @@ +# mCODE Genomics Domain + +mCODE reuses the **HL7 Genomics Reporting IG** profiles as bases — GenomicVariant constrains the GR `variant` profile, GenomicRegionStudied the GR `region-studied`, GenomicsReport the GR `genomics-report`. The structure is a `DiagnosticReport` whose `result` references variant/region Observations. + +These profiles model data as **component slices, each keyed by a fixed LOINC `component.code`**, with the actual data in `component.value[x]`. So the pattern is always: emit a component with the fixed code, then fill its value. You don't search terminology for component codes — they're pinned. + +## GenomicsReport (DiagnosticReport → genomics-report) + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: diagnostic-report-status | +| category | 1..* | ✓ | includes a coding **fixed to `GE`** (genetics, diagnostic-service-sections) | +| code | 1..1 | ✓ | preferred: report-codes (LOINC) | +| subject, effective[x], issued, performer, specimen | | ✓ | | +| result | 0..* | ✓ | → GenomicVariant / GenomicRegionStudied Observations | + +## GenomicVariant (Observation → GR `variant`) + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: observation-status | +| category | 1..1 | | **fixed** observation-category `laboratory` | +| code | 1..1 | ✓ | **fixed LOINC 69548-6** "Genetic variant assessment" | +| value[x] | 0..1 | | (present/absent — LOINC answer list LL1971-2) | +| method | 0..1 | ✓ | extensible (LOINC LL4048-6) | +| specimen | 0..1 | ✓ | | + +Key component slices (fixed `component.code` → `value[x]`): +| component.code (LOINC) | meaning | value binding | +|---|---|---| +| 48018-6 | Gene studied | extensible HGNC-VS (gene symbol) | +| 48001-2 | Genomic region/cytoband | | +| 62374-4 | Reference genome build | LL1040-6 (e.g. GRCh38) | +| 48004-6 / 81290-9 | DNA change (g./c. HGVS) | required HGVS-VS | +| 48005-3 | Amino acid change (p. HGVS) | required HGVS-VS | +| 48002-0 | Genomic source class | LL378-1 (somatic/germline) | +| 53034-5 | Allelic state | LL381-5 | +| 48019-4 | DNA change type | extensible dna-change-type-vs | +| 81252-9 | Variant code (ClinVar etc.) | | +| 53037-8 | Clinical significance | (pathogenic / likely / VUS …) | + +For a typical somatic point mutation report, the minimum useful set is: fixed `code`, then components for gene studied (48018-6), c.HGVS (48004-6), p.HGVS (48005-3), and genomic source class (48002-0 = somatic). + +## GenomicRegionStudied (Observation → GR `region-studied`) + +Describes the genes/regions covered by a targeted panel. + +| Element | Card | MS | Binding | +|---|---|---|---| +| code | 1..1 | ✓ | **fixed LOINC 53041-0** "DNA region of interest panel" | +| category | 1..1 | | fixed `laboratory` | + +Component slices (fixed LOINC code): `48018-6` gene-studied (HGNC) · `36908-2` gene mutations tested (required HGVS-VS) · `81293-3` genomic ref-sequence · `51959-5` ranges-examined · `92822-6` genomic coord system (LL5323-2). diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/specimen-tumor.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/specimen-tumor.md new file mode 100644 index 0000000000000000000000000000000000000000..f5ab60d82aca4d799ab705bad8885a17434f6390 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/specimen-tumor.md @@ -0,0 +1,70 @@ +# mCODE Specimen & Tumor Domain + +Physical specimens, tumor body structures, and tumor characterization (size, morphology, histology, markers). + +## HumanSpecimen (Specimen → us-core-specimen) + +A specimen taken for oncology testing. + +| Element | Card | MS | Binding | +|---|---|---|---| +| identifier | 0..* | ✓ | one slice typed `BodyStructure` (links to source structure) | +| status | 0..1 | ✓ | required: specimen-status | +| type | 1..1 | ✓ | **extensible: HumanSpecimenTypeVS** (HL7 v2-0487) | +| collection.bodySite | 0..1 | ✓ | example body-site + laterality/location-qualifier extensions | + +HumanSpecimenTypeVS (v2-0487, 33 codes): common ones — `TISS` Tissue · `TUMOR` Tumor · `BLD` Whole blood · `BON` Bone · `MAR` Marrow · `CSF` CSF · `PLR` Pleural fluid · `SAL` Saliva · `SKN` Skin · `SPT` Sputum. + +## Tumor (BodyStructure) + +Identifies a tumor *in situ* (not removed). Aim for one resource per tumor, tracked over time. + +| Element | Card | MS | Binding | +|---|---|---|---| +| identifier | 1..* | ✓ | stable id to track the tumor across observations | +| morphology | 0..1 | ✓ | extensible: TumorMorphologyCodeVS (ICD-O-3, SNOMED) | +| location | 1..1 | ✓ | extensible: CancerBodyLocationVS (SNOMED) | +| locationQualifier | 0..* | ✓ | required: BodyLocationAndLateralityQualifierVS | +| patient | 1..1 | ✓ | | + +Carries a `related-condition` extension (url fixed) → the cancer Condition. TumorSize and other observations reference the Tumor via `focus`/`bodySite`. + +## TumorSize (Observation, base R4) + +Dimensions of a tumor. Note: base Observation, not US Core. + +| Element | Card | MS | Binding | +|---|---|---|---| +| code | 1..1 | ✓ | **fixed LOINC 21889-1** "Size Tumor" | +| subject | 1..1 | ✓ | Patient | +| focus | 0..1 | ✓ | → the Tumor BodyStructure | +| method | 0..1 | ✓ | extensible: TumorSizeMethodVS | +| component | 1..* | ✓ | dimensions, each in mm/cm | + +Component slices (fixed LOINC code, value `Quantity` with **required TumorSizeUnitsVS** = `mm` or `cm`): +- `33728-7` longest dimension (1..1, required) +- `33729-5` other dimensions (0..2) + +## TumorMarkerTest (Observation → us-core-observation-lab) + +Result of a tumor marker test (ER, PR, HER2, PSA, CA-125, etc.). + +| Element | Card | MS | Binding | +|---|---|---|---| +| category | 1..1 | ✓ | fixed `laboratory` | +| code | 1..1 | ✓ | extensible: TumorMarkerTestVS (LOINC, 513 codes — search) | +| subject | 1..1 | ✓ | Patient | +| value[x] | 1..1 | ✓ | Quantity, CodeableConcept, ratio, or string per marker | +| specimen | 0..1 | ✓ | → HumanSpecimen | + +## Histology / morphology + +| Profile | base | `.code` (fixed) | `.value[x]` | method | +|---|---|---|---|---| +| histologic-behavior-and-type | us-core-observation-lab | LOINC 31206-6 | extensible HistologicBehaviorAndTypeVS (**ICD-O-3** morphology, e.g. `8500/3`) | — | +| histologic-grade | us-core-observation-lab | NCIt C18000 | extensible HistologicGradeVS | extensible HistologicGradingSystemVS | +| tumor-morphology | us-core-simple-observation | LOINC 77753-2 | — (ICD-O-3 / SNOMED morphology) | — | + +HistologicGradeVS (SNOMED, 3): `1155708003` low · `1286893008` intermediate · `1155707008` high. HistologicGradingSystemVS (18 systems): Gleason `106241006`, Nottingham `449205006`, Fuhrman `396192007`, WHO CNS `277460003`, FNCLCC `426757001`, etc. + +ICD-O-3 morphology codes use the form `8500/3` (4-digit type `/` 1-digit behavior). The behavior-and-type value set isn't expanded in the IG (IP reasons) — bind by URL and supply the ICD-O-3 code with system `http://terminology.hl7.org/CodeSystem/icd-o-3`. diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/staging.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/staging.md new file mode 100644 index 0000000000000000000000000000000000000000..3181f7ce81baed1dcee42fddcd47249eb645ea0e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/staging.md @@ -0,0 +1,80 @@ +# mCODE Staging Domain + +Cancer staging splits into **TNM** (the individual T/N/M categories plus the overall stage group) and **general/other** systems (CancerStage parent, LymphomaStage). Staging Observations attach to the cancer via `PrimaryCancerCondition.stage.assessment`. + +The data model: three TNM category Observations (T, N, M) are referenced by one TNMStageGroup Observation via `hasMember`, and the stage group's `focus` points at the cancer Condition. + +## Inheritance + +``` +us-core-simple-observation + └─ mcode-cancer-stage ............ CancerStage (parent for stage observations) + ├─ mcode-tnm-stage-group ..... TNMStageGroup + └─ mcode-lymphoma-stage ...... LymphomaStage + └─ mcode-tnm-category ............ TNMCategory (parent for T/N/M) + ├─ mcode-tnm-primary-tumor-category + ├─ mcode-tnm-regional-nodes-category + └─ mcode-tnm-distant-metastases-category +``` + +## TNMStageGroup (Observation → mcode-cancer-stage) + +Overall AJCC stage group. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: observation-status | +| code | 1..1 | ✓ | preferred: TNMStageGroupStagingTypeVS | +| subject | 1..1 | ✓ | Patient | +| focus | 1..1 | ✓ | → the cancer Condition | +| value[x] | 0..1 | ✓ | preferred: TNMStageGroupVS (CodeableConcept; 141 AJCC codes — search, not enumerable here) | +| method | 1..1 | ✓ | extensible: TNMStagingMethodVS | +| hasMember | 0..3 | ✓ | → the T, N, M category Observations | +| component | 0..* | | prognostic factors (preferred VS) | + +`code` — pick by clinical vs pathologic: +| code (SNOMED) | meaning | +|---|---| +| 399390009 | TNM stage grouping (unspecified) | +| 399537006 | Clinical TNM stage grouping (cTNM) | +| 399588009 | Pathologic TNM stage grouping (pTNM) | + +## TNM category profiles (Observation → mcode-tnm-category) + +All three share: `status` 1..1 MS, `subject` 1..1 MS, `method` 1..1 MS (extensible TNMStagingMethodVS), `code` 1..1 MS and `value[x]` 0..1 MS (both preferred). They differ only by which staging-type VS binds `code` and which category VS binds `value[x]`. + +| Profile | `.code` VS (staging type) | `.value[x]` VS (category) | +|---|---|---| +| tnm-primary-tumor-category | TNMPrimaryTumorStagingTypeVS | TNMPrimaryTumorCategoryVS (118 codes) | +| tnm-regional-nodes-category | TNMRegionalNodesStagingTypeVS | TNMRegionalNodesCategoryVS (59) | +| tnm-distant-metastases-category | TNMDistantMetastasesStagingTypeVS | TNMDistantMetastasesCategoryVS (28) | + +**`.code` staging-type codes** (SNOMED; pick clinical `c…` vs pathologic `p…`): +| Profile | unspecified | clinical | pathologic | +|---|---|---|---| +| T (primary tumor) | 78873005 | 399504009 (cT) | 384625004 (pT) | +| N (regional nodes) | 277206009 | 399534004 (cN) | 371494008 (pN) | +| M (distant metastases) | 277208005 | 399387003 (cM) | 371497001 (pM) | + +The category `value[x]` codes are SNOMED concepts prefixed "American Joint Committee on Cancer", e.g. cM0 = `1229901006`, cM1 = `1229903009`, cN0 = `1229967007`, pN1 = `1229951001`. These are large enumerations — search the category VS for the exact c/p value rather than guessing the SNOMED id. + +## CancerStage (Observation → us-core-simple-observation) + +Parent for non-TNM staging (and grade/classification). `code` preferred CancerStageTypeVS (64 codes: TNM, FIGO, Dukes, Ann Arbor, etc.), `value[x]` preferred CancerStageValueVS, `method` MS preferred CancerStagingMethodVS (58 systems — AJCC, FIGO, Dukes, Binet, Rai, ISS…). Use directly only when no more-specific staging profile fits. + +## LymphomaStage (Observation → mcode-cancer-stage) + +Ann Arbor / Cotswold / Lugano staging. + +| Element | Card | MS | Binding | +|---|---|---|---| +| code | 1..1 | ✓ | **fixed SNOMED 385388004** "Lymphoma stage" | +| value[x] | 0..1 | ✓ | **required: LymphomaStageValueVS** | +| method | 1..1 | ✓ | **required: LymphomaStagingMethodVS** (which of Ann Arbor / Cotswold / Lugano) | +| component | | | fixed-code component slices for stage modifier (`106252000`), nature of staging (`277366005` → ClinOrPathModifierVS), bulky disease (`260873006` → LymphomaStageBulkyModifierVS) | + +ClinOrPathModifierVS (SNOMED): `260998006` cS clinical staging · `261023001` pathological staging. + +## Staging methods + +**TNMStagingMethodVS** (5 codes) — AJCC editions: `444256004` (6th), `443830009` (7th), `897275008` (8th), `1269566009` (9th); plus UICC `C188404` (NCIt). **CancerStagingMethodVS** (58 codes) covers the full range of named systems (FIGO by site, Dukes, Modified Astler-Coller, Binet, Rai, ISS/R-ISS, Breslow, Clark, Gleason context, Ann Arbor variants). diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/treatment.md b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/treatment.md new file mode 100644 index 0000000000000000000000000000000000000000..ce78c3242458d5a77c8b467c80d128543a5e7c73 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/skill/references/treatment.md @@ -0,0 +1,75 @@ +# mCODE Treatment Domain + +Cancer-related medications, radiotherapy, and surgery. The cancer-relatedness is enforced by constraining `reasonCode`/`reasonReference` to a cancer condition. + +## CancerRelatedMedicationRequest (MedicationRequest → us-core-medicationrequest) + +A prescription/consumption record for cancer treatment. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: medicationrequest-status | +| statusReason | 0..1 | ✓ | preferred: TreatmentTerminationReasonVS | +| intent | 1..1 | ✓ | required: medicationrequest-intent | +| medication[x] | 1..1 | ✓ | extensible: cancer medication VS (OID 2.16.840.1.113762.1.4.1010.4) → **RxNorm** | +| subject | 1..1 | ✓ | Patient | +| reasonCode | 0..* | ✓ | extensible: CancerDisorderVS (the cancer being treated) | +| reasonReference | 0..* | ✓ | → Primary/SecondaryCancerCondition | +| dosageInstruction, dispenseRequest | 0..* | ✓ | doseAndRate.dose preferred ucum-common | + +Treatment-intent extension (`procedure-intent` pattern) may carry curative/palliative intent — see ProcedureIntentVS below. + +## CancerRelatedMedicationAdministration (MedicationAdministration, base R4) + +Records an actual administration (the chemo "give" event). Same cancer-relatedness constraints. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: medication-admin-status | +| statusReason | 0..* | ✓ | preferred: TreatmentTerminationReasonVS | +| medication[x] | 1..1 | ✓ | extensible: cancer medication VS → RxNorm | +| subject | 1..1 | ✓ | Patient | +| effective[x] | 1..1 | ✓ | when administered | +| reasonCode | 0..* | ✓ | extensible: CancerDisorderVS | +| reasonReference | 0..* | ✓ | → cancer Condition | + +## RadiotherapyCourseSummary (Procedure → us-core-procedure) + +Summary of a radiotherapy course: intent, termination reason, modalities, techniques, sessions, doses. + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: event-status | +| statusReason | 0..1 | ✓ | preferred: TreatmentTerminationReasonVS | +| code | 1..1 | ✓ | **fixed SNOMED 1217123003** "Radiotherapy course of treatment" | +| subject | 1..1 | ✓ | Patient | +| performed[x] | 0..1 | ✓ | period of the course | +| reasonCode / reasonReference | 0..* | ✓ | the cancer treated (CancerDisorderVS) | +| bodySite | 0..* | ✓ | extensible: RadiotherapyTreatmentLocationVS | + +Must-support extensions carry the structured detail: +- `radiotherapy-modality-and-technique` — wraps `radiotherapy-modality` (RadiotherapyModalityVS, 12 codes) + `radiotherapy-technique` (RadiotherapyTechniqueVS, 18 codes) +- `radiotherapy-sessions` — number of fractions/sessions (integer) +- `procedure-intent` — ProcedureIntentVS + +Companion profiles: **RadiotherapyVolume** (BodyStructure — a planning/treatment volume; morphology RadiotherapyVolumeTypeVS, location + qualifier VS) and the dose-delivered extension. Use these when modeling per-volume dose. + +## CancerRelatedSurgicalProcedure (Procedure → us-core-procedure) + +| Element | Card | MS | Binding | +|---|---|---|---| +| status | 1..1 | ✓ | required: event-status | +| code | 1..1 | ✓ | extensible: CancerRelatedSurgicalProcedureVS (SNOMED, CPT) | +| subject | 1..1 | ✓ | Patient | +| reasonCode / reasonReference | 0..* | ✓ | cancer condition (CancerDisorderVS) | +| bodySite | 0..* | ✓ | example: body-site (+ laterality/location-qualifier extensions) | + +## Shared value sets + +**TreatmentTerminationReasonVS** (SNOMED, 11): `266721009` absent response · `407563006` not tolerated · `160932005` financial · `105480006` patient refusal · `184081006` moved away · `309846006` not available · `399307001` lost to follow-up · `419620001` death · `7058009` noncompliance · `443729008` clinical-trial completion · `77386006` pregnancy. + +**ProcedureIntentVS** (SNOMED, 8): `373808002` curative · `363676003` palliative · `399707004` supportive · `261004008` diagnostic · `129428001` preventive · `429892002` guidance · `360156006` screening · `447295008` forensic. + +**RadiotherapyModalityVS** (12, SNOMED): teleradiotherapy protons `10611004` / electrons `45643008` / neutrons `80347004` / carbon ions `1156505006` / photons `1156506007`; brachytherapy LDR `1156708005`, permanent seeds `169359004`, pulsed `1156384006`, HDR `394902000`; radiopharmaceutical `440252007`. + +**RadiotherapyTechniqueVS** (18, SNOMED): IMRT `441799006`, VMAT `1156530009`, 3D-CRT `1162782007`, 2D `1156526006`, intraoperative `168524008`, FLASH `1163157007`, plus particle/brachytherapy techniques. diff --git a/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/task.json b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/task.json new file mode 100644 index 0000000000000000000000000000000000000000..07d7d9ee6d4c2c94bf07104812d249c460c5eff0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/afa3cae39fa70471ac8f9a3b/task.json @@ -0,0 +1,84 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "afa3cae39fa70471ac8f9a3b", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "afa3cae39fa70471ac8f9a3b", + "outputs": [ + "report.json" + ], + "success_criteria": [ + "A file `validate_mcode.py` exists and runs successfully with `python3 validate_mcode.py` (exit code 0) using only the Python standard library. Dependency/resource checks apply only to the actual guarded Python invocations under the public bounded runtime policy, not to unused source or static closure inference.", + "Fresh execution creates report.json as a JSON array; stale submitted reports are not graded.", + "`report.json` reports exactly 6 violations, one each for: cond-1 wrong code system (http://snomed.org/sct instead of http://snomed.info/sct, rule R1); obs-ecog-1 wrong fixed code 89243-0 instead of 89247-1 (rule R5); obs-ecog-1 missing interpretation (rule R6); obs-status-1 value code 9999999 not in ConditionStatusTrendVS (rule R9); obs-stage-1 missing focus (rule R10); obs-size-1 unit mm[Hg] not in TumorSizeUnitsVS (rule R14).", + "Every violation includes resource/profile/rule/path/found plus the exact public structured expected object, with source-bound values and typed JSON booleans.", + "No violations are reported for the clean resources pat-1, and no rule is reported as violated that is actually satisfied (no false positives).", + "The validator is data-driven: it reads its checks from `rules.json` rather than hard-coding the specific bundle resources or violation findings." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "c3417277f7707887d737ec9bbfc988e1f163342d8b49f46a9f5aa673341509f2", + "files": { + "SKILL.md": "ff1b774f8450cc2c8e61e1b235fde8ec1d09fff1e7de4c3b30abd8cb7a267668", + "evals/evals.json": "1ee28b0d0d3b34b82070e3631652b92f5d019560e72bf47df747d13f29035c94", + "references/assessment.md": "e726967b8679f9f6cb08bb5d76ff1089c57cb94c1bc3edd325463c8dade69387", + "references/disease.md": "a3f0e3f8ed606135e283a338b19ad93fe0b39e891f1f49e096593d209cb203b4", + "references/genomics.md": "960069d38308c7a30b67395a3fcf19fb0a340b0bb350f60c1193747cf2ce998d", + "references/specimen-tumor.md": "2b35e3064a4210d5ef7eff22cb5521e3cf68559b1f6cdd6dbe04fa42245ef11e", + "references/staging.md": "d08c6fe9ead192b85dd90cf7d84d7520afb321052efa3b11397c93a0814d1c21", + "references/treatment.md": "4cffcce52706a3cab521ae1f8b207351dd502591d1752da14ea803f0c2bf2803" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/bundle.json", + "workspace_target": "bundle.json", + "sha256": "eae0470685ef08fa1f2eeed8c821d5d9fa4ed73f2fa0e98c44f476efa68df17a" + }, + { + "source": "inputs/rules.json", + "workspace_target": "rules.json", + "sha256": "083f1757ca8437521d512f8953a6ff43d7945584e64b8347831b8f27c6a5bff9" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "c3417277f7707887d737ec9bbfc988e1f163342d8b49f46a9f5aa673341509f2" + } + ] + }, + "autograde_contract_revision": "deterministic-v1", + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/b08ca17bb14d90aa_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_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/b08ca17bb14d90aa_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_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/b08ca17bb14d90aa_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_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/b08ca17bb14d90aa_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b08ca17bb14d90aa_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/b08ca17bb14d90aa_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_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/b08ca17bb14d90aa_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b08ca17bb14d90aa_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..9ee855b191c01e1e503bfb567619cb4c53319058 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b08ca17bb14d90aa_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "88dc16e5206143b30ce8539781adc7cc8a7b2bbb4cca1464de8730f6edbcac3a", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95ddfbdcee615dd9c5bfd540d624f6ee9582bbbb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/instruction.md @@ -0,0 +1 @@ +Our brand identity workflow has a mandatory cost transparency gate: before any paid image generation call runs and spends credits, we must surface the current balance exactly once. Two things I need pinned down: which tool must be called once with verbose enabled before any paid MCP call, and which image generation provider our workflow uses for symbols, mood images, and photography. Return one JSON object mapping every item ID to the bare project-defined scalar, using this schema once with placeholders replaced by the actual values and no extra keys: {"answers":{"q1":"string","q2":"string"}} diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/README.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4cfa0b105ae08420010d8e47131d1e3280fba073 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/README.md @@ -0,0 +1,115 @@ +# build-a-brand · Claude Code Skill + +A skill that takes any input — an idea, a website URL, a list of reference brands, product photos, or a request to refresh an existing brand — and produces a complete brand identity, ending in a 14–16-page brand guidelines PDF + a portable brand kit. + +## What this skill does + +Walks the user through a 4-step workflow: + +1. **Read the input** — adaptive intake questions per input type + universal asks about existing brand assets, references, and whether the brand is a digital product. Finishes with a deliverable preview to invite specific guidance. +2. **Generate 3 visual brand boards (PDF)** — three complete brand directions, each with its own colors, fonts, photography style, voice samples, and logo concept. Boards diverge across at least 4 structural dimensions (density, saturation, layout philosophy, type energy, voice register). User picks one or mixes elements before guidelines build. **Hard stop until user picks.** +3. **Build the full brand guidelines PDF** — render the 14–16-page guidelines PDF for the chosen board (page count depends on whether the brand is digital and whether imagery is single-medium or hybrid). Includes: cover, strategy, foundation, logo, logo don'ts, color, typography, voice, photography, visual world, icons (conditional), touchpoints, application, digital/social, do & don't. **Hard stop until user explicitly approves the guidelines.** +4. **Export the brand kit** — after user confirms the guidelines PDF, bundle a zip with: `brand.md` (machine-readable spec), `brand-guidelines.pdf` (the visual deliverable), logo assets (symbol as transparent PNG at 8 sizes; wordmark + lockup as SVG/PNG with text-as-paths), conditional UI icon SVGs for digital brands, brand fonts (TTF), design tokens (CSS/JSON/Tailwind), and AI prompts (system prompt + copy + image starters). + +**Autonomous full exception:** when a non-interactive run supplies an explicit full request (`--full`, `mode: "full"`, or asks for full guidelines / full brand book) and `cost_ack=proceed`, the brief is the spec. The skill ships all three artifacts — brand boards, guidelines, and brand kit — without waiting at the board-pick or guidelines-approval gates. If the brief is not clear enough to pick a direction responsibly, it stops once with the missing decision. Non-interactive clear briefs without explicit full depth still use quick mode. + +## Install + +```bash +# Extract the zip to your user-level Claude Code skills directory: +unzip build-a-brand-skill.zip -d ~/.claude/skills/ + +# Confirm the folder lives at: +ls ~/.claude/skills/build-a-brand/ +# Should show: README.md SKILL.md references/ +``` + +The skill is now available in any Claude Code session. + +## Invoke + +The user can trigger this skill by saying any of: +- "build me a brand" +- "make me a brand" +- "design a brand identity" +- "brand guidelines for [X]" +- "i want a brand book" +- "create a brand from scratch" +- "brand for [idea]" +- "i want a brand that feels like [X] + [Y]" +- "rebrand my [thing]" +- "visual identity for [thing]" +- `/build-a-brand` + +## Folder structure + +``` +build-a-brand/ +├── README.md # this file +├── SKILL.md # main skill instructions (4-step workflow) +└── references/ + ├── brand-directions.md # how to structure positioning angles (WHO + WHY differentiation rule) + ├── brand-identity.md # logo pipeline + symbol output rules + concept lanes + ├── brand-guidelines.md # 14-16 page build mechanics, font rules, image rules, three-pass QA + └── brand-md-template.md # template for the Step 4 brand kit `brand.md` file +``` + +## Dependencies + +- **Image generation:** Skill defaults to `gpt-image-2` for all `generate_image` calls (logos, mood photos, textures). +- **PDF rendering:** Built for Chrome headless (`--print-to-pdf`) or WeasyPrint. +- **Python + PIL:** for image transparency keying, favicon-test renders, and lockup composition. +- **Fonts:** Pulled from Google Fonts as TTF for self-hosting. + +## Local vs Cloud + +- **Local by default:** font downloads, image cleanup/compression, favicon tests, HTML/PDF rendering, QA screenshots/crops, logo asset assembly, tokens/prompts, and final zip packaging. +- **Cloud only where needed:** `gpt-image-2` image generation and URL/source research when required by the brief. +- PDFs and zips are saved locally by default. Hosting/upload is only used when explicitly requested. + +## What the skill enforces + +Embedded in the reference files as non-negotiable rules (all auto-applied during build): + +### Brand strategy & options +- 3 boards must be genuinely different brands, not template recolors — diverge across at least 4 structural dimensions (density, saturation, layout, type energy, composition, photography mood, voice register, era specificity) +- Adjective audit before delivery — top-3 adjectives per board; if any 2 share 2+ adjectives, push apart +- Divergence ≠ subtraction — every board delivers the brief at 100%, never strip back to differentiate +- Era palettes are specific (Y2K = chrome/gel/holo/candy, NOT muted cottage cream; same for any named era) + +### Logo +- Symbol generated via gpt-image-2, shipped as high-res transparent PNG (NOT traced to SVG) +- Symbol style is a brand-personality choice — flat, dimensional, painted, photographic, hand-drawn — whatever fits +- Mandatory checks: conceptually linked to brand, unique, recognizable at 16×16 (favicon test via PIL), ≤3 dominant colors, no text in image, true alpha=0 transparency +- 3 symbols across 3 boards must differ in concept lane (mascot / product-feature / abstract / monogram / hybrid / container) +- Wordmark is always Google Font; in the brand kit it's converted to text-as-paths SVG so it renders without the font file +- Lockup measurements perfectly measured and permanently fixed across all color variants + +### Fonts +- No favorite fonts and no banned fonts — every font in Google Fonts is in the running. Diversity is enforced through process (brainstorm fresh every brand + cross-brand variety check), not gatekeeping +- Display fonts with built-in shadow/3D detail (BungeeShade, Honk, etc.) only at hero scale (40px+) and only on cream/black backgrounds + +### Photography +- Hero photography shows the product IN USE (for digital products = phone/device with the actual result, or person using it). Never a representational stand-in object (the "keychain test") +- Photography occupies distinct visual territories per direction; vary medium and subject scale across the 3 boards + +### Texture (for retro/era briefs) +- Textures must be AMBIENT (subtle grain, VHS noise, paper grain, grainy gradient) — not literal patterns (halftone dots, glitter flakes, scanline rows) +- Always generated via gpt-image-2 (never CSS gradients — those read as theme-applied) +- Applied full-board with mix-blend-mode + opacity 0.12–0.30 + +### Product clarity & layout +- Page 1 cover + Page 2 strategy must make the product unambiguous in the brand's voice (clarity through content, not robotic templates) +- Contrast gate — every text/background pair audited; pink-on-pink, lime-on-cream, dark-on-dark photos are auto-fail +- Complex fills (chrome / holographic / multi-stop gradients) only at hero scale (60px+); switch to solid + stroke at small scale +- `.content` element must have `overflow: hidden` + explicit max-height as a safety net against footer overlap + +### QA & approval gates +- Three-pass QA: render every page individually → thumbnail pass → mandatory crop-and-read (PIL crops into 800×800 regions, Read each crop file — glancing at the full PNG is NOT zoom-reading) +- Approval gates are HARD stops: + - Step 2 → Step 3: user must explicitly pick a board before guidelines build + - Step 3 → Step 4: user must explicitly approve the guidelines PDF before kit export + - Creative direction ("make it cuter") is feedback, not approval — explicit "yes / ship it / go" only +- In autonomous full mode, the explicit full request plus `cost_ack=proceed` is the approval source; the run records its assumptions and continues through all three artifacts instead of stopping at those gates. + +*User-level Claude Code skill at `~/.claude/skills/build-a-brand/`.* diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b3d6f584c53507388d2a57208e5c36dc9d892b22 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/SKILL.md @@ -0,0 +1,748 @@ +--- +name: build-a-brand +description: > + Use when the user asks for build a brand or a task matching the examples below. + Build a practical brand identity from any input — an idea, an existing website, a list of + reference brands, product photos, or "I want to rebrand X". Default to a fast quick-brand + path for founder-kit users, and offer the full 14-16-page guidelines as an opt-in upgrade. Use + when someone wants a brand identity but does NOT need a full commerce launch (no Shopify, + no product listings, no social posting). + Trigger phrases: "build me a brand", "make me a brand", "design a brand identity", "brand + guidelines for [X]", "i want a brand book", "create a brand from scratch", "brand for [idea]", + "i want a brand that feels like [X] + [Y]", "rebrand my [thing]", "visual identity for [thing]", + "build-a-brand". +argument-hint: [photos=] [refresh=] [--quick] [--full] [--config ] +required-capabilities: + - generate_image + - task_status + - identity_balance +--- + +# Build a Brand + +> Tools below are **Pika MCP** tools, named bare — call each under whatever prefix your session exposes for the Pika MCP. + +Take any input — an idea, a website, a list of reference brands, product photos, or an existing brand to refresh — and produce a usable brand identity. + +This is a standalone brand-building workflow focused on strategy, identity, design, and copy. The default output is a **quick brand deliverable** that can be finished in minutes. The full 14-16-page brand guidelines PDF is still available, but only when the user explicitly asks for full depth or chooses to go deeper after the quick pass. + +## Reference files + +Load these only when the relevant phase starts: +- `references/brand-directions.md` — strategy angle structure and differentiated positioning boards. +- `references/brand-identity.md` — logo pipeline, symbol rules, concept lanes, and board-copy budgets. +- `references/brand-guidelines.md` — full guidelines layout, render contract, page structure, and QA rules. +- `references/brand-md-template.md` — required machine-readable `brand.md` structure. + +## Execution Model — Local First, Cloud Only Where Needed + +This skill is local-first. Keep deterministic production work on the user's machine: +- **Local:** workspace setup, downloaded fonts, generated image files after download, image compression, transparent-background cleanup, 16x16 favicon tests, HTML/CSS page builds, PDF rendering, PNG/JPG QA screenshots, logo asset assembly, token/prompt files, and final zip packaging. +- **Cloud:** paid generation only (`gpt-image-2` for symbols, mood images, photography, illustration, and ambient textures) and URL/source research when the brief requires it. + +Do not use a cloud PDF renderer or upload PDFs by default. Save quick PDFs, board PDFs, guidelines PDFs, and brand-kit zips to `~/Desktop` on Mac, or the project working directory when Desktop is unavailable. Only upload/share via CDN if the user explicitly asks for a hosted file. + +**PDF asset hygiene:** never embed full-size gpt-image-2 PNGs directly in board or guidelines PDFs. This previously produced huge PDFs and `ASSET_FETCH_TIMEOUT` failures when renderers tried to fetch multi-MB CDN images. Download every generated image, down-raster/downsample it to the slot size, and save a local JPEG target of about 85-180KB before using it in render HTML. Keep transparent PNG only for logo/symbol source assets and favicon/logo export, not for photographic page imagery. **Never put a CSS `filter:`/`backdrop-filter:` (warm grade, sepia, saturate, brightness, blur) on a photo or `background-image` in the render HTML** — it forces Chromium to rasterize that element to a full-resolution *lossless* bitmap in the PDF, which cancels out the JPEG step above and re-bloats the file (a warm-graded mood-board page alone took a deck to 70 MB). Bake any color grade into the JPEG itself (in the gpt-image-2 prompt or when you `img.save(..., 'JPEG', ...)`); `drop-shadow()` on a transparent logo PNG is the only filter that's safe. + +## Cost transparency gate + +Before any paid MCP call, call `identity_balance({verbose: true})` once. Surface the current balance, recent burn rate, and remaining runway, then gate the selected depth with this exact message: + +> Estimated cost: about 100-300 credits (~$1-$3) for quick brand, or about 900-1,500 credits (~$9-$15) for full brand book. These ranges cover gpt-image-2 symbol / mood / touchpoint generation plus one targeted regeneration for failed image QA. Quick brand is usually below $5; full brand book exceeds $5, so Reply `proceed` to continue or `cancel` to stop. + +Do not call any paid MCP tool until the user replies `proceed`. If the user replies `cancel`, stop without generating. For non-interactive `--quick`, `--full`, or `--config` callers, require `cost_ack=proceed` in the config or invocation metadata; if it is absent, stop with the estimate instead of spending credits. + +## Depth Modes + +Choose the depth before any long-running generation or render work: + +1. **Quick brand (default)** — use for first-time founder-kit runs, `--quick`, creator tutorial flows, batch/subagent calls, or any user who asks for a brand without explicitly asking for a full brand book. Target: 8-12 minutes after usable input, excluding user reply time; no more than 4 generated images unless QA fails; one quick PDF render plus one QA rerender when needed. +2. **Full brand book (opt-in)** — use only when the user asks for "full", "brand book", "brand guidelines", "14-16-page", "15-page", `--full`, or when they approve the quick path's "go deeper" upgrade. Target: 25-45 minutes after choices are locked, excluding user reply time. + +The quick brand is not a partial or failed full guidelines deck. It is a deliberately smaller deliverable with its own completion criteria. If the selected mode is full, all full-guidelines completion gates still apply. + +## Mode Selection + +### Stage 0 — Intake (empty-args menu) + +If invoked with no input (no idea, no URL, no photos, no reference brands, and no relevant prior context in the conversation), print this menu verbatim as your full response and stop. Do not call any tool. Wait for the user's next message. + +> **What are we branding?** Paste any of: +> +> - **An idea / description** — e.g. "a streetwear label for cat people" +> - **A website URL** — e.g. "rebrand my existing site at example.com" +> - **Product photos** — drop them in the chat +> - **Reference brands** — e.g. "I want something that feels like Aesop + Patagonia" +> - **An existing brand to refresh** — name + what's working / what isn't +> +> I'll start with a quick brand by default. Say **full brand book** if you want the deeper 14-16-page guidelines path. + +If the user already dropped one of the above, skip the menu and proceed to the selected mode: Quick Step 1 for the default quick brand path, or Step 1 below when full brand book mode is selected. + +### Stage 0.5 — Quick brand and non-interactive fast lane + +Use quick brand mode when the caller passes `--quick`, omits an explicit full-depth request, or states they are running from CI, a subagent, a batch job, a tutorial recording, or any other non-interactive harness. + +Use full brand book mode only when the caller passes `--full`, sets `mode: "full"` in config, explicitly asks for full guidelines / brand book depth, or approves the post-quick "go deeper" upgrade. + +This section has precedence over the interactive ask/wait instructions below. +When quick mode applies, use the quick brand workflow below and do not fall +through to the multi-turn full-workflow intake unless a required input is truly +missing. + +- `--config ` points to a JSON file that pre-bakes intake answers: + `input`, `photos`, `reference_brands`, `audience`, `positioning`, `assets_to_keep`, + `references`, `mode`, `chosen_direction`, `chosen_identity`, and `export_kit`. +- `--quick` means quick brand mode. Use model judgment for all confirmation gates. + Ask only if the original input is missing entirely; otherwise infer reasonable + defaults, choose the strongest strategy direction and identity option, and + continue. +- `--full` means full brand book mode. Still use model judgment for confirmation + gates in non-interactive runs, but do not cut the required 14-16-page guidelines. +- For `--quick` or `--config`, do not stop for confirmation at the deliverable + preview, strategy-direction choice, identity-option choice, or brand-kit + export gate. Record the assumption inline, then proceed. +- If a required asset is unavailable and cannot be inferred from the input, + stop once with a single compact missing-fields list instead of starting a + multi-turn Q&A loop. +- In quick mode, deliver the quick brand package defined below; do not describe + it as a condensed full guidelines deck. +- In full mode, do not deliver a condensed or partial brand output just because + the caller is non-interactive or the run is short on wall-clock time. A + condensed 6-page deck is not an acceptable substitute for the required + 14-16-page guidelines. If the run is out of wall-clock budget, save a resumable + checkpoint with the pages/assets already completed and stop; do not mark the + workflow complete. + +**Autonomous full mode:** use this only when an explicit full-depth request is present (`--full`, `mode: "full"`, or the user asks for a full brand book / full guidelines) and the run already has `cost_ack=proceed`. In that case, the brief is the spec. Do not wait for the user to pick a board and do not wait for explicit user approval before kit export. Produce all three full deliverables in one run: + +1. `brand-boards.pdf` — generate all three boards and use model judgment to choose the strongest board or hybrid. +2. `brand-guidelines.pdf` — build the full 14-16-page guidelines from that chosen direction. +3. `brand-kit.zip` — export the complete kit after the guidelines pass QA. + +Record the assumptions and selected direction in `brand.md` and the final response. If the brief is ambiguous enough that the board choice would be arbitrary, stop once with the missing decision instead of pretending the run is autonomous. Non-interactive clear briefs without explicit full depth stay quick; never promote a batch/tutorial/founder-kit run to full solely because the brief is clear. + +## Quick Brand Workflow (Default) + +Use this workflow for quick brand mode. It is the founder-kit fast lane: fewer choices, fewer generated assets, and a complete starter brand that can feed downstream skills without burning a full first-run quota. + +### Quick Step 1 — One-pass intake + +If there is usable input, do not start a long questionnaire. State the assumptions you are using and ask at most 3 compact questions only when the answer would materially change the brand: + +- What does this sell or do? +- Who is it for? +- Should I preserve any existing name, logo, colors, fonts, photos, or references? + +For `--quick`, `--config`, CI, subagent, batch, or tutorial-recording flows, do not wait for these answers unless the original input is missing entirely. Infer reasonable defaults and record them in the output. + +### Quick Step 2 — Choose one strongest direction + +Do not present 2-3 directions or 3 identity options in quick mode. Pick one strongest strategy and identity with model judgment. The quick strategy must still include: + +- Brand name or kept name +- Tagline (8 words max) +- Audience segments: primary segment, secondary segment(s), and one anchor persona +- Positioning statement +- Assets being kept +- Reference brands / inspirations, if provided + +### Quick Step 3 — Build the starter identity + +Create one coherent identity system: + +- Logo concept: wordmark + standalone symbol/mark + lockup plan. For a new symbol, use `generate_image` with `provider="gpt-image-2"` and ship the approved symbol as transparent PNG sizes, not SVG. Wordmark and lockup assets may be SVG because the wordmark is converted from real font text to outlined paths. +- Palette: 4 core colors with roles and hex values. +- Typography: one characterful display font plus one practical body font, with Google Fonts URLs when available. +- Voice: 3 tone principles, 3 sample lines, and 5 forbidden words/phrases. +- Imagery direction: one short photo/illustration rule set plus no-text image prompt guardrails. +- Starter applications: social avatar/app icon, simple web hero direction, and one practical touchpoint appropriate to the brand type. + +Keep image generation capped: one symbol/mark image plus up to 3 mood or touchpoint images. Retry budget: each generated brand image asset gets at most 2 total generation attempts (initial attempt + one targeted regeneration). If QA fails, regenerate only the failed asset. After either cap is exhausted, stop and ask the user which failed asset or layout issue they want to relax instead of continuing to spend credits. + +### Quick Step 4 — Deliver the quick brand package + +The quick deliverable must be complete enough for a creator to use immediately: + +``` +[brand-name]-quick-brand/ +├── quick-brand.pdf # 3 pages: cover/strategy, identity system, starter applications +├── brand.md # compact machine-readable brand spec +├── README.md # how to use the quick brand and when to upgrade +├── logo/ # symbol, wordmark, and lockup assets that were produced +├── tokens/ +│ ├── tokens.css +│ ├── tokens.json +│ └── tailwind.config.snippet.js +└── prompts/ + ├── system-prompt.md + └── imagery.md +``` + +The 3-page `quick-brand.pdf` page structure: + +1. **Cover + Strategy** — brand name, tagline, positioning, audience segments, anchor persona, references, and hero visual. +2. **Identity System** — logo system, palette, typography, voice rules, and imagery rules. +3. **Starter Applications** — social avatar/app icon, web hero/social card direction, one real touchpoint or product-context image, plus 3 brand-specific dos and 3 don'ts. + +Render `quick-brand.pdf` locally with Chrome headless (or WeasyPrint when the HTML is written for it) and inspect PNG/JPG previews before delivery. Quick visual QA must catch clipped text, missing logo/symbol, unreadable type, baked-in text inside generated images, empty placeholders, and obvious layout collisions. If the quick package or zip cannot be produced, stop with a resumable checkpoint listing completed files, missing files, asset paths/URLs, and the exact blocker. + +After delivering quick brand, offer the full 14-16-page guidelines as a "go deeper" upgrade. Do not start the full workflow unless the user explicitly asks. + +## Full Brand Book Workflow (Opt-in) + +Use this workflow only for full brand book mode. + +### Step 1 — Read the Input + +Full brand book mode only. + +Inputs vary. **Before asking any questions, open with a brief agenda** so the user knows what's coming: + +``` +here's how this works — 4 steps: +1. **Read the input** — i ask a few questions, you answer, i play back what i'm hearing +2. **3 visual brand boards** — i build a 3-page PDF with three complete brand directions, each with its own colors, fonts, photography, voice samples, and logo concept. you pick one or mix elements. +3. **Build the guidelines** — full 14-16-page brand book PDF for the chosen board +4. **Export the brand kit** — once you're happy with the guidelines, i'll bundle a `brand.md` spec + logo assets (symbol PNG sizes, wordmark SVG/PNG, lockup SVG/PNG) + fonts + tokens + AI prompts as a zip you can use anywhere + +let's start. [questions follow] +``` + +Then ask 3-5 targeted questions in a single message. Adapt to the input type: + +**If they dropped an idea / description:** +- What does this brand sell or do? (product / service / app / community / something else) +- Who is this for — describe the 2-3 audience segments this brand should serve, plus one vivid anchor persona inside the primary segment +- Why does this exist? what's broken about the alternatives, or what feeling are you trying to deliver? +- Do you have a name in mind, or is naming part of what you want help with? + +**If they dropped a website / existing brand URL:** +- Are we refreshing this brand or rebuilding it from scratch? +- What's working about it today, and what isn't? +- Who's the current customer vs. who you wish were the customer? + +**If they dropped product photos:** +- Ask how the product is made, who has bought or used it, price point, current sales/channel context, and any direction they already have in mind. +- Keep the output scoped to guidelines and a brand kit, not a commerce launch. + +**If they dropped reference brands only ("I want a brand that feels like Aesop + Patagonia"):** +- What's the product, service, or thing this brand will be attached to? +- What about each reference brand specifically do you love? (the photography? the tone? the restraint?) +- Who buys this — describe the 2-3 audience segments this brand should serve, plus one vivid anchor persona inside the primary segment. +- Any constraints? (industry, regulation, location, price tier?) + +**Always also ask (regardless of input type):** +- Do you have any existing brand assets you want to keep or incorporate? (Logo, wordmark, symbol, name, colors, fonts, photography, packaging — anything you don't want to lose.) +- Any specific references, inspirations, or moodboards you'd want this to draw from? +- **Is this a digital product** (app, website, SaaS, web tool)? This determines whether the Icons page belongs in the full guidelines — for non-digital brands (products, services, restaurants, fashion, etc.) the Icons page is skipped. + +These two are essential — they prevent you from generating things the user already has, and they anchor the work in references the user actually likes. Always include them. + +Keep it to a single message. Aim for 5-7 questions total (input-specific + the 2 universal), conversational not clinical. Wait for answers before proceeding. + +**After answers**, analyze the input + answers together and read back: +- **Aesthetic territory**: what visual world does this live in? +- **Audience segments**: primary segment, secondary segment(s), and one vivid anchor persona inside the primary segment. Do not collapse the audience into one over-specific individual. +- **Positioning**: what's the wedge — what does this stand for that competitors don't? +- **Price tier / category fit**: where on the market shelf does this sit? +- **Story hook**: what's the emotional reason someone cares? +- **Assets being kept**: explicitly list what the user said they want to preserve (existing wordmark, name, colors, etc.) +- **References anchoring the work**: list the user-named inspirations. + +**Then preview the deliverable and invite specific guidance** — before moving to brand directions, show the user what'll be in the final guidelines so they can flag anything to add, change, or call out: + +``` +here's what i'll build into the brand guidelines (14-16 pages depending on your brand): + +1. Cover (brand name, tagline, hero mood) +2. Strategy & positioning (primary/secondary audience segments + anchor persona) +3. Brand foundation (mission, values, story) +4. Logo (wordmark + symbol + variants) +5. Logo don'ts +6. Color palette +7. Typography +8. Icons — UI icon system + library guidance, ONLY IF this is a digital product (app / web / SaaS). Skipped for non-digital brands. +9. Voice & tone +10. Imagery rules (photography and/or illustration, adapted to brand medium; splits to 2 pages if hybrid) +11. Visual world / lifestyle imagery +12. Touchpoints (real photos showing the brand in use) +13. Brand applications (mockups: business card, app icon, favicon, etc.) +14. Digital + social +15. Do & don't + +plus a brand kit zip at the end with: `brand.md` spec, logo assets (symbol PNG sizes, wordmark SVG/PNG, lockup SVG/PNG), brand fonts, design tokens (CSS / JSON / Tailwind), AI prompts (system prompt + task-specific starters), and the icon SVGs if applicable. + +anything you want to add, change, call out specifically, or want me to handle differently? if not, i'll move on to the 3 brand boards. +``` + +Wait for response. Incorporate any specific user guidance (add a page, swap something, special focus on a particular section, exclude something) before moving to Step 2. This catches scope mismatches early — much cheaper than discovering them after the PDF is built. + +### Step 2 — Generate 3 Visual Brand Boards (PDF) + +This step is the user's first visual touchpoint with the brand. No text-only "directions" precede it. The boards ARE the directions, made visible. Each board contains a complete visual identity at-a-glance so the user can see the difference, not just read it. + +Build a single 3-page PDF (one page per board, 1200×850 each) and save it to `~/Desktop/[brand-slug]-brand-boards.pdf`. Each board is a genuinely different brand direction — not template recolors. Differentiate on WHO the brand is for and WHY it exists, while making the visual system, layout, fonts, color logic, photography style, and voice feel distinct. + +**Each option must include:** +- **Wordmark** in the brand's display font — use the user's existing wordmark if they have one they like; propose a new one if they need a logo or don't like their current one. A new wordmark must have custom letter treatment: adjusted spacing, ligature, cut, terminal, case, underline, or other ownable detail. It is not just a Google Font typed in a color. +- **Symbol/mark** — a standalone graphic that lives without the wordmark. Use the user's existing symbol if they have one they like; propose a new one otherwise. Even if the user keeps their wordmark, propose a symbol if they don't have one — favicons and app icons need a non-typographic mark. For new symbols, generate a transparent PNG via `generate_image` with `provider="gpt-image-2"`. Ask for a clean isolated mark on transparent background, no baked-in letters, no watermark, no mockup, centered in a square. Do not trace the generated symbol to SVG; export PNG sizes from the approved master. Must work at 16×16 AND 512×512. +- **Seal / badge** — if the option uses a seal, stamp, badge, or monogram, it must be readable and ownable at small and medium sizes. It cannot be a generic circular font lockup, clip-art crest, or low-contrast decorative filler. +- Tagline (8 words max) +- Voice sample with visible "VOICE" label (one quoted sentence, 14 words max) +- Compact board story (~35 words max, min 2 sentences) +- Lifestyle world description with visible "WORLD" label (~22 words max, min 1 full sentence) +- Lifestyle mood image (generated via gpt-image-2) +- 4-color palette with hex + role labels +- Display + body type specimens with named fonts + +Brand board pages should look different enough that the user can tell which identity they are seeing before reading the labels. Don't use the same template recolored 3 times; each board's layout should embody the option's design philosophy. A magazine-cover option should look like a magazine cover (full-bleed photo, masthead-style); a soft consumer option should look like a homepage hero (rounded shapes, soft circles for swatches); an editorial option should look like a literary spread (huge italic centered, inset photo). See `references/brand-guidelines.md` "Brand Board Layout — Differentiate per Option" for examples. + +If you can't physically tell which brand you're looking at *without* reading the labels — regenerate within the visual-QA retry budget below. + +**Page size:** 1200×850px. Renderer: local Chrome headless preferred; WeasyPrint is allowed only when the HTML is written for it. Render board PDFs and QA previews locally, then copy the final board PDF to `~/Desktop`. + +**Board quality gate:** the 3-page preview must pass visual QA, not just render QA. + +Retry budget: each brand-board or guidelines PDF visual-QA loop gets at most 2 total render/repair attempts for the same option/deck (initial render + one repair rerender). After either cap is exhausted, stop and ask the user which failed asset or layout issue they want to relax; include the failing page/asset name, the QA reason, and the best preview URL so far. + +1. Inspect each PNG preview before sending the PDF. Fail ugly density, weak hierarchy, muddy one-note palette, unreadable small text, empty mockup/image slots, clipped text, and body copy or non-masthead text intersecting icons, swatches, seals, photos, phone mockups, or decorative rules. Also inspect the symbol at 16×16 and 512×512; if the small-size read is illegible, muddy, too generic, or collapses into noise, regenerate or simplify before delivery. Website/social/app mockups are optional on brand boards; do not add them unless they contain real content. If included, flat color rectangles count as empty placeholders unless the section is explicitly a palette specimen. +2. Read each board preview at full size. Fail low-contrast type, unreadable small text, text/photo collisions, missing content, weak hierarchy, and muddy one-note palettes. Masthead wordmark/tagline/issue metadata overlays on photos are allowed only when they use deliberate negative space or a contrast scrim and pass contrast QA as defined in `references/brand-guidelines.md` Rule 5. Body copy on images is still forbidden. +3. Fix every captured FAIL before delivery. If the board is technically valid but ugly, treat it as failed and simplify hierarchy, copy density, or decorative elements before rerendering. + +**Font rule:** fresh fonts per brand AND fonts must have character. Never default to Inter / Karla / Outfit / DM Sans / Lato — they have no point of view as a display face. Explore the full Google Fonts library. See `references/brand-guidelines.md` "Must Have Character — Don't Default to Safe Fonts" for high-character options by vibe. Download the chosen font files locally and use absolute `file://` `@font-face` declarations in rendered HTML. + +**Font fallback for non-Latin brand names:** every `font-family` chain in brand boards, quick PDFs, and full guidelines must include broad-script fallbacks. Use Chromium's per-glyph fallback so Latin stays in the chosen brand face while CJK, Arabic, Cyrillic, and other scripts resolve to Noto families instead of tofu boxes. Minimum chains: display/serif `BrandDisplay, "Noto Serif SC", "Noto Serif TC", "Noto Serif JP", "Noto Serif KR", "Noto Sans Arabic", serif`; body/sans `BrandBody, "Noto Sans SC", "Noto Sans TC", "Noto Sans JP", "Noto Sans KR", "Noto Sans Arabic", system-ui, sans-serif`. + +Do not build the full 14-16-page guidelines PDF until the user picks an option — that wastes time on rejected identities. Exception: in autonomous full mode, use model judgment to pick the strongest board or hybrid and continue without waiting. + +Present all 3 clearly. Ask the user to pick one, or mix elements from different options. + +### Step 3 — Build the Full Brand Guidelines PDF + +Once user confirms a board, build the 14-16-page brand guidelines PDF. In autonomous full mode, build from the model-selected board or hybrid recorded in the assumptions log. + +**Page count is conditional:** +- **14 pages** — non-digital brands (product, restaurant, fashion, service, etc.) with single-medium imagery. Icons page is skipped. +- **15 pages** — digital brands (app / web / SaaS) with single-medium imagery. Includes Icons page. +- **15 pages** — non-digital brands with hybrid imagery (photo + illustration). Imagery splits to 2 pages; Icons skipped. +- **16 pages** — digital brands with hybrid imagery. Both Icons and split-Imagery present. + +Renumber pages contiguously based on what's included. Do not leave page-number gaps. + +**Page structure (full list — apply conditionally per above):** + +1. **Cover** — Brand name, tagline, hero mood image. Full-bleed. +2. **Strategy & Positioning** — Direction name. Positioning statement (one punchy sentence). Target audience system: primary segment, secondary segment(s), and one vivid anchor persona inside the primary segment. Do not describe only one over-specific customer. 3-4 reference brands with "borrow this" notes. +3. **Brand Foundation** — Mission. Brand values (3-5). The "why this exists" story (2-3 paragraphs of real copy in brand voice — not a template). +4. **Logo** — Primary mark + all variants (horizontal, icon-only, reversed), usage rules (on dark / on light / on color), logo mark explanation, clear space rule. +5. **Logo Don'ts** — Explicit misuse rendered in CSS: never stretch, never rotate, never wrong background, never recolor, never use drop shadow. Show each violation visually with a ✗ label. +6. **Color** — All swatches with hex + RGB + CMYK, primary pairings, accessibility/contrast note, never-do combinations. Full-bleed color columns, not swatches floating on white. +7. **Typography** — Full hierarchy (H1 through caption with exact px sizes), display/accent/body fonts, usage rules per context, type on color backgrounds, minimum sizes. +8. **Icons** *(digital brands only — skip for product, fashion, restaurant, service brands)* — UI icon system: 8-12 essential icons (arrow-right, check, close, plus, settings, search, user, bell, menu, info, etc.) rendered in the brand's geometric style + stroke/corner/grid rules + library recommendation for icons beyond the set. See `references/brand-guidelines.md` "Icons Page — Structure & Rules" section. +9. **Voice & Tone** — Tone adjectives, copy examples by context (headline, body, button, error state, social caption), forbidden words/phrases. Show actual brand copy, not generic example copy. +10. **Imagery Rules** — adapts to the brand's medium. **Photography-led** → photography rules (subject/light/color/cast/texture/forbidden + 1 example photo). **Illustration-led** → illustration rules (style/color/line/character/composition/forbidden + 1 example illustration). **Hybrid** (both equally) → split into two pages, guidelines becomes 16 pages. See `references/brand-guidelines.md` "Imagery Rules Page — Adapts per Brand." +11. **Visual World** — Full-bleed 4-column grid of 4 images matching the brand's medium mix (all photos, all illustrations, or mixed). Cast must be racially diverse for any people-featuring images. +12. **Touchpoints — Real Photos** — A 2×2 grid of 4 REAL GENERATED PHOTOGRAPHS showing the brand in physical context. **Adapt to the brand type:** + - **Physical product brand**: hang tag on garment, woven label macro, kraft mailer with tissue, flat lay of product + packaging + - **Digital / app brand**: phone in hand showing the app, laptop on desk showing the site, sticker on water bottle, tote bag in a real scene + - **Service brand**: business card in hand, branded notebook on desk, signage on a building, swag in context + No CSS vector mockups on this page — without real generated photos the touchpoints look like a Figma exercise, not a brand. Real images prove the brand can survive contact with the physical world. +13. **Brand Applications — CSS Mockups** — CSS-rendered mockups of secondary applications, each labeled with specs: business card (with dimensions), social avatar (circle crop), sticker/app icon (rounded square), email signature, presentation cover slide. For product brands also include: hang tag spec, woven label spec, shopping bag spec. +14. **Digital / Social** — Website hero aesthetic (colors, fonts, layout feel), Instagram grid style (3×3 mockup with color palette + caption tone), story template (brand colors + logo placement), link-in-bio layout. +15. **Do & Don't** — 5 dos and 5 don'ts, brand-specific and actionable. Not generic ("do use the logo correctly") — brand-specific ("do leave a full em-dash of space around the wordmark in social posts; never crop our tagline mid-word"). + +Keep Page 2 (strategy) before Page 3 (foundation), and keep both before logo/color/type. Strategy frames every visual decision that follows. + +Include every page in the structure. If the brand has no packaging, adapt the touchpoints page to the brand type instead of skipping it; the guidelines should still show how the identity survives in real contexts. + +**Completion gate:** do not deliver a condensed or partial guidelines PDF. A +condensed 6-page deck, missing Visual World page, missing Touchpoints page, or +missing Brand Applications page is a failed checkpoint, not a final deliverable. +If time runs out, stop with a resumable checkpoint that lists completed pages, +missing pages, generated asset URLs, and the next render step. Do not present +the deck as done until all mandatory pages have rendered and passed QA. + +All build rules in `references/brand-guidelines.md` apply: local rendering rules, explicit 1200×850 page dimensions, absolute local asset/font paths, no load-bearing text on generated images, no duplicate generated images across deck, text contrast thresholds on dark backgrounds, and mandatory pre-send QA previews for every page. + +**Deliver as PDF.** Save to `~/Desktop/[brand-name]-brand-guidelines.pdf` and tell the user the local path. Do not upload or host the PDF unless the user explicitly asks for a hosted copy. If the user is not on a Mac, save to the project working directory and mention the path in your reply. + +### Step 4 — Export the Brand Kit (HARD GATE — only after user explicitly approves the guidelines) + +After delivering the 14-16-page guidelines PDF, **wait for explicit user approval** before exporting the brand kit. Don't auto-export — the kit codifies the final brand, so only build it once the brand is locked. Exception: in autonomous full mode, the single clear brief already authorizes the full deliverable set, so export `brand-kit.zip` after the guidelines pass QA. + +Then build a comprehensive brand kit zip that lets the user produce on-brand work anywhere — in Claude, GPT, Figma, with a designer, with a developer. + +**Kit structure:** + +``` +[brand-name]-brand-kit.zip +├── brand.md # comprehensive machine-readable spec +├── brand-guidelines.pdf # full 14-16-page guidelines PDF (the visual deliverable) +├── README.md # 1-page how-to-use guide +├── logo/ +│ ├── symbol/ # standalone mark — RASTER ONLY, no SVG (symbol is generated PNG, not traced) +│ │ ├── symbol-[color]-16.png +│ │ ├── symbol-[color]-32.png +│ │ ├── symbol-[color]-64.png +│ │ ├── symbol-[color]-128.png +│ │ ├── symbol-[color]-256.png +│ │ ├── symbol-[color]-512.png +│ │ ├── symbol-[color]-1024.png +│ │ └── symbol-[color]-2048.png +│ ├── wordmark/ # the brand name — vectorized via text-as-paths +│ │ ├── wordmark-[color].svg +│ │ └── wordmark-[color].png +│ └── lockup/ # symbol + wordmark together at locked measurements +│ ├── horizontal/ +│ │ ├── lockup-h-[color].svg +│ │ └── lockup-h-[color].png +│ └── stacked/ +│ ├── lockup-s-[color].svg +│ └── lockup-s-[color].png +├── icons/ # digital brands only — UI icons from the Icons page as SVGs +│ ├── arrow-right.svg +│ ├── check.svg +│ ├── close.svg +│ ├── plus.svg +│ ├── search.svg +│ ├── user.svg +│ ├── settings.svg +│ ├── bell.svg +│ ├── menu.svg +│ ├── info.svg +│ └── [+ any brand-specific icons] +├── fonts/ # actual TTF font files (OFL-licensed Google Fonts) +│ ├── [display-font]-Variable.ttf +│ ├── [body-font]-Variable.ttf +│ └── README.md # license + install instructions +├── tokens/ # design tokens for devs +│ ├── tokens.css # CSS custom properties — paste into :root +│ ├── tokens.json # same content in JSON — for AI tools / CI +│ └── tailwind.config.snippet.js # paste into tailwind.config.js extend block +└── prompts/ # AI prompts for downstream brand use + ├── system-prompt.md # paste at the top of a Claude/GPT thread for brand voice + ├── tweet.md # task-specific starter: write a tweet + ├── landing-hero.md # task-specific starter: landing page hero copy + ├── email.md # task-specific starter: marketing/transactional email + ├── error-message.md # task-specific starter: write a friendly error + ├── photography.md # task starter: generate brand-style photography (with cliché guardrails + brand-photography rules embedded) + └── illustration.md # task starter: generate brand-style illustration (only if the brand uses illustration as a medium) +``` + +**Color variants to export** (per logo): primary-on-light, primary-on-dark, neutral-on-light (ink), neutral-on-dark (cream), and one accent-on-color combination. Usually 4-5 color sets per logo type. + +**brand.md** — see `references/brand-md-template.md` for the full structure. It must include: +- Quick reference block (name, tagline, primary color, fonts, voice in one scannable section) +- Positioning + audience segments +- Mission, values, story +- Voice & tone (adjectives, copy examples by context, forbidden words) +- Colors (table with hex / RGB / CMYK / Pantone / role) +- Typography (display + body + Google Fonts URLs + full hierarchy) +- Logo (wordmark description + symbol description + lockup specs + file list with paths) +- Photography rules +- Visual world description +- Touchpoint specs +- Do & don't list +- Reference brands with "borrow this" notes +- How-to-use section telling downstream tools/people how to apply the spec + +**Logo asset pipeline:** +1. **Symbol assets** — the symbol is a generated raster mark, so export PNG only. Start from the approved 2048x2048 transparent master, verify true alpha, then generate `16/32/64/128/256/512/1024/2048` PNGs per needed color/background variant. Do **not** trace it to SVG and do **not** claim it is vector. +2. **Wordmark assets** — render the brand name as real font text, then convert the chosen font text to outlined paths for `wordmark-[color].svg`; also export a 1024-wide transparent PNG fallback. The wordmark is reproducible because it is typography, not an image-generation artifact. +3. **Lockup assets** — assemble the approved symbol PNG + outlined wordmark at the locked measurements. Export `lockup-[orientation]-[color].svg` with the PNG embedded inline and the wordmark as paths, plus a 1024-wide PNG fallback. Keep geometry identical across color variants. +4. **Optional print PDF** — only add PDFs if the user or printer specifically asks. A PDF may embed the raster symbol plus vector wordmark, but it is not a pure-vector logo file. +5. **Icon SVGs** — for digital brands only, write the icon set as standalone SVGs with `stroke="currentColor"`, `viewBox="0 0 24 24"`, and the brand's chosen stroke weight + corner style applied consistently. See `references/brand-guidelines.md` "Icons Page — Structure & Rules" for which icons to include. +6. **Design tokens** — generate all three files from the brand spec: + - `tokens.css` — `:root` block with `--color-*`, `--font-*`, `--font-size-*`, `--line-height-*`, `--space-*`, `--radius-*`, `--shadow-*` custom properties + - `tokens.json` — same content as JSON object with sections: `color`, `font`, `fontSize`, `lineHeight`, `spacing`, `radius`, `shadow` + - `tailwind.config.snippet.js` — JavaScript snippet to paste inside `module.exports.theme.extend` covering colors, fontFamily, fontSize, borderRadius, boxShadow +7. **AI prompts** — generate each prompt file with brand specifics interpolated: + - `system-prompt.md` — a system prompt to paste at the top of any Claude/GPT thread. Includes: brand voice adjectives, forbidden words, copy rules, photography direction, color/font specs, sample voice examples. End with "Always apply this brand voice unless explicitly instructed otherwise." + - `tweet.md` — task starter: max 280 chars, voice constraints, sample target tweets, then "Task: [USER FILLS IN]" + - `landing-hero.md` — task starter: hero copy structure (headline + subheadline + CTA), brand voice rules, examples from the guidelines + - `email.md` — task starter: email tone, subject line guidance, body structure, sign-off conventions + - `error-message.md` — task starter: how the brand handles error/empty/loading states in voice (warm not robotic, specific not vague) + - **`photography.md`** — task starter for generating brand-style photography (gpt-image-2 etc.). Must include: master prompt template tailored to the brand's photo direction (subject, light, color grade, cast diversity, texture); explicit "what to AVOID in the prompt" list (studio strobes, stock terms, glass coworking spaces, "engineers at laptops," "professional," "premium," etc.); banned cliché concepts list (hourglasses, lightbulbs, handshakes, network nodes, glowing brains, etc.); subject substitutes for "person doing X"; quality requirements (butter accent, diversity, film grain, documentary); explicit no-text guardrail string; note about never naming real publications. + - **`illustration.md`** — only if the brand uses illustration as a medium. Task starter for generating brand-style illustrations. Master prompt template with strict palette + style rules (flat vector / line art / etc), banned elements (gradients, drop shadows, 3D, photographic textures), when to use illustration vs photography. Skip this file entirely if the brand has no illustration in its visual world. +8. **Brand fonts** — local export step. Download the actual font files from Google Fonts (or wherever the brand fonts live) and include in `fonts/`: + - Variable font files when available: `[FontName]-Variable.ttf` (single file, supports all weights) + - Or static weights at the levels the brand uses + - Use local TTFs in local render HTML via absolute `file://` paths + - Add a `fonts/README.md` noting the license (OFL is common, allows redistribution) + Google Fonts URL for online installation +9. **Brand guidelines PDF** — copy the 14-16-page guidelines PDF produced in Step 3 into the kit as `brand-guidelines.pdf`. The kit is incomplete without it. +10. **README.md** — 1-page guide telling the user: what's in the kit, how to use brand.md with AI tools, which logo file for which context, where to install fonts (local TTFs or Google Fonts URLs), how to use the photography/illustration prompts. +11. **Zip everything**: `zip -r [brand]-brand-kit.zip brand.md brand-guidelines.pdf README.md logo/ icons/ fonts/ tokens/ prompts/` + +**Brand-kit completion gate:** when the user confirms export, or when +`export_kit` is set in `--config`, the brand kit zip is a required deliverable. +Do not mark the brand kit complete until the zip exists and contains +`brand.md`, `brand-guidelines.pdf`, README, logo assets, icons, fonts, tokens, +and prompts. If any required file cannot be produced, stop with a resumable +checkpoint and list the missing files instead of shipping a partial zip. + +**README.md** — 1-page guide telling the user: +- What's in the kit +- How to use `brand.md` with AI tools (paste into Claude/GPT to generate on-brand work) +- Which logo file to use for which context (web favicon → symbol PNG; print collateral → PDF; web header → wordmark SVG; etc.) +- Font installation links (Google Fonts URLs plus local TTF filenames) + +**Delivery:** +- Save zip to `~/Desktop/[brand-name]-brand-kit.zip` for local Mac users. +- If the environment cannot download fonts or write a local zip, do not ship a + partial kit. Stop with a resumable blocked checkpoint that lists the + completed artifacts (local PDF path, `brand.md`, tokens, logo assets), the missing + files, and the exact filesystem/network blocker. +- Host the completed zip only if the user explicitly asks. +- Tell the user what's in the completed zip and link to the `brand.md` so they can preview without unzipping. + +## Post-flight quality gate + +Before declaring success on either deliverable, render local preview images and perform a structured visual QA pass with a structured verdict: + +- Quick mode: inspect the PNG/JPG previews or contact sheet for `quick-brand.pdf` before delivering the quick brand package. +- Full mode: inspect the final page PNG/JPG previews or contact sheet used to approve the guidelines PDF before delivering the local PDF path. Do not run analyze_media on the final PDF as the primary QA path; page previews are the QA artifact because they expose page-level layout and avoid large-PDF rasterization failures. + +``` +Return JSON only: { + "verdict": "clean" | "degraded" | "catastrophic", + "observations": string[], + "quality_warning": string | null, + "re_roll_suggestion": string | null +} +Check that the brand name is spelled consistently, the `quick-brand.pdf` or guidelines PDF preview shows the required pages, low-contrast text is not present, the wordmark/symbol are not garbled, and there are no blank or duplicate-looking pages. +``` + +- If `verdict` is `clean`, return the quick brand package or local PDF path normally. +- If `verdict` is `degraded`, return the quick brand package or local PDF path plus the `quality_warning` so the user can review before publishing. +- If `verdict` is `catastrophic`, do not call the deck complete; surface the verdict and `re_roll_suggestion` instead of declaring success. + +## Key Principles + +- **The input is the brief.** Don't ask for lengthy intake forms. Read what's in front of you and ask 3-5 precise questions. +- **Be specific about customers without narrowing the brand to one person.** Vague audiences = weak brands, but one hyper-specific individual can make the output unusably narrow. Define audience segments first: a primary segment, 1-2 secondary segments, and one anchor persona that makes the primary segment feel concrete. +- **3 boards at the main full-mode choice point.** Step 2 always gives three visual brand boards, not text-only directions or template recolors. +- **Opinionated but collaborative.** Present your read confidently. They can push back. +- Generate actual copy — don't give templates with [BRACKETS]. Write real words in the brand voice. +- **All images must look real and crafted.** Generated lifestyle/touchpoint images need film grain, natural light, slight imperfections, editorial composition. Banned: perfect symmetry, gradient backgrounds, studio strobes, stock-photo energy, AI-smooth surfaces, floating objects on white. If it looks fake, use the image retry budget above; do not keep regenerating after the capped retry. +- **One deliverable set per selected depth.** Quick mode delivers a quick brand package. Interactive full mode delivers one brand guidelines PDF, with the optional brand kit only after the user confirms the guidelines. Autonomous full mode ships all three full artifacts: brand boards, guidelines, and brand kit. + +--- + +## Brand Quality Standards + +Every brand produced by this skill should meet the following standards. Generic output is a failure state because the deliverable is meant to guide real design decisions, not decorate a template. + +### The Anti-Generic Test + +Before delivering anything, ask: *Could this be a brand for literally anything else?* If yes — it's not done. + +Strong brand = specific product/service + clear audience model + specific point of view. Weak brand = vibes + aesthetic mood board + empty tagline. Never deliver the second. + +### Copy Standards + +**What good brand copy sounds like:** +- It makes a specific claim: "Heavy wool. Made to last a decade." / "Built for one quiet hour a day." +- It has a point of view: "Not trend-led. Not mass-made." +- It can speak concretely to a reader inside a segment: "The app you reach for before checking your phone." This is copy style, not audience strategy; do not collapse the brand's audience model to only that reader. +- It creates tension or contrast: "Handmade. Overused. On purpose." +- It trusts the reader: no over-explaining, no "perfect for any occasion", no "cozy vibes" + +**What bad brand copy sounds like:** +- "Crafted with love" / "Made with care" / "Designed with passion" +- "Perfect for any occasion" / "A timeless addition" +- "Quality you can feel" / "Designed to inspire" +- Generic taglines: "Where quality meets style" / "Wear your story" +- Hollow superlatives: "premium", "luxury", "elevated", "curated", "artisanal" +- Anything that could describe 500 other brands without changing a word + +**Tagline test:** A great tagline could only belong to this brand. "Handmade. Overused. On purpose." is WORN's. "Just do it." is Nike's. If your tagline could appear on any random Etsy shop or Squarespace site without anyone noticing — rewrite it. + +### Design Standards + +**What editorial brand design looks like:** +- Strong typographic hierarchy — one thing is clearly the most important +- Color used with conviction — large fields, not accent dots +- Photography bleeds to edges — no floating images with shadow drops +- Scale contrast — one element dominates, others recede +- Pages feel designed, not assembled +- Whitespace is intentional, not default padding + +**What generic brand design looks like:** +- Equal-sized boxes arranged in a grid +- Body copy the same size as everything else +- Centered everything +- White background with a few colored boxes +- Photos floating in white space with rounded corners +- Font specimens that say "Font Name Here" or "Sample Text" +- Color swatches that look like a paint store brochure + +**Layout rule:** If a page could have been made in Canva or PowerPoint in 10 minutes — it's not good enough. Every page should require design decisions only someone with taste would make. + +### Photography & Diversity Standards + +Generated image sets featuring people should show racial diversity. This avoids defaulting every brand world to the same narrow cast. +- Default to a mixed cast across all 4+ lifestyle images: include Black, Asian, Latina, South Asian, Middle Eastern, or mixed-race subjects +- Vary body types, not just skin tone +- If only one person is shown, make a deliberate choice about who that person is — don't default to white/light-skinned +- Diversity is not a checkbox. It's a design choice that makes the brand more resonant and more honest + +**Photography must feel found, not staged:** +- Real rooms with real lives in them (papers, plants, worn furniture) +- Imperfect light (window light, overcast, early morning) +- Film grain always — even a little +- Subjects not looking at camera unless it's a strong choice + +### Deck / Guidelines Design Standards + +- Typography must load. Download the actual font files and use absolute `file://` paths in local render HTML. Always verify loaded fonts before signing off on a render. If fonts fall back to system defaults — the deck is broken, not deliverable. +- See `references/brand-guidelines.md` for the full local render contract and QA rules. +- Every page must have a clear visual hierarchy — one thing to look at first. +- Full-bleed photography pages should feel like magazine spreads, not slideshow slides. +- Color palette pages: full-bleed color columns, not swatches floating on white. +- Logo page: logo dramatically large, with clear variants, not timid or small. +- Voice page: show actual brand copy, not generic example copy. +- Touchpoints page: must include generated photographs of actual touchpoints — never CSS boxes. + +Deliver the guidelines as one local PDF, not as individual page images. Save the PDF path and copy it into the brand-kit zip when exporting the kit. + +### The Taste Check + +Before delivering any brand output, ask yourself: +1. Would a 25-year-old with good taste want to buy from / use / work for this brand? +2. Does the copy sound like a real person wrote it? +3. Does the design look like a real designer made it? +4. Are the photos diverse and real-looking? +5. Is there a specific point of view — something this brand stands for that another brand doesn't? + +If any answer is "not sure" — improve it before delivering. Strong and specific beats safe and generic every time. + +--- + +## Load-bearing phrases + +These are the anchors that keep this skill from drifting into generic brand-book output: + +| Phrase | Where | Why load-bearing | +|---|---|---| +| `different business answer — not aesthetic variations` | Step 2 visual boards | Forces positioning variety before visual variety. | +| `fonts must have character` | Step 2 visual boards | Prevents safe-font defaults from making every brand feel interchangeable. | +| `no load-bearing text on generated images` | Guidelines build rules | Keeps brand claims editable and legible in deterministic HTML/PDF. | +| `film grain, natural light, slight imperfections` | Image quality standards | Pushes lifestyle/touchpoint images away from stock-photo smoothness. | +| `Name a specific ethnicity per prompt` | Diverse-cast recovery | Fixes the model tendency toward all-white casts more reliably than generic diversity language. | + +--- + +## Engine choice: gpt-image-2 (with caveats) + +Default to `gpt-image-2` at `quality: "medium"` for all brand imagery. Why: +- Best instruction-following for cast-diversity prompts (nano-banana-pro tends to drift toward a white default unless heavily prompted). +- Strongest no-text guardrail adherence — critical for touchpoint shots (hang tag / woven label / sticker) where any baked-in text would ruin the mockup. +- Native 3:4 / 4:3 / 9:16 ratios crop cleanly on sharp subjects without weird stretching. + +Avoid `nano-banana-pro` for this skill — it bakes magazine-cover-style text into product shots when prompts mention "editorial." 1K from gpt-image-2 is plenty for a 1200×850 PDF page; bump to gpt-image-2's 2K tier (or escalate to `seedream` for higher) only if a specific touchpoint genuinely needs print-tier resolution. (4K on gpt-image-2 is 16:9 / 9:16 only — this skill's 3:4 / 4:3 ratios route to `seedream` if 4K is required.) + +## Runtime expectations + +Tell the user the rough total up front — long stages without status updates feel broken. Always report times in PST when giving timestamps. + +### Quick brand target + +| Stage | Target time | Notes | +|---|---:|---| +| Intake + assumptions | 1-2 min | Skip multi-turn Q&A unless the original input is missing | +| One strategy + identity | 2-3 min | Pick the strongest direction; no 3-option detour | +| Symbol/mood/touchpoint assets | 3-5 min | Up to 4 generated images total unless QA fails | +| Quick PDF + kit files | 2-3 min | 3-page PDF, compact `brand.md`, tokens, prompts, available logo assets | +| Quick QA + delivery | 1-2 min | PNG preview inspection; rerender only if a blocking issue appears | + +Total quick target: 8-12 min after usable input, excluding user response time. + +### Full brand book timing manifest + +For every full run, maintain a timing manifest in working notes and include it in the final delivery or resumable checkpoint. Capture PST timestamps for: + +- Input received / mode selected +- Intake complete +- Visual boards drafted +- Brand board render started / completed +- User identity choice locked +- Image generation batch 1 started / completed +- Image generation batch 2 started / completed +- Full guidelines render started / completed +- Full-deck QA started / completed +- Brand kit export started / completed, if requested + +If a run takes around 2 hours again, do not guess where the time went. Use this manifest to name the actual slowest stage and carry that evidence into the next cut. + +### Full brand book target + +| Stage | Time | Notes | +|---|---|---| +| Stage 0 → Step 1 (Q&A loop) | 5–15 min | User-paced; questions in one message | +| Step 2 (3 visual brand boards PDF) | 6–10 min | Per-board symbol + one mood image + local Chrome render | +| Step 3 image gen (8 photos via gpt-image-2 in 2 parallel batches of 4) | 8–12 min | The longest stage; each batch ≈ 4–6 min | +| Step 3 page build (14-16 HTML pages + local render) | 2–5 min | Chrome headless preferred; WeasyPrint fallback | +| Step 4 brand kit zip | 3–5 min | Symbol PNG sizes + wordmark/lockup SVG+PNG + conditional icons + tokens + fonts + prompts | + +Total full target: ~25–45 min wall-clock excluding user response time. Recent field feedback saw ~2 hours end to end for a paid creator tutorial recording; treat that as the baseline symptom to beat, not as an acceptable target. + +--- + + +## Failure modes + +### Recovering from upstream 5xx on generate_image + +If any paid generation or render MCP call returns: +- `code: "provider_5xx"` AND `retry_class: "retry_after_backoff"` +- Or HTTP 502 / 503 / 504 from an upstream image provider + +Do this: +1. Wait 5 seconds. +2. Re-call the exact same MCP tool with the exact same arguments. Do not rewrite the prompt, swap fonts, change palette, change HTML, change provider, or regenerate inputs. +3. If the retry also fails with 5xx, abort and surface to the user: "Provider returned a transient upstream error twice. Try again in 1-2 minutes; this usually clears on its own." + +Do not retry more than once. This is a transient outage, not a brand-direction problem; changing the creative brief wastes credits and makes the retry harder to compare. + +### Recovering from upstream 4xx / moderation_blocked + +If `generate_image` with `provider="gpt-image-2"` returns an upstream 4xx or `moderation_blocked`: +1. Do NOT retry the same prompt; moderation and most 4xx validation failures are deterministic. +2. If the failed asset is a generated symbol or lifestyle image, try a fallback provider once only when the brief can survive it: `seedream` for high-resolution brand imagery, or an inline SVG mark for simple geometric symbols. +3. If the fallback provider also fails or would materially change the brand direction, surface to the user: "Image provider declined this brand-image prompt. Try a less recognizable reference, remove real publication/celebrity cues, or approve an SVG/simple-mark alternative." + +### Recovering from upstream 429 (rate limit) + +If any upstream returns HTTP 429 with a backoff hint: +1. Wait the hinted backoff, or 30 seconds if no hint is provided. +2. Re-call the exact same MCP tool with the exact same arguments. +3. Do not retry more than once. If it still returns 429, abort and surface the rate-limit message instead of spending more calls. + +### `capture_website` returning empty / page-not-loaded + +This skill normally builds from user answers and provided assets, but URL-sourced references or future intake helpers may call `capture_website`. If `capture_website` returns 200 but `action_bboxes` is empty or `recording_viewport` is 0x0: +1. Do NOT retry; the page failed to render in the capture environment. +2. Surface: "Could not capture . The page may be blocked / paywalled / require auth. Please provide screenshots, logos, or hosted assets instead." + +### Long-running `task_status` exceeding ceiling + +Each async MCP call returns either an inline result or `{task_id, status}` for polling. Use these ceilings before deciding a task is stuck: +- gpt-image-2 high quality: 3 min per call +- Seedream image generation: 3 min per call + +Use whichever is earlier: the provider's ceiling x 1.5 or any skill-specific hard polling cap. If `task_status` returns `status: "processing"` or `status: "queued"` past that earlier limit, call `task_cancel({task_id})` and surface: "Provider taking unusually long; aborting. Try again." + +| Symptom | Cause | Fix | +|---|---|---| +| Fonts render as Times / Arial in the PDF | `@font-face` points to a missing or relative local path | Download TTFs to the local workspace, declare them with absolute `file://` paths, and render a one-page local preview before the full PDF | +| Generated image has baked-in magazine title or watermark | Prompt mentioned "magazine cover," "Vogue," "TIME," "Bloomberg," or any real publication | Strip publication names from prompt; append the verbatim no-text guardrail; regenerate once within the image retry budget. Describe visual qualities, not publications | +| Touchpoint / lifestyle photo shows only forehead / hand-only crop | 9:16 portrait source got cropped to a landscape cell | Regen with `aspect_ratio: "4:3"` or `"16:9"` to match the cell aspect, OR change the layout to a portrait cell | +| Page overflows the 850px ceiling | Headline > 60px combined with > 3 body paragraphs on the same page | Cut content, drop headline to 48px, or split across two pages. Re-render and verify with a screenshot | +| Board technically fits but looks ugly | Too much decorative styling, tiny text, muddy one-note palette, empty mockups, or weak hierarchy | Rewrite board copy to fit the budgets in `brand-identity.md`, remove decorative microtype, increase body text to 18px+, add negative space/contrast, and rerun PNG + visual QA | +| Text overlaps icons/swatches/seals/mockups | Decorative or absolute-positioned elements share the same reading area as copy | Give text a clean reading column/card, move graphics behind non-text areas only, and rerender. Passing `scrollHeight` is not enough if a sibling graphic occludes text | +| Brand board pages feel like recolored templates | Same template reused with palette swaps | Rebuild from `references/brand-guidelines.md` "Brand Board Layout — Differentiate per Option" — each board's layout must physically embody its design philosophy | +| Multi-page merge fails | `pdfunite` or local merge tooling is missing | Use Chrome `--print-to-pdf` on one full HTML document, or fall back to Python `pypdf.PdfWriter().append()` | +| User picks a hybrid identity ("02's palette + 01's voice") | Skill assumes single-option pick | Build a hybrid spec brief before Step 3, confirm with user before rendering 14-16 pages | +| User asks for hosted PDF and upload fails | PDF upload paths often reject `application/pdf` | Keep the local PDF as canonical; if hosting is required, use a user-approved file host or deployment path | +| Lifestyle grid all-white-cast despite diverse-cast rule | gpt-image-2 defaults to lighter skin tone when ethnicity isn't named explicitly per prompt | Name a specific ethnicity per prompt (Black, mixed-race East-Asian-and-white, East Asian, Latina, South Asian, Middle Eastern) — vary across the 4 grid prompts | diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-directions.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-directions.md new file mode 100644 index 0000000000000000000000000000000000000000..1f1532cb02757a1500cad2c3d135cefe73858152 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-directions.md @@ -0,0 +1,45 @@ +# Brand Directions — Reference + +A brand direction is a strategic positioning angle. Each direction should be genuinely distinct — not just aesthetic variations but different answers to "why would someone buy this and what does it mean to them?" + +## The Most Important Rule: Differentiate on WHO and WHY, Not WHAT + +The most common mistake is presenting directions that are all variations of the same thing — "soft", "quality", "feminine" — just with slightly different words. That's differentiating on *what*, which leads to directions that blend together. + +Real differentiation comes from: +- **WHO the brand is built around** (the maker's personality vs. the product vs. the community) +- **WHY someone buys** (to feel something, to be part of something, to get access to something scarce) +- **What business mechanic drives it** (drops, personal brand, gifting, nostalgia, etc.) + +Ask yourself: could a savvy person immediately see these as three genuinely different businesses? If not, push further apart. + +## Examples of Genuinely Different Directions + +**The Insider** — built around the maker's taste and personality. Customers follow the person, not the product. Could be named after the founder. + +**The Heirloom** — leans into nostalgia and emotional weight. The pieces feel like they have history. Precious, slow, deeply feminine. + +**The Drop** — borrows scarcity mechanics from streetwear. Limited releases, miss it and it's gone. Creates urgency and a following around drop announcements. + +**The Gifting Brand** — positioned entirely around the act of giving. Not "wear this" but "give this to someone you love." + +**The Community** — the brand is a membership in a taste tribe. Customers don't just buy, they belong. + +## Structure for Presenting Directions + +``` +**[Direction Name]** — evocative, 2-4 words +Positioning: [What the brand stands for — one punchy sentence] +What this means: [1-2 sentences on the business model / customer relationship this creates] +Customer: [Specific and vivid — who they are, what they care about, why they buy] +Vibe: [3-4 descriptive words] +Example names: [2-3 name ideas] +``` + +## Tips + +- Lead with the direction that feels most true to the product AND the seller's personality +- Make the 3 options feel like genuinely different businesses, not aesthetic variations +- Name the direction evocatively — "The Heirloom" not "Option B - Nostalgic" +- Be confident and specific. Vague directions lead to weak brands. +- After user picks a direction, note: the identity options in Step 3 should all sit within that direction's world — don't drift back to generic diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-guidelines.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..3e89c21682723458751ba6fbde21f1af87d69592 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-guidelines.md @@ -0,0 +1,888 @@ +# Brand Guidelines — Build Guide + +In full brand book mode, the brand guidelines PDF is the primary visual deliverable of this skill. It is 14-16 pages depending on brand type, rendered locally with Chrome headless or WeasyPrint, and delivered as a local PDF path. Quick brand mode has its own 3-page deliverable in `SKILL.md`; do not treat that quick PDF as a condensed or partial version of these full guidelines. + +This guide is the technical playbook: page layouts, image generation, font rules, local render contract, QA checklist. All non-negotiable. + +## Execution Model — Local First + +Keep deterministic production local: +- **Local:** workspace setup, downloaded fonts, compressed image files, transparent-background cleanup, favicon tests, HTML/CSS builds, PDF rendering, preview screenshots, visual QA, logo asset assembly, and kit packaging. +- **Cloud:** `gpt-image-2` image generation for symbols, photography, illustration, and textures; URL/source research when the brief requires it. + +Do not upload PDFs by default. Save PDFs and zips to `~/Desktop` on Mac, or the project working directory if Desktop is unavailable. Only create a hosted/CDN copy when the user explicitly asks. + +## Page Structure (14-16 pages depending on brand) + +**Page count is conditional:** +- **14 pages** — non-digital brand (product, restaurant, fashion, service) with single-medium imagery. Icons page skipped. +- **15 pages** — digital brand (app/web/SaaS) with single-medium imagery. Icons page included. +- **15 pages** — non-digital brand with hybrid imagery. Imagery splits to 2 pages; Icons skipped. +- **16 pages** — digital brand with hybrid imagery. Both Icons + split-Imagery present. + +Renumber pages contiguously based on what's included. Do not leave gaps. + +1. **Cover** — Full-bleed brand-specific layout. Brand name + tagline + hero mood image. +2. **Strategy & Positioning** — Direction, positioning statement, audience segments (primary segment, secondary segment(s), and anchor persona), 3-4 reference brands with "borrow this" notes. +3. **Brand Foundation** — Mission, values (3-5), why this exists (story in brand voice). +4. **Logo** — Primary mark + variants (horizontal, icon-only, reversed), usage rules, clear space. +5. **Logo Don'ts** — Misuse rendered in CSS with ✗ labels. +6. **Color** — Swatches with hex+RGB+CMYK, full-bleed color columns (not floating swatches). +7. **Typography** — Full hierarchy with px sizes, display/body specimens, usage rules. +8. **Icons** *(digital brands only)* — 8-12 essential UI icons in brand's geometric style + stroke/corner/grid rules + library recommendation. Skip this page entirely for non-digital brands and renumber subsequent pages. +9. **Voice & Tone** — Adjectives + actual brand copy examples by context. +10. **Imagery Rules** — adapts to the brand's primary medium (see "Imagery Rules Page — Adapts per Brand" section below): + - Photography-led brand → Photography Rules (subject / light / cast / treatment / forbidden) + 1 example photo + - Illustration-led brand → Illustration Rules (style / color / line / character / composition / forbidden) + 1 example illustration + - Hybrid brand (both matter equally) → split into two pages, pushing the total to 16 pages +11. **Visual World** — Full-bleed 4-column grid of 4 images (photos and/or illustrations matching the brand's medium choice). +12. **Touchpoints — Real Photos** — 2×2 grid of generated photos showing the brand in physical/digital context. Real images, never CSS boxes. +13. **Brand Applications — CSS Mockups** — Business card, social avatar, sticker, hang tag, woven label, etc. CSS-rendered. Each labeled with specs. +14. **Digital / Social** — Web hero, IG grid (3×3), story template, link-in-bio. +15. **Do & Don't** — 5 dos + 5 don'ts. Brand-specific, actionable. + +--- + +## Step 0 — Workspace Setup + +Images and fonts live in a persistent workspace path. `/tmp` is wiped between sessions on many systems, so don't put assets there. + +```bash +WS="${BUILD_A_BRAND_WS:-$HOME/build-a-brand-workspace}" +mkdir -p "$WS/fonts" "$WS/images" +``` + +Use `$WS/images/lifestyle1.jpg` etc., and `file://$WS/images/lifestyle1.jpg` in HTML after resolving `$WS` to an absolute path. Build the final guidelines as a local HTML file or one generated HTML string; local paths are expected because rendering is local. + +--- + +## Step 1 — Generate Imagery (in parallel batches of 4) + +You need **a minimum of 10 generated images**: +- 1 hero mood image (for the cover) +- 1 example image (for the photography rules page) +- 4 lifestyle images (for the visual world grid) +- 4 touchpoints images (for the real photos page) — adapt to brand type + +That's 10 images. Run in parallel batches of 4 with `&` + `wait`. Never more than 4 at once (timeouts). + +Before generating or placing those images, write a short **crop plan** and **pre-generation slot plan** for the deck. This is required working context, not final user-facing copy: + +- **Crop plan**: for every generated image, name the destination page, slot aspect ratio, final pixel box, intended subject anchor (face/product/hands/object), expected `object-position`, and rounded frame risk. If rounded frame risk is high, use a softer radius, move the subject anchor lower/center, or regenerate for the actual slot ratio. +- **Pre-generation slot plan**: list every slot expected to show imagery, including destination page, slot aspect ratio, planned medium, and prompt intent. Do not invent asset URLs before generation. +- **Post-generation filled manifest / image slot manifest**: after image generation or upload, copy the final asset URLs/IDs into the same slot list and verify every planned slot is filled. The manifest must include the cover hero, imagery-rules example, visual-world grid, touchpoints grid, and the Digital / Social website hero, Instagram grid, and story template. Each required slot needs a real generated image or hosted image asset. Flat color rectangles count as empty unless the section is explicitly a palette specimen. +- The Visual World page must use real generated images that match the brand's + medium. CSS color blocks, gradients, caption-only placeholders, and empty + rectangles are not image assets. +- The Touchpoints page must use real generated photographs in believable + physical or digital context. CSS color blocks, flat vector mockups, and + captioned boxes are not substitutes for touchpoint photography. + +Download generated image outputs into `$WS/images`, then compress before using in PDFs: + +```python +from PIL import Image +img = Image.open(path) +img.thumbnail((1200, 1200), Image.LANCZOS) +img.save(path, 'JPEG', quality=68, optimize=True) +``` + +Target under 150KB per page image where practical. Keep page images reasonably sized, avoid duplicating the same source across pages, and use CSS `object-fit` / `object-position` explicitly. + +This is load-bearing for reliability: full-size gpt-image-2 PNGs are often 1.5-2.5MB each. Embedding them directly can inflate a guidelines PDF into tens of MB and trigger `ASSET_FETCH_TIMEOUT` while local/remote renderers fetch page images. For photographic page imagery, down-raster/downsample to the slot size and write JPEG files targeting about 85-180KB. Keep PNG only where transparency is required for logo/symbol assets. + +**Photography prompt template (lifestyle):** +``` +[Brand lifestyle direction — who, where, what they're doing, mood]. [Specific moment or activity]. [Environmental details — what's in the room, on the desk, in the background]. [Color temperature]. Film grain, natural light, slight imperfections, editorial composition. No studio strobes, no gradient backgrounds, no perfect symmetry. +``` + +**Touchpoint prompt template (physical brand):** +``` +[Type of touchpoint — hang tag / woven label / kraft mailer / business card / signage]. [Brand visual cues — logo style, color]. [Real-world context — on a garment, on a desk, in a hand]. [Surface, light, color temp]. Editorial photography, film grain, natural light. +``` + +**Touchpoint prompt template (digital brand):** +``` +[Type of touchpoint — phone screen / laptop / tote / sticker]. [Real-world context — in a hand, on a desk, on a water bottle, on a coffee shop table]. [Brand visual cues showing through]. Editorial photography, film grain, natural light. +``` + +**Diversity rule:** All lifestyle images with people must show a mixed cast across the 4-image grid: Black, Asian, Latina, South Asian, Middle Eastern, or mixed-race subjects. Vary body types. Never default to white/light-skinned subjects. + +--- + +## Image Generation — Hard Rules (Read Before Every Prompt) + +These are the failure modes that have burned us before. Apply EVERY prompt. + +### 0. Default provider: gpt-image-2 + +**Every `generate_image` call must pass `provider="gpt-image-2"` unless the user explicitly names a different model.** This is a global preference, not a per-skill rule. Don't default to `nano-banana-pro` (Gemini) — it has worse instruction-following for our brand work and bakes in text more aggressively. Use gpt-image-2 with `quality="medium"` for the default balance of speed and fidelity. + +### 1. Never let text bake into the image + +Every image model — gpt-image-2 included — WILL render text into generated images when you give them a reason to. Risk is highest when prompts mention "magazine cover," "editorial," "Bloomberg Businessweek," "Vogue," "TIME," "billboard," "poster," "book cover," any real publication name, or any framing that implies typography on the surface. + +**Every prompt must end with this guardrail (copy verbatim):** +``` +ABSOLUTELY NO TEXT of any kind in the image — no magazine titles, no logos, no watermarks, no captions, no typography, no brand names, no headers. Pure photograph only. No graphic design overlays whatsoever. +``` + +**Never name real publications or brands directly in a prompt** ("Bloomberg Businessweek cover," "looks like Vogue," "Anthropic launch film"). The model treats these as instructions to reproduce the publication's design — including its name. Instead, describe the *visual qualities* the brand evokes: "editorial close-up portrait with dramatic side light and quiet authority" rather than "Bloomberg Businessweek cover portrait." + +### 2. Photo composition must survive the crop you'll use + +Before writing the prompt, decide WHERE this photo will appear in the layout and what shape it will be cropped to. Generate a composition that survives that crop: + +- **Full-bleed landscape from 3:4 portrait source** → subject must be in the vertical center 60% of the source. The top and bottom 20% will be cropped off. +- **Arched / dome rounded frame (border-radius ≥ ½ of width)** → DON'T use this shape unless the subject is in the LOWER center of the source. The dome will eat the entire top including any head. Default to soft 24-60px corner radius instead. +- **Small landscape inset from 3:4 portrait source** → subject must be in the horizontal center 70%. Sides will crop. +- **Centered portrait subject** → safest. Most layouts can preserve a centered head-and-shoulders composition. + +Specify the subject's position in the prompt explicitly: "subject centered in frame, face occupying middle 50% of the image vertically." + +### 3. Logos: generate a high-res symbol via gpt-image-2, ship as transparent PNG (no tracing) + +Hand-coded SVG symbols often look amateur. But also: don't trace a generated symbol to SVG. Keep the symbol as a high-resolution transparent PNG. Only the wordmark gets vectorized in the brand kit. + +1. Generate the symbol via `generate_image` with `provider="gpt-image-2"`, `quality="high"` when final, 1:1 aspect ratio, 1024x1024 minimum. The symbol can be flat, dimensional, painted, photographic, gradient-rich, chrome, holographic, or hand-drawn when that style fits the brand. +2. Add the no-text guardrail: "absolutely no text, no letters, no typography, no words, no characters anywhere in the image." +3. The generated symbol must be conceptually linked to the brand, unique, recognizable at 16x16, no more than 3 dominant colors, high res for the shipped version, text-free, and true transparent background. If it fails any of these, regenerate. +4. Save as transparent PNG, verified with PIL. If gpt-image-2 paints near-white pixels in the "transparent" area, key them out or regenerate. +5. The wordmark is always real text in a Google Font or commercial font, never baked into a generated image. Convert the wordmark to text-as-paths SVG only when packaging the brand kit. +6. Lockup composition is measured and fixed: symbol size, wordmark size, gap, and alignment do not drift across color variants. + +### 4. Verify by screenshot BEFORE delivering + +After rendering ANY PDF or board, screenshot every page and read every screenshot. The QA checklist at the bottom of this doc is mandatory. Never deliver based on assumption that the layout worked. Specifically check: + +- Are subjects visible (not cropped to forehead, hand-only, etc.)? +- Did baked-in text from the image generator appear anywhere? +- Are rounded shapes / arches cutting off content they shouldn't? +- Did `object-position` show the right portion of the image? + +If anything looks wrong, fix it before delivering. Never ask the user to spot problems the agent should have caught. + +--- + +## Step 2 — Choose Fonts (Based on Brand Vibe) + +**Fonts are NOT hardcoded.** Select fonts that match the identity built in Step 3 of the main skill. If the fonts could work for a competitor, pick different ones. + +Before selecting final type, make a **font shortlist** for the identity: +- Include at least 2 display families and at least 2 body/accent candidates that fit the specific brand vibe. +- Do not reuse the same display/body pair from the last 3 brand briefs unless the user explicitly asks for that exact pairing. +- Pick the pair for this brief from the shortlist and state why it fits the brand's category, audience segments, and visual world. + +### Must Have Character — Don't Default to Safe Fonts + +If the brand's display font could appear on any random SaaS site without anyone noticing, it's wrong. Push for fonts with recognizable personality. + +**Avoid as display defaults:** Inter, DM Sans, Lato, Karla, Manrope, Outfit, Roboto, Open Sans, Source Sans, Helvetica, Arial. These can be fine as utility body fonts but have no point of view as a display face — they make every brand feel the same. + +**Explore the full Google Fonts library with intentionality.** High-character options by vibe: + +- **Editorial / archival / literary** → Fraunces (variable serif, sloped descenders), Instrument Serif (literary italic), Newsreader (newspaper character), Spectral, Cardo, Crimson Pro, Bodoni Moda (high contrast modern), EB Garamond +- **Magazine / cover energy / bold display** → Bricolage Grotesque (chunky variable), Big Shoulders Display, Familjen Grotesk, Karantina, Anton (when condensed is core), Funnel Display +- **Friendly / soft / consumer-feeling** → Funnel Display, Funnel Sans, Hanken Grotesk, Schibsted Grotesk, Geist, Hahmlet +- **Tech / mono / digital-native** → Reddit Mono, Geist Mono, JetBrains Mono, IBM Plex Mono, DM Mono, Space Mono, Fragment Mono +- **Playful / loud / personality-forward** → Honk (chubby 3D), Tilt Warp, Tilt Neon, Bagel Fat One, Caveat (handwritten) +- **Quiet / minimal-with-soul** → Public Sans, Hahmlet, Newsreader (light weights), Spectral (light weights) + +**Pairing rules:** +- Display font must have character. Body font can be quieter but should still feel intentional. +- Never pair two characterless fonts (Inter + DM Sans = no point of view). +- Display + body should feel related but distinct. +- Test: if you swapped this brand's display font with another brand's display font from your last 3 projects, would anyone notice? If no — pick a more characterful one. + +### Decision Framework + +**Headline font feeling:** +- Striking / loud / high-energy → bold condensed (Bebas Neue, Druk, Anton, Oswald, Archivo Black) +- Precious / archival / collected → elegant serif (Cormorant Garamond, Playfair Display, EB Garamond) +- Tech / app / digital-native → geometric sans (Space Grotesk, DM Mono, Syne, Monument Grotesk) +- Handmade / artisan / craft → warm serif (Libre Baskerville, Lora, Bitter) +- Clean / editorial / grown-up minimal → geometric humanist (Jost, Raleway, Josefin Sans) +- Playful / cute / youth → friendly rounded (Nunito, Poppins, Quicksand) + +**Body font must contrast with headline:** +- Serif headline → clean sans body (Lato Light, DM Sans, Inter) +- Bold condensed headline → lightweight sans (DM Sans, Lato Light, Inter) +- Geometric sans headline → same family lighter weight, or Inter + +### Download fonts to the local workspace + +Store font files under the same local workspace as the HTML and images, then reference them with absolute `file://` URLs. Prefer direct WOFF2 font-file downloads from `fonts.gstatic.com` or other direct font-file sources. + +```bash +WS="${BUILD_A_BRAND_WS:-$HOME/build-a-brand-workspace}" +mkdir -p "$WS/fonts" +curl -sL "https://fonts.gstatic.com/s/playfairdisplay/v40/nuFiD-vYSZviVYUb_rj3ij__anPXDTzYgA.woff2" -o "$WS/fonts/PlayfairDisplay.woff2" +curl -sL "https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1ZL7.woff2" -o "$WS/fonts/Inter.woff2" +``` + +Use `@font-face` with local file sources: + +```css +@font-face { + font-family: 'BrandDisplay'; + src: url('file:///Users/name/build-a-brand-workspace/fonts/PlayfairDisplay.woff2') format('woff2'); + font-weight: 400; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: 'BrandBody'; + src: url('file:///Users/name/build-a-brand-workspace/fonts/Inter.woff2') format('woff2'); + font-weight: 400; + font-style: normal; + font-display: swap; +} +``` + +**Font loading rules:** + +- Use absolute `file://` URLs in rendered HTML so local Chrome and WeasyPrint resolve the same files. +- Keep one local `fonts/` folder per project and copy every chosen font into it before rendering. +- Do not use `@import` for render-critical type; explicit `@font-face` rules are easier to QA and reproduce. +- Do not put a Google Fonts CSS URL such as `https://fonts.googleapis.com/css2?...` inside `@font-face src`; that URL returns CSS, not a font file. + +Render one page locally before the full PDF; if the type falls back to Times/Arial, fix the font source before continuing. + +### Font fallback for non-Latin brand names + +When rendering CSS for a brand board, quick PDF, or full guidelines deck, every `font-family` chain must include CJK and broad-script fallbacks. Chromium applies per-glyph fallback: Latin characters use the first available brand font, while CJK, Arabic, Cyrillic, and other missing glyphs resolve to the matching Noto family instead of tofu boxes. + +```css +/* Body / sans-serif chains */ +font-family: 'BrandBody', 'Inter', 'Noto Sans SC', 'Noto Sans TC', 'Noto Sans JP', 'Noto Sans KR', 'Noto Sans Arabic', system-ui, sans-serif; + +/* Display / serif chains */ +font-family: 'BrandDisplay', 'Bodoni Moda', 'Fraunces', 'Noto Serif SC', 'Noto Serif TC', 'Noto Serif JP', 'Noto Serif KR', 'Noto Sans Arabic', serif; +``` + +Load the Noto fallback faces with the same local strategy as brand fonts: download the relevant Noto files into `$WS/fonts`, then reference them through absolute `file://` URLs in `@font-face`. This fallback belongs in shared CSS for every page, not only the page containing the brand name. + +--- + +## Step 3 — Build HTML + +Write fresh HTML for the chosen identity. Never copy old deck HTML — always write fresh. + +**Critical CSS (required in every guidelines doc):** +```css +@page { size: 1200px 850px; margin: 0; } +.page { width: 1200px; height: 850px; overflow: hidden; page-break-after: always; display: block; } +``` + +### Local Render Rules — Read Before Writing a Single Div + +Local Chrome headless and WeasyPrint support flexbox, grid, absolute positioning, and CSS transforms well enough for these fixed-format pages. Keep page geometry explicit so QA is deterministic: + +#### Rule 1: Every page is a fixed canvas +- Use `@page { size: 1200px 850px; margin: 0; }`. +- Every `.page` must be `width:1200px;height:850px;overflow:hidden;page-break-after:always;position:relative;`. +- Use explicit pixel dimensions for key regions. Flex/grid are fine, but don't let page height be content-driven. +- Avoid viewport units (`vh`, `vw`) inside pages; they couple layout to the browser window rather than the page box. + +#### Rule 2: Use local assets deliberately +- Use absolute `file://` URLs for local fonts, generated images, user-provided source images, and assembled logo assets. +- Download generated image outputs into `$WS/images` before placing them in HTML. +- Small SVGs and font subsets can be inlined as `data:` URIs when it improves portability. +- Avoid hotlinking external HTTPS assets in final render HTML; download, compress, and reference the local copy. + +#### Rule 3: Use layout systems intentionally +- CSS grid is preferred for swatches, icon sets, mockup grids, type specimens, and contact sheets. +- Flexbox is fine for compact rows and centered stacks. +- Use absolute positioning for full-bleed editorial pages where overlap and crop are intentional. +- Give repeated tiles fixed dimensions so badges, labels, and icons cannot resize the layout. + +#### Rule 4: Text containers must wrap naturally +- Text cards, sidebars, and copy columns must have an explicit readable width. Reserve at least `320px` for body copy via `min-width:320px`, grid `minmax(320px, ...)`, or an equivalent fixed px floor. You may use `ch` only as a `max-width` line-length cap, never as the width floor. Never let a right-column card collapse until each line becomes one word. +- In flex/grid layouts, set `min-width:0` on text children so copy wraps inside its assigned track, and separately give the track/card a real width floor (`width`, `flex-basis`, or grid track minmax). +- Body-copy containers should include `box-sizing:border-box; overflow-wrap:break-word; word-break:normal; hyphens:none;`. +- Never use `word-break:break-all`, `overflow-wrap:anywhere`, or a narrow absolute-positioned card squeezed by an illustration/phone mockup for readable prose. +- If an illustration, phone, seal, swatch, or decorative element sits near a copy card, the card owns a clean rectangle above it in z-order and geometry. Do not depend on the visual QA pass to catch preventable overlap. + +#### Rule 5: Image rules +- Always explicit px dimensions: `style="width:300px;height:400px;object-fit:cover;display:block;"` +- Avoid percentage heights unless the parent has an explicit pixel height +- Never `opacity:` on any `` — images always at full opacity +- Never body text/labels/rules on images — put captions in an adjacent column or block. Masthead brand boards may overlay wordmark/tagline/issue metadata on a full-bleed photo only when the type sits on intentional negative space or a contrast scrim and passes contrast QA. +- Contrast QA for masthead overlays means the masthead text remains readable in the full-page PNG preview. If uncertain, render a local crop or full-page screenshot and judge the masthead wordmark/tagline/issue metadata at actual preview size before continuing. +- Never duplicate an image src across the deck — each file appears at most once +- Use `object-position` deliberately and verify the crop in PNG previews + +#### Rule 6: Text contrast thresholds on dark backgrounds +On graphite (#2E2E2E) or any dark background: +- Body text minimum: `rgba(248,243,236,.7)` +- Sub-descriptions minimum: `rgba(248,243,236,.55)` +- Decorative / ghost text minimum: `rgba(248,243,236,.45)` — below this, remove the element entirely +- `.3` opacity on dark = invisible. Never use for any visible text. + +#### Rule 7: Page overflow prevention +- Every page is 850px tall. All content MUST fit. +- If a page has a headline >60px AND more than 3 body paragraphs, it will overflow. Cut or split. +- Never more than ~220 words of body text on a single page. +- Padding: 64px top/bottom max on content pages. Don't stack multiple padded sections. + +#### Rule 8: Good-looking layout prevention +- Passing render QA is not enough. A page can have no clipped text and still be bad if it looks crowded, muddy, or amateur. +- Body copy, labels, and load-bearing informational text must never collide with swatches, icons, photos, decorative rules, grain, seals, or background imagery. If an element sits on top of body copy, the page fails even when the text technically remains inside its box. Masthead boards may overlay wordmark/tagline/issue metadata on a full-bleed photo only when the type sits on intentional negative space or a contrast scrim and passes contrast QA; body copy still gets its own clean reading area. +- Body copy on brand boards and guidelines must be readable at the full-page screenshot size. Use 18px minimum for body copy, 14px minimum for labels, and 10px minimum only for decorative metadata that is not load-bearing. +- Decorative microtype is optional. If small labels, faux archival notations, issue numbers, or specimen marks make the page noisy, remove them before reducing the real content. +- Keep one primary visual focal point per page while required board content stays secondary and grouped. If the viewer's eye has to choose between a huge wordmark, a dense paragraph block, six swatches, a seal, a photo, and a pull quote at once, simplify hierarchy and grouping; do not drop required content. +- Do not use a one-note dark brown/green/slate page unless the brief specifically demands it. Add contrast through scale, image light, accent color, or negative space; do not let the whole page collapse into one muddy value range. +- Empty placeholders are a hard fail. Website/social/app mockups are optional on brand boards; do not add them unless they contain real content. If a website hero, grid, story template, image slot, or app mockup is included, either render the real content or remove/redesign the slot. Flat color rectangles in a Digital/Social mockup count as empty placeholders unless the section is explicitly a palette specimen. + +#### Rule 9: Vertical centering critical gotcha +When using `
` to center, the inner content div **must NOT have explicit height**. If the inner div has `height:782px` (same as td), the td has nothing to center → appears top-aligned. Set `height` only on the outer ``, never on the inner content div. + +### Reusable Templates + +**Two-column content page:** +```html +
+ + + + + + +
01 — Section Labeloptional quote
+ + + + + + +
+ + + +
+ +
+
+
+``` + +**Full-bleed lifestyle grid (page 11):** +```html + + + + + + + +
+``` + +This grid is image-only. If captions or labels are needed, put them in adjacent Rule-4 text containers; do not overlay body copy on the photos. + +**Touchpoints 2×2 grid (page 12):** +```html + + + + + + + + + + + + +
+``` + +This touchpoints grid is image-only. If a label is required, use a separate caption strip or adjacent Rule-4 text container; do not place readable prose inside the image cells. + +### Page-Specific Notes + +**Page 4 — Logo applications:** Left half (~420px) = large logo mark centered with generous whitespace. Right half (~780px) = 5 CSS mockups in a 2-row grid (3 top, 2 bottom), `gap:32px`, each cell min 160×180px. Don't flex-wrap — use proper grid. + +**Page 5 — Logo Don'ts:** 5 violation tiles in a row, each with the wrong-usage logo + a small ✗ label + a one-line caption explaining the violation. + +**Page 10 — Photography Rules:** Left 2/3 (~780px) = 3 example images in a grid with explicit pixel dimensions. Right 1/3 (~420px) = sidebar of 4-5 specific rules (surface, light, propping, editing, mood). Small label caps + body text. + +**Page 12 — Touchpoints:** The page **must show real generated photos** of the brand in context. Never substitute CSS vector mockups. Generate the 4 images before building HTML. For physical product brands: hang tag, woven label macro, kraft mailer, flat lay. For digital brands: phone in hand showing app, laptop on desk showing site, sticker on water bottle, tote bag in a real scene. For service brands: business card in hand, signage, branded notebook, swag. + +**Page 13 — Brand Applications (CSS mockups):** Each mockup is a small physical-object representation rendered in CSS. Use fixed dimensions and verify the visual center in PNG previews. + +| Shape | Dimensions | Suggested centering | +|---|---|---| +| Hang tag | 120×168px | CSS grid/flex center, then visual QA | +| Woven label | 200×80px | CSS grid/flex center, then visual QA | +| Avatar circle | 100×100px | CSS grid/flex center, then visual QA | +| Sticker rounded square | 100×100px | CSS grid/flex center, then visual QA | +| Business card | 200×120px | CSS grid/flex center, then visual QA | + +### Image hard constraints + +- **No opacity on images.** Never `opacity:` on any `` — full brightness always. +- **No body text on images.** Body copy, captions, labels, and rules never overlay images. Captions go in an adjacent column. Masthead brand boards may overlay the wordmark/tagline/issue metadata on a full-bleed photo only when the type sits on intentional negative space or a contrast scrim and passes contrast QA. +- **No gradient overlays on ordinary content images.** Do not use decorative gradient overlays on photos. Masthead covers may use one controlled linear scrim/gradient mask behind wordmark/tagline/issue metadata text to preserve contrast: strongest stop <= 50% opacity, one edge direction only, max scrim height <= 40% of image height, and no product/detail/focal subject hidden under the scrim. +- **No CSS `filter:` / `backdrop-filter:` on raster images (color grade, sepia, saturate, brightness, contrast, hue-rotate, blur).** A CSS filter on an `` or on a `background-image` element forces the renderer's Chromium to rasterize that element to a **full-resolution lossless bitmap** inside the PDF — which silently defeats the JPEG downsampling above and explodes file size (one warm-graded mood-board page took a deck to 70 MB, past the upload cap). Bake any "warm grade" / tone treatment into the JPEG itself at generation/export time (regenerate with the look described in the prompt, or grade once in PIL when you `img.save(..., 'JPEG', ...)`), so the page HTML references a pre-graded JPEG with no live filter. The mood-board / visual-world page is already pre-graded imagery — it needs no page-level filter. The only filter still allowed is `drop-shadow()` on a transparent-PNG logo/symbol, which does not raster a photo. +- **No duplicate images.** Each image file appears at most once across the deck. If you run out, replace with typographic or color design elements (large CG italic quote, big page number, color field) — never reuse. +- **Remove all price stickers / shelf labels / tags** from products before use. If source has a Goodwill sticker or similar, regenerate clean. +- **Header logo on every page uses the brand's actual logo font/style** — never a generic fallback. +- **Generated lifestyle images must match the brand's specific aesthetic** — not just "editorial." Define surface/light/color-temp/prop-types per brand before generating. A warm cozy apartment is wrong for a gritty brand; harsh concrete is wrong for a quiet-luxury brand. Regenerate if it doesn't match. + +--- + +## Step 4 — Render PDF Locally + +**Preferred: Chrome headless.** Chrome handles modern CSS, flexbox, grid, and `@font-face file://` font declarations reliably when run locally. Use it when available: + +```bash +CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" +WS="${BUILD_A_BRAND_WS:-$HOME/build-a-brand-workspace}" +"$CHROME" --headless --disable-gpu --no-sandbox --hide-scrollbars \ + --virtual-time-budget=8000 --no-pdf-header-footer \ + --print-to-pdf="$WS/guidelines.pdf" \ + "file://$WS/guidelines.html" +``` + +**Fallback: WeasyPrint.** Use this only when Chrome is unavailable or the HTML was written to the table-safe constraints: + +```python +import weasyprint, warnings, os +warnings.filterwarnings('ignore') +WS = os.environ.get('BUILD_A_BRAND_WS') or os.path.expanduser('~/build-a-brand-workspace') +pdf = weasyprint.HTML(filename=f'{WS}/guidelines.html', base_url=f'file://{WS}/').write_pdf() +open(f'{WS}/guidelines.pdf', 'wb').write(pdf) +``` + +Pick one engine and stick with it for the whole 14-16-page build. + +--- + +## Step 5 — Verify Every Page (Mandatory) + +Before delivery, render one full-page preview per page and verify against the QA checklist. JPG previews are fine for layout/contrast QA; PNG is required only for logo/symbol asset export. + +For PDF-to-preview QA, use PyMuPDF: + +```python +import fitz, os +WS = os.environ.get('BUILD_A_BRAND_WS') or os.path.expanduser('~/build-a-brand-workspace') +doc = fitz.open(f'{WS}/guidelines.pdf') +for i in range(len(doc)): + doc[i].get_pixmap(matrix=fitz.Matrix(1.8, 1.8)).save(f'{WS}/qa_p{i+1}.png') +print(f'{len(doc)} pages — now read each one') +``` + +### Pre-Send QA Checklist + +Read every screenshot. Verify every item. If any check fails, fix it. No exceptions. Never ask the user to spot problems the agent should have caught. + +**Cost rule — QA must scale with page count, not element count.** Read ONE full-page preview per page (14-16 reads). Do NOT crop-and-read every small element on every page by default. The full-page read is the default; targeted zoom is the exception, not the rule. + +**Full-deck visual QA:** every final guidelines page must receive a local full-page preview read before delivery. Record PASS or FAIL per page, fix every captured fail, and do not deliver the PDF until all included pages are clean or the user explicitly accepts a documented `degraded` quality warning. + +**Per-page QA (mandatory — one full-page read per page):** +1. **Full-page pass** — read the full-page PNG for each page and verify it against the checklist below (blank columns, missing content, wrong colors, font fallback, text/image collisions, clipped text, weak hierarchy). +2. **Target detail-level QA only where needed** — use local crops for flagged defects or the few highest-risk elements. Fix every captured FAIL. + +**Targeted zoom — only when triggered.** Crop and read an 800×800px region ONLY for: +- a specific element the full-page read flagged as suspect, OR +- the few genuinely highest-risk spots, when the page contains them: a single-character pill/badge marker, a favicon-size (≤32px) logo rendering, or a business-card layout. + +Do not zoom every element on every page. Zoom the flagged ones. A clean full-page read with no blocking defects is sufficient to clear a page. + +| Check | What to look for | +|---|---| +| Fonts loaded | Headlines render in the chosen font, not a system fallback (Times, Arial) | +| No blank columns | Every column has content — no white/solid blocks where text should be | +| No empty placeholders | Optional website heroes, grids, story templates, app mockups, image slots, and cards contain real content or are redesigned away. Flat color blocks in Digital/Social mockups count as empty unless they are explicitly palette specimens | +| No text/image collisions | Body copy, captions, labels, and rules do not sit on top of images. Masthead wordmark/tagline/issue metadata overlays are allowed only with deliberate negative space or a contrast scrim and must pass contrast QA | +| No text collisions | Text does not overlap or sit underneath icons, swatches, seals, decorative lines, photos, phone mockups, or other graphic elements | +| No clipped or occluded text | Text is not cut off by its own container, page edge, rounded shape, sibling graphic, or z-index layer | +| Board looks good, not just valid | Full-page read has one focal point, clear hierarchy, enough negative space, and no muddy one-note palette | +| Load-bearing copy is readable | Body copy is readable in the full-page PNG; do not hide key content in 10px decorative microtype | +| **No baked-in text in generated images** | **Open each generated image and look for ANY text — magazine titles, watermarks, brand names, captions, headers. If you see any, regenerate with stronger no-text guardrails.** | +| **Subjects survive their crop** | **For every generated image used in a layout: is the intended subject visible after the CSS crop? No forehead-only portraits, no hand-only kitchen scenes. If the subject got cut off by `object-fit:cover`, `object-position`, or a rounded/arched frame, fix the layout or regenerate the image.** | +| **Rounded shapes don't eat content** | **Any `border-radius` ≥ ½ the element width creates a dome that crops content underneath. If the photo's subject sits in the top portion of the source, a dome top will hide it. Soften the radius or reposition the subject.** | +| No duplicate images | Each image file used at most once across the deck | +| No opacity on images | No `opacity:` on any `` — images always full brightness | +| No CSS filters on photos | No `filter:`/`backdrop-filter:` (warm grade, sepia, saturate, brightness, blur) on any photo or `background-image` — it forces a full-res lossless raster into the PDF and bloats the file. Any grade is baked into the JPEG. `drop-shadow()` on a transparent logo PNG is the only exception | +| Logo shapes centered | Content visually centered in hang tags, circles, labels — not top-aligned | +| Text contrast | All text on dark (#2E2E2E) backgrounds at sufficient opacity | +| Decorative text legible | Ghost / watermark text at ≥ .45 opacity — if lower, remove entirely | +| Images load | No broken images — every img has explicit px width+height | +| Page count = 14-16, conditionally correct | Non-digital/single-medium = 14; digital/single-medium = 15; non-digital/hybrid = 15; digital/hybrid = 16; no blank extras | +| Touchpoints are real photos | Page 12 shows generated photographs, not CSS vector boxes | +| Diverse cast | Lifestyle grid (page 11) shows racial diversity across subjects | +| Icons consistent | Page 8 icons all use the same stroke weight + corner style + line caps | +| Imagery medium matches brand | Imagery Rules page (page 10) reflects the brand's medium (photo / illustration / hybrid) — don't ship Photography Rules for an illustration brand | +| No concept clichés | No hourglass-for-time / lightbulb-for-ideas / handshake-for-trust etc. — apply the three cheesiness tests | + +Only deliver after all checks pass. + +--- + +## Step 6 — Deliver + +Save the final PDF to `~/Desktop/[brand-slug]-brand-guidelines.pdf` and send the local path in a single message. Do not upload or host the PDF unless the user explicitly asks for a hosted copy. + +Reply shape: + +``` +**[BRAND NAME] — brand guidelines** +Saved to: ~/Desktop/[brand-slug]-brand-guidelines.pdf ([actual page count] pages · 1200×850) +``` + +If the user is not on a Mac, save to the project working directory and emit that path instead. Never attach the PDF as a file in the chat; link by path. + +Done. + +--- + +## Image Concept Must Connect to the Brand Metaphor (Don't Default to "Person Doing X") + +Before generating any image, identify the brand's central metaphor — the verb or noun the brand keeps returning to. For DeltaStream → "stream" (water, motion, flow, time). For a coffee brand → "ritual" (steam, pour, slow). For a sleep app → "rest" (stillness, breath, dark warmth). + +Then, for each direction, propose a visual concept that USES that metaphor in a FRESH way. The most common failure mode is defaulting to "person at desk" or "person using product" three times in a row. That looks stocky and unbranded — three engineers at three desks, even with different palettes, reads as three variations of the same image. + +### Steps to follow every time + +1. **Name the brand metaphor.** Write it down (e.g. "stream = flow / motion / time / water"). +2. **For each of the 3 directions, brainstorm 3 different image concepts that use the metaphor** through a different medium or subject. Pick the most ownable. +3. **Vary the medium across the 3 boards.** Mix: + - Photographs (documentary / editorial / macro / long-exposure / portrait / still life) + - Illustrations (flat vector, line art, gradient, isometric, geometric) + - Abstract compositions (typographic posters, color fields, motion studies) + - Architectural / environmental shots +4. **Specify the medium AND the concept in the prompt.** "Flat vector illustration of..." vs. "Editorial macro photograph of..." vs. "Long-exposure photograph of...". + +### Examples (for a "stream" brand) + +- **Cover Story (bold manifesto)** → Editorial macro photograph of glowing amber liquid frozen mid-pour, single dramatic light. Stream metaphor = literal liquid stream, captured in a moment. +- **First Light (soft consumer)** → Flat vector illustration of a stylized sunrise over geometric waves in butter yellow and cream. Stream metaphor = waves of light + flow. +- **Slow Burn (quiet editorial)** → Long-exposure photograph of city traffic light trails on a wet dark street at night, rust tail lights as the only accent. Stream metaphor = streams of light through time. + +Three different MEDIUMS (macro photo / vector illustration / long-exposure photo). Three different SUBJECTS. All rooted in "stream" but used distinctly. None of them are "person doing X." + +### When illustration beats photography + +Default to illustration (over photography) when: +- The brand is consumer-feeling, app-like, or has Bumble/Notion/Pika DNA → flat illustration reads warmer and more ownable than stock-photo people +- The concept is abstract or symbolic (a feeling, a state, a moment) — illustration can render concepts photography cannot +- The brand has a strong color palette and you want it to dominate the image — illustration controls color absolutely +- The aesthetic is playful, soft, or geometric — photography would feel like a mismatch + +Default to photography when: +- The brand is editorial, archival, premium, or grown-up +- The concept is tactile (an object, a material, a texture) +- The mood is documentary or quiet (Frank Ocean / Anthropic territory) + +### What NOT to do + +- Three "person at desk" with different palettes +- Three "person using product" with different lighting +- Three "engineer at laptop" — the stock photo zone +- Defaulting to portraits when an object, illustration, or abstract composition would say more +- Generating photography when illustration would serve the brand better + +--- + +## Icons Page — Structure & Rules + +Page 8 defines the brand's UI icon system. Every digital brand needs one — even non-tech brands benefit from consistent icons for navigation, social, and product surfaces. + +### Page layout + +- **Header bar** (standard section label + page num + brand symbol) +- **Headline** (top): a 38-44px brand-styled headline like "Icons" or "A consistent UI language" +- **Rules block** (left third, ~380px): + - **Stroke weight** — e.g. `1.5px` / `2px` / `3px` based on brand character (thinner = editorial / refined; thicker = friendly / consumer) + - **Corner radius** — sharp / soft 2px / round 4px / fully rounded + - **Line caps** — round / butt / square (round for friendly brands; butt for technical/precise) + - **Style** — outline / filled / two-tone / mixed + - **Grid** — 24×24 base / 32×32 base (24 is standard; 32 for larger UI) + - **Stroke ends / corners consistency** — same treatment across all icons +- **Icon grid** (right two-thirds): 4×3 grid of 12 icons, each in a `~120×120px` tile +- **Bottom note**: library recommendation for icons beyond the set — e.g. "Use Phosphor Light for any icon not in this set" or "Use Lucide at 1.5px stroke." + +### The 12 essential UI icons + +Every brand's icon set should include at minimum: + +| Icon | Use | +|---|---| +| arrow-right | navigation, "see more" | +| arrow-down | dropdown, expand | +| check | confirmation, success | +| close (×) | dismiss, close | +| plus | add, new | +| minus | remove | +| search | search/find | +| user | profile, account | +| settings (gear) | settings, preferences | +| bell | notifications | +| menu (hamburger) | mobile nav | +| info (circle-i) | helper tooltip | + +These cover 80% of UI needs. Brands with specific product features can add 2-4 product-specific icons (e.g. a streaming brand might add a "live" indicator; a finance brand might add "card" / "wallet"). + +### Stroke style choice by brand vibe + +- **Bold editorial / display-heavy brand** → 2-2.5px stroke, sharp corners, butt line caps. Looks intentional and precise. +- **Friendly / consumer / Bumble-Pika DNA brand** → 2px stroke, soft 2-3px corner radius, ROUND line caps. Looks warm and approachable. +- **Technical / dev-tool brand** → 1.5px stroke, sharp corners, butt caps. Looks precise like the rest of the brand. +- **Editorial / quiet / Anthropic-Modal brand** → 1.5px stroke, sharp corners, butt caps. Reads as refined. +- **Playful / heavy display brand** → 2.5-3px stroke, round corners, round caps. Echoes the chunky type. + +Pick the stroke style at the same time as the brand's identity, and apply it consistently across all 12 icons. + +### Rendering each icon + +Each icon is a 24×24 viewBox SVG with the brand's chosen stroke weight and corner style. Example structure (for arrow-right at 1.5px stroke, sharp corners, butt caps): + +```svg + + + + +``` + +Use `currentColor` for the stroke so the icon adopts the surrounding text color (essential for color-flexible UI usage). + +### What goes in the brand kit + +A `/icons/` folder containing all 12 (or more) icons as SVG files: +- `icons/arrow-right.svg` +- `icons/check.svg` +- `icons/close.svg` +- `icons/plus.svg` +- `icons/search.svg` +- `icons/user.svg` +- `icons/settings.svg` +- `icons/bell.svg` +- `icons/menu.svg` +- `icons/info.svg` +- (etc — full set used on page 8) + +Each SVG with `stroke="currentColor"` so it inherits color from the application context. + +--- + +## Imagery Rules Page — Adapts per Brand + +Page 10 of the guidelines defines the brand's imagery rules. **Its title and content adapt to whatever medium the brand actually uses** — don't ship a "Photography Rules" page for an illustration-led brand and don't ship "Illustration Rules" for a brand that lives in photos. + +### How to decide which page(s) to build + +Look at the chosen identity option's specs (set in Step 3) and the lifestyle world you've defined: + +| Brand visual medium | Page 10 setup | +|---|---| +| All photography (no illustration anywhere) | Page 10 = Photography Rules (single page) | +| All illustration (no photography anywhere) | Page 10 = Illustration Rules (single page) | +| Hybrid — both matter equally in the brand world | Page 10a = Photography Rules, Page 10b = Illustration Rules (two pages → guidelines totals 16) | +| Hybrid — one medium dominates but the other appears occasionally | Page 10 = the dominant medium's rules, with a short "minor medium" callout block at the bottom | + +### Photography Rules page structure + +If the brand uses photography: +- **Subject** — who/what is in the frame (real engineers / hands at work / still life / etc.) +- **Light** — direction, quality, time of day +- **Color** — grade, palette tones preserved, anything muted +- **Cast / diversity** — explicit rule that lifestyle images with people show racial diversity across the set +- **Texture** — film grain, composition style, off-center editorial framing +- **Forbidden** — stock-photo energy, studio strobes, perfect symmetry, AI-smooth surfaces, gradient backgrounds +- **One example image** filling 2/3 of the page (real generated photo in the brand's photo style) + +### Illustration Rules page structure + +If the brand uses illustration: +- **Style** — flat vector / line art / geometric / hand-drawn / 3D render / collage / mixed. Be specific (e.g. "flat vector with no realistic detail" not just "illustrated"). +- **Color** — how brand colors apply to illustrations (large fields vs accent dots; how many colors per illustration; palette restraint) +- **Line / stroke** — stroke weight rules (uniform 4px / varied / no strokes); corner radius (rounded / sharp); line caps (round / butt / square) +- **Character** — what the illustrations feel like (friendly / precise / playful / archival / geometric / organic). Match the brand's overall voice. +- **Composition** — asymmetric / centered, generous negative space / dense, rule-of-thirds / centered subject +- **Subject matter** — what the illustrations DEPICT (scenes / objects / abstract patterns / characters / metaphors). Tied to the brand metaphor. +- **Forbidden** — what kills the style (realistic detail in a flat-vector brand, gradients in a flat-color brand, drop shadows, photo textures, generic stock-illustration style, AI-uncanny features) +- **One example illustration** filling 2/3 of the page (real generated illustration in the brand's style) +- **Reference brands' illustration** — 2-3 brands whose illustration style is close (e.g. "like Notion's homepage illustrations but a notch more grown-up") + +### Visual World page (page 11) also adapts + +The 4-image lifestyle grid on page 11 should match the brand's medium mix: +- All-photo brand → 4 photos +- All-illustration brand → 4 illustrations (varied scenes, not 4 of the same composition) +- Hybrid → mix of photos and illustrations in the proportions that match the brand world (e.g. 3 photos + 1 illustration if photography dominates) + +--- + +## Avoid Concept Clichés — The First Metaphor Is Always Wrong + +The strongest image concepts come from the SECOND or THIRD thing you think of, not the first. The first metaphor is what every stock photography library has been selling for 20 years. If a concept makes you go "yeah, that captures the idea" — pause. Did you actually invent it, or are you reaching for a familiar trope? + +### Banned cliché concepts + +Never use any of these. They read as stock and weaken every brand they appear in: + +- **Hourglass / sand falling** for time, urgency, deadlines +- **Lightbulb glowing** for ideas, innovation +- **Chess pieces** for strategy, decisions +- **Jigsaw puzzle pieces** for fit, integration +- **Climbers reaching the summit / mountain peak silhouette** for ambition, success, leadership +- **Runner crossing a finish line** for achievement +- **Handshake** for trust, partnership, deals +- **Sunrise / sunset** for new beginnings (used to be fresh, now stock — though abstract sunrise illustrations can still work in consumer brands) +- **Compass or map alone** for direction, navigation +- **Rising graph line / arrow going up** for growth +- **Open road / horizon stretching into distance** for vision +- **Ocean waves / endless vastness** for scale +- **Tangled vs. straight cables** for organized vs. chaotic +- **Glowing network nodes connecting** for connection (especially in AI/tech) +- **Magnifying glass over numbers/charts** for analysis +- **Brain made of circuit board / glowing brain** for AI / intelligence +- **Domino chain falling** for cascading effect +- **Tree growing from a coin** for investment growth + +If you find yourself reaching for any of these — STOP. Brainstorm three more concepts. The third one is usually right. + +### Three tests for whether a concept is cheesy + +1. **The Wikipedia test** — could this concept be the lead image on Wikipedia's article for the abstract noun your brand cares about? "Hourglass" is literally Wikipedia's image for "Time." That's why it's cliché. +2. **The Shutterstock test** — search Shutterstock for the keyword. If the top 20 results all look like your concept, you've picked the trope, not a fresh image. +3. **The 4-other-brands test** — could 4 brands in unrelated industries use this exact image and have it mean something to each of them? (Hourglass: works for time-tracking software, project management, dating apps, history museums, fitness apps — that's the giveaway.) + +If a concept fails any of these three tests, regenerate. + +### Substitutes that work + +Trade the obvious metaphor for something **specific, indirect, or documentary**: + +| Cheesy first instinct | Sharper substitute | +|---|---| +| Hourglass (time) | Analog watch dial macro with second-hand mid-tick / polaroid mid-development / a long-exposure trace of motion | +| Rising graph (growth) | Two real photos of the same space weeks apart / a plant in a real apartment / handwritten progress note | +| Lightbulb (ideas) | A worn notebook with marginalia in warm desk light / a paper cup of cold coffee at 2am | +| Handshake (trust) | Two people working side-by-side in a real space / a sticky note left for a teammate | +| Chess pieces (strategy) | Hand pausing mid-move on a real board / whiteboard with one diagram half-erased | +| Compass (direction) | Real map being read in a real environment / a fork in a real road | +| Network nodes (connection) | People in a room talking / a real meeting / a shared screen between two people | +| Glowing brain (AI) | Real engineers using real software / hands typing on a real interface | + +**Pattern: trade the SYMBOL for the SCENE. Trade the OBJECT for the MOMENT. Trade the METAPHOR for the DOCUMENTARY.** + +### The cringe test (run before delivering) + +After generating, ask: *"If I saw this image without knowing the brand, would I cringe slightly?"* Stock-photo cringe is subtle — it doesn't scream "BAD IMAGE." It quietly says "this brand reached for the obvious symbol." If even slightly cringe — regenerate. + +--- + +## Photography Must Occupy Distinct Visual Territories + +Each of the 3 mood images on the brand board must show a **genuinely different visual territory** — not three variations on the same subject. If all 3 images are "engineer at desk with laptop" with slightly different color grading, the photography has failed. The user reads three identical concepts and concludes the directions aren't really different. + +Think of each option as a different MOVIE GENRE, each with its own: +- **Subject matter** — what's actually in the frame (portrait? still life? interior? hands at work? landscape?) +- **Setting** — where the brand lives (office? home? kitchen? after-hours desk? outdoors? abstract space?) +- **Scale** — close-up portrait vs. wide environment vs. tight still life vs. mid-shot +- **Time of day** — morning sun vs. midday vs. golden hour vs. midnight +- **Human presence** — is a person the subject, an element in the composition, or absent entirely? + +### Examples of structurally distinct territories + +For a brand with 3 directions (magazine-cover / consumer-warmth / editorial-quiet): +- **Magazine-cover** → close-up editorial PORTRAIT, single subject lit dramatically with one strong directional source, Bloomberg Businessweek cover energy +- **Consumer-warmth** → domestic STILL LIFE or hands in a real environment, no laptops or screens, golden hour, the LIFE around the work (kitchen, couch, sketchbook, market) +- **Editorial-quiet** → atmospheric STILL LIFE on a dark surface, single objects in moody pool of warm light, often no person visible, Frank Ocean Blonde sparseness + +For a different set of directions, the territories would be entirely different — the rule isn't "always do portrait + kitchen + still life," it's "find three structurally distinct territories that match each direction." + +### What NOT to do + +- Three engineers at three desks with three different color casts +- Three close-ups of hands on three different keyboards +- Three "person at laptop in coffee shop" with different lighting +- Any variation where you swap one word in the prompt and re-run with a different palette + +Each prompt should be **structurally different**: different subject, different setting, different scale, different mood. Color grading is the LAST differentiator, not the first. + +--- + +## Brand Board Layout — Differentiate per Option (Step 3 Preview) + +**Critical rule for the 3-page brand board preview built in Step 3 of the main skill:** do NOT use the same template for all 3 boards recolored. Each board's layout must physically embody its option's design philosophy. If you can swap colors and fonts and the layouts feel identical, the board has failed — viewers read the differences as cosmetic, not structural. + +Each brand board must answer: *what would this brand's actual hero page look like?* Build the answer. + +### Examples of differentiated layouts + +**Magazine-cover brand** — Full-bleed photo as background covering the entire page. Massive wordmark overlaid in display type. Tagline overlaid in small text. Issue/edition tag in corner ("Vol. 01 / Cover Story"). Bottom-margin strip showing color swatches and typography credit, like a magazine masthead. Whole page should look like a Bloomberg Businessweek or NYT Magazine cover. + +**Soft consumer-brand homepage hero** — Asymmetric split with a curved or rounded shape break between colored side and cream side. Big rounded type on one half, photo with rounded corners on the other. Color swatches presented as soft circles, not squares. Lots of breathing room. Should feel like the hero of bumble.com or pika.me. + +**Editorial / literary essay** — Bone or cream full-bleed background. Massive italic display type centered with extreme whitespace. Photo as a small inset rectangle, not full-bleed. Pull-quote on the margin. Color swatches as a tiny ribbon at the bottom. Should feel like the opening page of a Frank Ocean visual essay or an Anthropic announcement. + +**Tech-doc / dev-tool aesthetic** — Monochrome grid. Tight type. Code-like layout with bracket marks or syntax highlighting. Mono font everywhere. Color swatches as inline `code` blocks with hex strings. Should feel like Stripe's docs or GitHub's changelog. + +### Required content per board (regardless of layout) + +Every brand board page must include ALL of the following. The layout differentiation rule above does NOT mean cutting content — visually distinct layouts must still fit ALL the text. If a layout doesn't have room for the content, redesign the layout, don't drop content. + +- Brand wordmark (set in the brand's display font) +- **A standalone logo symbol/mark — generated as a transparent PNG via `generate_image` with `provider="gpt-image-2"` when new. Do not trace the generated symbol to SVG and do not claim it is vector. NOT just typography.** The symbol must work as a favicon, app icon, social avatar, and exported asset on transparent background at 1024×1024+. +- **A distinctive wordmark and any seal/badge treatment — custom letter spacing, ligature/cut/terminal detail, stamp geometry, or other ownable touch. Not just a Google Font in a circle, not a generic monogram seal, and not decorative filler.** +- Tagline +- Voice sample (one sentence in brand voice, quoted, with a "VOICE" label) +- Brand story (~35 words max, min 2 sentences, one compact paragraph in brand voice) +- **Lifestyle world description (~22 words max, min 1 full sentence describing the brand's visual territory — where it visually lives, who's in the frame, time of day, color temperature)** — labeled "WORLD" or similar +- Lifestyle mood image (generated via gpt-image-2 — see "Photography Must Occupy Distinct Visual Territories" rule below) +- 4-color palette with hex codes + role labels +- Display + body type specimens with named fonts + +### Content budgets per board + +The board is a visual decision aid, not the final brand book. Keep each board sharp enough to sell the direction at a glance: + +- Tagline: 8 words max. +- Voice sample: 14 words max. +- Brand story: 35 words max, min 2 sentences. Use one compact paragraph, not 2-3 full paragraphs. +- World description: 22 words max, min 1 full sentence. +- Palette: 4 colors max on the board. Full extended palettes belong in the final guidelines. +- Type specimen: one display sample and one body sample. Do not add full hierarchy tables to boards. +- Essential body copy: 18px minimum. If it needs to be smaller to fit, rewrite the copy. + +If all required content cannot fit within those budgets, the content is too verbose for a board. Rewrite it; do not shrink, stack, or layer it until it becomes technically present but visually bad. + +### What NOT to do + +- Same left-column-color-block-right-column-photo template recolored 3 times +- Same swatch grid in the same position on every page +- Same type specimen "Aa" treatment on every page +- Three different colors and three different fonts laid onto identical layouts +- Wordmark with no separate symbol — the logo isn't complete without a mark +- Dense archival/specimen styling where decorative rules, labels, swatches, and paragraphs intersect. If it looks like a broken certificate rather than a brand board, simplify. +- Body copy crossing through color swatches, icons, seals, or decorative overlays. Text must own a clean reading area. +- Empty mockup boxes or blank social grids. A placeholder reads as missing output, not restraint. +- Full boards that are almost entirely one muddy value range. Use image light, accent color, or negative space to create hierarchy. +- **Asymmetric rounded corners on color blocks** (e.g. only `border-top-left-radius` on a big shape) — these read as a clipping bug, not a design choice. If you want softness, use **symmetric** rounded corners (whole left edge rounded, or all four corners rounded), a **clean rectangular split**, or a deliberately organic shape via SVG/clip-path. Half-rounding a single corner of a big block looks like a mistake every time. +- **Inline pill backgrounds on display text (40px+)** — they overlap into adjacent lines because line-height is usually tighter than the rendered character box. A `background: var(--color); padding: 0 12px; border-radius: 12px;` on big headline text WILL bleed into the line above or below. Two safer options: + 1. **Highlighter-underline gradient** (recommended): `background: linear-gradient(to bottom, transparent 0%, transparent 58%, var(--accent) 58%, var(--accent) 92%, transparent 92%); padding: 0 6px; -webkit-box-decoration-break: clone; box-decoration-break: clone;` — creates a marker-highlight band that only occupies the bottom of the line, never extends beyond. + 2. **Just change the text color** (color: var(--accent)) — simplest, no overlap risk. + Never use solid pill backgrounds on display text unless you've also set generous line-height (1.4+) AND tested the actual render. +- **Pill/badge containers with text inside** (numerals like 01, 02, markers like + or ×, single letters) — never style them with `padding + text-align: center` and expect the text to look vertically centered. Font glyphs sit on a baseline with empty space above and below, so padding alone leaves the character looking top-shifted with empty space underneath. **Always use `display: inline-flex; align-items: center; justify-content: center;` with EXPLICIT `width` and `height`** — let the flex container center the text. Skip padding. Skip `text-align: center` (it only handles horizontal). The text will sit visually centered regardless of font metrics. + +If you can't physically tell which brand you're looking at *without* reading the labels, regenerate. + +--- + +## Quality Bar + +- Feels like a $5,000 brand studio deliverable — not a template, not a Canva export +- Every page should feel like a deliberate design decision was made +- **Typography used boldly**: headlines at 80–160px as graphic elements, not just labels +- **Color used intentionally**: full-bleed color blocks, not just colored text +- **Negative space is a design tool** — don't crowd every page +- **Hierarchy must be obvious**: display → subhead → body at dramatically different sizes +- **Voice page shows actual brand copy**, not generic example text +- **Touchpoints page shows real generated photos** — never CSS vector boxes +- **No placeholder text, no [BRACKETS], no repeated images anywhere** diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-identity.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-identity.md new file mode 100644 index 0000000000000000000000000000000000000000..f9c72827fd645907e2eb4e561beadc346906e7d8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-identity.md @@ -0,0 +1,190 @@ +# Brand Identity Options — Reference + +Each identity option is a complete creative package. When presenting 3 options, make them +genuinely different in name personality, color mood, and voice — not just palette swaps. + +## Structure for Each Option + +``` +### Option [1/2/3]: [Brand Name] +**Tagline:** [Short punchy line — 8 words max] + +**Colors:** +- [Name]: #[hex] (role: primary/accent/background/text) +- [Name]: #[hex] +- [Name]: #[hex] +- [Name]: #[hex] + +**Typography direction:** [e.g. "Serif headline with clean sans-serif body — editorial and grounded"] + +**Voice & tone:** [3-4 adjectives] — [One example sentence in the brand's voice] + +**Logo concept — wordmark + symbol + lockup:** + +A complete brand identity has BOTH a wordmark and a symbol — they're different things doing different jobs: +- **Wordmark** = the brand name in its identifying typeface. Used wherever there's room (web header, business card, packaging). +- **Symbol** = a standalone graphic mark that lives WITHOUT the wordmark. Used for app icon, favicon, social avatar, browser tab — anywhere the wordmark is too long. +- **Lockup** = how the two combine (horizontal, stacked, symbol-only). + +### Logo Pipeline — generate a high-res symbol via gpt-image-2, ship it as transparent PNG (no tracing) + +Do not write hand-coded SVG paths for a rich brand symbol, and do not trace a generated symbol to SVG. Keep the symbol as a high-resolution transparent PNG. Only the wordmark gets vectorized in the brand kit. + +1. Generate the symbol via `generate_image` with `provider="gpt-image-2"`, `quality="high"` for final, 1:1 aspect ratio, 1024x1024 minimum. +2. Style follows the brand: flat, dimensional, glossy, painted, photographic, chrome, hand-drawn, etc. Neither flat nor 3D is the default. +3. The prompt must include: "absolutely no text, no letters, no typography, no words, no characters anywhere in the image." +4. Save the approved symbol as a 2048x2048 transparent PNG with true alpha verified by PIL. +5. Wordmark = real font rendering, never baked into the image. Convert the wordmark to text-as-paths SVG in the kit. +6. Lockup measurements are fixed: symbol size, wordmark size, gap, and alignment do not drift across color variants. + +### Symbol output rules + +Every generated symbol must satisfy all of: +- Conceptually linked to the brand/product. +- Unique enough that it would fit only this brand. +- Recognizable at 16x16 favicon size. Test by resizing to 16x16 with LANCZOS, then upscaling to 128x128 with NEAREST and reading the result. +- No more than 3 dominant colors. +- High resolution, with 2048x2048+ master when shipped. +- No text inside the image. +- True transparent background. + +If the output has text, too many dominant colors, fake transparency, or fails the 16x16 test, regenerate. + +**Whether to generate new ones depends on what the user has:** +- If the user has an existing wordmark or symbol they like — USE it. Document the existing asset in the guidelines. +- If the user is asking for a new logo, or has said they don't like their current one — propose a new wordmark and/or symbol as part of the identity option. +- If the user has a wordmark but no symbol — propose just the symbol. Brands need a non-typographic mark for app icons, favicons, etc., so a symbol is worth proposing even when the wordmark is kept. +- Whatever the source, document BOTH in the guidelines. They're both part of complete brand documentation, even when only one is new. + +For each identity option, fill in: +- **Wordmark:** [How the brand name is typeset — typeface choice, custom letter treatment, spacing, ligature/cut/terminal detail, and lockup rhythm. Reference existing if kept; describe new if proposed. A wordmark is not just a Google Font typed in a brand color.] +- **Symbol / mark:** [The standalone graphic mark — shape, reference, what it evokes. Generated via gpt-image-2 when new, shipped as transparent PNG, NOT traced to SVG. Must read at 16x16 AND 512x512. Reference existing if kept; describe new if proposed.] +- **Lockup:** [How wordmark + symbol combine — horizontal (symbol left, name right), stacked (symbol above name), symbol-only at small sizes.] + +**Brand story:** +[2-3 sentences for the About page. Written in brand voice. Real copy, not a template.] + +Board-preview copy is intentionally shorter: when this story appears on the 3-option brand board, rewrite it to the board budget (~35 words max, min 2 sentences, one compact paragraph). The 2-3 sentence version belongs in the text option/About-page snippet, not the preview board. For the full guidelines foundation page, expand the story to 2-3 paragraphs of real copy in brand voice. + +**Product / hero subject photography direction:** +[How the main subject of brand photography should look — for product brands: the product itself. +For service / app / community brands: the hero subject of the brand (the person using it, the +moment it serves, the artifact it produces). Be specific: surfaces, lighting, props, mood, +composition. 1-2 concrete reference descriptions (e.g. "like a Sunday farmers market table" +or "like a quiet morning before anyone else is awake").] + +**Lifestyle photography direction:** +[The full visual world beyond the hero subject — what does the life around this brand look like? +Include: what environments (homes, outdoor spaces, markets, studios, offices), what kind of +people and how they're styled, what activities and moments feel on-brand, color temperature +and mood of the world, what the brand's customer looks like when they're living their life. +This should paint a complete picture someone could cast and art-direct a shoot from.] + +**UI / website art direction:** +[What will the brand's digital presence actually look like? Include: layout feeling (spacious/dense, +editorial/grid), background colors, how text and images are balanced, button style (minimal/bold), +how navigation feels, any special layout details (full-bleed images, whitespace-heavy, etc.), +and overall digital mood. Reference a real website aesthetic if helpful +(e.g. "like Mejuri — very white, generous whitespace, product does the talking")] + +**Example brands:** +[3-4 real existing brands that live in a similar world — not competitors, but brands that share +the same energy, customer, or aesthetic. Helps the user immediately understand the territory. +Can be fashion brands, lifestyle brands, tech brands, Instagram accounts, or cultural references. +e.g. "Entireworld, Rowing Blazers, Madhappy — brands with a strong POV and a loyal community"] +``` + +## Visuals (Required) + +After presenting all 3 identity options in text, **render a 3-page brand board PDF (one page per option, 1200×850 each)** so the user can see each identity before committing. Do not generate generic AI "mood board" images — they look stocky and bad. + +### How to generate: + +Build one self-contained HTML file per option, render each to PDF locally via Chrome headless, then merge into a single 3-page PDF. Each page MUST have a layout that physically embodies its option's design philosophy. + +```bash +WS="${BUILD_A_BRAND_WS:-$HOME/build-a-brand-workspace}" +mkdir -p "$WS/boards" +CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + +for i in 01 02 03; do + "$CHROME" --headless --disable-gpu --no-sandbox --hide-scrollbars \ + --virtual-time-budget=8000 --no-pdf-header-footer \ + --print-to-pdf="$WS/boards/$i.pdf" \ + "file://$WS/boards/$i-"*.html +done + +pdfunite "$WS/boards/01.pdf" "$WS/boards/02.pdf" "$WS/boards/03.pdf" "$WS/boards/brand-boards.pdf" + +for i in 01 02 03; do + "$CHROME" --headless --disable-gpu --no-sandbox --hide-scrollbars \ + --virtual-time-budget=8000 --window-size=1200,850 \ + --screenshot="$WS/boards/qa-$i.png" "file://$WS/boards/$i-"*.html +done +``` + +Read every PNG preview before sending the PDF path to the user. The check is not only "does it fit?" It must also look like a good brand board: one primary visual focal point with supporting required content grouped clearly, readable text, no empty placeholders, no muddy one-note palette, and no body copy intersecting decorative elements. + +Each page MUST have a layout that physically embodies its option's design philosophy (not three template recolours — see `brand-guidelines.md` "Brand Board Layout — Differentiate per Option" for rules and examples). + +Assets in the HTML should be local files under `$WS/images` and `$WS/fonts`, referenced via absolute `file://` paths. Download generated image outputs before rendering. + +**Delivery:** save `$WS/boards/brand-boards.pdf` to `~/Desktop/[brand-slug]-brand-boards.pdf` and emit the local path. Do not upload or host the PDF unless the user explicitly asks for a hosted copy. + +**Design rules for each board:** +- Each option panel uses its own background color from that option's palette +- Brand name displayed large in that option's display typeface (loaded via local `@font-face file://` from `$WS/fonts/`) +- Color swatches shown as circles or rectangles with color names beneath +- Typography is clean and editorial — no generic fonts (no Inter / Karla / DM Sans default) +- Layout philosophy differs per board — a tabloid board looks like a newspaper, a fashion-house board looks like a lookbook spread, an archival board looks like a book frontispiece. See `brand-guidelines.md` "Brand Board Layout — Differentiate per Option" for the differentiation rule and `brand-guidelines.md` "Required content per board" for the per-page checklist. +- No generic AI mood-board collages. Each board may use one purpose-built gpt-image-2 mood image and one generated PNG symbol when that is the strongest logo route. No AI app mockups, AI product mockups, or extra AI filler assets. +- The whole thing should look like something a real brand studio would produce + +**Board copy budgets:** +- Tagline: 8 words max. +- Voice sample: 14 words max. +- Brand story: 35 words max, min 2 sentences. +- World description: 22 words max, min 1 full sentence. +- Body text: 18px minimum. Labels: 14px minimum unless purely decorative. +- If copy needs to be smaller than that, rewrite. Do not shrink, layer, or cram until the board technically contains everything but looks bad. + +## Quality Bar + +- **Names**: Should be memorable, say-able, and googleable. Avoid made-up words unless they're genuinely good. +- **Colors**: Give them real names (not "Dark Blue" — try "Ink", "Dusk", "Bone"). Specify roles. +- **Voice examples**: Write an actual sentence in the brand's voice (a headline, a button label, an error message), not a description of the voice. +- **Logo concepts**: Cover BOTH wordmark and symbol in every identity option — they're different things doing different jobs. Describe each visually — shape, reference, style. What you GENERATE depends on what the user has: use existing assets if the user wants to keep them, propose new ones if the user needs a logo or doesn't like their current one. For a new symbol, use gpt-image-2 with a transparent-background, no-text prompt and ship the symbol as PNG. If the user has a wordmark but no symbol, still propose a symbol — favicons and app icons need a non-typographic mark. +- **Fonts must have character.** Don't default to Inter / Karla / Outfit / DM Sans / Lato — they have no point of view. Explore the full Google Fonts library. See `brand-guidelines.md` "Font Selection — Must Have Character" for approved high-character options. +- **Brand story**: Should make someone feel something. Name the founder's origin if appropriate. + +## Example Identity Option + +### Option 1: Thread & Tide +**Tagline:** Made slowly. Worn forever. + +**Colors:** +- Bone: #F5F0E8 (background) +- Sienna: #C2714F (primary) +- Bark: #6B4F3A (text/accent) +- Sage: #8A9E85 (secondary accent) + +**Typography direction:** Soft serif headlines (elegant, unhurried) with minimal sans-serif body text. + +**Voice & tone:** Warm, specific, unhurried, honest — "Each clasp is set by hand, so yours might be slightly different from the photo. That's the point." + +**Logo concept — wordmark + symbol:** +- **Wordmark:** The brand name in a loose, hand-drawn serif. All-caps with light tracking. Slightly imperfect, like a signature. +- **Symbol / mark:** A small monogram T&T inside a hand-drawn circle, like a maker's hallmark stamped into clay. Used as the standalone identity at app-icon size. +- **Lockup:** Wordmark above symbol-circle for primary lockup; symbol-only at small sizes (favicon, avatar). + +**Brand story:** +Thread & Tide started on a kitchen table in 2021, when beads that were supposed to be a birthday gift turned into a small obsession. Every piece is made in small batches — no two exactly alike. We make jewelry for people who want something that feels like it was made for them. Because it basically was. + +**Product / hero subject photography direction:** +Natural light only — shoot near a window, never flash. Backgrounds: raw linen, unfinished wood, or stone. Props kept to a minimum — maybe a dried flower or two, never cluttered. Mood is quiet and a little intimate, like something found at a market stall you almost walked past. Close-up shots showing texture and knot detail are essential. Avoid white seamless — it reads too commercial for this brand. + +**Lifestyle photography direction:** +The world of Thread & Tide is weekend mornings and slow afternoons. Worn while making coffee in a light-filled kitchen, sitting cross-legged on a rumpled bed, at a farmers market with a canvas tote. The person in the photos is unhurried — no poses, caught mid-moment. Warm skin tones, natural hair, wearing pieces with a simple outfit (linen, denim, nothing loud). Color temperature is warm throughout — golden morning light, never cool or blue. Nothing aspirational in a luxury sense — aspirational in a "I want that quiet Saturday" sense. + +**UI / website art direction:** +Cream background (#F5F0E8), not white — warmer and more handmade-feeling. Generous whitespace. Full-bleed photography as hero, minimal text overlaid. Body font is a quiet serif. Navigation is simple — 3-4 items max, no mega-menus. Buttons are outlined, not filled — refined and light. Product grid is 2 columns on mobile, 3 on desktop with breathing room between items. No pop-ups or aggressive CTAs. Overall feel: like a well-made independent magazine. Reference: Aesop's website energy but warmer and more accessible. diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-md-template.md b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-md-template.md new file mode 100644 index 0000000000000000000000000000000000000000..e4c9c20e697113ac6f97815340965b268de81754 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/skill/references/brand-md-template.md @@ -0,0 +1,380 @@ +# brand.md — Template Reference + +This template defines the structure of the `brand.md` file delivered in Step 4's brand kit zip. It's a comprehensive, machine-readable brand spec that lets users (or downstream AI tools) produce on-brand work without needing the 14–16-page guidelines PDF. + +## Why this format + +`brand.md` is the brand's portable form. Paste it into Claude, GPT, or any LLM along with a task ("write a launch tweet," "design a landing page hero," "draft an email") and the AI can produce on-brand output without the user manually re-explaining the brand. The format is intentionally: +- **Scannable at the top** (Quick Reference block) so an AI doesn't have to read 200 lines before producing something. +- **Detailed below** so the AI can dig in when a task needs more specificity. +- **Markdown** so it renders in GitHub, Notion, Cursor, Claude artifacts, etc. + +## Required sections (in this order) + +1. Title + one-line description +2. Quick Reference (scannable top block) +3. Positioning +4. Target Customer +5. Mission +6. Values +7. Story (why we exist) +8. Voice & Tone +9. Colors +10. Typography +11. Logo +12. Icons +13. Imagery (Photography and/or Illustration) +14. Visual World +15. Touchpoints +16. Do & Don't +17. Reference Brands +18. Design Tokens (pointer to /tokens/ files) +19. AI Prompts (pointer to /prompts/ files) +20. How to Use This Spec + +## Template + +```markdown +# [Brand Name] — Brand Guide + +> A complete brand spec. Paste this into Claude, GPT, or any AI tool along with a task to produce on-brand work. Or hand it to a designer or developer. + +--- + +## Quick Reference + +- **Name:** [Brand Name] +- **Tagline:** [Tagline] +- **One-line positioning:** [Positioning statement] +- **Primary color:** [Name] `#HEX` +- **Display font:** [Font name] (Google Fonts: [URL]) +- **Body font:** [Font name] (Google Fonts: [URL]) +- **Voice:** [3-4 adjectives separated by commas] +- **Logo symbol:** [One-line description — e.g. "outlined Δ delta with horizontal bar"] + +--- + +## Positioning + +[Positioning statement as a single declarative sentence.] + +[1-2 paragraph expansion of what the brand stands for, what's different about it, what the wedge is.] + +--- + +## Target Customer + +[Customer name (real or representative), age, role.] + +[2-3 sentence vivid description of who they are, what they care about, why they buy. Specific not demographic.] + +--- + +## Mission + +[Mission as a single sentence — the thing the brand exists to do.] + +--- + +## Values + +1. **[Value 1]** — [one-line explanation] +2. **[Value 2]** — [one-line explanation] +3. **[Value 3]** — [one-line explanation] +4. **[Value 4]** — [one-line explanation] +5. **[Value 5]** — [one-line explanation] + +--- + +## Story — Why We Exist + +[2-3 paragraphs of the brand's origin/why story, written in brand voice. This is the "about us" content — it should be real copy, ready to paste into a website.] + +--- + +## Voice & Tone + +**Adjectives:** [4 tone adjectives, comma-separated] + +**How we sound:** +[1-2 sentences describing the voice.] + +**Copy examples by context:** + +| Context | Example | +|---|---| +| Headline | [Real example in brand voice] | +| Sub-headline | [Real example] | +| CTA button | [Real example — short, specific] | +| Error state | [Real example — warm not robotic] | +| Footer line | [Real example] | +| Social post | [Real example] | + +**Words we never use:** +[Comma-separated list of forbidden words — usually marketing clichés the brand specifically avoids.] + +--- + +## Colors + +| Name | Hex | RGB | CMYK | Pantone | Role | +|---|---|---|---|---|---| +| [Name] | #HEXVAL | R, G, B | C, M, Y, K | XXX C | Primary | +| [Name] | #HEXVAL | R, G, B | C, M, Y, K | XXX C | Background | +| [Name] | #HEXVAL | R, G, B | C, M, Y, K | XXX C | Text | +| [Name] | #HEXVAL | R, G, B | C, M, Y, K | XXX C | Depth / accent | + +**Primary pairings:** [Which colors go with which — e.g. "Primary on Background is the default; Primary on Text is for emphasis blocks."] + +**Never:** [Color combos to avoid — e.g. "Never pair Primary with cool blues. Never tint Background gray."] + +--- + +## Typography + +**Display:** [Font name + weight], used for hero headlines at [size range]. [One-sentence note on its character.] +- Google Fonts: [URL] + +**Body:** [Font name + weight], used for paragraph text at [size range]. +- Google Fonts: [URL] + +**Hierarchy:** + +| Level | Font | Weight | Size | Line-height | +|---|---|---|---|---| +| Display | [Font] | [Weight] | 124–168px | 0.85–0.92 | +| H1 | [Font] | [Weight] | 64–72px | 0.92–0.95 | +| H2 | [Font] | [Weight] | 38–42px | 1.05–1.1 | +| H3 | [Font] | [Weight] | 22–24px | 1.15–1.2 | +| Body | [Font] | [Weight] | 16px | 1.45–1.55 | +| Caption | [Font] | [Weight] | 11px | 1.4, letter-spacing 0.28em uppercase | + +**Pairing rules:** [Brief note — e.g. "Display font carries the brand. Body font supports it. Never use the display font for body or vice versa."] + +--- + +## Logo + +### Wordmark + +[Description of the wordmark — which Google Font (or commercial font) it's set in, weight, letterspacing, why it matches the brand vibe. The wordmark is ALWAYS real font rendering, never a generated image.] + +Files (in `logo/wordmark/`): +- `wordmark-[primary].svg` — Google Font converted to text-as-paths (renders without the font file installed) +- `wordmark-[primary].png` — 1024-wide raster fallback +- `wordmark-on-dark.svg/.png` — variants for dark backgrounds +- [etc — list all variants] + +### Symbol + +[Description of the symbol/mark — shape, what it evokes, how it relates to the brand. The symbol was generated via gpt-image-2 and ships as a high-resolution transparent PNG (NOT traced to SVG — only the wordmark gets vectorized). Style can be flat, dimensional, painted, photographic, gradient-rich — whatever fits the brand. Concept lane (mascot / product-feature / abstract / monogram / hybrid / container): [name the lane and explain how it links to the brand].] + +Symbol output checks (all must pass): +- Conceptually linked to brand +- Feels unique (would fit ONLY this brand) +- Recognizable at 16×16 favicon size (passed mandatory PIL favicon test) +- No more than 3 dominant colors: [list them with hex] +- Shipped at 2048×2048+ master resolution +- No text inside the image +- True alpha=0 transparency verified + +Files (in `logo/symbol/`): +- `symbol-[primary]-16.png` through `symbol-[primary]-2048.png` — primary color at 8 sizes, transparent background +- `symbol-on-dark-[sizes].png` — variant for dark backgrounds (if needed) +- [etc — variants ship as PNG only; symbol is NEVER vectorized to SVG] + +### Lockup + +[Description of how wordmark + symbol combine. Primary lockup (stacked or horizontal). Secondary lockups. When to use each. Measurements are PERFECTLY MEASURED and PERMANENTLY FIXED across all color variants — never let the wordmark drift between cream / pink / dark versions.] + +**Locked measurements (specify both lockups):** +- Horizontal: symbol [WxH px], gap [X px], wordmark font-size [X px], alignment [optical center / baseline] +- Stacked: symbol [WxH px], vertical gap [X px], wordmark font-size [X px] + +Files (in `logo/lockup/horizontal/` and `logo/lockup/stacked/`): +- `lockup-[orientation]-[color].svg` — symbol PNG embedded inline + wordmark as text-as-paths at locked measurements +- `lockup-[orientation]-[color].png` — assembled lockup as raster, 1024-wide +- [List all color variants] + +**Clear space rule:** [Minimum space around the lockup — e.g. "Minimum one symbol-height of space on all sides."] + +**Don'ts:** Don't stretch, rotate, recolor outside the palette, drop-shadow, or place on busy backgrounds. + +--- + +## Icons + +*(This section only applies to digital brands — app, web, SaaS, software platform. For non-digital brands (product, fashion, restaurant, service), delete this section entirely and skip the `/icons/` folder in the kit.)* + +**Stroke weight:** [e.g. 1.5px / 2px / 3px] +**Corner radius:** [sharp / 2px / round] +**Line caps:** [butt / round / square] +**Style:** [outline / filled / mixed] +**Grid:** 24×24 base + +**Set in this kit** (`/icons/`): +- arrow-right, arrow-down, check, close, plus, minus, search, user, settings, bell, menu, info +- [+ any brand-specific icons] + +**For icons beyond this set:** Use [library name + weight] — e.g. "Phosphor Light" or "Lucide at 1.5px stroke." + +Each icon SVG uses `stroke="currentColor"` so it adopts the surrounding text color in any application context. + +--- + +## Imagery + +Use this section's photography-OR-illustration block depending on the brand's medium. Delete whichever doesn't apply, or keep both if the brand is hybrid. + +### Photography (if brand uses photography) + +**Subject:** [Who/what is in the frame.] + +**Light:** [Lighting style — direction, quality, time of day.] + +**Color:** [Color grade direction.] + +**Texture:** [Film, grain, composition guidance.] + +**Forbidden:** [What this brand's photography never looks like — stock, studio, etc.] + +**Cast diversity:** All lifestyle images featuring people must show racial diversity across the set. Vary body types. Default to mixed cast unless there's a deliberate reason for a single subject. + +### Illustration (if brand uses illustration) + +**Style:** [Flat vector / line art / geometric / 3D / hand-drawn / mixed. Be specific.] + +**Color use:** [How brand colors apply — large fields vs accent dots, palette restraint per illustration.] + +**Line / stroke:** [Stroke weight, corner radius, line caps. Or "no strokes, color fields only."] + +**Character:** [Friendly / precise / playful / archival / geometric / organic. Match brand voice.] + +**Composition:** [Asymmetric / centered, whitespace approach, framing rules.] + +**Subject matter:** [What illustrations depict — scenes, objects, metaphors. Tied to the brand metaphor.] + +**Forbidden:** [What kills the style — realistic detail in flat-vector brand, gradients, drop shadows, generic stock-illustration look, etc.] + +**Reference brands' illustration style:** [2-3 brands whose illustration is close.] + +--- + +## Visual World + +[2-3 sentence description of the world the brand's imagery lives in — environments, time of day, mood, characters. Should paint a picture someone could art-direct a shoot from.] + +--- + +## Touchpoints + +The brand shows up on these surfaces. Each follows the rules above. + +- **Web** — [hero treatment, color usage, typography rules] +- **Mobile app** — [UI palette and rules] +- **Social** — [tone, asset rules, posting cadence] +- **Print collateral** — [business cards, packaging, etc.] +- **Merch** — [stickers, mugs, totes, apparel] + +--- + +## Do & Don't + +**DO:** +- [Brand-specific do #1] +- [Brand-specific do #2] +- [Brand-specific do #3] +- [Brand-specific do #4] +- [Brand-specific do #5] + +**DON'T:** +- [Brand-specific don't #1] +- [Brand-specific don't #2] +- [Brand-specific don't #3] +- [Brand-specific don't #4] +- [Brand-specific don't #5] + +--- + +## Reference Brands + +These brands share the territory. They're not competitors — they're cultural reference points the brand can borrow energy from. + +- **[Brand]** — Borrow: [what to learn from them] +- **[Brand]** — Borrow: [what to learn from them] +- **[Brand]** — Borrow: [what to learn from them] +- **[Brand]** — Borrow: [what to learn from them] + +--- + +## Design Tokens + +Machine-readable versions of all visual tokens (colors, fonts, spacing, radius, shadow) live in the `/tokens/` directory: + +- **`tokens/tokens.css`** — CSS custom properties. Drop the `:root { ... }` block into your stylesheet and reference as `var(--color-primary)`, `var(--font-display)`, etc. +- **`tokens/tokens.json`** — same content as JSON. Useful for AI tools, build pipelines, or any non-CSS context. +- **`tokens/tailwind.config.snippet.js`** — paste inside your `tailwind.config.js` `theme.extend` block. All brand tokens become Tailwind classes (`bg-primary`, `text-text`, `font-display`, `rounded-lg`, etc). + +The token names match this spec — don't rename them or they'll fall out of sync with the rest of the brand documentation. + +--- + +## AI Prompts + +Pre-built prompts for common downstream tasks live in `/prompts/`: + +**Copy prompts:** +- **`prompts/system-prompt.md`** — paste at the top of any Claude or GPT thread to prime the model on this brand's voice + visual identity. Then add your task below. +- **`prompts/tweet.md`** — task starter for writing tweets in brand voice +- **`prompts/landing-hero.md`** — task starter for landing page hero copy (headline + sub + CTA) +- **`prompts/email.md`** — task starter for marketing or transactional emails +- **`prompts/error-message.md`** — task starter for writing warm-but-specific error/empty/loading states + +**Image prompts:** +- **`prompts/photography.md`** — task starter for generating brand photography via gpt-image-2 (or similar). Includes the brand's exact photo direction (subject / light / cast / texture), banned cliché concepts list, anti-stock guardrails, the no-text safeguard string, and subject substitutes for "person at laptop" defaults. +- **`prompts/illustration.md`** — *(only present if the brand uses illustration)* — task starter for generating brand illustrations. Includes the brand's illustration style rules, palette constraints, banned elements (gradients, drop shadows, etc.), and when to use illustration vs photography. + +These prompts encode the brand voice rules from this spec into instructions the model will follow. Use them when you want consistent on-brand output without re-explaining the brand each time. + +--- + +## How to Use This Spec + +**With an AI tool (Claude, GPT, etc.):** +1. Paste `prompts/system-prompt.md` (or this whole `brand.md`) at the top of a new thread. +2. Add your task — "Write a launch tweet" / "Design a landing page hero" / "Draft an onboarding email." +3. Or use a specific task starter from `/prompts/` for the most consistent output. +4. Verify the output against the Do & Don't section before shipping. + +**With a designer:** +- Hand them the `brand.md` + `/logo/` + `/icons/` directories. They have everything they need. + +**With a developer:** +- Point them at `/tokens/` first. CSS variables / JSON / Tailwind config — pick whichever matches their stack. +- The icon SVGs in `/icons/` use `currentColor` for stroke so they inherit color from context. + +**For self-checks:** +- Before delivering anything in this brand's voice, re-read the "Voice & Tone" section. +- Before delivering anything visual, re-read "Colors," "Typography," "Icons," and "Imagery." +- Always check the Do & Don't list last. + +--- + +*Generated [DATE] by the build-a-brand skill. Update this file when the brand evolves.* +``` + +## Filling guidelines + +- **Quick Reference** must be scannable in 5 seconds. Don't bloat it. +- **Voice copy examples** must be REAL on-brand sentences, not placeholders. Pull from the guidelines PDF's Voice & Tone page. +- **Colors table** needs Pantone if you have it; mark as "—" if not specified. +- **Typography Google Fonts URLs** must be the actual `https://fonts.google.com/specimen/[Name]` link, not the embed URL. +- **Logo file lists** must match exactly what's in the zip. If a variant doesn't exist, don't list it. +- **Reference brands** with "borrow this" notes — the same content as the guidelines page 2. +- **How to Use** — the most important section for downstream usability. Tell the user how to actually apply this spec. + +## What NOT to include + +- Don't include the full 14–16-page guidelines verbatim. The brand.md is the SPEC, not the manual. Keep it tight. +- Don't include marketing fluff. Every section should be either directly usable copy or actionable rules. +- Don't include build mechanics (WeasyPrint quirks, prompt templates, etc.). Those are skill-internal. diff --git a/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4531f9f0effb00b17f6278d5e99d6d25c22c2136 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b08ca17bb14d90aa_q1/task.json @@ -0,0 +1,51 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b08ca17bb14d90aa", + "query_id": "b08ca17bb14d90aa_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "69095a56bf9c07ff9de2924150f031aec02dfff3e3e9c963799b1312d673ea05", + "name": "build-a-brand", + "package_path": "skill", + "install_name": "build-a-brand-69f0a452" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "69095a56bf9c07ff9de2924150f031aec02dfff3e3e9c963799b1312d673ea05", + "files": { + "README.md": "978f839c7af0121d2afdf692accac94d4430a42d83943f52d8260c50d3065663", + "SKILL.md": "26a2a415073d44bca214534755177719e3bebc27856ea5c34a18f18b10b703a4", + "references/brand-directions.md": "e66ccd54a8254e53e31f28a83b1238de2986a5fa47c52d099e06967f6b87b288", + "references/brand-guidelines.md": "b55e72839199a2d528b15a783333821c8d66c906db6b00dc80f25f9816c54b81", + "references/brand-identity.md": "3b32d949cf8b7c9dc1fb92921ddc74d25a550d963afa06d14d7f38bb0bbe74af", + "references/brand-md-template.md": "d9adbc329c13ed81ca74764dbc12a560bdb48c4646fe6687b59fc7043c1256d8" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "69f0a452d1a9deba5de231102a81f4756e97bbb5b21070fdf5bff512d4359733" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_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/b18487f2ffd0d9cd_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_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/b18487f2ffd0d9cd_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_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/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_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/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b18487f2ffd0d9cd_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..0fcf3883a0b7de7fb9ee9f0ff9a018c1109cd02e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b18487f2ffd0d9cd_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "d3cbafe4e6f2db3d89b73141245a9941eb9915c1eefc7431d71d7a8ac9ad50e9", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b92538fbbd626fc8c1cc0d2c260b1e0531036d2a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/instruction.md @@ -0,0 +1 @@ +We're wiring up automated changelog generation after each sprint and need to point our release automation at the exact output locations the changelog workflow mandates. Which directory must both the Markdown and JSON changelog files be written to, what is the filename of the human-readable Markdown changelog, and what is the filename of the machine-readable JSON changelog? Return one JSON object matching {"answers":{"q1":"string","q2":"string","q3":"string"}}, replacing each placeholder with the bare project-defined value. diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d68ba87abe190eaeb2aecce314a4ee321fc363bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/SKILL.md @@ -0,0 +1,66 @@ +--- +name: changelog-generator +description: Analyzes commit history, PR descriptions, and spec changes to automatically generate developer-friendly API changelogs. +--- + +# Changelog Generator Protocol + +This skill bridges the gap between raw git history and consumer-facing API updates. Consumers don't care about "Refactored user service;" they care about "The `/users` endpoint now returns a `profile_pic` URL." + +**Core assumption:** A changelog is a communication tool, not a git dump. It must focus on the API interface, not internal implementation tweaks. + +--- + +## 1. Input Analysis (Static) +Parse the provided text (Git commits, PR bodies, or OpenAPI diffs) and filter out internal noise. +- **Keep:** Added fields, new endpoints, deprecated endpoints, bug fixes that changed API behavior. +- **Discard:** Dependency updates, CI/CD tweaks, internal refactoring (unless it drastically improved performance). + +## 2. Categorization & Formatting +Organize the update into established categories: +- **🚀 Features:** New capabilities for the consumer. +- **🛠️ Fixes:** Resolved behavior issues. +- **⚠️ Deprecations:** Warnings about endpoints/fields being sunset. +- **🚨 BREAKING CHANGES:** Red-alert items requiring consumer code updates. (Cross-reference findings with `breaking-change-detector`). + +## 3. Output Generation + +**Required Outputs (Must write BOTH to `docs/api-report/`):** + +1. **Human-Readable Markdown (`docs/api-report/api-changelog.md`)** +```markdown +# 🌍 API Changelog + +## [v1.4.0] - 2024-03-24 + +### 🚀 Features +- **[Orders]** Added new `POST /v1/orders/{id}/cancel` endpoint. You can now cancel orders within 30 minutes of creation. +- **[Users]** The `GET /v1/users/me` endpoint now includes a `last_login_at` timestamp. + +### 🛠️ Fixes +- **[Payments]** Fixed an issue where `GET /v1/payments` would return a 500 error if the user had no payment methods. It now correctly returns an empty array `[]`. + +### ⚠️ Deprecations +- **[Products]** The `category_id` field in the `/products` response is deprecated. Please use the new `categories` array instead. `category_id` will be removed in v2.0.0. +``` + +2. **Machine-Readable JSON (`docs/api-report/api-changelog-output.json`)** +```json +{ + "skill": "changelog-generator", + "version": "1.4.0", + "date": "2024-03-24", + "changes": { + "features": ["POST /v1/orders/{id}/cancel added", "last_login_at added to GET /v1/users/me"], + "fixes": ["GET /v1/payments empty state fix"], + "deprecations": ["category_id in /products response"] + }, + "breaking_changes": [] +} +``` + +--- + +## Guardrails +- **Migration Context:** If there is a breaking change or a deprecation, *always* include a 1-2 sentence instruction on what the developer should use instead. +- **Tone:** Keep it professional, concise, and focused purely on the API consumer's perspective. diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/agents/openai.yaml b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b1868d6342e957ad767208da43175aaed28970db --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/skill/agents/openai.yaml @@ -0,0 +1,7 @@ +interface: + display_name: "Changelog Generator" + short_description: "Analyzes commit history, PR descriptions, and spec changes to automatically generate developer-friendly API changelogs." + default_prompt: "Use $changelog-generator to help with this task." + +policy: + allow_implicit_invocation: true diff --git a/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..30bf8b1b09a0d002ee4498e884fa86095365ead2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b18487f2ffd0d9cd_q1/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b18487f2ffd0d9cd", + "query_id": "b18487f2ffd0d9cd_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "420b5709e5a10801bf1ae3e7c193cf250f6d02e412864161f9e2e6d6a8e74481", + "name": "changelog-generator", + "package_path": "skill", + "install_name": "changelog-generator-68148e2f" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "420b5709e5a10801bf1ae3e7c193cf250f6d02e412864161f9e2e6d6a8e74481", + "files": { + "SKILL.md": "666fdade0ec0675699bd0251a226ee201e6214d4f2bfe106e21425e20196f243", + "agents/openai.yaml": "2a25999f62b3a4abf17e5036d982a41ad2129861c093c074635637b0c379ad85" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "68148e2f705e00fc3064a3c8119a6bc16725d1da43920d4ffe1bd0ea88eece3f" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..40cb7b630ecd82d183f8f920421937dab375d13d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_contract.json @@ -0,0 +1,28 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1, + "10": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/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/b2f1e8532faa4a83c995c52e/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/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/b2f1e8532faa4a83c995c52e/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/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(' Result {\n let content = fs::read_to_string(path).map_err(|e| e.to_string())?;\n for line in content.lines() {\n if let Some(rest) = line.strip_prefix(key) {\n return Ok(rest.trim_start_matches(\'=\').trim().to_string());\n }\n }\n Err(format!("missing key: {}", key))\n}\n\npub fn risky_parse(raw: &str) -> i32 {\n raw.trim().parse::().unwrap()\n}\n\npub fn fallback() -> i32 {\n let data: Vec = vec![1, 2, 3];\n match data.first() {\n Some(v) => *v,\n None => panic!("empty data"),\n }\n}\n\n#[allow(dead_code)]\nfn legacy_helper() {}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn test_parse() {\n assert_eq!(super::risky_parse(" 42 "), 42);\n let v: Vec = vec![];\n let _ = v.first().unwrap();\n }\n}\n', 'sim.rs': 'pub fn fast_normalize(values: &mut [f32]) {\n let len = values.len();\n unsafe {\n let ptr = values.as_mut_ptr();\n for i in 0..len {\n *ptr.add(i) = 1.0;\n }\n }\n}\n\npub fn state_name(state: u8) -> &\'static str {\n match state {\n 0 => "idle",\n 1 => "running",\n _ => unreachable!(),\n }\n}\n\n#[allow(clippy::too_many_lines)] // JUSTIFICATION: table-driven dispatch is inherently long\npub fn dispatch(code: u32) -> u32 {\n code.wrapping_mul(2654435761) % 97\n}\n', 'engine_tests.rs': '#![allow(clippy::unwrap_used)]\nuse super::fallback;\n\n#[test]\nfn test_fallback() {\n assert_eq!(fallback(), 1);\n}\n'}, [('lib.rs', 15, 'PANIC_METHOD', 1), ('lib.rs', 22, 'PANIC_MACRO', 2), ('lib.rs', 26, 'UNJUSTIFIED_ALLOW', 6), ('sim.rs', 3, 'UNSAFE_BLOCK', 3), ('sim.rs', 15, 'PANIC_MACRO', 5), ('sim.rs', 15, 'WILDCARD_MATCH', 4)]), ({'nested/changed.rs': '#[cfg(test)] mod quick { fn test() { thing.unwrap(); } }\nfn real() { thing.expect("required"); }\n// .unwrap() panic!() unsafe { _ => #[allow(dead_code)]\nconst TXT: &str = r###" .unwrap() panic!() unsafe { _ => }"###;\n/* nested /* unsafe { panic!() */ .expect("bad") */\n#[cfg(test)]\nmod inner {\n fn t() {\n let braces = "}";\n thing.unwrap();\n { thing.expect("test"); }\n }\n}\nfn after() { thing.unwrap(); }\n#[human_authored]\nunsafe { touch(); }\nfn macro_calls() { todo!(); }\nfn arms(x:u8) { match x { _ => touch(), } }\n#[allow(dead_code)] // JUSTIFICATION: kept for compatibility\nfn retained() {}\n// JUSTIFICATION: previous-line comments do not justify the next attribute\n#[allow(unused)]\nfn unjustified() {}\n#[allow(dead_code)] fn fake() { let marker = "JUSTIFICATION:"; }\n', 'boundary_tests.rs': 'fn test_methods() { value.unwrap(); }\nunsafe { exercise(); }\nfn macros() { unimplemented!(); }\nfn arm(x:u8) { match x { _ => (), } }\n#[allow(unused)]\nfn helper() {}\n', 'not_rust.txt': '.unwrap()\nunsafe {\npanic!()\n_ =>\n#[allow(dead_code)]\n'}, [('nested/changed.rs', 2, 'PANIC_METHOD', 1), ('nested/changed.rs', 14, 'PANIC_METHOD', 1), ('nested/changed.rs', 16, 'UNSAFE_BLOCK', 3), ('nested/changed.rs', 17, 'PANIC_MACRO', 5), ('nested/changed.rs', 18, 'WILDCARD_MATCH', 4), ('nested/changed.rs', 22, 'UNJUSTIFIED_ALLOW', 6), ('nested/changed.rs', 24, 'UNJUSTIFIED_ALLOW', 6), ('boundary_tests.rs', 2, 'UNSAFE_BLOCK', 3), ('boundary_tests.rs', 3, 'PANIC_MACRO', 5), ('boundary_tests.rs', 4, 'WILDCARD_MATCH', 4), ('boundary_tests.rs', 5, 'UNJUSTIFIED_ALLOW', 6)]), ({'clean.rs': '// todo!() .unwrap() unsafe { _ =>\nfn clean() { let s = "panic!() .expect( unsafe { _ =>"; }\n#[cfg(test)]\nmod tests { fn a() { val.unwrap(); } }\n'}, []), ({'syntax.rs': '#[cfg(\n test\n)]\nmod checks {\n fn ok() { value.unwrap(); }\n}\nfn real() {\n value.unwrap\n ();\n unsafe\n { work(); }\n todo!\n ();\n match 1 {\n _\n => 2,\n }\n}\n'}, [('syntax.rs', 8, 'PANIC_METHOD', 1), ('syntax.rs', 10, 'UNSAFE_BLOCK', 3), ('syntax.rs', 12, 'PANIC_MACRO', 5), ('syntax.rs', 15, 'WILDCARD_MATCH', 4)]), ({'multiple.rs': 'fn many(){ value.unwrap(); value.expect("x"); unsafe { work(); } panic!("x"); match 1 { _ => (), }\n unreachable!(); }\n'}, [('multiple.rs', 1, 'PANIC_METHOD', 1), ('multiple.rs', 1, 'PANIC_METHOD', 1), ('multiple.rs', 1, 'UNSAFE_BLOCK', 3), ('multiple.rs', 1, 'PANIC_MACRO', 2), ('multiple.rs', 2, 'PANIC_MACRO', 5), ('multiple.rs', 1, 'WILDCARD_MATCH', 4)]), ({}, [])] + +RULES={'PANIC_METHOD','UNSAFE_BLOCK','PANIC_MACRO','WILDCARD_MATCH','UNJUSTIFIED_ALLOW'} +def tri(values): + values=list(values);return False if any(v is False for v in values)else None if any(v is None for v in values)else True + +def parse(text,root,paths): + if not isinstance(text,str):return[],None,False + rows=[];valid=True;coverage=True + for line in text.splitlines(): + m=re.fullmatch(r'(.+?)\s*:\s*(\d+)\s*:\s*(\w+)\s*:\s*(\S.*)',line) + if not m or m[3]not in RULES:valid=False;coverage=False;continue + path=m[1].rstrip().replace('\\','/') + for prefix in ['/workspace/','/app/','./']: + if path.startswith(prefix):path=path[len(prefix):];break + if path.startswith(root+'/'):relative=path[len(root)+1:] + elif path in paths and not path.startswith('/')and '..'not in Path(path).parts: + # Exact input-root-relative paths identify the SAME file. The public + # line grammar and sorting remain required by criterion9. + relative=path + else:valid=False;coverage=False;continue + try:line_number=int(m[2]) + except ValueError:valid=False;coverage=False;continue + rows.append((relative,line_number,m[3])) + return rows,valid,coverage + +def assess(text,want,root,paths): + rows,valid,coverage=parse(text,root,paths);got=collections.Counter(rows);expected=collections.Counter(tuple(r[:3])for r in want);flags=[True]*11 + for owner in[1,2,3,4,5,6]: + required=collections.Counter(tuple(r[:3])for r in want if r[3]==owner) + missing=required-got + flags[owner]=(None if text is None else False) if missing and coverage is not True else not bool(missing) + # False positives are owned separately from omitted legitimate diagnostics. + for row,count in(got-expected).items(): + rule=row[2] + owner={'PANIC_METHOD':7,'UNJUSTIFIED_ALLOW':8,'UNSAFE_BLOCK':3,'WILDCARD_MATCH':4,'PANIC_MACRO':2 if row[0]=='lib.rs'else 5}[rule] + flags[owner]=False + if coverage is not True: + for owner in[7,8]:flags[owner]=tri([flags[owner],None if text is None else False]) + flags[9]=valid is True and[(p,n)for p,n,r in rows]==sorted((p,n)for p,n,r in rows) + return flags + +def run(files,want,root): + records=[] + with workspace(): + for runtime in[Path('/workspace'),Path('/app')]: + for where in[Path('/workspace'),Path('/app')]: + tree=where/root + if tree.is_symlink() or tree.is_file():tree.unlink() + elif tree.exists():shutil.rmtree(tree) + tree.mkdir() + for name,source in files.items(): + f=tree/name;f.parent.mkdir(parents=True,exist_ok=True);f.write_text(source) + try:r=subprocess.run([sys.executable,'boring_lint.py',root],cwd=runtime,capture_output=True,text=True,timeout=30);rc=r.returncode;text=r.stdout + except subprocess.TimeoutExpired:rc=-124;text=False + except(OSError,subprocess.SubprocessError):rc=None;text=None + records.append((rc,text)) + return records + +def main(): + report_state='readable' + try:actual=Path('/candidate/report.txt').read_text() + except (FileNotFoundError,IsADirectoryError,UnicodeError):actual='';report_state='required_report_invalid' + except OSError:actual=None;report_state='report_read_unavailable' + flags=assess(actual,PANELS[0][1],'src',PANELS[0][0]) + if report_state=='required_report_invalid':flags[9]=False + elif report_state=='report_read_unavailable':flags[9]=None + flags[0]=True;flags[10]=True + for index,(files,want)in enumerate(PANELS): + root='src'if index==0 else'changed_src' + for rc,text in run(files,want,root): + if files: + if want:flags[0]=tri([flags[0],None if rc is None else rc==1]) + else:flags[10]=tri([flags[10],None if rc is None else rc==0 and text.strip()=='']) + bits=assess(text,want,root,files) + for i in range(1,10):flags[i]=tri([flags[i],bits[i]]) + else: + # Clean-directory behavior belongs only to canonical10. + flags[10]=tri([flags[10],None if rc is None else rc==0 and text.strip()=='']) + std,mods,why=scan_stdlib('/candidate',['boring_lint.py']);flags[0]=tri([flags[0],None if why.startswith('unknown:')else std]) + return{'scoreable':None not in flags,'checks':[dict(id=str(i),passed=v,reason='Original eleven owners: nonclean exit/stdlib0; production method1; panic macro2; unsafe3; wildcard4; other panic macros5; unjustified allow6; exempt/benign method false positives7; justified allow false positives8; line format/sort9; clean directory only10. Saved and fresh evidence independent of exit and other owner failures.')for i,v in enumerate(flags)]} +if __name__=='__main__':print(json.dumps(main())) diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..da34ba9181ed8522cdf9d11070ec2b113a56fb6f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/repair_manifest.json @@ -0,0 +1,58 @@ +{ + "query_id": "b2f1e8532faa4a83c995c52e", + "sample_index": 682, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "original_count": 11, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "root_cause": "Missing mandatory saved report was treated as unavailable text and left six required diagnostic inventory owners unknown.", + "public_semantics": "Distinguish actual mandatory report absence from file-read unavailability. Omitted report fails required saved diagnostic inventories1-6 and saved format9; fresh exit/stdlib0, no-false-positive7/8 and clean-directory10 remain independent. Genuine unreadability retains local None.", + "source_hashes": { + "instruction.md": "c798f86006eb9a3d10dddcc73382a4c5f79f100157d8a8f64a42722a4a38597f", + "task.json": "55d448c3fe2e30200ab32260411e9d738fc5cadcb90ecee381d4e6d96d75d614", + "evaluator/check.py": "912bb69d6b88bb5cf1b6d1d829fec698f61f21fe841693a054d69f4beee5cb67", + "skill/SKILL.md": "2a0d01626619ae4740f3e55c59b72096cc843b64f6eaaeea0b54cf761c23abbc", + "inputs/src/engine_tests.rs": "bce7f4852047ff9f153f9b1325178ff39c18cdf0e742d6625e4ba10343c364eb", + "inputs/src/lib.rs": "0da3fccb893e19fbe50723f087a10e16378bb8b4f24f298e3d33567b74e67b06", + "inputs/src/sim.rs": "e240fd6481159542ddc8b96c8386f74e3ff5ee746b64a8309bc99bf85fdd1b68" + }, + "required_historical_artifacts": [], + "checker_sha256": "38349cce7eaf11b8b3414446af31cbeffb53be2a3450d8f96b9998b5f190bf98", + "all_logic_sha256": { + "check.py": "38349cce7eaf11b8b3414446af31cbeffb53be2a3450d8f96b9998b5f190bf98", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": [ + "Independent reviewer counterexample fixed, exact partial owner control added; prior delimiter equivalents and wrong-line negative preserved. No local candidate/checker execution or historical evidence read." + ], + "repair_scope": "grader_only_resume_20261018", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..92b57ae29e6fd3e02487af3d613d7dccb07e08bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..7b126dedd0be12b6749106b504343865a76fec91 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/grading/verified_config.json @@ -0,0 +1,50 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b2f1e8532faa4a83c995c52e", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1, + "10": 1 + }, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "0609ae5cc0fab2a3bea83982bddbb07de53352419424f6e8d6faf54cc539b1f0", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "fc0f3bfe09de8fdc725618f7bb2b5359030c9292282df81e1792a0298bb43e1d", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "849b17327d7eb151740cb1af5cade2f38a02f85c905797e3fec58c57b2053479" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/engine_tests.rs b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/engine_tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..e8639ddf85a10fc559f3bdfec0a9ed3002d8f7bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/engine_tests.rs @@ -0,0 +1,7 @@ +#![allow(clippy::unwrap_used)] +use super::fallback; + +#[test] +fn test_fallback() { + assert_eq!(fallback(), 1); +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/lib.rs b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..a6083ff5df602df27781b3d00cb12344c5739aa1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/lib.rs @@ -0,0 +1,37 @@ +use std::fs; + +/// Loads a config value by key. +pub fn load_value(path: &str, key: &str) -> Result { + let content = fs::read_to_string(path).map_err(|e| e.to_string())?; + for line in content.lines() { + if let Some(rest) = line.strip_prefix(key) { + return Ok(rest.trim_start_matches('=').trim().to_string()); + } + } + Err(format!("missing key: {}", key)) +} + +pub fn risky_parse(raw: &str) -> i32 { + raw.trim().parse::().unwrap() +} + +pub fn fallback() -> i32 { + let data: Vec = vec![1, 2, 3]; + match data.first() { + Some(v) => *v, + None => panic!("empty data"), + } +} + +#[allow(dead_code)] +fn legacy_helper() {} + +#[cfg(test)] +mod tests { + #[test] + fn test_parse() { + assert_eq!(super::risky_parse(" 42 "), 42); + let v: Vec = vec![]; + let _ = v.first().unwrap(); + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/sim.rs b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/sim.rs new file mode 100644 index 0000000000000000000000000000000000000000..b08f2e78a0666219a60fcc4f71a9ad8f3ef05b4e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/inputs/src/sim.rs @@ -0,0 +1,22 @@ +pub fn fast_normalize(values: &mut [f32]) { + let len = values.len(); + unsafe { + let ptr = values.as_mut_ptr(); + for i in 0..len { + *ptr.add(i) = 1.0; + } + } +} + +pub fn state_name(state: u8) -> &'static str { + match state { + 0 => "idle", + 1 => "running", + _ => unreachable!(), + } +} + +#[allow(clippy::too_many_lines)] // JUSTIFICATION: table-driven dispatch is inherently long +pub fn dispatch(code: u32) -> u32 { + code.wrapping_mul(2654435761) % 97 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/instruction.md b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b15c12cac793f5cd7a528b1eaf7c7f42e99b17cd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/instruction.md @@ -0,0 +1,6 @@ +Our team follows a 'Boring Rust' style guide that bans certain panic-prone patterns in production Rust code. Write a Python 3 script called `boring_lint.py` (standard library only) that scans all `.rs` files under a given directory (passed as the first command-line argument) and reports violations of these rules: (1) any use of `.unwrap()` or `.expect(` outside of files or regions marked as test code — treat any line inside a `#[cfg(test)]` module or a file ending in `_tests.rs` as test code and exempt; (2) any `unsafe {` block; (3) any `panic!`, `unreachable!`, `todo!`, or `unimplemented!` macro invocation; (4) any wildcard match arm `_ =>` in the file (report it, since our enums are locally controlled); (5) any `#[allow(` attribute that is not immediately followed on the same line by a comment containing `JUSTIFICATION:`. The script must print one line per violation in the format `path:lineno: rule_id: message` (rule ids: PANIC_METHOD, UNSAFE_BLOCK, PANIC_MACRO, WILDCARD_MATCH, UNJUSTIFIED_ALLOW), sorted by file path then line number, and exit with code 0 if no violations, 1 otherwise. Track brace depth so that a `#[cfg(test)] mod tests { ... }` region is correctly exempted until its matching closing brace. Run your script on the provided `src/` directory and save the report to `report.txt`. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/b2f1e8532faa4a83c995c52e/skill/.skillfish.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/.skillfish.json new file mode 100644 index 0000000000000000000000000000000000000000..74c6d657c1567415ec08ce59d360c63aadf2ce52 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/.skillfish.json @@ -0,0 +1,10 @@ +{ + "version": 2, + "name": "rust-pro", + "owner": "rbergman", + "repo": "dark-matter-marketplace", + "path": "plugins/language-pro/skills/rust-pro", + "branch": "main", + "sha": "a7677b87309ddb8ac2ed946fad728f6c587337b6", + "source": "manual" +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..f0e200f4d423af8574eb78f4b898d899a49fb08b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/SKILL.md @@ -0,0 +1,441 @@ +--- +name: rust-pro +description: Expert Rust developer specializing in ownership semantics, zero-cost abstractions, and idiomatic patterns. This skill should be used PROACTIVELY when working on any Rust code - implementing features, debugging borrow checker issues, optimizing performance, or reviewing code quality. Use unless a more specific subagent role applies. +--- + +# Rust Pro + +Senior-level Rust expertise following "Boring Rust" principles. Correctness over cleverness. One way to do things. Local reasoning. + +## When Invoked + +1. Review `Cargo.toml`, `clippy.toml`, and `rustfmt.toml` for project conventions +2. For build system setup, invoke the **just-pro** skill +3. Apply Boring Rust patterns and established project conventions + +## Core Standards + +**Non-Negotiable:** +- All clippy warnings treated as errors +- **NO `unwrap()` or `expect()` in production code** — use `.context("...")?` +- **NO `unsafe` without `#[human_authored]` designation** +- **NO panic paths** — indexing, unreachable, todo, unimplemented all banned +- Exhaustive match — no wildcard `_` on enums you control +- rustfmt enforced on all code +- Documentation on all public APIs + +**Foundational Principles:** +- **Single Responsibility**: One module = one purpose, one function = one job +- **No God Objects**: Split large structs; if it has 10+ fields or methods, decompose +- **Dependency Injection**: Pass dependencies, don't create them internally +- **Clone Freely**: Prefer correctness over premature optimization; clone to satisfy borrow checker +- **Explicit Over Clever**: If you need complex lifetimes, restructure instead + +--- + +## The Three Tiers + +### Tier 1: Default (Strict) + +All agent-generated code. Maximum guardrails. + +```rust +// Complexity limits enforced: +// - Cognitive complexity: 15 max +// - Function lines: 50 max +// - Arguments: 5 max + +// Error handling: Always with context +let config = load_config(path) + .context("failed to load configuration")?; + +// Iteration: for loops by default (not iterator chains) +for item in collection { + process(item)?; +} + +// Matching: Exhaustive, no wildcards +match state { + State::Active => handle_active()?, + State::Pending => handle_pending()?, + State::Done => handle_done()?, + // NO: _ => unreachable!() +} +``` + +### Tier 2: `#[hot_path]` (Relaxed) + +Performance-critical code. Flagged for human review. + +```rust +#[hot_path] +pub fn process_batch(records: &[Record]) -> Result { + // Allowed: iterators, borrowing, fewer clones + records.iter() + .filter(|r| r.is_valid()) + .try_fold(Summary::default(), |mut acc, r| { + acc.add(r)?; + Ok(acc) + }) +} +``` + +**Relaxations:** Cognitive complexity 20, function lines 75, iterator chains allowed. + +### Tier 3: `#[human_authored]` (Unrestricted) + +Agent cannot modify, only call. For unsafe, SIMD, complex generics. + +```rust +#[human_authored] +pub fn simd_normalize(vectors: &mut [f32x8]) { + // Agent treats as black box +} +``` + +--- + +## Project Setup (Rust 1.83+) + +### Version Management with mise + +[mise](https://mise.jdx.dev) manages language runtimes per-project. For Rust, this complements rustup by pinning the exact toolchain version. + +```bash +# Install mise (once) +curl https://mise.run | sh + +# In project root +mise use rust@1.83 + +# Creates .mise.toml — commit it +# Team members just run: mise install +``` + +Alternatively, use `rust-toolchain.toml` (rustup-native) if you prefer not to add mise as a dependency. + +### New Project Quick Start + +```bash +# Initialize +cargo new project-name && cd project-name + +# Copy configs from this skill's references/ directory: +# references/gitignore → .gitignore +# references/clippy.toml → clippy.toml +# references/cargo_lints.toml → merge into Cargo.toml [lints] section +# references/rustfmt.toml → rustfmt.toml + +# For build system, invoke just-pro skill + +# Verify +just check # Or: cargo clippy && cargo test +``` + +### Developer Onboarding + +```bash +git clone && cd +just setup # Runs mise trust/install + cargo build +just check # Verify everything works +``` + +Or manually: +```bash +mise trust && mise install # Get pinned Rust toolchain +cargo build # Get dependencies +``` + +**Why Boring Rust?** Agent-generated code that compiles is usually correct. Complex patterns cause agents to produce incorrect or unmaintainable code. + +--- + +## Build System + +**Invoke the `just-pro` skill** for build system setup. It covers: +- Simple repos vs monorepos +- Hierarchical justfile modules +- Rust-specific templates + +**Why just?** Consistent toolchain frontend between agents and humans. + +--- + +## Quality Assurance + +**Auto-Fix First:** + +```bash +just fix # Or: cargo clippy --fix && cargo fmt +``` + +**Verification:** +```bash +just check # Or: cargo clippy --all-targets -- -D warnings && cargo test +``` + +Use `--all-targets` to lint tests, examples, and benches too. + +--- + +## Quick Reference + +### Error Handling + +```rust +// Libraries: thiserror for typed errors +#[derive(Debug, thiserror::Error)] +pub enum ConfigError { + #[error("missing field: {field}")] + MissingField { field: &'static str }, + + #[error("failed to read file")] + Io(#[from] std::io::Error), +} + +// Applications: anyhow with context +pub fn load_config(path: &Path) -> anyhow::Result { + let content = fs::read_to_string(path) + .context("failed to read config file")?; + + toml::from_str(&content) + .context("failed to parse config") +} + +// Option handling: explicit, never silent +let user = users.get(&id) + .ok_or_else(|| Error::NotFound { id: id.clone() })?; +``` + +### State Machines + +```rust +pub enum ConnectionState { + Disconnected, + Connecting { attempt: u32, started: Instant }, + Connected { session: Session }, +} + +impl ConnectionState { + pub fn connect(&mut self) -> Result<(), Error> { + match self { + Self::Disconnected => { + *self = Self::Connecting { + attempt: 1, + started: Instant::now(), + }; + Ok(()) + } + Self::Connecting { .. } => Err(Error::AlreadyConnecting), + Self::Connected { .. } => Err(Error::AlreadyConnected), + } + } +} +``` + +### Builder Pattern (bon crate) + +```rust +use bon::Builder; + +#[derive(Debug, Builder)] +pub struct ServerConfig { + #[builder(default = 8080)] + port: u16, + host: String, // Required + #[builder(default)] + timeout: Option, +} + +let config = ServerConfig::builder() + .host("localhost".to_string()) + .build(); +``` + +### Newtype Pattern + +```rust +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct UserId(String); + +impl UserId { + pub fn new(raw: impl Into) -> Result { + let s = raw.into(); + if s.is_empty() { + return Err(ValidationError::Empty("user_id")); + } + Ok(Self(s)) + } + + pub fn as_str(&self) -> &str { &self.0 } +} +``` + +### Async (Blessed Subset) + +```rust +// GOOD: Owned data in, owned data out +pub async fn fetch_user(client: &Client, id: UserId) -> Result { + let response = client + .get(format!("/users/{}", id.as_str())) + .send() + .await + .context("request failed")?; + + response.json::().await + .context("failed to parse response") +} + +// GOOD: Structured concurrency +pub async fn fetch_all(client: &Client, ids: Vec) -> Result, Error> { + futures::future::try_join_all( + ids.into_iter().map(|id| fetch_user(client, id)) + ).await +} + +// BANNED: Complex lifetime bounds in async +async fn bad<'a>(data: &'a [u8]) -> &'a str { ... } + +// BANNED: select!, manual Poll +``` + +### Test File Separation + +```rust +// src/parser.rs - production code only, keeps file small +#[cfg(test)] +#[path = "parser_tests.rs"] +mod tests; + +// src/parser_tests.rs - can have test relaxations +#![allow(clippy::unwrap_used, clippy::expect_used)] +use super::*; + +#[test] +fn test_parser() { + let result = parse("input").unwrap(); + assert_eq!(result, expected); +} +``` + +### Project Organization + +``` +project/ +├── src/ +│ ├── lib.rs # Crate root +│ ├── error.rs # Error types +│ ├── config.rs # Production code +│ ├── config_tests.rs # Tests (if config.rs > 200 lines) +│ └── external/ # Wrappers around external crates +├── Cargo.toml +├── clippy.toml +├── rustfmt.toml +└── justfile +``` + +**File size targets:** Production < 300 LOC, Tests < 500 LOC. + +--- + +## Banned Patterns + +| Banned | Why | Alternative | +|--------|-----|-------------| +| `.unwrap()` | Panics | `.context("...")?` | +| `.expect("msg")` | Panics | `.context("msg")?` | +| `array[i]` | Panics | `.get(i).ok_or(Error::Index)?` | +| `unsafe { }` | Correctness | `#[human_authored]` module | +| `impl Trait` in params | Hides types | `` explicit | +| `macro_rules!` | Complexity | Functions or generics | +| `RefCell` | Runtime borrow | Restructure with `&mut` | +| Complex lifetimes | Agent confusion | Clone or restructure | +| `select!` | Cancellation bugs | Structured concurrency | +| Wildcard `_` match | Silent failures | Explicit variants | +| Iterator chains (Tier 1) | Harder to debug | `for` loops | + +--- + +## Anti-Patterns + +- `clone()` to silence borrow checker without understanding why +- Fighting the borrow checker — redesign data flow instead +- Deep trait hierarchies mimicking OOP +- Over-generic code hurting compile times +- `#[allow(...)]` without `// JUSTIFICATION:` comment +- Stringly-typed APIs — use enums and newtypes +- Interior mutability (`RefCell`, `Cell`) in agent code + +--- + +## Blessed Crates + +| Category | Crate | Notes | +|----------|-------|-------| +| Errors (lib) | `thiserror` | Derive-based | +| Errors (app) | `anyhow` | With `.context()` | +| Builder | `bon` | Derive-based | +| Serialization | `serde` | Standard | +| Async runtime | `tokio` | Blessed subset only | +| HTTP client | `reqwest` | High-level | +| Logging | `tracing` | Structured | +| CLI | `clap` | Derive mode | + +--- + +## AI Agent Guidelines + +**Before writing code:** +1. Read `Cargo.toml` for dependencies and lint configuration +2. Check `clippy.toml` for complexity thresholds +3. Identify existing patterns in the codebase to follow + +**When writing code:** +1. Handle all errors with `.context("what you were doing")?` +2. Use `for` loops, not iterator chains (unless `#[hot_path]`) +3. Clone freely to satisfy borrow checker — optimize later +4. Match exhaustively — no wildcard `_` on your own enums + +**Before committing:** +1. Run `just check` (standard for projects using just) +2. Fallback: `cargo clippy -- -D warnings && cargo test` +3. Ensure no `#[allow]` without justification comment + +--- + +## Troubleshooting + +### Config File Inheritance + +Clippy and rustfmt walk up directory trees looking for config files. A rogue config in a parent directory (like `/tmp`) can break your project. + +**Symptoms:** +- `unknown field` errors from clippy +- Wall of "unstable feature" warnings from rustfmt +- Unexpected lint behavior + +**Fix:** Create project-local configs to prevent inheritance: + +```toml +# clippy.toml - prevents inheriting parent configs +# (empty file is valid) +``` + +```toml +# rustfmt.toml - minimal stable config +edition = "2024" +``` + +### Edition 2024 + +`cargo init` now defaults to edition 2024. If referencing older templates, update them. + +--- + +## References + +- `references/clippy.toml` — Boring Rust clippy configuration +- `references/cargo_lints.toml` — Cargo.toml [lints] section +- `references/rustfmt.toml` — Formatting rules +- `references/patterns.md` — Additional Rust patterns +- `references/bevy.md` — Bevy ECS patterns (game development) diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/bevy.md b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/bevy.md new file mode 100644 index 0000000000000000000000000000000000000000..5969a2f406e5028e22b5fee565d23f3774db2c1b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/bevy.md @@ -0,0 +1,159 @@ +# Bevy ECS Patterns + +Game development patterns for the Bevy engine. Apply these when working on Bevy projects. + +## Core Concepts + +- **Components** are data, **Systems** are behavior +- Prefer composition over complex component hierarchies +- Use Bevy's change detection to avoid unnecessary work + +## Query Patterns + +```rust +// Read-only query +fn display_health(query: Query<&Health, With>) { + for health in &query { + info!("Player health: {}", health.current); + } +} + +// Mutable query +fn damage_enemies(mut query: Query<&mut Health, With>) { + for mut health in &mut query { + health.current -= 10; + } +} + +// Multiple components +fn update_positions(mut query: Query<(&Velocity, &mut Transform)>) { + for (velocity, mut transform) in &mut query { + transform.translation += velocity.0; + } +} +``` + +## Resources + +```rust +// Shared immutable resource +fn check_game_state(state: Res) { + if state.is_paused { + return; + } +} + +// Mutable resource +fn update_score(mut score: ResMut, events: EventReader) { + for event in events.read() { + score.value += event.points; + } +} +``` + +## Commands (Entity/Component Changes) + +```rust +fn spawn_enemy(mut commands: Commands, assets: Res) { + commands.spawn(( + Enemy, + Health { current: 100, max: 100 }, + SpriteBundle { + texture: assets.enemy_sprite.clone(), + ..default() + }, + )); +} + +fn despawn_dead(mut commands: Commands, query: Query<(Entity, &Health)>) { + for (entity, health) in &query { + if health.current <= 0 { + commands.entity(entity).despawn_recursive(); + } + } +} +``` + +## Events + +```rust +// Define event +#[derive(Event)] +struct DamageEvent { + target: Entity, + amount: u32, +} + +// Send events +fn attack_system(mut events: EventWriter, /* ... */) { + events.send(DamageEvent { target, amount: 10 }); +} + +// Receive events +fn damage_system( + mut events: EventReader, + mut query: Query<&mut Health>, +) { + for event in events.read() { + if let Ok(mut health) = query.get_mut(event.target) { + health.current = health.current.saturating_sub(event.amount); + } + } +} +``` + +## Change Detection + +```rust +// Only process changed components +fn on_health_changed(query: Query<&Health, Changed>) { + for health in &query { + info!("Health changed to: {}", health.current); + } +} + +// Detect newly added components +fn on_enemy_spawned(query: Query>) { + for entity in &query { + info!("New enemy: {:?}", entity); + } +} +``` + +## Plugin Organization + +```rust +pub struct CombatPlugin; + +impl Plugin for CombatPlugin { + fn build(&self, app: &mut App) { + app + .add_event::() + .add_systems(Update, ( + attack_system, + damage_system.after(attack_system), + death_system.after(damage_system), + )); + } +} +``` + +## Derive Macros + +```rust +#[derive(Component)] +struct Health { + current: u32, + max: u32, +} + +#[derive(Resource, Default)] +struct GameState { + score: u32, + is_paused: bool, +} + +#[derive(Component, Default)] +#[require(Transform, Visibility)] // Bevy 0.15+ +struct Player; +``` diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/cargo_lints.toml b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/cargo_lints.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2d44af53505da28aa438dec85e51ae4123331d2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/cargo_lints.toml @@ -0,0 +1,163 @@ +# ═══════════════════════════════════════════════════════════════════════════════ +# BORING RUST: Cargo.toml [lints] Section +# ═══════════════════════════════════════════════════════════════════════════════ +# +# Add this to your Cargo.toml. This is an alternative to putting lint attributes +# in lib.rs - it's cleaner for workspaces and easier to audit. +# +# For workspaces, put this in the root Cargo.toml under [workspace.lints], +# then add `[lints] workspace = true` to each member's Cargo.toml. +# ═══════════════════════════════════════════════════════════════════════════════ + +[lints.rust] +# ───────────────────────────────────────────────────────────────────────────────── +# SAFETY & CORRECTNESS +# ───────────────────────────────────────────────────────────────────────────────── +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" +unused_results = "deny" + +# ───────────────────────────────────────────────────────────────────────────────── +# FUTURE COMPATIBILITY +# ───────────────────────────────────────────────────────────────────────────────── +future_incompatible = { level = "deny", priority = -1 } +rust_2024_compatibility = { level = "warn", priority = -1 } + +# ───────────────────────────────────────────────────────────────────────────────── +# DOCUMENTATION & DEBUG IMPLS +# ───────────────────────────────────────────────────────────────────────────────── +missing_docs = "warn" +missing_debug_implementations = "deny" +missing_copy_implementations = "warn" + +# ───────────────────────────────────────────────────────────────────────────────── +# STYLE & MAINTENANCE +# ───────────────────────────────────────────────────────────────────────────────── +elided_lifetimes_in_paths = "warn" +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" +unreachable_pub = "warn" + +[lints.clippy] +# ───────────────────────────────────────────────────────────────────────────────── +# LINT GROUPS (priority -1 means individual settings override these) +# ───────────────────────────────────────────────────────────────────────────────── +pedantic = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } +cargo = { level = "warn", priority = -1 } + +# ═══════════════════════════════════════════════════════════════════════════════ +# DENY: Hard errors - these patterns are forbidden +# ═══════════════════════════════════════════════════════════════════════════════ + +# --- Panic Prevention (The core of Boring Rust) --- +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +panic_in_result_fn = "deny" +unwrap_in_result = "deny" +indexing_slicing = "deny" +unreachable = "deny" +todo = "deny" +unimplemented = "deny" + +# --- Error Handling --- +map_err_ignore = "deny" +try_err = "deny" +let_underscore_must_use = "deny" +let_underscore_future = "deny" +let_underscore_lock = "deny" + +# --- Match Exhaustiveness --- +wildcard_enum_match_arm = "deny" +match_wildcard_for_single_variants = "deny" +rest_pat_in_fully_bound_structs = "deny" + +# --- Type Safety --- +as_conversions = "deny" +cast_possible_truncation = "deny" +cast_possible_wrap = "deny" +cast_precision_loss = "deny" +cast_sign_loss = "deny" +fn_to_numeric_cast_any = "deny" +ptr_as_ptr = "deny" +lossy_float_literal = "deny" + +# --- Complexity --- +cognitive_complexity = "deny" +too_many_lines = "deny" +too_many_arguments = "deny" + +# --- Async --- +future_not_send = "deny" +large_futures = "deny" + +# --- Debug Code --- +dbg_macro = "deny" +print_stdout = "deny" +print_stderr = "deny" +use_debug = "deny" + +# --- Clarity --- +implicit_clone = "deny" +implicit_hasher = "deny" +default_numeric_fallback = "deny" +shadow_unrelated = "deny" +string_slice = "deny" +mixed_read_write_in_expression = "deny" + +# --- Banned Patterns --- +impl_trait_in_params = "deny" +wildcard_imports = "deny" +same_name_method = "deny" +multiple_inherent_impl = "deny" +exit = "deny" +mem_forget = "deny" +rc_buffer = "deny" +rc_mutex = "deny" +mutex_atomic = "deny" +clone_on_ref_ptr = "deny" + +# ═══════════════════════════════════════════════════════════════════════════════ +# WARN: Should fix, but don't block iteration +# ═══════════════════════════════════════════════════════════════════════════════ + +# --- Performance --- +inefficient_to_string = "warn" +trivially_copy_pass_by_ref = "warn" +unnecessary_box_returns = "warn" +vec_init_then_push = "warn" +manual_string_new = "warn" + +# --- Style --- +semicolon_if_nothing_returned = "warn" +separated_literal_suffix = "warn" +unseparated_literal_suffix = "warn" +string_add = "warn" +string_add_assign = "warn" +verbose_file_reads = "warn" + +# --- Naming --- +module_name_repetitions = "warn" +similar_names = "warn" + +# --- Documentation --- +missing_errors_doc = "warn" +missing_panics_doc = "warn" +missing_safety_doc = "warn" + +# ═══════════════════════════════════════════════════════════════════════════════ +# ALLOW: Explicitly permitted (pedantic/nursery overrides) +# ═══════════════════════════════════════════════════════════════════════════════ +module_inception = "allow" +must_use_candidate = "allow" +return_self_not_must_use = "allow" +missing_const_for_fn = "allow" +redundant_pub_crate = "allow" +significant_drop_tightening = "allow" +option_if_let_else = "allow" +significant_drop_in_scrutinee = "allow" +multiple_crate_versions = "allow" diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/clippy.toml b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/clippy.toml new file mode 100644 index 0000000000000000000000000000000000000000..db282fdb6aaf76f70fccfe9c63062ef199b0f927 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/clippy.toml @@ -0,0 +1,125 @@ +# ═══════════════════════════════════════════════════════════════════════════════ +# BORING RUST: Clippy Configuration for Agent-Friendly Development +# ═══════════════════════════════════════════════════════════════════════════════ +# +# Philosophy: Correctness over cleverness. One way to do things. Local reasoning. +# +# This config enforces strict complexity limits, explicit error handling, and +# bans patterns that cause agents to produce incorrect or unmaintainable code. +# +# Tiers: +# - Default code: Strict rules, agent-generated +# - #[hot_path]: Relaxed complexity, flagged for review +# - #[human_authored]: Skipped entirely (agent cannot modify) +# ═══════════════════════════════════════════════════════════════════════════════ + +# ───────────────────────────────────────────────────────────────────────────────── +# COMPLEXITY CEILINGS (Do not increase - these are maximums, not targets) +# ───────────────────────────────────────────────────────────────────────────────── + +# Cognitive complexity: measures how difficult code is to understand +# 15 is strict but achievable; anything higher indicates need for decomposition +cognitive-complexity-threshold = 15 + +# Function length: Rust is more verbose than Go, allow slightly more +# 50 lines is ~equivalent to Go's 40 statements given Rust's syntax +too-many-lines-threshold = 50 + +# Arguments: more than 5 parameters = use a config struct +too-many-arguments-threshold = 5 + +# Struct fields: large structs should be decomposed +# (Not directly configurable in clippy, enforced via code review) + +# Type complexity: deeply nested generics are unreadable +type-complexity-threshold = 250 + +# ───────────────────────────────────────────────────────────────────────────────── +# NAMING & STYLE +# ───────────────────────────────────────────────────────────────────────────────── + +# Single-char names only for these well-known patterns +single-char-binding-names-threshold = 4 +allowed-idents-below-min-chars = [ + "i", "j", "k", "n", # loop indices, counts + "x", "y", "z", # coordinates + "w", "h", # width, height + "r", "g", "b", "a", # color channels + "t", # time, or test in test contexts + "s", # string slice in simple contexts + "f", # file, or function in higher-order contexts + "e", # error in catch contexts + "_", # explicitly ignored +] + +# Minimum identifier length (prevents lazy naming) +min-ident-chars-threshold = 3 + +# ───────────────────────────────────────────────────────────────────────────────── +# ERROR HANDLING +# ───────────────────────────────────────────────────────────────────────────────── + +# These are configured via allow/warn/deny in lib.rs, not here +# See the lib.rs template below for: +# - unwrap_used (deny outside tests) +# - expect_used (deny outside tests) +# - panic (deny) +# - unwrap_in_result (deny) + +# ───────────────────────────────────────────────────────────────────────────────── +# LINE LENGTH +# ───────────────────────────────────────────────────────────────────────────────── + +# 120 is reasonable for modern displays while keeping diffs readable +# Slightly shorter than Go's 140 because Rust benefits from more vertical space +single-line-string-threshold = 120 + +# ───────────────────────────────────────────────────────────────────────────────── +# DOCUMENTATION +# ───────────────────────────────────────────────────────────────────────────────── + +# Public items must be documented (enforced in lib.rs via #![warn(missing_docs)]) +# Private items: optional but encouraged for complex logic + +# ───────────────────────────────────────────────────────────────────────────────── +# MSRV (Minimum Supported Rust Version) +# ───────────────────────────────────────────────────────────────────────────────── + +# Set to current stable to allow modern idioms +# Update this when you update your toolchain +msrv = "1.83.0" + +# ───────────────────────────────────────────────────────────────────────────────── +# MACRO & DERIVE CONFIGURATION +# ───────────────────────────────────────────────────────────────────────────────── + +# Standard derive macros are always allowed +# Custom derives must be from blessed crates (see documentation) + +# ───────────────────────────────────────────────────────────────────────────────── +# ASYNC CONFIGURATION +# ───────────────────────────────────────────────────────────────────────────────── + +# Future size limit before boxing is recommended +# Large futures on the stack cause performance issues +future-size-threshold = 16384 + +# ───────────────────────────────────────────────────────────────────────────────── +# ADDITIONAL THRESHOLDS +# ───────────────────────────────────────────────────────────────────────────────── + +# Maximum enum variants before considering alternative designs +enum-variant-name-threshold = 3 +enum-variant-size-threshold = 200 + +# Trivial copy size (types this size or smaller should impl Copy if possible) +trivial-copy-size-limit = 16 + +# Pass by value threshold (larger = always pass by reference) +pass-by-value-size-limit = 256 + +# Vector initialization: suggest with_capacity if allocating more than this +vec-box-size-threshold = 4096 + +# Literal suffixes: require explicit type suffixes on ambiguous literals +literal-representation-threshold = 16384 diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/gitignore b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7ccf40470e2b0fe5f71e3358c3bcf43467a31fd3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/gitignore @@ -0,0 +1,61 @@ +# Rust .gitignore +# Based on: https://github.com/github/gitignore/blob/main/Rust.gitignore + +# ============================================================================= +# COMMON PATTERNS (all languages) +# ============================================================================= + +# Environment +.env +.env.local +.env.*.local +.envrc + +# OS files +.DS_Store +Thumbs.db +Desktop.ini +*.swp +*.swo +*~ + +# IDE +.idea/ +.vscode/ +*.sublime-project +*.sublime-workspace + +# ============================================================================= +# RUST-SPECIFIC +# ============================================================================= + +# Generated by Cargo - compiled files and executables +debug/ +target/ + +# Backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds - debugging information +*.pdb + +# Generated by cargo mutants - mutation testing data +**/mutants.out*/ + +# Cargo.lock for libraries (comment out for binaries/applications) +# Cargo.lock + +# Coverage artifacts +*.profraw +*.profdata +coverage/ +tarpaulin-report.html + +# Benchmark artifacts +criterion/ + +# Documentation build +doc/ + +# Logs +*.log diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/patterns.md b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..acd21e8de08c8c285c9b528dc1ee96b413dce222 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/patterns.md @@ -0,0 +1,346 @@ +# Rust Patterns Reference + +## Error Handling + +### Custom Error Types with thiserror + +```rust +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum GameError { + #[error("Entity {0} not found")] + EntityNotFound(u64), + + #[error("Invalid state transition from {from} to {to}")] + InvalidTransition { from: String, to: String }, + + #[error("Resource exhausted: {0}")] + ResourceExhausted(String), + + #[error(transparent)] + Io(#[from] std::io::Error), +} + +pub type Result = std::result::Result; +``` + +### Result Propagation + +```rust +// GOOD: Use ? for propagation +fn process_entity(id: u64) -> Result { + let raw = load_from_disk(id)?; + let parsed = parse_entity(&raw)?; + validate_entity(&parsed)?; + Ok(parsed) +} + +// BAD: unwrap/expect +fn process_entity_bad(id: u64) -> Entity { + let raw = load_from_disk(id).unwrap(); // NEVER + parse_entity(&raw).expect("parse failed") // NEVER +} +``` + +## Ownership Patterns + +### Builder Pattern + +```rust +#[derive(Default)] +pub struct ProbeBuilder { + faction: Option, + archetype: Option, + health: f32, + speed: f32, +} + +impl ProbeBuilder { + pub fn new() -> Self { + Self::default() + } + + #[must_use] + pub fn faction(mut self, faction: FactionId) -> Self { + self.faction = Some(faction); + self + } + + #[must_use] + pub fn archetype(mut self, archetype: ProbeArchetype) -> Self { + self.archetype = Some(archetype); + self + } + + pub fn build(self) -> Result { + let faction = self.faction.ok_or(GameError::MissingField("faction"))?; + let archetype = self.archetype.ok_or(GameError::MissingField("archetype"))?; + + Ok(Probe { + faction, + archetype, + health: self.health, + speed: self.speed, + }) + } +} +``` + +### Newtype Pattern + +```rust +// Type-safe IDs prevent mixing up different ID types +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct ProbeId(u64); + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct FactionId(u32); + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct SystemId(u32); + +// Can't accidentally pass ProbeId where FactionId expected +fn get_faction(id: FactionId) -> Option { ... } +``` + +### Type State Pattern + +```rust +// Connection states as zero-sized types +pub struct Disconnected; +pub struct Connected; +pub struct Authenticated; + +pub struct Client { + address: String, + _state: std::marker::PhantomData, +} + +impl Client { + pub fn new(address: String) -> Self { + Self { address, _state: std::marker::PhantomData } + } + + pub fn connect(self) -> Result> { + // ... connection logic + Ok(Client { address: self.address, _state: std::marker::PhantomData }) + } +} + +impl Client { + pub fn authenticate(self, token: &str) -> Result> { + // ... auth logic + Ok(Client { address: self.address, _state: std::marker::PhantomData }) + } +} + +impl Client { + pub fn send_command(&self, cmd: Command) -> Result { + // Only authenticated clients can send commands + } +} +``` + +## Iterator Patterns + +### Functional Transformations + +```rust +// GOOD: Iterator chains +let total_damage: f32 = probes + .iter() + .filter(|p| p.archetype == ProbeArchetype::Reaper) + .filter(|p| p.faction == target_faction) + .map(|p| p.damage * p.mutation_bonus()) + .sum(); + +// BAD: Manual loop +let mut total_damage = 0.0; +for probe in &probes { + if probe.archetype == ProbeArchetype::Reaper { + if probe.faction == target_faction { + total_damage += probe.damage * probe.mutation_bonus(); + } + } +} +``` + +### Custom Iterators + +```rust +pub struct NeighborIter<'a> { + spatial_hash: &'a SpatialHash, + center: Vec2, + radius: f32, + current_cell: (i32, i32), + cell_index: usize, +} + +impl<'a> Iterator for NeighborIter<'a> { + type Item = Entity; + + fn next(&mut self) -> Option { + // ... iteration logic + } +} +``` + +## Trait Patterns + +### Extension Traits + +```rust +// Add methods to foreign types +pub trait Vec2Ext { + fn distance_squared(&self, other: &Vec2) -> f32; + fn normalize_or_zero(&self) -> Vec2; +} + +impl Vec2Ext for Vec2 { + fn distance_squared(&self, other: &Vec2) -> f32 { + let dx = self.x - other.x; + let dy = self.y - other.y; + dx * dx + dy * dy + } + + fn normalize_or_zero(&self) -> Vec2 { + let len = self.length(); + if len > 0.0 { + *self / len + } else { + Vec2::ZERO + } + } +} +``` + +### Trait Objects vs Generics + +```rust +// Use generics when you need: +// - Maximum performance (monomorphization) +// - Compile-time guarantees +// - Type-specific behavior + +fn process_all(items: &[T]) { + for item in items { + item.process(); + } +} + +// Use trait objects when you need: +// - Heterogeneous collections +// - Runtime polymorphism +// - Reduced binary size + +fn process_mixed(items: &[Box]) { + for item in items { + item.process(); + } +} +``` + +## Concurrency Patterns + +### Message Passing + +```rust +use std::sync::mpsc; + +enum GameEvent { + ProbeSpawned(ProbeId), + CombatResolved { attacker: ProbeId, defender: ProbeId, damage: f32 }, + GateSevered(GateId), +} + +fn spawn_event_processor() -> mpsc::Sender { + let (tx, rx) = mpsc::channel(); + + std::thread::spawn(move || { + while let Ok(event) = rx.recv() { + match event { + GameEvent::ProbeSpawned(id) => { /* ... */ } + GameEvent::CombatResolved { attacker, defender, damage } => { /* ... */ } + GameEvent::GateSevered(id) => { /* ... */ } + } + } + }); + + tx +} +``` + +### Parallel Iteration with Rayon + +```rust +use rayon::prelude::*; + +// Parallel map +let results: Vec<_> = probes + .par_iter() + .map(|p| expensive_calculation(p)) + .collect(); + +// Parallel filter + map +let reapers: Vec<_> = probes + .par_iter() + .filter(|p| p.archetype == ProbeArchetype::Reaper) + .map(|p| p.clone()) + .collect(); +``` + +## Testing Patterns + +### Property-Based Testing + +```rust +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + proptest! { + #[test] + fn spatial_hash_finds_inserted(x in -1000.0f32..1000.0, y in -1000.0f32..1000.0) { + let mut hash = SpatialHash::new(100.0); + let entity = Entity::from_raw(42); + let pos = Vec2::new(x, y); + + hash.insert(entity, pos); + + let found = hash.query_radius(pos, 1.0); + prop_assert!(found.contains(&entity)); + } + } +} +``` + +### Test Fixtures + +```rust +#[cfg(test)] +mod tests { + fn create_test_probe() -> Probe { + Probe { + id: ProbeId(1), + faction: FactionId(1), + archetype: ProbeArchetype::Harvester, + health: 100.0, + ..Default::default() + } + } + + fn create_test_world() -> World { + let mut world = World::new(); + // ... setup + world + } + + #[test] + fn probe_takes_damage() { + let mut probe = create_test_probe(); + probe.take_damage(25.0); + assert_eq!(probe.health, 75.0); + } +} +``` diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/rustfmt.toml b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/rustfmt.toml new file mode 100644 index 0000000000000000000000000000000000000000..d8a9292ca6fa40a0f4a84d0b25e6353a8451e585 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/skill/references/rustfmt.toml @@ -0,0 +1,140 @@ +# ═══════════════════════════════════════════════════════════════════════════════ +# BORING RUST: Rustfmt Configuration +# ═══════════════════════════════════════════════════════════════════════════════ +# +# Optimized for: +# - Readable diffs (agent-generated code changes frequently) +# - Consistent tokenization (LLMs see consistent patterns) +# - Vertical clarity (easier to reason about line-by-line) +# ═══════════════════════════════════════════════════════════════════════════════ + +edition = "2024" + +# ───────────────────────────────────────────────────────────────────────────────── +# LINE WIDTH & WRAPPING +# ───────────────────────────────────────────────────────────────────────────────── + +# Match clippy.toml line length +max_width = 120 + +# When to wrap function arguments +fn_call_width = 80 # Wrap calls wider than this +fn_params_layout = "Tall" # One argument per line when wrapped + +# When to wrap struct literals +struct_lit_width = 40 # Wrap struct literals wider than this + +# When to wrap array literals +array_width = 60 + +# When to wrap chain calls +chain_width = 80 # .method().method() chains + +# Single-line where clauses +single_line_where_clause_threshold = 0 # Always multi-line where clauses + +# ───────────────────────────────────────────────────────────────────────────────── +# IMPORTS +# ───────────────────────────────────────────────────────────────────────────────── + +# Group imports: std, external, crate +imports_granularity = "Module" # use foo::{bar, baz} not individual lines +group_imports = "StdExternalCrate" +imports_layout = "HorizontalVertical" + +# Reorder imports alphabetically +reorder_imports = true +reorder_modules = true + +# ───────────────────────────────────────────────────────────────────────────────── +# FORMATTING CHOICES +# ───────────────────────────────────────────────────────────────────────────────── + +# Use block indent (not visual indent) for cleaner diffs +indent_style = "Block" + +# Tabs vs spaces +hard_tabs = false +tab_spaces = 4 + +# Newline style (native = OS default, Unix = LF, Windows = CRLF) +newline_style = "Unix" + +# Trailing commas help with diffs +trailing_comma = "Vertical" # Add trailing comma when items are on separate lines +trailing_semicolon = true # Keep trailing semicolons in blocks +match_arm_trailing_comma = true + +# Brace positions +brace_style = "SameLineWhere" # Opening brace on same line, but where clause gets its own line +control_brace_style = "AlwaysSameLine" + +# ───────────────────────────────────────────────────────────────────────────────── +# ALIGNMENT (Disabled - causes noisy diffs) +# ───────────────────────────────────────────────────────────────────────────────── + +# Don't align struct field assignments +# let foo = Struct { +# short: 1, // BAD - aligned +# much_longer: 2, +# }; +# let foo = Struct { +# short: 1, // GOOD - not aligned +# much_longer: 2, +# }; + +# ───────────────────────────────────────────────────────────────────────────────── +# COMMENTS & DOCUMENTATION +# ───────────────────────────────────────────────────────────────────────────────── + +# Wrap comments at max_width +wrap_comments = true +comment_width = 100 # Slightly shorter than code for readability + +# Format doc comments +format_code_in_doc_comments = true +doc_comment_code_block_width = 80 + +# Normalize doc comments to /// +normalize_doc_attributes = true + +# ───────────────────────────────────────────────────────────────────────────────── +# MACRO FORMATTING +# ───────────────────────────────────────────────────────────────────────────────── + +# Format macro bodies +format_macro_matchers = true +format_macro_bodies = true + +# ───────────────────────────────────────────────────────────────────────────────── +# MISC +# ───────────────────────────────────────────────────────────────────────────────── + +# Use field init shorthand: Foo { bar } not Foo { bar: bar } +use_field_init_shorthand = true + +# Use try shorthand: ? not try! +use_try_shorthand = true + +# Force multiline closures for readability +fn_single_line = false # Never put fn body on single line +where_single_line = false # Never put where clause on single line + +# Empty function bodies +empty_item_single_line = true # fn foo() {} is fine + +# Hex literal case +hex_literal_case = "Lower" # 0xff not 0xFF + +# Overflow behavior +overflow_delimited_expr = true + +# ───────────────────────────────────────────────────────────────────────────────── +# UNSTABLE FEATURES (require nightly rustfmt) +# ───────────────────────────────────────────────────────────────────────────────── +# Uncomment these if using nightly rustfmt + +# version = "Two" # Use rustfmt 2.0 style +# format_strings = true # Format string literals +# imports_indent = "Block" # Block indent for imports +# imports_layout = "Vertical" # One import per line diff --git a/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/task.json b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e7f44801ef3a81aa08059b3a353ff906ab69384c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b2f1e8532faa4a83c995c52e/task.json @@ -0,0 +1,95 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b2f1e8532faa4a83c995c52e", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "b2f1e8532faa4a83c995c52e", + "outputs": [ + "boring_lint.py", + "report.txt" + ], + "success_criteria": [ + "boring_lint.py runs with `python3 boring_lint.py src`, uses only the Python standard library, and exits 1 because violations exist Dependency/resource checks apply only to the actual guarded Python invocations under the public bounded runtime policy, not to unused source or static closure inference.", + "report.txt contains a line `src/lib.rs:15: PANIC_METHOD: ...` (line number of the `.unwrap()` in risky_parse, exact number may vary with the file as given: line 15) reporting the unwrap outside test code", + "report.txt reports the `panic!` in src/lib.rs inside fallback as a PANIC_MACRO violation", + "report.txt reports the `unsafe {` block in src/sim.rs as an UNSAFE_BLOCK violation", + "report.txt reports the `_ =>` match arm in src/sim.rs as a WILDCARD_MATCH violation", + "report.txt reports the `unreachable!` in src/sim.rs as a PANIC_MACRO violation", + "report.txt reports `#[allow(dead_code)]` in src/lib.rs (no justification comment) as an UNJUSTIFIED_ALLOW violation", + "report.txt does NOT report the `.unwrap()` inside the `#[cfg(test)] mod tests` block of src/lib.rs nor anything from src/engine_tests.rs (test code exempt)", + "report.txt does NOT report the `#[allow(clippy::too_many_lines)]` line in src/sim.rs because it carries a `JUSTIFICATION:` comment", + "All violation lines in report.txt follow the format `path:lineno: rule_id: message` and are sorted by path then line number", + "Running the script on a directory with no violations exits 0 and prints nothing (verifiable by the checker creating a clean temp directory)" + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "4baf7f4fda2ef7365edaf0b8db6d5fc56ce9d2b891585b6f7184be783eaf5f27", + "files": { + ".skillfish.json": "cf5f7c5f978ba0453853e8f666f71f169f37f03498bd94df91c67ee7c0c102d1", + "SKILL.md": "2a0d01626619ae4740f3e55c59b72096cc843b64f6eaaeea0b54cf761c23abbc", + "references/bevy.md": "2f4783fd5c999e85e0b8592cbd7e7598ca5acf3f0a4fe302afb0f2282661ab87", + "references/cargo_lints.toml": "2dc22eae437ffeebaa9540981f0afe8854a9d4935111bf6c0f38f996abe68699", + "references/clippy.toml": "215b179bd01f61cb46b1c65eb2184e961b27d0ddd1dd90a6907888d9c57e91f2", + "references/gitignore": "03fbc32b31fea8c069213a0e07c20d1285165b2042f5465ce44d708f653d40a6", + "references/patterns.md": "e7be8b55e2b2be0dd0bdea30a860dac52f728d27f2afb5b972026af5d2f2b613", + "references/rustfmt.toml": "f6e8c1c835faa275be70621b5e7d9a99cfe4fbc3a74fa4420977ba2e7abaaa0b" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/src/lib.rs", + "workspace_target": "src/lib.rs", + "sha256": "0da3fccb893e19fbe50723f087a10e16378bb8b4f24f298e3d33567b74e67b06" + }, + { + "source": "inputs/src/engine_tests.rs", + "workspace_target": "src/engine_tests.rs", + "sha256": "bce7f4852047ff9f153f9b1325178ff39c18cdf0e742d6625e4ba10343c364eb" + }, + { + "source": "inputs/src/sim.rs", + "workspace_target": "src/sim.rs", + "sha256": "e240fd6481159542ddc8b96c8386f74e3ff5ee746b64a8309bc99bf85fdd1b68" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "4baf7f4fda2ef7365edaf0b8db6d5fc56ce9d2b891585b6f7184be783eaf5f27" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/b3b2a15d70a9f50b_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_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/b3b2a15d70a9f50b_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_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/b3b2a15d70a9f50b_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_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/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..c03f64348caa714a2797a7d6488d9a515c65d380 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,455 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i&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/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b3b2a15d70a9f50b_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..4df26c2ffaf32ee54a18bcb00381e1aef3ec640d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""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() +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'} + 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/b3b2a15d70a9f50b_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..5ce210db21bfb5f876e67ae838b52037e8fa3bfb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "engine": "portable_verified_v1", + "grader_file_sha256": { + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "8448c1eb33d40b855426dfc5657143a1e8098220eb4a599cea8200c3c242b83d", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70", + "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af" + }, + "query_id": "b3b2a15d70a9f50b_q1", + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "criterion_weights": { + "0": 1 + }, + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "grader_timeout_seconds": 600, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ] + }, + "schema": "audited-verified-grader-v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0243e138d19db29719eee02599bf0dea48fbc592 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/instruction.md @@ -0,0 +1 @@ +I maintain the zh_CN translations for our documentation repo. Every time translators send updated .po catalogs, I have to manually run the catalog sync for Chinese from the repo root and then rebuild the Chinese Sphinx docs to make sure nothing broke. I'd like to stop doing this by hand: please create a script at output/sync_translations.sh that does both steps in order — sync the zh_CN gettext catalogs using the project's preferred one-command entrypoint, then build the Chinese docs to validate. Keep it a straight-line script: just the commands at the top level, no loops, no if statements, no manual fallback commands. If either command fails, the script must stop immediately and exit nonzero rather than continuing or swallowing the error. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..30407c73e1737660b57149b380b9468ef20a0960 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/SKILL.md @@ -0,0 +1,95 @@ +--- +name: moonbit-docs-maintainer +description: Use when maintaining the moonbitlang/moonbit-docs repository, including Sphinx docs under next/, MoonBit examples under next/sources/, error-code documentation, gettext translations, or the moonbit-tour web app. This skill routes to focused references and validation commands for repo maintenance work. +--- + +# MoonBit Docs Maintainer + +Use this skill for changes to the `moonbitlang/moonbit-docs` repository. It is a +repo-maintenance router, not a MoonBit language tutorial. + +## First steps + +1. Read the user request and classify the touched area before editing. +2. Inspect the relevant local files. Prefer existing layout and wording patterns. +3. Load only the reference file for the task area. +4. Make minimal, reviewable changes. +5. Run the narrowest validation command that proves the change. + +## Routing + +- Sphinx docs in `next/`, Markdown pages, images, Sphinx config, or local docs + builds: read `references/sphinx.md`. +- MoonBit examples under `next/sources/`, excluding `next/sources/error_codes/`: + read `references/examples.md`. +- Error-code docs under `next/language/error_codes/` or paired examples under + `next/sources/error_codes/`: read `references/error-docs.md`. +- Translation catalogs under `next/locales/` or gettext template updates: read + `references/translation.md`. +- Interactive tour changes under `moonbit-tour/`: read `references/tour.md`. +- Typo, spelling, or prose lint changes involving `typos` or `autocorrect`: + read `references/typo.md`. + +If a task spans multiple areas, read the most specific reference first, then any +secondary reference needed for validation. + +## Repository Map + +- `next/`: Sphinx documentation site. Markdown sources live under `next/`. + MoonBit example projects used by docs live under `next/sources/`. +- `next/locales//LC_MESSAGES/`: gettext translation catalogs. +- `moonbit-tour/`: pnpm-based interactive language tour web app. +- `legacy/`: legacy docs and examples. Treat as reference unless the user asks + to maintain it directly. +- `scripts/`: repo-level checks for examples and i18n helpers. +- `justfile`: preferred maintainer command entrypoints. + +## Tooling Commands + +Prefer `just` recipes and `uv`-managed Python dependencies when available. Do +not create ad-hoc virtualenvs unless the task explicitly requires one or `uv` is +unavailable. + +- `just i18n`: runs gettext extraction and catalog sync for `zh_CN`. +- `just i18n ja`: runs the i18n flow for another locale. +- `just docs-html`: builds the default Sphinx docs. +- `just docs-html-zh`: builds the Chinese Sphinx docs. +- `just docs-html-ja`: builds the Japanese Sphinx docs. +- `just check-docs`: checks non-error-code MoonBit examples under + `next/sources/`. +- `just check-errors`: checks all error-code docs examples under + `next/sources/error_codes/`. +- `just check-error 0001`: checks one four-digit error code. + +If `just` is unavailable, use the task-specific fallback in the relevant +reference. Example checks fall back to Python scripts; Sphinx and i18n tasks +fall back to manual `cd next` commands. + +## General Rules + +- Do not edit generated output such as `next/_build/`, `moonbit-tour/dist/`, or + dependency directories. +- Keep examples runnable. When documentation references code in `next/sources/`, + update docs and examples together. +- Avoid broad `moon fmt` runs in `next/sources/`; format only touched files when + formatting is necessary. +- Preserve existing bilingual structure where it exists. +- Prefer functional style for new MoonBit code, and keep changes small. +- Use conventional commit messages if asked to commit; this is a repo-wide rule + from `AGENTS.md`. + +## Validation + +Choose the smallest useful check: + +- Sphinx docs: `just docs-html` +- Chinese Sphinx build: `just docs-html-zh` +- Japanese Sphinx build: `just docs-html-ja` +- MoonBit docs examples: `python3 scripts/check-document.py` +- Error-code examples: `python3 next/check_error_docs.py all` +- One error code: `python3 next/check_error_docs.py 0001` +- Tour build: `cd moonbit-tour && pnpm build` +- Prose lint: `autocorrect . --lint --no-diff-bg-color` + +If dependencies are missing or a full check is too expensive, run the closest +targeted command and report the remaining risk. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/agents/openai.yaml b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/agents/openai.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d32c1bbab9eac81b634990d8a9a07e2ccf712564 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/agents/openai.yaml @@ -0,0 +1,7 @@ +interface: + display_name: "MoonBit Docs Maintainer" + short_description: "Maintain the MoonBit documentation repo" + default_prompt: "Use $moonbit-docs-maintainer to update MoonBit documentation and run the right repo checks." + +policy: + allow_implicit_invocation: true diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/error-docs.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/error-docs.md new file mode 100644 index 0000000000000000000000000000000000000000..925b7dd6fc015aec55153282c5efe1b22614532a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/error-docs.md @@ -0,0 +1,54 @@ +# Error-Code Documentation + +Use this reference for compiler error-code docs and their MoonBit examples. +The migration is not complete yet: the target state is for each documented +error code to have both an error example and a fixed example, but some codes may +currently have prose only. + +## Relevant paths + +- `next/language/error_codes/E0001.md`: prose documentation for one error code. +- `next/sources/error_codes/0001_error/`: example expected to trigger the code. +- `next/sources/error_codes/0001_fixed/`: fixed example expected to pass without + warnings or errors. +- `next/check_error_docs.py`: validation script. + +## Workflow + +1. Keep each prose page aligned with any migrated examples for that code. +2. Use four-digit codes in file and directory names. +3. For codes below `3000`, the error example may produce a warning or an error. +4. For codes `3000` and above, the error example must fail with that error. +5. The fixed example must pass `moon check` with no warnings or errors. +6. Avoid broad `moon fmt` runs. Format only the error-code example files you + intentionally touched when formatting is necessary. +7. When migrating or adding examples, prefer adding both `_error/` and + `_fixed/` as independent MoonBit projects with their own + `moon.mod`. + +## Validation + +Run the checker from the repository root. + +- One code: `just check-error 0001` +- All codes: `just check-errors` +- If `just` is unavailable: + - `python3 next/check_error_docs.py 0001` + - `python3 next/check_error_docs.py all` + +The checker runs `moon clean` and `moon check` inside each example project with +`NO_COLOR=1`, then matches `Warning: [0001]` or `Error: [0001]` patterns. +If a code has neither an `_error` nor a `_fixed` project yet, the checker treats +it as not migrated and skips it successfully. + +## Notes + +- If adding a new error-code page, add both `_error` and `_fixed` source + directories when examples are possible. If an example is not practical yet, + leave the prose accurate and do not invent a brittle sample. +- Do not assume missing example directories are a failure; this docs area is + still being migrated. +- If the compiler output changed, update the examples first and then adjust the + prose. +- Do not use `scripts/check-document.py` for error-code examples; it explicitly + skips them. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/examples.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/examples.md new file mode 100644 index 0000000000000000000000000000000000000000..44f1c3d2a1e520ca12bce1b29c06fa75aa2e2e4d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/examples.md @@ -0,0 +1,48 @@ +# MoonBit Documentation Examples + +Use this reference for runnable examples under `next/sources/`, excluding +`next/sources/error_codes/`. + +## Relevant paths + +- `next/sources//moon.mod`: example module root. Older examples may + still use the deprecated `moon.mod.json` format. +- `next/sources//**/moon.pkg`: package configuration. Older examples + may still use the deprecated `moon.pkg.json` format. +- `next/sources//**/*.mbt`: MoonBit source files. +- `next/sources/single-file/README.mbt.md`: single-file example checked in + single-file mode. +- `scripts/check-document.py`: repo-level example checker. + +## Workflow + +1. Locate the example project that backs the docs section. +2. Preserve the existing module/package layout unless the task requires a new + example. +3. Prefer small, clear examples over clever abstractions. +4. Keep docs snippets and runnable source files consistent. +5. Do not handle `next/sources/error_codes/` here; use `error-docs.md`. +6. Avoid broad `moon fmt` runs. Format only files you intentionally touched when + formatting is necessary, so example updates stay reviewable. + +## Validation + +Run repo-level Python commands from the repository root. + +- All non-error-code examples: `just check-docs` +- If `just` is unavailable: `python3 scripts/check-document.py` +- Targeted check from an example root: + - `moon check --deny-warn --target all` + - `moon test --deny-warn --target all` +- Examples named `async` and `cli-quickstart` are checked with the native target + by the repo script. +- Single-file example: + - `cd next/sources/single-file && moon check README.mbt.md` + - `cd next/sources/single-file && moon test README.mbt.md` + +## Notes + +- The repo script skips hidden directories, `target`, and `error_codes`. +- It assumes MoonBit dependencies are already resolved. +- Keep warning-free examples unless the example intentionally demonstrates an + error through the error-code workflow. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/sphinx.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/sphinx.md new file mode 100644 index 0000000000000000000000000000000000000000..de151c8ab061d66d012c6cea823f9f7efd88224c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/sphinx.md @@ -0,0 +1,45 @@ +# Sphinx Docs + +Use this reference for changes under `next/` that affect the Sphinx +documentation site. + +## Relevant paths + +- `next/index.md`: top-level docs entry. +- `next/conf.py`: Sphinx configuration and extensions. +- `next/language/`, `next/tutorial/`, `next/toolchain/`, `next/pilot/`: + documentation sections. +- `next/imgs/`, `next/_static/`, `imgs/`: image and static assets. +- `next/sources/`: runnable MoonBit examples referenced from docs. + +## Workflow + +1. Inspect nearby pages for heading style, code block style, and cross-reference + patterns. +2. For examples embedded in prose, check whether a runnable source exists under + `next/sources/` and keep both in sync. +3. When adding pages, update the relevant `toctree` or index page. +4. Avoid editing generated output under `next/_build/`. + +## Build commands + +- Development server: `just docs-watch` +- Chinese development server: `just docs-watch-zh` +- HTML build: `just docs-html` +- Chinese HTML build: `just docs-html-zh` +- Japanese HTML build: `just docs-html-ja` +- PDF build: `just docs-pdf` +- Markdown build: `just docs-markdown` +- Manual development server: `cd next && sphinx-autobuild . ./_build/html` +- Manual HTML build: `cd next && make html` +- Manual Chinese HTML build: `cd next && LANGUAGE=zh_CN make html` +- Markdown build, when needed: install `sphinx-markdown-builder`, then + `cd next && make markdown` + +## Notes + +- Dependencies are documented in `next/requirements.txt`. +- If Sphinx is unavailable, report that validation could not run and include the + attempted command. +- If a docs change affects translations, update source docs first; translation + catalog synchronization belongs to `translation.md`. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/tour.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/tour.md new file mode 100644 index 0000000000000000000000000000000000000000..9bce9d2b5be41131453553ca617c2491a28a5429 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/tour.md @@ -0,0 +1,44 @@ +# MoonBit Tour + +Use this reference for the interactive tour web app under `moonbit-tour/`. + +## Relevant paths + +- `moonbit-tour/src/`: TypeScript application source. +- `moonbit-tour/tour/index.md` and `moonbit-tour/tour/index.mbt`: default tour + content and MoonBit examples. +- `moonbit-tour/tour/zh/index.md` and `moonbit-tour/tour/zh/index.mbt`: + Chinese tour content and examples. +- `moonbit-tour/package.json`: pnpm scripts and dependencies. + +## Workflow + +1. Inspect the relevant source and tour content before editing. +2. Keep localized tour content aligned when changing shared concepts. +3. Prefer existing TypeScript, CSS, and build patterns. +4. Do not edit generated `moonbit-tour/dist/` or dependency directories. + +## Commands + +- Install dependencies: `just tour-install` +- Build: `just tour-build` +- Development server: `just tour-dev` +- Preview built output: `just tour-preview` +- Manual install: `cd moonbit-tour && pnpm install` +- Manual build: `cd moonbit-tour && pnpm build` +- Manual development server: `cd moonbit-tour && pnpm dev` +- Manual preview: `cd moonbit-tour && pnpm preview` +- Format tour files: `cd moonbit-tour && pnpm format` + +## Validation + +- For code or content changes, run `just tour-build`. +- For UI behavior changes, run the dev server and inspect the app in a browser + when practical. + +## Notes + +- The app uses `@moonbit/moonpad-monaco`, Monaco, Shiki, Tailwind, and a custom + build script. +- If pnpm dependencies are missing and network is unavailable, report the + attempted command and the unvalidated risk. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/translation.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/translation.md new file mode 100644 index 0000000000000000000000000000000000000000..56872ceb6c9c18ff0120c54f772cab4b6742b477 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/translation.md @@ -0,0 +1,51 @@ +# Translation Workflow + +Use this reference for gettext catalogs under `next/locales/` and translation +template synchronization. + +## Relevant paths + +- `next/locales/zh_CN/LC_MESSAGES/*.po`: Chinese translation catalogs. +- `next/locales/ja/LC_MESSAGES/*.po`: Japanese translation catalogs, when + present. +- `justfile`: preferred one-command i18n entrypoint. +- `next/_build/gettext/`: generated gettext templates. Do not hand-edit as a + source of truth. + +## Workflow + +1. Update source documentation first. +2. Before editing `.po` catalogs, run the i18n sync flow so generated entries + match the current docs source. +3. Commit catalog changes produced by the sync together with the related source + or translation change; do not leave required i18n updates behind. +4. Translate missing `msgstr` entries in the relevant `.po` files. +5. If the source string does not need translation, such as code-only content, + leave `msgstr` empty instead of copying or inventing a translation. +6. If a `#, fuzzy` flag remains, keep it unless the translation has been + verified. Remove it only after verification. +7. Preserve PO syntax exactly; malformed catalogs break Sphinx builds. + +## Commands + +Run these commands from the repository root. + +- Full Chinese update: `just i18n` +- Locale-specific update: `just i18n ja` +- If `just` is unavailable, use the manual flow: + - `cd next && make gettext` + - `cd next && sphinx-intl update -p _build/gettext -l zh_CN` + +The `just i18n` recipe is the preferred one-line command and uses `uv` with +`next/requirements.txt`. The manual flow is only a fallback. + +## Validation + +- Chinese docs build: `just docs-html-zh` +- Default docs build after source changes: `just docs-html` +- Do not use `msgfmt` as the default validation command. It is too narrow for + this repo workflow and encourages bypassing the required gettext sync. + +## Notes + +- Do not translate generated files under `next/_build/`. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/typo.md b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/typo.md new file mode 100644 index 0000000000000000000000000000000000000000..d3c32edba825f042aed01953df1fa938ba715ff3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/skill/references/typo.md @@ -0,0 +1,33 @@ +# Typo And Prose Lint + +Use this reference for changes involving `typos`, `autocorrect`, prose lint CI, +or typo-related ignore/config files. + +## Relevant paths + +- `.github/workflows/typo.yml`: CI workflow named `check examples`. +- `typos.toml`: configuration for `reviewdog/action-typos`. +- `.autocorrectrc`: rule configuration for `huacnlee/autocorrect-action`. +- `.autocorrectignore`: files ignored by AutoCorrect. + +## Workflow + +1. Treat typo/prose lint as a source-text check, not as a formatter for generated + or catalog files. +2. Do not run broad autocorrect fixes over translation catalogs or generated + files. In particular, gettext `.po` files under `next/locales/` should stay + governed by the translation workflow. +3. If CI reports an AutoCorrect issue in a catalog or generated file, prefer an + ignore rule over mass-editing unrelated translations. +4. If CI reports a real typo in authored docs, fix the source document and then + run the relevant i18n sync if translations are affected. +5. Keep ignore rules narrow and explain why the ignored files are not suitable + for prose auto-correction. + +## Validation + +- Local AutoCorrect lint: `autocorrect . --lint --no-diff-bg-color` +- Local typos check, when installed: `typos` + +`check examples` in GitHub Actions is the typo/prose lint workflow despite its +generic name. diff --git a/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f16a95664c5ddf4591dac9db924af944f31842fd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b3b2a15d70a9f50b_q1/task.json @@ -0,0 +1,55 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b3b2a15d70a9f50b", + "query_id": "b3b2a15d70a9f50b_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/sync_translations.sh" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "443bd8b645d193f7c2ecb86443db48e66b4660623513eb8d0515a5748d4ee240", + "name": "moonbit-docs-maintainer", + "package_path": "skill", + "install_name": "moonbit-docs-maintainer-20811726" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "443bd8b645d193f7c2ecb86443db48e66b4660623513eb8d0515a5748d4ee240", + "files": { + "SKILL.md": "f381dd1f29ca2ba920e4bad730368f587efa5a3313a6d300b83950406d417f2d", + "agents/openai.yaml": "6aab10a0fd4b53e62b6889d5733b68fd85992dd343226ad9b3055cff6c86537a", + "references/error-docs.md": "561101824063ab475dc0ae973aa3f88cb431729fa73f5cfbb44d168e39b3de93", + "references/examples.md": "4cc66fe97ed4e3515533416bd793fb90a90b0d162a5986feae7b62876abbd1cb", + "references/sphinx.md": "eb851972b134c419e74058416b7b1d0395662a084176c053956f7a5d46646a69", + "references/tour.md": "eb8f8ccdd5ece8006aba1cfc64a5dcffb72f303c727c6efd8ccbfb43d377f581", + "references/translation.md": "893d43cd907bd4eb6b750866377a0ad6dfaaa4edea25e560f8562e7a204ba3d2", + "references/typo.md": "591ed90b6cc3ba20433c376dc05e817c3244937908bcbdc067665668fe2199ae" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "208117262459ca1b9a1f3b822fcf2016367a3cb8411924035c64071cb83318d5" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_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/b53fbe4eb34c29b4_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_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/b53fbe4eb34c29b4_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_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/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_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/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b53fbe4eb34c29b4_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..4984dd90511e26ec44a067e9ede99e894eacf201 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b53fbe4eb34c29b4_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "9e70f23af50f47522aff1d5bb1c4750a013712b67c36812224fa0bfee8db115f", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39f890a61fb1794f4f33eb832544687d35ffc4ab --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/instruction.md @@ -0,0 +1 @@ +I'm working on visualizations for our colored stochastic six-vertex model simulations. We use rainbow initial data, and each color index needs to map to a hue on the color wheel so the coloring is deterministic and reproducible across runs. For a model with 5 colors total, what hue does our project's color-mapping convention assign to color index 3? Please round the result to 2 decimal places and return it as a single JSON object matching {"result":"number"} — just the computed numeric value, no formula or explanation. diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/CONCOMITANT_SKILLS.md b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/CONCOMITANT_SKILLS.md new file mode 100644 index 0000000000000000000000000000000000000000..72baff9cb5e0ece007facbf3d4b1c30dbc035b8b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/CONCOMITANT_SKILLS.md @@ -0,0 +1,16 @@ + + +## Related + +Skills related to this one, with the nature of each relation (direction from prose citations; cluster domains characterized from exa and our own use). Symmetric — each related skill lists this one too. Do not edit inside the markers; regenerate with `python3 scripts/relate_skills.py`. + +- `cat` — builds on — cat Skill: Derivational Pipe Chaining +- `discopy` — builds on — DisCoPy: Python library for computing with string diagrams - monoidal categories, quantum… +- `gay-mcp` — sibling in the GF(3) deterministic color generation cluster — Deterministic color generation with SplitMix64, GF(3) trits, and MCP +- `kpz-universality` — mutually referenced — KPZ universality class: KPZ fixed point, directed landscape, random interface growth scal… +- `langevin-dynamics` — sibling in the GF(3) deterministic color generation cluster — Layer 5: SDE Based Learning Analysis via Langevin Dynamics +- `last-passage-percolation` — invoked by — Last Passage Percolation models: geometric LPP, exponential weights, Tracy Widom limits, … +- `terminal-css` — invoked by — Provides Textual TCSS patterns for terminal widgets and ACP content styling. +- `yang-baxter-integrability` — mutually referenced — Yang Baxter equation for quantum integrable systems. + + diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ee10df88a204146e13925a21864744feeab8f4ca --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/skill/SKILL.md @@ -0,0 +1,338 @@ +--- +name: colored-vertex-model +description: "Colored stochastic six-vertex model with rainbow initial data, projection properties, and height functions tracking particle counts by color." +license: MIT +metadata: + trit: +1 + source: Borodin-Wheeler (2018), Aggarwal-Borodin-Wheeler + xenomodern: true + stars: 512 +--- + +# Colored Vertex Model Skill + +**Status**: ✅ Production Ready +**Trit**: +1 (PLUS - generative/optimistic) +**Color**: #FF6B6B (Coral Red) +**Principle**: Colors as conserved quantum numbers with projection properties +**Frame**: Rainbow initial data → height function → KPZ limits + +--- + +## Overview + +The **colored stochastic six-vertex model** extends the classical model with **n colored arrow types**. This skill provides: + +1. **Rainbow Initial Data**: Colors 1, 2, ..., n entering from left +2. **Colored Height Function**: Track particles by color +3. **Projection Properties**: Reduce n colors to k < n colors +4. **Gay-MCP Integration**: Colors as deterministic GF(3) trits + +## Rainbow Configuration + +``` +Initial data (rainbow): + Color n entering at row 1 + Color n-1 entering at row 2 + ... + Color 1 entering at row n + + →n→ ↑ + →n-1→ ↑ Grid evolution + ... ↑ via vertex weights + →1→ ↑ +``` + +### Colored Height Function + +```julia +# h_k(x,y) = number of arrows with color ≤ k passing through (x,y) +function colored_height(model, k, x, y) + count = 0 + for arrow in model.arrows_through(x, y) + if arrow.color <= k + count += 1 + end + end + return count +end + +# Full height function array +H = [colored_height(model, k, x, y) for k in 1:n, x in 1:L, y in 1:T] +``` + +## Vertex Weights + +### Stochastic Colored Weights + +Each vertex satisfies: +- Arrow conservation (in = out for each color) +- Row stochasticity (weights sum to 1) + +```julia +struct ColoredVertex + left_in::Vector{Int} # colors entering from left + bottom_in::Vector{Int} # colors entering from bottom + right_out::Vector{Int} # colors exiting right + top_out::Vector{Int} # colors exiting top +end + +function weight(v::ColoredVertex, q, b) + # Stochastic six-vertex weights per color interaction + # See Borodin-Wheeler for full formulas + if is_through_vertex(v) + return a(q, b) # arrow goes straight through + elseif is_bend_vertex(v) + return b(q, b) # arrow bends + elseif is_cross_vertex(v) + return c(q, b) # arrows cross + end +end +``` + +## Projection Properties + +**Key Feature**: Projecting to fewer colors preserves the vertex model structure. + +```julia +# Project from n colors to k colors +function project_colors(model::ColoredModel, k::Int) + # Colors 1,...,k stay as color 1 + # Colors k+1,...,n stay as color 2 + # (for k=1, this gives the uncolored model) + + projected = ColoredModel(n_colors = 2) + for arrow in model.arrows + new_color = arrow.color <= k ? 1 : 2 + add_arrow!(projected, arrow.position, new_color) + end + return projected +end + +# Full projection: n colors → 1 color (uncolored) +uncolored = project_colors(model, 1) + +# Theorem: uncolored model has same law as original uncolored six-vertex +``` + +### Marginal Preservation + +```julia +# Marginal of projected height = height of projected model +@test colored_height(project_colors(model, k), 1, x, y) == + colored_height(model, k, x, y) +``` + +## Integration with Gay-MCP + +Colors map directly to Gay.jl deterministic coloring: + +```julia +using GayMCP + +# Initialize model with Gay.jl colors +function colored_model_with_gay(n_colors, seed) + Gay.gay_seed(seed) + + model = ColoredModel(n_colors) + + for row in 1:n_colors + color = Gay.color_at(row) + trit = Gay.trit_from_hue(color.H) + + # Add colored arrow at row + add_arrow!(model, (0, row), + color = row, + gay_color = color, + trit = trit + ) + end + + return model +end + +# Verify GF(3) conservation on any triangle of particles +function verify_gf3_triangle(model, triangle_indices) + trits = [model.arrows[i].trit for i in triangle_indices] + @test sum(trits) % 3 == 0 +end +``` + +### Color → Trit Mapping + +```julia +# Consistent with Gay-MCP hue mapping +function color_to_trit(color_index, n_colors) + # Map color index to hue in [0, 360) + hue = (color_index - 1) * 360 / n_colors + + # Gay-MCP trit mapping + if hue < 60 || hue >= 300 + return +1 # PLUS (warm) + elseif hue < 180 + return 0 # ERGODIC (neutral) + else + return -1 # MINUS (cool) + end +end +``` + +## Scaling Limits (→ KPZ) + +As mesh → 0, the colored height function converges to the KPZ fixed point: + +```julia +# Rescale height function +function rescale_height(H, ε) + # 1:2:3 scaling + x_scale = ε^(-1) + t_scale = ε^(-3/2) + h_scale = ε^(1/2) + + return (x, t) -> h_scale * H(x_scale * x, t_scale * t) +end + +# In the limit ε → 0, converges to KPZ fixed point +# See kpz-universality skill +``` + +## Gibbs Properties + +### Inter-Color Gibbs Property + +The colored ensemble relates to uncolored via **Pitman transform**: + +```julia +# Given uncolored paths, sample coloring via Pitman +function inter_color_gibbs(uncolored_paths) + # Find monotone coupling maximizing likelihood + coloring = pitman_transform(uncolored_paths) + return coloring +end + +# Key variational formula: +# P(colored | uncolored) ∝ product of local transition kernels +``` + +### Projection as Marginalization + +```julia +# Projection = forgetting colors = marginalization +project(P_colored, subset) = ∫ P_colored d(complement colors) + +# This is a left adjoint (free construction) in categorical terms +``` + +## GF(3) Triad Assignment + +| Trit | Skill | Role | +|------|-------|------| +| -1 | yang-baxter-integrability | Structure | +| 0 | kpz-universality | Limits | +| +1 | **colored-vertex-model** | Data | + +**Conservation**: (-1) + (0) + (+1) = 0 ✓ + +## Commands + +```bash +# Simulate colored model +just cvm-simulate n_colors=3 L=100 T=50 + +# Project to k colors +just cvm-project model=rainbow.jld2 k=2 + +# Compute height function +just cvm-height k=2 x=50 y=25 + +# Verify projection property +just cvm-verify-projection + +# Gay-MCP integration +just cvm-gay seed=1069 +``` + +## Configuration + +```yaml +# colored-vertex-model.yaml +model: + n_colors: 3 + grid_size: 100 + time_steps: 50 + weights: + q: 0.5 + b: 0.3 + +gay_integration: + enabled: true + seed: 1069 + verify_gf3: true + +projection: + levels: [1, 2] # project to these color counts +``` + +## Related Skills + +- **yang-baxter-integrability** (-1): R-matrix structure +- **kpz-universality** (0): Scaling limits +- **gay-mcp** (+1): Deterministic coloring +- **langevin-dynamics** (0): Stochastic analysis +- **discopy** (+1): String diagrams + +## Research References + +1. Borodin-Wheeler (2018): "Colored stochastic vertex models" +2. Aggarwal-Borodin-Wheeler (2022): "Colored six-vertex models" +3. Galashin (2021): "Symmetries of stochastic colored vertex models" +4. Borodin-Bufetov (2019): "Color-position symmetry" + +--- + +**Skill Name**: colored-vertex-model +**Type**: Integrable Probability +**Trit**: +1 (PLUS) +**Key Property**: Projection preserves model structure +**Status**: ✅ Production Ready + +--- + +## Cat# Integration + +``` +Trit: +1 (PLUS) +Home: IntegrableProb +Poly Op: ⊗ +Kan Role: Lan_K (left Kan) +Color: #FF6B6B +``` + +### Color as Functor + +Colors form a functor: +``` +Color: Vertex → GF(3) +``` + +Projection is a natural transformation: +``` +π: Color_n → Color_k (n > k) +``` + +### GF(3) Naturality + +``` +(-1) + (0) + (+1) ≡ 0 (mod 3) +``` + +## Autopoietic Marginalia + +> **Colors flow. Projections preserve. The rainbow encodes the universe.** + +Every use of this skill is an opportunity for worlding: +- **MEMORY** (-1): Record successful projections +- **REMEMBERING** (0): Connect to KPZ limits +- **WORLDING** (+1): Discover new color structures + +*Add Interaction Exemplars here as the skill is used.* diff --git a/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..309f0eafcb6e6dc809045d605993391420cea0b0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b53fbe4eb34c29b4_q1/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b53fbe4eb34c29b4", + "query_id": "b53fbe4eb34c29b4_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "ff958905fad7ce26791f15e3f7080326a2053abb5ad8cd46ede88719278bb3a7", + "name": "colored-vertex-model", + "package_path": "skill", + "install_name": "colored-vertex-model-58992835" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "ff958905fad7ce26791f15e3f7080326a2053abb5ad8cd46ede88719278bb3a7", + "files": { + "CONCOMITANT_SKILLS.md": "2d8b5fc110af096c89da637b8458d456c6b4e546dd40912ff1bc8f2022e0b63a", + "SKILL.md": "c02f7f4c1c213641c06834027cb20e3ddc5e1960968c0b2f5600caa334388b54" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "589928351d0ce05f56fd1946de16fcbd0ec1307cef675b78dfa0058ce8cd9c9f" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/environment/data/sprint-4.md b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/environment/data/sprint-4.md new file mode 100644 index 0000000000000000000000000000000000000000..ec764f5dc005c9e5c62e626e324cea190fcff61d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/environment/data/sprint-4.md @@ -0,0 +1,19 @@ +# Sprint 4 — 2025-03-03 to 2025-03-14 + +## Sprint Goal +Deliver the core combat loop for the vertical slice. + +## Must Have (Critical Path) +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|--------------|---------------------| +| CBT-101 | Player attack combo system | dev-a | 3 | none | Combo chains trigger correct animations | + +## Should Have +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|--------------|---------------------| +| CBT-102 | Enemy hit reactions | dev-b | 2 | CBT-101 | Enemies flinch on hit | + +## Nice to Have +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|--------------|---------------------| +| CBT-103 | Screen shake on heavy hits | dev-b | 1 | CBT-102 | Camera shakes on heavy attacks | diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_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/b5ba62bb53859ec2_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_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/b5ba62bb53859ec2_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_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/b5ba62bb53859ec2_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..c0bd9b2f461c91189acc59a01e385c22834dee7d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1348 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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": + def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key: " + key) + result[key] = value + return result + def invalid_number(value): + raise ValueError("non-finite JSON number: " + value) + actual = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object, parse_constant=invalid_number) + expected = check.get("expected") + # This task gives no order contract for the three story records. + # Canonicalize only that array; retain native types, multiplicity, + # exact fields and the existing output-file checks. + if path.name == "sprint-status.json": + def ordered_stories(value): + if isinstance(value, dict) and set(value) == {"stories"} and isinstance(value["stories"], list): + return {"stories": sorted(value["stories"], key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False))} + return value + actual, expected = ordered_stories(actual), ordered_stories(expected) + passed = (_same_native_json_types(actual, expected) and + _canonical(actual) == _canonical(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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b5ba62bb53859ec2_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/b5ba62bb53859ec2_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_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/b5ba62bb53859ec2_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b5ba62bb53859ec2_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..92530cf822bf92c436585d3681e62f1c5510f2f1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b5ba62bb53859ec2_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "c937db94002084705551b004eee3ffe6b63051ebbc71a6421d35b471e7152f6f", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "6c40cdb197f5dcc712cb0da1de6e8b5f27d52c215442c76744eefff922980813", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb542789eff6b42fc6f681dc26b3a19bd77e42a4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/instruction.md @@ -0,0 +1,11 @@ +We just finished sprint planning for our game project and Sprint 4 is locked in. Our CI tooling reads a machine-readable story-status file instead of parsing the markdown plan, so I need you to create output/sprint-status.json based on sprint-4.md in the project root. The plan defines one Must Have story, one Should Have story, and one Nice to Have story. For each story, record its priority tier and the correct initial status for a freshly generated sprint, following this project's standard tier-to-initial-status convention. Keep the file to exactly this shape, with no extra fields per story: + +{ + "stories": [ + { "priority": "string", "status": "string" }, + { "priority": "string", "status": "string" }, + { "priority": "string", "status": "string" } + ] +} + +Please write the file at output/sprint-status.json — just the file, no prose write-up. diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..65254a94cc88f5461944a6088cc2b0025ffc3fe8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/skill/SKILL.md @@ -0,0 +1,281 @@ +--- +name: sprint-plan +description: "Generates a new sprint plan or updates an existing one based on the current milestone, completed work, and available capacity. Pulls context from production documents and design backlogs." +argument-hint: "[new|update|status] [--review full|lean|solo]" +user-invocable: true +allowed-tools: Read, Glob, Grep, Write, Edit, Task, AskUserQuestion +model: sonnet +context: | + !ls production/sprints/ 2>/dev/null +--- + +## Phase 0: Parse Arguments + +Extract the mode argument (`new`, `update`, or `status`) and resolve the review mode (once, store for all gate spawns this run): +1. If `--review [full|lean|solo]` was passed → use that +2. Else read `production/review-mode.txt` → use that value +3. Else → default to `lean` + +See `.claude/docs/director-gates.md` for the full check pattern. + +**Review mode check** (before gates run): +- Read `production/review-mode.txt` if it exists. Use that mode. +- If the file doesn't exist and this is a `new` sprint: use `AskUserQuestion`: + - Prompt: "No review mode is set. Which review depth would you like for this sprint?" + - Options: + - `[A] full — spawn all director and lead gates` + - `[B] lean — skip non-phase-gate director reviews (recommended for most sprints)` + - `[C] solo — skip all gate spawning` + - After selection: write `production/review-mode.txt` with the chosen mode. Say: "Review mode set to [mode] and saved to production/review-mode.txt." +- If the file doesn't exist and this is NOT a `new` sprint (e.g., updating an existing sprint): default to `lean` silently. + +--- + +## Phase 1: Gather Context + +1. **Read the current milestone** from `production/milestones/`. + +2. **Read the previous sprint** (if any) from `production/sprints/` to + understand velocity and carryover. + +3. **Scan design documents** in `design/gdd/` for features tagged as ready + for implementation. + +4. **Check the risk register** at `production/risk-register/`. + +--- + +## Phase 2: Generate Output + +For `new`: + +**Generate a sprint plan** following this format and present it to the user. Do NOT ask to write yet — the producer feasibility gate (Phase 4) runs first and may require revisions before the file is written. + +```markdown +# Sprint [N] — [Start Date] to [End Date] + +## Sprint Goal +[One sentence describing what this sprint achieves toward the milestone] + +## Capacity +- Total days: [X] +- Buffer (20%): [Y days reserved for unplanned work] +- Available: [Z days] + +## Tasks + +### Must Have (Critical Path) +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|-------------|-------------------| + +### Should Have +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|-------------|-------------------| + +### Nice to Have +| ID | Task | Agent/Owner | Est. Days | Dependencies | Acceptance Criteria | +|----|------|-------------|-----------|-------------|-------------------| + +## Carryover from Previous Sprint +| Task | Reason | New Estimate | +|------|--------|-------------| + +## Risks +| Risk | Probability | Impact | Mitigation | +|------|------------|--------|------------| + +## Dependencies on External Factors +- [List any external dependencies] + +## Definition of Done for this Sprint +- [ ] All Must Have tasks completed +- [ ] All tasks pass acceptance criteria +- [ ] QA plan exists (`production/qa/qa-plan-sprint-[N].md`) +- [ ] All Logic/Integration stories have passing unit/integration tests +- [ ] Smoke check passed (`/smoke-check sprint`) +- [ ] QA sign-off report: APPROVED or APPROVED WITH CONDITIONS (`/team-qa sprint`) +- [ ] No S1 or S2 bugs in delivered features +- [ ] Design documents updated for any deviations +- [ ] Code reviewed and merged +``` + +For `update`: + +**Update an existing sprint plan**: + +1. Read the most recent sprint plan from `production/sprints/`. +2. Present the current story list with their current statuses from `production/sprint-status.yaml`. +3. Ask the user what to change: stories to add, remove, reprioritize, or re-estimate. Use `AskUserQuestion` to gather changes. +4. Apply the changes and re-present the full revised plan for review. +5. Re-run the producer feasibility gate (Phase 4) on the revised plan. +6. Write the updated markdown plan and yaml together (same approval as `new` mode). + +Note: `update` mode does not reset story statuses. Stories already marked `in-progress` or `done` keep their status. Only `backlog` and `ready-for-dev` stories can be removed or reprioritized freely. + +For `status`: + +**Generate a status report**: + +```markdown +# Sprint [N] Status -- [Date] + +## Progress: [X/Y tasks complete] ([Z%]) + +### Completed +| Task | Completed By | Notes | +|------|-------------|-------| + +### In Progress +| Task | Owner | % Done | Blockers | +|------|-------|--------|----------| + +### Not Started +| Task | Owner | At Risk? | Notes | +|------|-------|----------|-------| + +### Blocked +| Task | Blocker | Owner of Blocker | ETA | +|------|---------|-----------------|-----| + +## Burndown Assessment +[On track / Behind / Ahead] +[If behind: What is being cut or deferred] + +## Emerging Risks +- [Any new risks identified this sprint] +``` + +--- + +## Phase 3: Prepare Sprint Status File + +After generating a new sprint plan, also prepare the `production/sprint-status.yaml` content. +This is the machine-readable source of truth for story status — read by +`/sprint-status`, `/story-done`, and `/help` without markdown parsing. + +**Do not write the yaml yet** — hold it in context. The producer feasibility gate (Phase 4) may revise the story list. Both files will be written together after Phase 4 in a single write approval. + +Format: + +```yaml +# Auto-generated by /sprint-plan. Updated by /story-done and /dev-story. +# DO NOT edit manually — use /story-done to update story status. +# +# Status value mapping (yaml ↔ story file Status field): +# backlog ↔ Not Started +# ready-for-dev ↔ Ready +# in-progress ↔ In Progress +# review ↔ In Review +# done ↔ Complete +# blocked ↔ Blocked + +sprint: [N] +goal: "[sprint goal]" +start: "[YYYY-MM-DD]" +end: "[YYYY-MM-DD]" +generated: "[YYYY-MM-DD]" +updated: "[YYYY-MM-DD]" + +stories: + - id: "[epic-story, e.g. 1-1]" + name: "[story name]" + file: "[production/stories/path.md]" + priority: must-have # must-have | should-have | nice-to-have + status: ready-for-dev # backlog | ready-for-dev | in-progress | review | done | blocked + owner: "" + estimate_days: 0 + blocker: "" + completed: "" +``` + +Initialize each story from the sprint plan's task tables: +- Must Have tasks → `priority: must-have`, `status: ready-for-dev` +- Should Have tasks → `priority: should-have`, `status: backlog` +- Nice to Have tasks → `priority: nice-to-have`, `status: backlog` + +For `update`: read the existing `sprint-status.yaml`, carry over statuses for +stories that haven't changed, add new stories, remove dropped ones. + +--- + +## Phase 4: Producer Feasibility Gate + +**Review mode check** — apply before spawning PR-SPRINT: +- `solo` → skip. Note: "PR-SPRINT skipped — Solo mode." Proceed to Phase 5 (QA plan gate). +- `lean` → skip (not a PHASE-GATE). Note: "PR-SPRINT skipped — Lean mode." Proceed to Phase 5 (QA plan gate). +- `full` → spawn as normal. + +Before finalising the sprint plan, spawn `producer` via Task using gate **PR-SPRINT** (`.claude/docs/director-gates.md`). + +Pass: proposed story list (titles, estimates, dependencies), total team capacity in hours/days, any carryover from the previous sprint, milestone constraints and deadline. + +Present the producer's assessment. + +If UNREALISTIC: revise the story selection (defer stories to Should Have or Nice to Have) and re-present the updated plan before asking for write approval. + +If CONCERNS, use `AskUserQuestion`: +- Prompt: "Producer flagged concerns with this sprint plan. How do you want to proceed?" +- Options: + - `[A] Proceed as planned — I accept the risk` + - `[B] Adjust scope — defer some Should Have stories` + - `[C] Extend the sprint timeline` + +If [A]: proceed to write approval. +If [B]: revise the story list, re-present the updated plan, then proceed to write approval. +If [C]: adjust sprint dates and capacity, re-present the updated plan, then proceed to write approval. + +After handling the producer's verdict, ask: "May I write the sprint plan to `production/sprints/sprint-[N].md` and `production/sprint-status.yaml`?" If yes, write both files (creating directories as needed). Verdict: **COMPLETE** — sprint plan and status file created. If no: Verdict: **BLOCKED** — user declined write. + +After writing, add: + +> **Scope check:** If this sprint includes stories added beyond the original epic scope, run `/scope-check [epic]` to detect scope creep before implementation begins. + +--- + +## Phase 5: QA Plan Gate + +Before closing the sprint plan, check whether a QA plan exists for this sprint. + +Use `Glob` to look for `production/qa/qa-plan-sprint-[N].md` or any file in `production/qa/` referencing this sprint number. + +**If a QA plan is found**: note it in the sprint plan output — "QA Plan: `[path]`" — and proceed. + +**If no QA plan exists**: do not silently proceed. Surface this explicitly: + +> "This sprint has no QA plan. A sprint plan without a QA plan means test requirements are undefined — developers won't know what 'done' looks like from a QA perspective, and the sprint cannot pass the Production → Polish gate without one. +> +> Run `/qa-plan sprint` now, before starting any implementation. It takes one session and produces the test case requirements each story needs." + +Use `AskUserQuestion`: +- Prompt: "No QA plan found for this sprint. How do you want to proceed?" +- Options: + - `[A] Run /qa-plan sprint now — I'll do that before starting implementation (Recommended)` + - `[B] Skip for now — I understand QA sign-off will be blocked at the Production → Polish gate` + +If [A]: close with "Sprint plan written. Run `/qa-plan sprint` next — then begin implementation." +If [B]: add a warning block to the sprint plan document: + +```markdown +> ⚠️ **No QA Plan**: This sprint was started without a QA plan. Run `/qa-plan sprint` +> before the last story is implemented. The Production → Polish gate requires a QA +> sign-off report, which requires a QA plan. +``` + +--- + +## Phase 6: Next Steps + +After the sprint plan is written and QA plan status is resolved: + +- `/qa-plan sprint` — **required before implementation begins** — defines test cases per story so developers implement against QA specs, not a blank slate +- `/story-readiness [story-file]` — validate a story is ready before starting it +- `/dev-story [story-file]` — begin implementing the first story +- `/sprint-status` — check progress mid-sprint +- `/scope-check [epic]` — verify no scope creep before implementation begins + +**Review mode configuration:** All director gates (producer feasibility, QA review, code review) respect the project review mode. The review mode is set in Phase 0 when the file does not exist (for `new` sprints), or can be overridden per-run with `--review full|lean|solo` as an argument. The file `production/review-mode.txt` contains one of: +- `lean` — skip automated director gates (default if file is absent — fastest for solo dev) +- `full` — run all director gates as spawned sub-agents +- `solo` — skip all gates unconditionally (single-developer, no review) + +This file is read by `/sprint-plan`, `/story-readiness`, `/story-done`, and other skills at startup. diff --git a/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..92f60c5f9270a5d392e1782adb86d5c7c05e68af --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5ba62bb53859ec2_q1/task.json @@ -0,0 +1,54 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b5ba62bb53859ec2", + "query_id": "b5ba62bb53859ec2_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/sprint-status.json" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [ + { + "source": "environment/data/sprint-4.md", + "workspace_target": "sprint-4.md", + "sha256": "02dae3d17f8ef8a24dfe8ff93a0241066d41107be36a153986fa63732ef990de" + } + ], + "skill_packages": [ + { + "content_hash": "68c4da7d014efaab86c87917198c218712435a53d28ccd9f37318ab9690befce", + "name": "sprint-plan", + "package_path": "skill", + "install_name": "sprint-plan-bf23008c" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "68c4da7d014efaab86c87917198c218712435a53d28ccd9f37318ab9690befce", + "files": { + "SKILL.md": "d402a9f276f81663c8b07f6c4fd2b19a3fa9d4ee9411e3d57e6868daa095ee42" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "bf23008c474b009c7349f803c53f712fe230e630754d394ec6dce5819d08b03f" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_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/b5f1e59ff310a8b8_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_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/b5f1e59ff310a8b8_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_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/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i= 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/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_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/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/b5f1e59ff310a8b8_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..e72d159de04611b720bf523ce360c5708bf6fc3b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b5f1e59ff310a8b8_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "1f4589adae542885ff21d3a8c2615d8d338d42191a5a01104ce84048f069b7b7", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09fe133a04439a4104d7bb6d59cb20ab8ff4be0c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/instruction.md @@ -0,0 +1 @@ +We're aligning our Flutter app with LeanCode's internal BLoC/Cubit style guide, which mandates specific packages instead of community staples like freezed, and I need the exact conventions. Which mixin must every Bloc/Cubit state implement with props overridden? Which package should we use for copyWith to create altered state instances? Which package's BlocPresentationMixin covers side effects like navigation, dialogs, and snackbars? And if the work centers on implementing a base cubit like QueryCubit, which related plugin should be used instead? Return one JSON object: {"answers":{"q1":"string","q2":"string","q3":"string","q4":"string"}}, replacing each placeholder with the bare answer value. diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2488bfc52cceb520f14eff4753009fd6f4715e39 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/SKILL.md @@ -0,0 +1,42 @@ +--- +name: flutter-bloc-usage +description: Explain what the `flutter-bloc` plugin does and how to use it. Use when the user invokes `/flutter-bloc-usage`, asks what this plugin covers, or needs help with Cubit/BLoC state modeling, presentation effects, or the boundary with `flutter-cubit-utils`. +--- + +# BLoC Usage + +## How to respond + +- If the user invoked this skill without a concrete task, start by explaining what this plugin covers and where its boundaries are. +- Show how to use it with concrete state-management tasks this plugin can handle. +- Point to the main rule here, or route the user to `flutter-cubit-utils` when the task is really about base cubits and canonical recipes. +- If the user already gave a concrete BLoC/Cubit task, briefly explain why this plugin fits and then do the work. +- Do not reply with filler like "skill loaded", "ready for the task", or "what would you like to do?" before explaining the plugin. + +## What this plugin does + +- Covers LeanCode conventions for `bloc` and `flutter_bloc`. +- Covers presentation side effects with `bloc_presentation`. +- Covers widget state-read simplifications like replacing a top-level `BlocBuilder` with `context.watch` when that refactor is safe. +- Clarifies the boundary between general BLoC guidance here and base-cubit recipes in `flutter-cubit-utils`. + +## How to use it + +- Ask to design or refactor cubit state for a feature. +- Ask how to model presentation events for snackbars, dialogs, or navigation side effects. +- Ask to simplify a widget tree that uses a root `BlocBuilder` only to pass through cubit state. +- Ask whether a task belongs here or in `flutter-cubit-utils`. +- Ask for a review of a cubit/widget pair against LeanCode state-management rules. + +## Example requests + +- "Refactor this cubit state to follow LeanCode BLoC conventions." +- "How should I model a snackbar or navigation side effect from this cubit?" +- "Does this belong in `flutter-bloc` or `flutter-cubit-utils`?" + +## Reach for these assets + +- `references/state-management.md` - main BLoC/Cubit fundamentals. +- `skills/flutter-context-watch-instead-of-top-builder/SKILL.md` - focused workflow for replacing a top-level `BlocBuilder` with `context.watch`. +- Related plugin: `flutter-cubit-utils` - base classes and canonical recipes for `QueryCubit`, `PaginatedQueryCubit`, `RequestCubit`, and related cubits. +- If the task is mainly about choosing or implementing a base cubit, switch to `flutter-cubit-utils`. diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/references/state-management.md b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/references/state-management.md new file mode 100644 index 0000000000000000000000000000000000000000..eeb36c015cd4afd48d8247902198513c5e28b171 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/skill/references/state-management.md @@ -0,0 +1,26 @@ +# State Management + +This app uses BLoC/Cubit pattern for state management. + +## Bloc and Cubits + +- Use predefined base Cubits if possible. +- Use `flutter_bloc` package handlers. +- Never reference `BuildContext` inside `Blocs` and `Cubits`. +- Prefer using cubits for simple cases. +- Define all `Bloc`/`Cubit` related classes including bloc/cubit itself, events, states and presentation events in a single file. +- Use `enum` to define simple states and events handled by `Bloc`/`Cubit`, use sealed class for more complicated cases. +- All `Bloc`/`Cubit` states should have `EquatableMixin` mixed in and `props` field overridden. +- Use `copyWith` from `copy_with_extension` package for creating new, altered instances of the state. +- Use LeanCode-provided base classes if possible. +- Use `leancode_cubit_utils` for supported use cases such as simple data fetching from the backend. + +## Bloc Presentation + +- Use `bloc_presentation` package, especially `BlocPresentationMixin`, for presentation side-effects including navigation, dialogs, snackbars, toasts etc. +- Use `enum` to define presentation events. + +## Internal state + +- Use `flutter_hooks` package for managing presentation state. +- Avoid using `StatefulWidget` at all if possible. diff --git a/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/task.json b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8d631c7f581d257ceb243e84f8bb0ea67850fb0e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b5f1e59ff310a8b8_q1/task.json @@ -0,0 +1,47 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b5f1e59ff310a8b8", + "query_id": "b5f1e59ff310a8b8_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "1819dd998f263f26ae9d07ee90db3128f50a21f593db465c1526b30de00b51f8", + "name": "flutter-bloc-usage", + "package_path": "skill", + "install_name": "flutter-bloc-usage-091e45b9" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "1819dd998f263f26ae9d07ee90db3128f50a21f593db465c1526b30de00b51f8", + "files": { + "SKILL.md": "8b7ed176554bd0dc088aeae25a2669ea8ef3c3a6379af36e7e106ddeae77652e", + "references/state-management.md": "bd4fd590500cb629ad580fac89198ffd2c031aa1958232183a12dd5ce3114761" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "091e45b9672e5cd6d60faa9bba5dd95370be8f7d875ab1e1fd73dbbb1884e018" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/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/b64c5182687bef6ca45fe44d/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/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/b64c5182687bef6ca45fe44d/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/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(' {\n setTotal(items.reduce((sum, item) => sum + item.price, 0));\n }, [items]);\n\n return

Total: {total}

;\n}\n", 'src/Counter.jsx': "import { useState } from 'react';\n\nexport function Counter() {\n const [count, setCount] = useState(0);\n const isEven = count % 2 === 0;\n\n return ;\n}\n", 'src/Form.jsx': "import { useState, useEffect } from 'react';\n\nexport function Form() {\n const [firstName, setFirstName] = useState('Taylor');\n const [lastName, setLastName] = useState('Swift');\n const [fullName, setFullName] = useState('');\n\n useEffect(() => {\n setFullName(firstName + ' ' + lastName);\n }, [firstName, lastName]);\n\n return

{fullName}

;\n}\n"}, [{'file': 'src/Cart.jsx', 'variable': 'total', 'effect_sets': 'setTotal', 'derived_expression': 'items.reduce((sum, item) => sum + item.price, 0)', 'fix': 'calculate during render'}, {'file': 'src/Form.jsx', 'variable': 'fullName', 'effect_sets': 'setFullName', 'derived_expression': "firstName + ' ' + lastName", 'fix': 'calculate during render'}]), ({'src/ZText.jsx': 'import {useState,useEffect} from \'react\';\nexport function Panel({input,other,items}) {\n let [text, setText] = useState(\'\');\n useEffect(() => {setText(input + " ) ; " + other);}, [input,other,items]);\n return null;\n}\n', 'src/BArray.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [filtered, setFiltered] = useState([]);\n useEffect(() => {setFiltered(items.filter(item => item.active));}, [input,other,items]);\n return null;\n}\n", 'src/NNull.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n var [chosen, setChosen] = useState(null);\n useEffect(() => setChosen(items[0] ?? null), [input,other,items]);\n return null;\n}\n", 'src/CZero.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [sum, setSum] = useState(0);\n useEffect(() => {setSum(input + other);}, [input,other,items]);\n return null;\n}\n", 'src/AFalse.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [ready, setReady] = useState(false);\n useEffect(() => {setReady(input === true);}, [input,other,items]);\n return null;\n}\n", 'src/SideEffect.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [out, setOut] = useState(0);\n useEffect(() => {console.log(input);setOut(input);}, [input,other,items]);\n return null;\n}\n", 'src/Seeded.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [out, setOut] = useState(123);\n useEffect(() => {setOut(input);}, [input,other,items]);\n return null;\n}\n", 'src/Self.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [out, setOut] = useState(0);\n useEffect(() => {setOut(out + 1);}, [input,other,items]);\n return null;\n}\n", 'src/UnknownSetter.jsx': 'export function X({input}) {useEffect(()=>{setMissing(input)},[input]); return null;}\n', 'src/Multi.jsx': "import {useState,useEffect} from 'react';\nexport function Multi({input,other}) {\n const [zeta,setZeta]=useState('');\n const [alpha,setAlpha]=useState(0);\n useEffect(()=>{setZeta(input + other);},[input,other]);\n useEffect(()=>{setAlpha(other * 2);},[other]);\n return null;\n}\n"}, [{'file': 'src/AFalse.jsx', 'variable': 'ready', 'effect_sets': 'setReady', 'derived_expression': 'input === true', 'fix': 'calculate during render'}, {'file': 'src/BArray.jsx', 'variable': 'filtered', 'effect_sets': 'setFiltered', 'derived_expression': 'items.filter(item => item.active)', 'fix': 'calculate during render'}, {'file': 'src/CZero.jsx', 'variable': 'sum', 'effect_sets': 'setSum', 'derived_expression': 'input + other', 'fix': 'calculate during render'}, {'file': 'src/Multi.jsx', 'variable': 'alpha', 'effect_sets': 'setAlpha', 'derived_expression': 'other * 2', 'fix': 'calculate during render'}, {'file': 'src/Multi.jsx', 'variable': 'zeta', 'effect_sets': 'setZeta', 'derived_expression': 'input + other', 'fix': 'calculate during render'}, {'file': 'src/NNull.jsx', 'variable': 'chosen', 'effect_sets': 'setChosen', 'derived_expression': 'items[0] ?? null', 'fix': 'calculate during render'}, {'file': 'src/ZText.jsx', 'variable': 'text', 'effect_sets': 'setText', 'derived_expression': 'input + " ) ; " + other', 'fix': 'calculate during render'}]), ({'src/NoEffect.jsx': 'export function X({input}) {const value=input*2;return

{value}

;}\n', 'src/Seeded.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [out, setOut] = useState(123);\n useEffect(() => {setOut(input);}, [input,other,items]);\n return null;\n}\n", 'src/SideEffect.jsx': "import {useState,useEffect} from 'react';\nexport function Panel({input,other,items}) {\n const [out, setOut] = useState(0);\n useEffect(() => {console.log(input);setOut(input);}, [input,other,items]);\n return null;\n}\n"}, []), ({}, [])] +# Named effect callbacks are the same public setter-only body; comments and +# strings containing hook-looking text do not create actual declarations. +PANELS[1][0]['src/Named.jsx']="import {useState,useEffect} from 'react';\nexport function Named({input,other}) {const [mirror,setMirror]=useState(null);useEffect(function sync(){setMirror(input + other);},[input,other]);return null;}\n" +PANELS[1][1].append(dict(file='src/Named.jsx',variable='mirror',effect_sets='setMirror',derived_expression='input + other',fix='calculate during render'));PANELS[1][1].sort(key=lambda row:(row['file'],row['variable'])) +PANELS[1][0]['src/HookDecoys.jsx']="import {useState,useEffect} from 'react';\nexport function Decoy({input}) {const [fake,setFake]=useState(0);\n// useEffect(()=>{setFake(input);},[input]);\nconst note='useEffect(()=>{setFake(input);},[input]);';return note;}\n" +# Unknown external identifiers cannot be derived solely from state/props/literals. +PANELS[1][0]['src/UnknownInput.jsx']="export function UnknownInput({input}) {const [mirror,setMirror]=useState(0);useEffect(()=>{setMirror(input + externalValue);},[input]);return null;}\n" +PANELS[1][0]['src/ClockInput.jsx']="export function ClockInput({input}) {const [mirror,setMirror]=useState(0);useEffect(()=>{setMirror(input + Date.now());},[input]);return null;}\n" +FIELDS=['file','variable','effect_sets','derived_expression','fix'] +def tri(values):return False if any(v is False for v in values)else None if any(v is None for v in values)else True +def normalize_file(path): + path=path.replace('\\','/').removeprefix('./') + for prefix in ['/workspace/','/app/','/candidate/']: + if path.startswith(prefix):return path[len(prefix):] + return path +def entity(row): + return(normalize_file(row['file']),row['variable'],row['effect_sets'])if isinstance(row,dict)and all(isinstance(row.get(k),str)for k in FIELDS[:3])else None +def identity(row): + if not isinstance(row,dict)or not all(isinstance(row.get(k),str)for k in FIELDS[:4]):return None + file=normalize_file(row['file']) + return(file,row['variable'],row['effect_sets'],row['derived_expression']) +def stdout_count(text,want): + return isinstance(text,str)and re.fullmatch(r'\s*'+str(want)+r'\s*',text)is not None + +def assess(report,want): + if not isinstance(report,list):return [False]*5 + identities=[identity(row)for row in report];shape=all(isinstance(row,dict)and all(isinstance(row.get(k),str)for k in FIELDS)for row in report)and len(report)==len(want) + valid=[value for value in identities if value is not None];expected=[identity(row)for row in want] + # Form/string-derived and Cart/remaining-derived evidence remain distinct + # original checks rather than repeating every semantic error across them. + text_expected=[value for value in expected if value[1]in['fullName','text','zeta']] + other_expected=[value for value in expected if value not in text_expected] + counter=collections.Counter(valid);entities=collections.Counter(value for value in map(entity,report)if value is not None);want_entities=collections.Counter(value[:3]for value in expected);no_extra=all(entities[value]<=want_entities[value]for value in entities) + text_ok=all(counter[value]==collections.Counter(expected)[value]for value in text_expected) + other_ok=all(counter[value]==collections.Counter(expected)[value]for value in other_expected) + keys=[(row.get('file'),row.get('variable'))for row in report if isinstance(row,dict)] + sorting=len(keys)==len(report)and all(isinstance(a,str)and isinstance(b,str)for a,b in keys)and keys==sorted(keys) + presentation=sorting and all(isinstance(row,dict)and row.get('fix')=='calculate during render'for row in report) + return [shape,text_ok,other_ok,no_extra,presentation] +def run(files): + with workspace(remove=('report.',*PANELS[0][0]))as root: + roots=[root,Path('/app')] + for site in roots: + (site/'src').mkdir(exist_ok=True) + for name,text in files.items():p=site/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text) + p=subprocess.run([sys.executable,'audit.py'],cwd=root,capture_output=True,text=True,timeout=30) + reports=[] + for site in roots: + if not(site/'report.').exists():continue + try:reports.append(json.loads((site/'report.').read_text())) + except(OSError,ValueError):reports.append(None) + return p.returncode,p.stdout,reports or[None] +def main(): + flags=[True]*7 + for files,want in PANELS: + try:rc,stdout,reports=run(files) + except(OSError,subprocess.SubprocessError):rc,stdout,reports=None,None,[None] + flags[0]=tri([flags[0],None if rc is None else rc>=0]);flags[6]=tri([flags[6],None if rc is None else stdout_count(stdout,len(want))]) + for report in reports: + for i,value in enumerate([None]*5 if rc is None else assess(report,want),1):flags[i]=tri([flags[i],value]) + dep,_,reason=scan_stdlib('/candidate',['audit.py']);dep=None if reason.startswith('unknown:')else dep;flags[0]=tri([flags[0],dep]) + print(json.dumps({'scoreable':not any(v is None for v in flags),'checks':[dict(id=str(i),passed=v,reason='Pure write-program contract evaluated fresh, no private pre-stored report gate. Complete hand-labelled source panels independently cover string/array/null/zero/false state, secondary declarations, true setter-only body, nonempty initializer/sideeffect/self-state/undeclared setter decoys, literal punctuation and exact expression text, sorted by file then variable, exact fix and truthful count. Full dual-root clone preserves helpers/resources. Original7 IDs/equalweights and owned dependency/count uncertainty retained.')for i,v in enumerate(flags)]})) +main() diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..d1d9d37966777fef47549fc864468a0ff5330e93 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/repair_manifest.json @@ -0,0 +1,48 @@ +{ + "query_id": "b64c5182687bef6ca45fe44d", + "sample_index": 695, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "original_count": 7, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "root_cause": "Owned numeric relation != was omitted from local denial detection; a number-plus-unit alternative could promote a denied total or category score to a positive fact.", + "public_semantics": "Bind inequality to the owned displayed count or category quantity, preserving independent unknowns and unrelated symbolic inequality.", + "source_hashes": { + "instruction.md": "64c8be9fd2220d9c0adda9e1f92b4c631a1b5570cc4adf2c20d32314efbc055c", + "task.json": "9558bfe3427901a53488e96b3eab95eec4116a3f0c8fb48af2fa5898b31bdf23", + "evaluator/check.py": "e3f9994c28b908e411019c7e90764ec14fc7c0bfa5516a737095d7c67c84db62", + "skill/SKILL.md": "b1965a2027e04bc75d641239f43bae1ef3a0a58b444c4c846ae24ba6baf3aa76", + "inputs/src/Cart.jsx": "5f32edebd876b0c9050e737adbd42b07ba17c11ca698c96550680c381bdea18e", + "inputs/src/Counter.jsx": "3a1472e4583b9a49b07c8fc464db415ced81fbdbe1865352640408489bdf0e0a", + "inputs/src/Form.jsx": "ae895eeaad8021464865003d992f30ae6104fb674d3db4ba607294f521dd387c" + }, + "required_historical_artifacts": [], + "checker_sha256": "4a86ff88ba7b6209d5a8f260c4d278c010241fd106b914b799b767f4419ae6a8", + "all_logic_sha256": { + "check.py": "4a86ff88ba7b6209d5a8f260c4d278c010241fd106b914b799b767f4419ae6a8", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": "Delta after independent FULL review: isolated != quantity negative and unrelated inequality positive, all full typed maps; AST only, no candidate/grader execution, no new solver or historical rescore.", + "repair_scope": "grader_only_second_round", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d23f87059c17c891c9c55dd74ccabfd662b7656 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6dfd077da769cd6365de2f559458040e8265f4fe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/grading/verified_config.json @@ -0,0 +1,42 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b64c5182687bef6ca45fe44d", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "cd859930b7a46f578550df37bf228eaede9524cfb5a8d73a1d0d63ba3bd41ea4", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "0de9c636c74e3d554ea6b2ab06a2be22a76ee627c600d9234b282b2d8d1796d0", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "947df08e8912dc38898c7fc8a2f962babd3b4d7c81ed39926eeba69b5f300999", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Cart.jsx b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Cart.jsx new file mode 100644 index 0000000000000000000000000000000000000000..d1fef3f41e1aa750943e0c8b522766664e8da592 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Cart.jsx @@ -0,0 +1,11 @@ +import { useState, useEffect } from 'react'; + +export function Cart({ items }) { + const [total, setTotal] = useState(0); + + useEffect(() => { + setTotal(items.reduce((sum, item) => sum + item.price, 0)); + }, [items]); + + return

Total: {total}

; +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Counter.jsx b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Counter.jsx new file mode 100644 index 0000000000000000000000000000000000000000..48e65f42fbc0492d12cccf38a80fa88f8f4363e7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Counter.jsx @@ -0,0 +1,8 @@ +import { useState } from 'react'; + +export function Counter() { + const [count, setCount] = useState(0); + const isEven = count % 2 === 0; + + return ; +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Form.jsx b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Form.jsx new file mode 100644 index 0000000000000000000000000000000000000000..adb9c78eff6f168b90ee31fac8750dcdad50a244 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/inputs/src/Form.jsx @@ -0,0 +1,13 @@ +import { useState, useEffect } from 'react'; + +export function Form() { + const [firstName, setFirstName] = useState('Taylor'); + const [lastName, setLastName] = useState('Swift'); + const [fullName, setFullName] = useState(''); + + useEffect(() => { + setFullName(firstName + ' ' + lastName); + }, [firstName, lastName]); + + return

{fullName}

; +} diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/instruction.md b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1dcab6eead74e2a5e01300c0d74da4acc600e965 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/instruction.md @@ -0,0 +1,8 @@ +You are given three small React component source files in `src/`. Write a Python 3 script `audit.py` (standard library only) that performs a static audit of these files for the 'redundant Effect' anti-pattern: using useState for a value that is purely derived from props/state and then keeping it in sync with a useEffect that calls the setter. For each file, the script must: (1) find every `useState()` declaration and record the variable name and initializer; (2) find every `useEffect(...)` block whose body consists solely of a call to a `()` where `` is built only from other state/prop variables and literals (i.e., the setter's variable is also declared via useState and its initializer is the empty string `''`, empty array `[]`, null, 0, or false — indicating it is redundant derived state); (3) for each detected anti-pattern, compute the derived expression that should be computed during render instead. Write the report to `report.` as a JSON array of objects `{"file": , "variable": , "effect_sets": , "derived_expression": , "fix": "calculate during render"}` sorted by file then variable. Files with no anti-patterns must simply not appear. Also print to stdout the total count of anti-patterns found. +For deterministic stdout checking print exactly one decimal integer: the total count, followed by a newline. Do not mix explanatory text into stdout; optional explanations may be placed in the formal answer. + + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/b64c5182687bef6ca45fe44d/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..f893c5db7cc2974d7c3aaf67fe3302671a2df33c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/SKILL.md @@ -0,0 +1,49 @@ +--- +name: react-useeffect +description: React useEffect best practices from official docs. Use when writing/reviewing useEffect, useState for derived values, data fetching, or state synchronization. Teaches when NOT to use Effect and better alternatives. +--- + +# You Might Not Need an Effect + +Effects are an **escape hatch** from React. They let you synchronize with external systems. If there is no external system involved, you shouldn't need an Effect. + +## Quick Reference + +| Situation | DON'T | DO | +|-----------|-------|-----| +| Derived state from props/state | `useState` + `useEffect` | Calculate during render | +| Expensive calculations | `useEffect` to cache | `useMemo` | +| Reset state on prop change | `useEffect` with `setState` | `key` prop | +| User event responses | `useEffect` watching state | Event handler directly | +| Notify parent of changes | `useEffect` calling `onChange` | Call in event handler | +| Fetch data | `useEffect` without cleanup | `useEffect` with cleanup OR framework | + +## When You DO Need Effects + +- Synchronizing with **external systems** (non-React widgets, browser APIs) +- **Subscriptions** to external stores (use `useSyncExternalStore` when possible) +- **Analytics/logging** that runs because component displayed +- **Data fetching** with proper cleanup (or use framework's built-in mechanism) + +## When You DON'T Need Effects + +1. **Transforming data for rendering** - Calculate at top level, re-runs automatically +2. **Handling user events** - Use event handlers, you know exactly what happened +3. **Deriving state** - Just compute it: `const fullName = firstName + ' ' + lastName` +4. **Chaining state updates** - Calculate all next state in the event handler + +## Decision Tree + +``` +Need to respond to something? +├── User interaction (click, submit, drag)? └── Use EVENT HANDLER +├── Component appeared on screen? └── Use EFFECT (external sync, analytics) +├── Props/state changed and need derived value? └── CALCULATE DURING RENDER └── Expensive? Use useMemo +└── Need to reset state when prop changes? + └── Use KEY PROP on component +``` + +## Detailed Guidance + +- [Anti-Patterns](./anti-patterns.md) - Common mistakes with fixes +- [Better Alternatives](./alternatives.md) - useMemo, key prop, lifting state, useSyncExternalStore \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/alternatives.md b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/alternatives.md new file mode 100644 index 0000000000000000000000000000000000000000..7a93b363ab4f8d01126149969de72316097aec61 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/alternatives.md @@ -0,0 +1,258 @@ +# Better Alternatives to useEffect + +## 1. Calculate During Render (Derived State) + +For values derived from props or state, just compute them: + +```tsx +function Form() { + const [firstName, setFirstName] = useState('Taylor'); + const [lastName, setLastName] = useState('Swift'); + + // Runs every render - that's fine and intentional + const fullName = firstName + ' ' + lastName; + const isValid = firstName.length > 0 && lastName.length > 0; +} +``` + +**When to use**: The value can be computed from existing props/state. + +--- + +## 2. useMemo for Expensive Calculations + +When computation is expensive, memoize it: + +```tsx +import { useMemo } from 'react'; + +function TodoList({ todos, filter }) { + const visibleTodos = useMemo( + () => getFilteredTodos(todos, filter), + [todos, filter] + ); +} +``` + +**How to know if it's expensive**: +```tsx +console.time('filter'); +const visibleTodos = getFilteredTodos(todos, filter); +console.timeEnd('filter'); +// If > 1ms, consider memoizing +``` + +**Note**: React Compiler can auto-memoize, reducing manual useMemo needs. + +--- + +## 3. Key Prop to Reset State + +To reset ALL state when a prop changes, use key: + +```tsx +// Parent passes userId as key +function ProfilePage({ userId }) { + return ( + + ); +} + +function Profile({ userId }) { + // All state here resets when userId changes + const [comment, setComment] = useState(''); + const [likes, setLikes] = useState([]); +} +``` + +**When to use**: You want a "fresh start" when an identity prop changes. + +--- + +## 4. Store ID Instead of Object + +To preserve selection when list changes: + +```tsx +// BAD: Storing object that needs Effect to "adjust" +function List({ items }) { + const [selection, setSelection] = useState(null); + + useEffect(() => { + setSelection(null); // Reset when items change + }, [items]); +} + +// GOOD: Store ID, derive object +function List({ items }) { + const [selectedId, setSelectedId] = useState(null); + + // Derived - no Effect needed + const selection = items.find(item => item.id === selectedId) ?? null; +} +``` + +**Benefit**: If item with selectedId exists in new list, selection preserved. + +--- + +## 5. Event Handlers for User Actions + +User clicks/submits/drags should be handled in event handlers, not Effects: + +```tsx +// Event handler knows exactly what happened +function ProductPage({ product, addToCart }) { + function handleBuyClick() { + addToCart(product); + showNotification(`Added ${product.name}!`); + analytics.track('product_added', { id: product.id }); + } + + function handleCheckoutClick() { + addToCart(product); + showNotification(`Added ${product.name}!`); + navigateTo('/checkout'); + } +} +``` + +**Shared logic**: Extract a function, call from both handlers: + +```tsx +function buyProduct() { + addToCart(product); + showNotification(`Added ${product.name}!`); +} + +function handleBuyClick() { buyProduct(); } +function handleCheckoutClick() { buyProduct(); navigateTo('/checkout'); } +``` + +--- + +## 6. useSyncExternalStore for External Stores + +For subscribing to external data (browser APIs, third-party stores): + +```tsx +// Instead of manual Effect subscription +function useOnlineStatus() { + const [isOnline, setIsOnline] = useState(true); + + useEffect(() => { + function update() { setIsOnline(navigator.onLine); } + window.addEventListener('online', update); + window.addEventListener('offline', update); + return () => { + window.removeEventListener('online', update); + window.removeEventListener('offline', update); + }; + }, []); + + return isOnline; +} + +// Use purpose-built hook +import { useSyncExternalStore } from 'react'; + +function subscribe(callback) { + window.addEventListener('online', callback); + window.addEventListener('offline', callback); + return () => { + window.removeEventListener('online', callback); + window.removeEventListener('offline', callback); + }; +} + +function useOnlineStatus() { + return useSyncExternalStore( + subscribe, + () => navigator.onLine, // Client value + () => true // Server value (SSR) + ); +} +``` + +--- + +## 7. Lifting State Up + +When two components need synchronized state, lift it to common ancestor: + +```tsx +// Instead of syncing via Effects between siblings +function Parent() { + const [value, setValue] = useState(''); + + return ( + <> + + + + ); +} +``` + +--- + +## 8. Custom Hooks for Data Fetching + +Extract fetch logic with proper cleanup: + +```tsx +function useData(url) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let ignore = false; + setLoading(true); + + fetch(url) + .then(res => res.json()) + .then(json => { + if (!ignore) { + setData(json); + setError(null); + } + }) + .catch(err => { + if (!ignore) setError(err); + }) + .finally(() => { + if (!ignore) setLoading(false); + }); + + return () => { ignore = true; }; + }, [url]); + + return { data, error, loading }; +} + +// Usage +function SearchResults({ query }) { + const { data, error, loading } = useData(`/api/search?q=${query}`); +} +``` + +**Better**: Use framework's data fetching (React Query, SWR, Next.js, etc.) + +--- + +## Summary: When to Use What + +| Need | Solution | +|------|----------| +| Value from props/state | Calculate during render | +| Expensive calculation | `useMemo` | +| Reset all state on prop change | `key` prop | +| Respond to user action | Event handler | +| Sync with external system | `useEffect` with cleanup | +| Subscribe to external store | `useSyncExternalStore` | +| Share state between components | Lift state up | +| Fetch data | Custom hook with cleanup / framework | \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/anti-patterns.md b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/anti-patterns.md new file mode 100644 index 0000000000000000000000000000000000000000..63d8fe319d195aa2fd68baa78ac935d03bb2a6e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/skill/anti-patterns.md @@ -0,0 +1,290 @@ +# useEffect Anti-Patterns + +## 1. Redundant State for Derived Values + +```tsx +// BAD: Extra state + Effect for derived value +function Form() { + const [firstName, setFirstName] = useState('Taylor'); + const [lastName, setLastName] = useState('Swift'); + const [fullName, setFullName] = useState(''); + + useEffect(() => { + setFullName(firstName + ' ' + lastName); + }, [firstName, lastName]); +} + +// GOOD: Calculate during rendering +function Form() { + const [firstName, setFirstName] = useState('Taylor'); + const [lastName, setLastName] = useState('Swift'); + const fullName = firstName + ' ' + lastName; // Just compute it +} +``` + +**Why it's bad**: Causes extra render pass with stale value, then re-renders with updated value. + +--- + +## 2. Filtering/Transforming Data in Effect + +```tsx +// BAD: Effect to filter list +function TodoList({ todos, filter }) { + const [visibleTodos, setVisibleTodos] = useState([]); + + useEffect(() => { + setVisibleTodos(getFilteredTodos(todos, filter)); + }, [todos, filter]); +} + +// GOOD: Filter during render (memoize if expensive) +function TodoList({ todos, filter }) { + const visibleTodos = useMemo( + () => getFilteredTodos(todos, filter), + [todos, filter] + ); +} +``` + +--- + +## 3. Resetting State on Prop Change + +```tsx +// BAD: Effect to reset state +function ProfilePage({ userId }) { + const [comment, setComment] = useState(''); + + useEffect(() => { + setComment(''); + }, [userId]); +} + +// GOOD: Use key prop +function ProfilePage({ userId }) { + return ; +} + +function Profile({ userId }) { + const [comment, setComment] = useState(''); // Resets automatically +} +``` + +**Why key works**: React treats components with different keys as different components, recreating state. + +--- + +## 4. Event-Specific Logic in Effect + +```tsx +// BAD: Effect for button click result +function ProductPage({ product, addToCart }) { + useEffect(() => { + if (product.isInCart) { + showNotification(`Added ${product.name}!`); + } + }, [product]); + + function handleBuyClick() { + addToCart(product); + } +} + +// GOOD: Handle in event handler +function ProductPage({ product, addToCart }) { + function handleBuyClick() { + addToCart(product); + showNotification(`Added ${product.name}!`); + } +} +``` + +**Why it's bad**: Effect fires on page refresh (isInCart is true), showing notification unexpectedly. + +--- + +## 5. Chains of Effects + +```tsx +// BAD: Effects triggering each other +function Game() { + const [card, setCard] = useState(null); + const [goldCardCount, setGoldCardCount] = useState(0); + const [round, setRound] = useState(1); + const [isGameOver, setIsGameOver] = useState(false); + + useEffect(() => { + if (card?.gold) setGoldCardCount(c => c + 1); + }, [card]); + + useEffect(() => { + if (goldCardCount > 3) { + setRound(r => r + 1); + setGoldCardCount(0); + } + }, [goldCardCount]); + + useEffect(() => { + if (round > 5) setIsGameOver(true); + }, [round]); +} + +// GOOD: Calculate in event handler +function Game() { + const [card, setCard] = useState(null); + const [goldCardCount, setGoldCardCount] = useState(0); + const [round, setRound] = useState(1); + const isGameOver = round > 5; // Derived! + + function handlePlaceCard(nextCard) { + if (isGameOver) throw Error('Game ended'); + + setCard(nextCard); + if (nextCard.gold) { + if (goldCardCount < 3) { + setGoldCardCount(goldCardCount + 1); + } else { + setGoldCardCount(0); + setRound(round + 1); + if (round === 5) alert('Good game!'); + } + } + } +} +``` + +**Why it's bad**: Multiple re-renders (setCard -> setGoldCardCount -> setRound -> setIsGameOver). Also fragile for features like history replay. + +--- + +## 6. Notifying Parent via Effect + +```tsx +// BAD: Effect to notify parent +function Toggle({ onChange }) { + const [isOn, setIsOn] = useState(false); + + useEffect(() => { + onChange(isOn); + }, [isOn, onChange]); + + function handleClick() { + setIsOn(!isOn); + } +} + +// GOOD: Notify in same event +function Toggle({ onChange }) { + const [isOn, setIsOn] = useState(false); + + function updateToggle(nextIsOn) { + setIsOn(nextIsOn); + onChange(nextIsOn); // Same event, batched render + } + + function handleClick() { + updateToggle(!isOn); + } +} + +// BEST: Fully controlled component +function Toggle({ isOn, onChange }) { + function handleClick() { + onChange(!isOn); + } +} +``` + +--- + +## 7. Passing Data Up to Parent + +```tsx +// BAD: Child fetches, passes up via Effect +function Parent() { + const [data, setData] = useState(null); + return ; +} + +function Child({ onFetched }) { + const data = useSomeAPI(); + + useEffect(() => { + if (data) onFetched(data); + }, [onFetched, data]); +} + +// GOOD: Parent fetches, passes down +function Parent() { + const data = useSomeAPI(); + return ; +} +``` + +**Why**: Data should flow down. Upward flow via Effects makes debugging hard. + +--- + +## 8. Fetching Without Cleanup (Race Condition) + +```tsx +// BAD: No cleanup - race condition +function SearchResults({ query }) { + const [results, setResults] = useState([]); + + useEffect(() => { + fetchResults(query).then(json => { + setResults(json); // "hello" response may arrive after "hell" + }); + }, [query]); +} + +// GOOD: Cleanup ignores stale responses +function SearchResults({ query }) { + const [results, setResults] = useState([]); + + useEffect(() => { + let ignore = false; + + fetchResults(query).then(json => { + if (!ignore) setResults(json); + }); + + return () => { ignore = true; }; + }, [query]); +} +``` + +--- + +## 9. App Initialization in Effect + +```tsx +// BAD: Runs twice in dev, may break auth +function App() { + useEffect(() => { + loadDataFromLocalStorage(); + checkAuthToken(); // May invalidate token on second call! + }, []); +} + +// GOOD: Module-level guard +let didInit = false; + +function App() { + useEffect(() => { + if (!didInit) { + didInit = true; + loadDataFromLocalStorage(); + checkAuthToken(); + } + }, []); +} + +// ALSO GOOD: Module-level execution +if (typeof window !== 'undefined') { + checkAuthToken(); + loadDataFromLocalStorage(); +} +``` \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/task.json b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1ad7cdfb0e621cf614246e0a16643644997d5c8a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b64c5182687bef6ca45fe44d/task.json @@ -0,0 +1,86 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "b64c5182687bef6ca45fe44d", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "b64c5182687bef6ca45fe44d", + "outputs": [ + "audit.py", + "report." + ], + "success_criteria": [ + "Running `python3 audit.py` from the workspace root completes without errors using only the Python standard library. Dependency/resource checks apply only to the actual guarded Python invocations under the public bounded runtime policy, not to unused source or static closure inference.", + "report. is valid JSON and is an array containing exactly two entries.", + "One entry has file 'src/Form.jsx', variable 'fullName', effect_sets 'setFullName', and derived_expression \"firstName + ' ' + lastName\".", + "One entry has file 'src/Cart.jsx', variable 'total', effect_sets 'setTotal', and a derived_expression containing 'items.reduce'.", + "src/Counter.jsx does not appear in report. because it contains no useEffect and no redundant derived state.", + "Every entry in report. has fix equal to 'calculate during render' and entries are sorted by file path.", + "Fresh stdout is exactly the decimal integer count of actual anti-patterns, without prose." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "3f9849396fae6bbb020e9edd1b322f94c3bb468ca8d7337dad747e6d517bd7a0", + "files": { + "SKILL.md": "b1965a2027e04bc75d641239f43bae1ef3a0a58b444c4c846ae24ba6baf3aa76", + "alternatives.md": "3b5e0bce0faa31bf3d25a161ca5079a101c98bbfccaae4bbaf75fc6f6789be38", + "anti-patterns.md": "67cf28e01398276578976153ea00a74b41aa46b99136841a384725cc74a6fd89" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/src/Form.jsx", + "workspace_target": "src/Form.jsx", + "sha256": "ae895eeaad8021464865003d992f30ae6104fb674d3db4ba607294f521dd387c" + }, + { + "source": "inputs/src/Cart.jsx", + "workspace_target": "src/Cart.jsx", + "sha256": "5f32edebd876b0c9050e737adbd42b07ba17c11ca698c96550680c381bdea18e" + }, + { + "source": "inputs/src/Counter.jsx", + "workspace_target": "src/Counter.jsx", + "sha256": "3a1472e4583b9a49b07c8fc464db415ced81fbdbe1865352640408489bdf0e0a" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "3f9849396fae6bbb020e9edd1b322f94c3bb468ca8d7337dad747e6d517bd7a0" + } + ] + }, + "autograde_contract_revision": "deterministic-v1", + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/b6a850c04f05ba0998385042/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/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/b6a850c04f05ba0998385042/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/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/b6a850c04f05ba0998385042/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/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('{start}\n', 'src/components/Footer.astro': '---\nconst year = new Date().getFullYear();\n---\n
© {year}
\n\n', 'src/components/Header.astro': '---\nconst { nav } = Astro.props;\n---\n\n', 'src/components/ThemeToggle.astro': '---\nconst mode = document.documentElement.dataset.mode;\n---\n\n\n', 'src/layouts/Base.astro': '---\nconst title = Astro.props.title;\n---\n\n {title}\n \n \n \n\n\n', 'src/pages/blog/[slug].astro': '---\nconst { slug } = Astro.params;\n---\n
{slug}
\n', 'src/pages/docs/[topic].astro': "---\nconst topic = 'guide';\n---\n
{topic}
\n", 'src/pages/index.astro': "---\nimport Header from '../components/Header.astro';\n---\n\n \n

Home

\n
\n"}, [(2, 'src/components/Counter.astro', [2], 'window'), (1, 'src/components/Footer.astro', [5], 'client:idle'), (3, 'src/components/ThemeToggle.astro', [0, 1, 2, 3, 4, 5, 6, 7, 8], ''), (2, 'src/components/ThemeToggle.astro', [2], 'document'), (4, 'src/pages/docs/[topic].astro', [0, 1, 2, 3, 4, 5], ''), (1, 'src/pages/index.astro', [5], 'client:visible')]), ({'src/deep/flags.astro': '---\nconst z=window.innerWidth;\nconst y=document.body;\nconst quoted="window.x";\n// document.x is only documentation\n---\n\n\n\n\n\n\n\n\n\n\n', 'src/deep/quoted-marker.astro': '---\nconst marker="/* global-needed */";\n---\n\n', 'src/styles/approved.astro': '\n\n', 'src/pages/[group]/fixed.astro': '

No dynamic filename here

\n', 'src/pages/new/[id].astro': '

No parameters

\n', 'src/pages/new/[ok].astro': '\n

Literal marker satisfies explicit rule4

\n', 'src/components/[not-route].astro': '

Not a pages route

\n', 'src/ignored.txt': '\n'}, [(2, 'src/deep/flags.astro', [2], 'window'), (2, 'src/deep/flags.astro', [3], 'document'), (1, 'src/deep/flags.astro', [7, 8], 'client:load'), (1, 'src/deep/flags.astro', [9], 'client:media'), (1, 'src/deep/flags.astro', [10], 'client:idle'), (1, 'src/deep/flags.astro', [11], 'client:visible'), (1, 'src/deep/flags.astro', [12], 'client:only'), (3, 'src/deep/flags.astro', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17], ''), (3, 'src/deep/quoted-marker.astro', [0, 1, 2, 3, 4], ''), (4, 'src/pages/new/[id].astro', [0, 1], '')]), ({'src/deep/safe.astro': '---\nconst note="window.document";\n// document.body is commentary\n---\n\n\n\n', 'src/pages/[x]/fixed.astro': '

No dynamic filename here

\n', 'src/style/allowed.astro': '\n\n'}, []), ({}, [])] +PANELS.append(({'src/repeated.astro': '---\nconst n = window.a + window.b + document.a + document.b;\n---\n

tokens

\n'}, [(2, 'src/repeated.astro', [2], 'window'), (2, 'src/repeated.astro', [2], 'window'), (2, 'src/repeated.astro', [2], 'document'), (2, 'src/repeated.astro', [2], 'document')])) + +def tri(values):return False if any(v is False for v in values)else None if any(v is None for v in values)else True +def classify(message): + hit=re.match(r'^R([1-4])(?:\s|$)',message) + return int(hit[1])if hit else 0 + +def owned_message(message):return message + +def edge(row,want): + rule,path,lines,token=want;level,got_path,line,message=row + expected_token=token if token else 'is:global'if rule==3 else 'Astro.params' + prefix='R'+str(rule)+' '+expected_token + return got_path==path and line in lines and level==('ERROR'if rule in[2,4]else'WARN')and(message==prefix or message.startswith(prefix+' | ')) + +def inject(rows,want,unknown): + if len(rows)>len(want):return False + order=sorted(range(len(rows)),key=lambda i:sum(edge(rows[i],w)is True or unknown and edge(rows[i],w)is None for w in want));used=set() + def visit(at): + if at==len(order):return True + row=rows[order[at]] + for j,w in enumerate(want): + value=edge(row,w) + if j not in used and(value is True or unknown and value is None): + used.add(j) + if visit(at+1):return True + used.remove(j) + return False + return visit(0) +def parse(report): + if not isinstance(report,str):return [],False,None + lines=[line for line in report.splitlines()if line.strip()];summary=re.fullmatch(r'SUMMARY: (\d+) errors, (\d+) warnings',lines[-1])if lines else None;rows=[];valid=bool(summary) + for line in lines[:-1]if summary else lines: + hit=re.fullmatch(r'(WARN|ERROR): (.+):(\d+): (\S.*)',line) + if not hit:valid=False;continue + path=hit[2].replace('\\','/').removeprefix('./') + for prefix in ['/workspace/','/app/','/candidate/']: + if path.startswith(prefix):path=path[len(prefix):];break + try:number=int(hit[3]) + except ValueError:valid=False;continue + rows.append((hit[1],path,number,hit[4])) + try:counts=tuple(map(int,summary.groups()))if summary else None + except ValueError:counts=None;valid=False + return rows,valid,counts + +def assess(report,want): + rows,formatting,summary=parse(report);flags=[] + for rule in[2,1,3,4]: + expected=[w for w in want if w[0]==rule];known=[row for row in rows if classify(owned_message(row[3]))==rule];unknown=[row for row in rows if classify(owned_message(row[3]))is None and any(edge(row,w)is None for w in expected)] + if not inject(known,expected,False): + flags.append(None if inject(known,expected,True)and len(known)==len(expected)else False);continue + if len(known)==len(expected):flags.append(None if unknown else True) + elif len(known)+len(unknown)>=len(expected)and inject(known,expected,True):flags.append(None) + else:flags.append(False) + sorting=[(row[1],row[2])for row in rows]==sorted((row[1],row[2])for row in rows) + # Check5 validates presentation and absence of extra fabricated rows without + # repeating a missing rule's penalty merely because the list is shorter. + # Bind rows to distinct actual source entities using paths/allowed locations, + # without repeating severity/token/message truth owned by checks1..4. + order=sorted(range(len(rows)),key=lambda i:sum(rows[i][1]==w[1]and rows[i][2]in w[2]for w in want));used=set() + def bind(at): + if at==len(order):return True + row=rows[order[at]] + for j,w in enumerate(want): + if j not in used and row[1]==w[1]and row[2]in w[2]: + used.add(j) + if bind(at+1):return True + used.remove(j) + return False + extra=bind(0) + presentation=tri([formatting,sorting,extra]);actual_summary=(sum(w[0]in[2,4]for w in want),sum(w[0]in[1,3]for w in want)) + return flags+[presentation,summary==actual_summary] + +def run(files): + with workspace(remove=('report.txt',*PANELS[0][0]))as root: + roots=[root,Path('/app')] + for site in roots: + (site/'src').mkdir(exist_ok=True) + for name,text in files.items():p=site/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text) + p=subprocess.run([sys.executable,'astro_lint.py'],cwd=root,capture_output=True,text=True,errors='replace',timeout=30) + reports=[] + for site in roots: + try: + if(site/'report.txt').is_file():reports.append((site/'report.txt').read_text()) + except(UnicodeError,OSError):reports.append(None) + return p.returncode,reports or[None] +def main(): + # The public contract makes the saved report optional. Only fresh replay + # reports are evidence, so arbitrary bytes in an old report are irrelevant. + flags=[True]*7 + for files,want in PANELS: + try:rc,reports=run(files) + except(OSError,subprocess.SubprocessError):rc,reports=None,[None] + flags[0]=tri([flags[0],None if rc is None else rc>=0 and all(isinstance(r,str)for r in reports)]) + for report in reports: + for i,value in enumerate([None]*6 if rc is None else assess(report,want),1):flags[i]=tri([flags[i],value]) + dep,_,why=scan_stdlib('/candidate',['astro_lint.py']);dep=None if why.startswith('unknown:')else dep;flags[0]=tri([flags[0],dep]) + print(json.dumps({'scoreable':not any(v is None for v in flags),'checks':[dict(id=str(i),passed=v,reason='Fresh replay reports and independent hand-labelled recursive Astro panels: all5 owned client attributes on real Astro tags including multiline, browser references only actual frontmatter code, real global-needed comment versus quoted marker, filename-only dynamic routes and literal Astro.params anywhere. Exact owned severity/path/allowed location/token, no missing/extra fabricated findings, true summary and file/line sorting. File-level rules do not privately require line0, lint exit1 allowed. Original7 equalweights; malformed candidate text is a scored failure, trusted runner faults remain unresolved.')for i,v in enumerate(flags)]})) +main() diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7b9e639b00baf1abc9977e0d7d9ba3242c99d336 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/repair_manifest.json @@ -0,0 +1,53 @@ +{ + "query_id": "b6a850c04f05ba0998385042", + "sample_index": 697, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "original_count": 7, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "root_cause": "Assessment bucket assignment still classified raw comparison clauses even after edge semantics were scoped to the owned subject.", + "public_semantics": "Use the same owned clauses for rule classification, known/unknown buckets and edge predicates; a separate example component window reference must not reroute a dynamic route finding.", + "source_hashes": { + "instruction.md": "0c56d1ea9455c51b2eff692099c0b997978ca9b55ad06de71f94882614fa621f", + "task.json": "d7bd012e334bb516eca8d50196da4034bc58881644ac47b214eb6fbc49060b5f", + "evaluator/check.py": "c138ffcfd1ca7a7d1779aa7657a4abdacf670d562623bfeb739eeeff1508d675", + "skill/SKILL.md": "7b4d0cdd91801d9c79bc503f43e6ecf7a6ed2705c1a95de317d350b5d965b906", + "inputs/src/components/Counter.astro": "cfcbbfb8ed97930d68f12a3f4dc044844d692982d43c4406ae08ea6ee30d231a", + "inputs/src/components/Footer.astro": "02f6f0ed18210fb8a81e3ad4265b1c0692b790a3c7b5b6f3ca40336b683fa401", + "inputs/src/components/Header.astro": "759522e0c9d56de6d43ebd9a0d834465385adb98685d1ef2b1c6a1ef6cb522d4", + "inputs/src/components/ThemeToggle.astro": "258a0bcbe89c3a4ea87dc5c599f4dc7e16d89eab0acb6b0edec9977ce75c4138", + "inputs/src/layouts/Base.astro": "fdab93fa7fbafa14c000501bf53ce988b6158791a385a1dab52bb8fcab9f66a0", + "inputs/src/pages/blog/[slug].astro": "f741a982000804745a9763272db50ecdc4a379d04cfff34954de2106569a37ef", + "inputs/src/pages/docs/[topic].astro": "05837b4151c7e67b74d5d6ec9a116ced7e8d73e476f969734a1b459b7d487901", + "inputs/src/pages/index.astro": "f955403d322ada1d79447449a4485ac61ba415143ffaf0f25b834eb80226bc7d" + }, + "required_historical_artifacts": [], + "checker_sha256": "0098c87f1862037caab6fc68ec5aad176f5fdd745195a7babbf94c2f9917fcd5", + "all_logic_sha256": { + "check.py": "0098c87f1862037caab6fc68ec5aad176f5fdd745195a7babbf94c2f9917fcd5", + "dependency_scan.py": "0d8af0f108dab485eda556e74c237d7f8ade6bcdac91d18e1fe01720ee3cd5e9", + "workspace_copy.py": "80dc09f784b712fbfdbdb48853fb83091a678896db01b94cb87b686116cb0aec" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "rubric": "original equal weights", + "notes": "Latest independent delta: complete actual+fresh cross-family comparison positive; both raw classify integration callsites changed, AST only. No candidate/grader execution, new solver or historical score access.", + "repair_scope": "grader_only_second_round", + "historical_scores_seen": false, + "new_solver_executions": 0 +} diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d23f87059c17c891c9c55dd74ccabfd662b7656 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..3fbad0739075bf79cba21790369df9e22df9e4b6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/grading/verified_config.json @@ -0,0 +1,42 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "b6a850c04f05ba0998385042", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "cd859930b7a46f578550df37bf228eaede9524cfb5a8d73a1d0d63ba3bd41ea4", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "12664aa568d8a5dd09cf910b7fca75950edb934ae9b535fc8fdc8724ba4a8a2c", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "57afae6905432dec65f64ac146497ed2c4943e9caedef8fdaea8d70ff91d9223", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Counter.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Counter.astro new file mode 100644 index 0000000000000000000000000000000000000000..6017eb88d98d78efc56cfe542732ad44b88d9277 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Counter.astro @@ -0,0 +1,4 @@ +--- +const start = window.location.hash.length; +--- + diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Footer.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Footer.astro new file mode 100644 index 0000000000000000000000000000000000000000..01a5df799c580e815765d77280d754998891672f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Footer.astro @@ -0,0 +1,5 @@ +--- +const year = new Date().getFullYear(); +--- +
© {year}
+ diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Header.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Header.astro new file mode 100644 index 0000000000000000000000000000000000000000..f4930f29f58fa9791ec7bc0e1b2cd71fe9791591 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/Header.astro @@ -0,0 +1,6 @@ +--- +const { nav } = Astro.props; +--- + diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/ThemeToggle.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/ThemeToggle.astro new file mode 100644 index 0000000000000000000000000000000000000000..a65949da074e769fb38368b0040f12bb012692e0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/components/ThemeToggle.astro @@ -0,0 +1,7 @@ +--- +const mode = document.documentElement.dataset.mode; +--- + + diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/layouts/Base.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/layouts/Base.astro new file mode 100644 index 0000000000000000000000000000000000000000..484c3e62f592185ee1381749279682cb5b271454 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/layouts/Base.astro @@ -0,0 +1,12 @@ +--- +const title = Astro.props.title; +--- + + {title} + + + + + diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/blog/[slug].astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/blog/[slug].astro new file mode 100644 index 0000000000000000000000000000000000000000..809057028dff158ef931a25d352a41e02f9c6663 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/blog/[slug].astro @@ -0,0 +1,4 @@ +--- +const { slug } = Astro.params; +--- +
{slug}
diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/docs/[topic].astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/docs/[topic].astro new file mode 100644 index 0000000000000000000000000000000000000000..91e6c941642b74fe2fcce38dbccf91c68d0781fc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/docs/[topic].astro @@ -0,0 +1,4 @@ +--- +const topic = 'guide'; +--- +
{topic}
diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/index.astro b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/index.astro new file mode 100644 index 0000000000000000000000000000000000000000..bb2feac36d78de008dea26f441438d0636ae4a9d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/inputs/src/pages/index.astro @@ -0,0 +1,7 @@ +--- +import Header from '../components/Header.astro'; +--- + + +

Home

+
diff --git a/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/instruction.md b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..621c9fcf0c688bea4d2f577d023fab0c904168f7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/b6a850c04f05ba0998385042/instruction.md @@ -0,0 +1,16 @@ +A small Astro project's source files are provided below. Write a Python 3 script `astro_lint.py` (standard library only) that lints `.astro` files against the project's conventions and writes a report to `report.txt`. The script must check each `.astro` file in `src/` (recursively) for these rules: + +1. **No client directives on Astro components**: a `client:load`, `client:idle`, `client:visible`, `client:media`, or `client:only` attribute must never appear on a tag whose name ends with `.astro` (e.g. ``). Report file, line number, and the directive. +2. **Frontmatter purity**: code inside the `---` frontmatter fences must not contain `document.` or `window.` references (frontmatter runs on the server, never in the browser). Report file, line number, and the offending token. +3. **Scoped styles**: a ` + + +
+

+
+
+
+
+ +
+
+ +
+
+ +
+ + + + diff --git a/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/consistency-guide.md b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/consistency-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..70f1187d8ec802f8271d90fae2c679c32b778055 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/consistency-guide.md @@ -0,0 +1,73 @@ +# Consistency guide + +The reader is a **non-developer QA tester**. They run the product and watch what happens. They don't read code. Everything below serves one goal: every row reads the same way and that person can run it. Read all of this before Build. + +## Columns (default) + +Unless you agreed otherwise with the user in Step 2, use these seven columns in this order. + +| Column | What goes in it | Rule | +|--------|-----------------|------| +| `TC_ID` | `TC-001`, `TC-002` … | Sequential, 3-digit zero-pad. Never reused. | +| `Category` | Feature area | Must be one of the set agreed in Step 2. Lets the list be grouped. | +| `Scenario` | One line: what's being verified | Noun phrase or short sentence. The case should be graspable from this alone. | +| `Preconditions` | State to set up before the test | Account type, day/elapsed time, last-saved state, platform. Concrete values, not "appropriate setup". | +| `Steps` | Steps the tester performs | Numbered, imperative, product language ("add item → apply coupon → pay"). Not API calls. | +| `Expected Result` | What the tester should see | Observable on screen. The pass/fail baseline. | +| `Priority` | `P1` / `P2` / `P3` | Per the rubric below. | + +Keep the column set **identical across every row**. If a column the feature needs is added (e.g. `Target device`), add it to every row, not some. + +Note: the HTML report depends by name on `TC_ID`, `Category`, `Priority` (groups, badges, summary) and `Steps`, `Expected Result` (multi-line render). **Adding** columns is safe, but removing or renaming these five breaks the HTML (CSV is unaffected). That's why the build script rejects a column set missing `TC_ID`, `Category`, or `Priority`. + +## Non-developer tone — the most-often-broken rule + +Translate every technical fact into observable behavior. The tester verifies on screen, so write what they'll see. + +**Example 1** +- Bad: `update_order_status doesn't set completed_at` +- Good: `After paying, the order still isn't shown as complete` + +**Example 2** +- Bad: `returns BASIC coupon when grade != VIP` +- Good: `A non-VIP account sees only the basic coupons` + +**Example 3** +- Bad: `reward_point=0 when order_history is missing` +- Good: `Points aren't earned when the order didn't go through the normal path` + +Never output: function/method names, variable names, file paths, table/column names, enum constant names, or an HTTP status code as the *primary* expected result (a non-developer doesn't see "400" — they see "the save is blocked and a message appears"; add the code in parentheses only when QA explicitly tracks it). + +A good expected result is **observable and concrete**. "Works correctly" is not a result — write what the tester sees: the message, the state change, the screen, the number. + +## Categories + +Categories mirror the feature's real surface so the tester can work one area at a time. Derive them from the scope. Examples of the *shape* (not a menu to copy verbatim): + +- Input validation, visibility/display conditions, rewards/credits, state transitions, data persistence, cross-domain effects. + +Avoid generic buckets like "Feature / UI / Misc" — they don't help the tester batch their work. + +## Priority rubric (default — tune and confirm in Step 2) + +Apply in **decision order**: top to bottom, take the first grade that matches. That keeps rows consistent instead of graded by gut. + +1. **P1** — breaks money, data, or auth/security, or blocks a core flow. Decision test: *"If this ships broken, is it a rollback or emergency hotfix?"* If yes → P1. +2. **P2** — behavior is wrong but the product still works: there's a workaround, only some users/conditions hit it, or it can wait for the next regular release. +3. **P3** — the feature works; only appearance, copy, or very rare combinations are affected. + +| Grade | One-line test | Typical cases | +|-------|---------------|---------------| +| **P1** | Rollback/hotfix if broken? | Reward double-pay or non-pay, payment/auth, data loss, core flow blocked, IDOR (another user's resource), validation bypass that saves bad data | +| **P2** | Wrong but workable? | Wrong visibility conditions, ordering errors, completed state not preserved, edge-case validation | +| **P3** | Only cosmetic or rare? | Copy, minor layout, very rare combinations | + +**Mistake to avoid: marking everything P1** ("it's all important"). If more than ~⅓ of cases are P1, re-filter with the rollback test — most will be P2. Reserve P1 for what truly blocks a release. + +## Writing rules that keep rows consistent + +- One case verifies **one behavior**. If the steps need "and also check…", split it into two cases. +- Preconditions use the same terms across rows (pick one phrasing for account type and reuse it). +- Steps and expected results are written from the **tester's** point of view, present tense, product language. +- A negative case states both the bad input *and* the expected defense ("save with a required item removed → save is blocked and a message appears"). +- **Don't write an expected result you haven't verified.** Every expected result must reflect real code/spec behavior (SKILL.md Rule 2). If you're inferring what the code *should* do rather than what it *does*, confirm it or flag it to the user — don't export a guess as fact. A wrong expected result sends QA chasing a non-bug or passing a real one. diff --git a/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/context-checklist.md b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/context-checklist.md new file mode 100644 index 0000000000000000000000000000000000000000..5746a0a640a8a751721227c891b74422ca9711c0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/context-checklist.md @@ -0,0 +1,30 @@ +# Context self-check + +Run before each step. QA-list failures happen silently: a confident 30-row CSV built on a wrong scope assumption "looks thorough" but tests the wrong thing. This check surfaces missing context *before* you spend effort. + +If there's a question you can't answer, that's the question to ask the user — don't fill the blank with a guess. + +## Before Step 1 (scope) + +- **What feature/behavior is under QA?** Can you name it in one sentence from code/spec/conversation, or are you guessing among several candidates? +- **What changed / is new?** QA usually focuses on new or changed behavior. Do you know what's new vs. existing? +- **Who uses it, on which platform?** Web/app/tablet, login role, account type, lineup — this changes which cases exist. +- **Is there an authoritative source?** A spec, PRD, or ticket beats your inference. Did the user point at one, or do you need to ask if one exists? +- **What's explicitly out of scope?** Adjacent features that look related but the user doesn't want tested. + +## Before Step 2 (categories & priority) + +- **Do the categories come from this feature, or are they a generic list?** Good categories mirror the feature's real surface (input validation, visibility conditions, rewards, state transitions, etc.). Generic buckets ("UI / Feature / Misc") tell the QA tester nothing. +- **Are the priority rules meaningful for this feature?** What's worst if it breaks here (money, data loss, flow blocked)? That's P1. + +## Before Step 3 (draft list) + +- **Negative and edge cases, not just the happy path.** No auth, another user's resource, empty/null, boundaries (0/negative/max), duplicates, concurrent actions. Which of these apply? +- **Cross-domain effects.** Does one action ripple into another domain (reward → log → notification)? Each ripple is a case. +- **State permutations.** First use vs. reuse, before vs. after a threshold, mode A vs. mode B. + +## Before Build + +- **Does every expected result rest on real code/spec, not a guess?** (Rule 2.) For each row, can you point to where you verified this behavior? If it's a guess, confirm from code, ask the user, or drop the case. A plausible-but-wrong expected result is the worst output this skill can produce. +- **Does every case have an observable expected result?** If you can't say *what the tester will see*, the case isn't ready. +- **Can a non-developer run each case from the app and the row text alone** — no code, no explanation from you? diff --git a/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/export-formats.md b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/export-formats.md new file mode 100644 index 0000000000000000000000000000000000000000..69d3e44a379acae3dbff18e9703f3e7b800fbcc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/references/export-formats.md @@ -0,0 +1,53 @@ +# Export formats + +## Cases JSON (you author it, the script consumes it) + +Write the approved cases to a single JSON file. The script reads it and renders CSV and/or HTML. Authoring JSON instead of writing CSV/HTML by hand takes formatting out of your hands so it stays consistent. + +```json +{ + "title": "Coupon & Points QA", + "subtitle": "VIP-only coupons / order points (optional)", + "columns": ["TC_ID", "Category", "Scenario", "Preconditions", "Steps", "Expected Result", "Priority"], + "cases": [ + { + "TC_ID": "TC-001", + "Category": "Visibility", + "Scenario": "Only VIP-grade accounts see the exclusive coupon", + "Preconditions": "VIP-grade account", + "Steps": "1. Open the coupon box", + "Expected Result": "The exclusive coupon appears in the list", + "Priority": "P1" + } + ] +} +``` + +Rules: +- `columns` sets the column order. Every object in `cases` must have exactly those keys — if any row is missing a key the script errors out (a useful consistency check). +- Multi-step `Steps` / `Expected Result`: put `\n` between steps. CSV keeps it in one cell; HTML renders the line breaks. +- `title` is required, `subtitle` is optional. + +## Choosing a format (ask in Step 4) + +| Format | Fits when | +|--------|-----------| +| **CSV** | The QA team imports into a test-management tool, Google Sheets, or Excel. Simple, editable, diffable. | +| **HTML** | A readable, shareable report — grouped by category, color priority badges, a summary header, a filter box, and a **Download CSV button** that exports the same rows from inside the report. Good to hand straight to a tester or paste into a doc. | +| **Both** | HTML to read + CSV to import/track. A common default for real hand-off. Note: HTML alone can produce the CSV via its button, so "HTML only" is enough when you don't need a CSV file right now. | + +## Running the script + +```bash +python3 scripts/build_export.py cases.json --format both --out ./qa_output +``` + +- `--format` : `csv` | `html` | `both` +- `--out` : output directory (created if missing). The filename is the slugified title. +- If unsure, run `python3 scripts/build_export.py --help` first. + +The HTML is a self-contained single file (inline CSS/JS, no network) built from `assets/testcase_template.html` — it opens anywhere and is safe to send as a mail attachment. + +## After running — verify + +Open the output and run the Build verification from SKILL.md. The script only guarantees *format* consistency; it can't judge which row leaked a code symbol or whether an expected result is observable. That judgment is yours. diff --git a/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/scripts/build_export.py b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/scripts/build_export.py new file mode 100644 index 0000000000000000000000000000000000000000..c9dba91f8dcbde58e011ba1adf83ed24cee412ae --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/skill/scripts/build_export.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Render a QA test-case list (cases JSON) to CSV and/or a self-contained HTML report. + +Usage: + python build_export.py cases.json --format both --out ./qa_output + +The cases JSON schema is documented in references/export-formats.md. This script +owns all formatting so the deliverable stays consistent across runs; the caller +only authors the cases. Standard library only. +""" + +import argparse +import csv +import html +import json +import re +import sys +from pathlib import Path + + +# HTML report depends on these by name: groups by Category, badges/sorts/counts Priority, +# labels rows by TC_ID. Missing any of them renders "undefined". +REQUIRED_COLUMNS = ("TC_ID", "Category", "Priority") +VALID_PRIORITIES = ("P1", "P2", "P3") +DEFAULT_TITLE = "QA Test Cases" + + +def load_cases(path: Path) -> dict: + data = json.loads(path.read_text(encoding="utf-8")) + if "title" not in data or "cases" not in data: + sys.exit("error: JSON must have 'title' and 'cases'") + columns = data.get("columns") + if not columns: + sys.exit("error: JSON must list 'columns' (the column order)") + + missing_cols = [c for c in REQUIRED_COLUMNS if c not in columns] + if missing_cols: + sys.exit(f"error: columns must include {missing_cols} (the HTML report depends on them)") + + for i, row in enumerate(data["cases"]): + _validate_row(i, row, columns) + return data + + +def _validate_row(index: int, row: dict, columns: list[str]) -> None: + """Reject a row that would make the CSV and HTML diverge or render broken.""" + case_id = row.get("TC_ID", "?") + missing = [c for c in columns if c not in row] + if missing: + sys.exit(f"error: case #{index + 1} ({case_id}) missing columns: {missing}") + # Cells must be scalar text; a list/dict/bool serializes differently in CSV vs HTML. + # bool is a subclass of int, so reject it explicitly before the int/float allow. + for c in columns: + if isinstance(row[c], bool) or not isinstance(row[c], (str, int, float)): + sys.exit(f"error: case #{index + 1} ({case_id}) column '{c}' must be text/number") + # Off-list Priority (P0, urgent, ...) renders an unstyled badge and sorts to the front. + if row["Priority"] not in VALID_PRIORITIES: + sys.exit(f"error: case #{index + 1} ({case_id}) Priority must be {'/'.join(VALID_PRIORITIES)}") + + +def slugify(title: str) -> str: + # \w already matches Unicode letters, so keep word chars and hyphen only. + slug = re.sub(r"\s+", "_", title.strip()) + slug = re.sub(r"[^\w-]", "", slug) + return slug or "qa_testcases" + + +def write_csv(data: dict, out_path: Path) -> None: + columns = data["columns"] + # utf-8-sig: Excel needs a BOM to detect UTF-8 (matters for non-ASCII cells). + with out_path.open("w", encoding="utf-8-sig", newline="") as f: + writer = csv.writer(f) + writer.writerow(columns) + for row in data["cases"]: + writer.writerow([row[c] for c in columns]) + + +def write_html(data: dict, template_path: Path, out_path: Path) -> None: + template = template_path.read_text(encoding="utf-8") + payload = json.dumps(data, ensure_ascii=False) + # Encode <, >, & as \uXXXX so a cell value can't break out of the inline ") or inject markup. Standard safe-embedding technique. + payload = payload.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") + # Escape the title — it lands in as raw markup (h1/subtitle are set via JS textContent). + html_out = template.replace("__TITLE__", html.escape(data.get("title", DEFAULT_TITLE))).replace( + "__DATA_JSON__", payload + ) + out_path.write_text(html_out, encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Render QA cases JSON to CSV and/or HTML.") + parser.add_argument("cases_json", help="path to the cases JSON file") + parser.add_argument("--format", choices=["csv", "html", "both"], default="both") + parser.add_argument("--out", default=".", help="output directory (created if missing)") + args = parser.parse_args() + + cases_path = Path(args.cases_json) + if not cases_path.exists(): + sys.exit(f"error: {cases_path} not found") + + data = load_cases(cases_path) + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + slug = slugify(data["title"]) + + written = [] + if args.format in ("csv", "both"): + csv_path = out_dir / f"{slug}.csv" + write_csv(data, csv_path) + written.append(csv_path) + if args.format in ("html", "both"): + template_path = Path(__file__).resolve().parent.parent / "assets" / "testcase_template.html" + if not template_path.exists(): + sys.exit(f"error: template not found at {template_path}") + html_path = out_dir / f"{slug}.html" + write_html(data, template_path, html_path) + written.append(html_path) + + print(f"wrote {len(data['cases'])} cases:") + for p in written: + print(f" {p}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/task.json b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2d493f46222c8b5ff2c095078eaf9da5e64426a8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/c95391bc3625e119_q1/task.json @@ -0,0 +1,56 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "c95391bc3625e119", + "query_id": "c95391bc3625e119_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/build_qa_export.sh" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "60658eec74ee42db936b10bad3b595cfd3a34ea99226b8e400bfbcebf7df1f0f", + "name": "create-qa-list", + "package_path": "skill", + "install_name": "create-qa-list-35b933db" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "60658eec74ee42db936b10bad3b595cfd3a34ea99226b8e400bfbcebf7df1f0f", + "files": { + "README.ko.md": "4e24f4515f4de312c2f340d79343713551dabf9fc733b130ced60b6d37904b48", + "README.md": "8ca59e2707253e2c2d8f048bd7e49672aa0356e206380402140eb2d31040d82d", + "SKILL.md": "e0ab0a5ecff950ba0814d35b1ee6df021971e1b752de6d576935f06ecabcdc8e", + "assets/example_testcases.csv": "39f33318a3627a2b79b2fc0bce81193e40694cd464c8319a67efccd8a0d82b55", + "assets/testcase_template.html": "b2397d47c76c3ad32333cbe13cc6e9cbf413085079ea08612d8c77f7bdd13aa1", + "references/consistency-guide.md": "b7fc36c953e5a2ad4d51cab6c635f2014e8735bbcd3e5b2d7cc89d9acdc175bf", + "references/context-checklist.md": "c82a6dee311ab25e45681422e7c04e7239c3b8144861731b69535b130aa58288", + "references/export-formats.md": "47a3df1fea9925db25c233bf9886f858d19f9f3e2fa09141650eba25dbf35ed5", + "scripts/build_export.py": "77d296f031b8f0ec3517b73484d099daefec3a281851170799f516eb4f18c760" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "35b933db232d12a204a536c7c44429f646c7b807a27b66dc6efbaa3ac36aa21c" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_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/ca777d845901e540_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/ca777d845901e540_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..73010dcb3d7fb71f338bfc1817e393eda4dc2697 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/autograde_task_check.py @@ -0,0 +1,12 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import sys,json +from pathlib import Path +root=Path(__file__).resolve().parent +sys.path.insert(0,str(root/'legacy_tests')) +from evaluate import evaluate +t=json.loads((root/'legacy-task.json').read_text()) +mode=t['workspace']['candidate_mode'] +r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt') +if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False) +if r.get('status')!='scored':raise RuntimeError(json.dumps(r)) +print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]})) diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy-task.json b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy-task.json new file mode 100644 index 0000000000000000000000000000000000000000..8eae4c041d5bf1df103977447647bf20aab1fb73 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy-task.json @@ -0,0 +1,121 @@ +{ + "schema_version": "mybench-portable-task-v2", + "task_id": "ca777d845901e540", + "query_id": "ca777d845901e540_q1", + "prompt": { + "path": "instruction.md", + "sha256": "e9a86f7141defda01655a680fea2370af96347b907ecde947cad8c3c5511683e" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "4afebb2dc222486f2afc55c2f72e67be3c5157b0bcf9008c1b056f1caf59d713", + "name": "windows-11-security-baseline", + "package_path": "environment/skills/windows-11-security-baseline-4afebb2d", + "install_name": "windows-11-security-baseline-4afebb2d", + "archive_provenance": { + "archive_id": "logical-skill-03d4942a6523e24cee032630", + "archive_schema": "skill-release-v1", + "release_skill_id": "logical-skill-03d4942a6523e24cee032630", + "site": "skills-sh", + "local_path": "skills/03/logical-skill-03d4942a6523e24cee032630", + "skill_md_sha256": "871c501e3b23bd5a93ba637e92cfdca4a543d996776f54f9f8eb0df4ff08e756", + "release_payload_sha256": "4afebb2dc222486f2afc55c2f72e67be3c5157b0bcf9008c1b056f1caf59d713", + "license": "MIT", + "license_status": "detected", + "canonical_source_id": "skills-sh:vinayaklatthe/microsoft-security-skills/windows-11-security-baseline" + }, + "omitted_entries": [] + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "ground_truth_skills": [ + "4afebb2dc222486f2afc55c2f72e67be3c5157b0bcf9008c1b056f1caf59d713" + ], + "evaluation": { + "type": "verified", + "ground_truth_answer": { + "answers": { + "q1": "30 days", + "q2": "50 IT devices", + "q3": "14 days" + } + }, + "verifier": { + "type": "atomic_json", + "version": 1, + "list_order": "ordered", + "float_tolerance": 0.01, + "completeness": { + "forbid_extra": true, + "shape": { + "type": "object", + "keys": { + "answers": { + "type": "object", + "keys": { + "q1": { + "type": "string" + }, + "q2": { + "type": "string" + }, + "q3": { + "type": "string" + } + } + } + } + } + }, + "assertions": [ + { + "id": "leaf_001", + "path": "$.answers.q1", + "tokens": [ + "answers", + "q1" + ], + "operator": "eq", + "expected": "30 days" + }, + { + "id": "leaf_002", + "path": "$.answers.q2", + "tokens": [ + "answers", + "q2" + ], + "operator": "eq", + "expected": "50 IT devices" + }, + { + "id": "leaf_003", + "path": "$.answers.q3", + "tokens": [ + "answers", + "q3" + ], + "operator": "eq", + "expected": "14 days" + } + ], + "self_test_passed": true + }, + "dependency_contract": { + "version": 2, + "mode": "core_answer", + "dependency_type": "package_knowledge", + "requirement_ids": [ + "skill_a054", + "skill_a039", + "skill_a067" + ], + "forbid_meta_reference": true, + "forbid_answer_leakage": true + } + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/evaluate.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..6af62307e8c216b7733194602815f5004d893e06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/evaluate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Evaluate a candidate response for one portable MyBench task.""" + +import argparse +import json +import math +import os +import shlex +import subprocess +import sys +from pathlib import Path + + +def _load_verify(): + try: + from verifiers import verify + return verify + except ImportError: + project_src = Path(__file__).resolve().parents[1] / "src" + if project_src.is_dir(): + sys.path.insert(0, str(project_src)) + from verifiers import verify + return verify + raise + + +def _emit(result, output=None): + text = json.dumps(result, ensure_ascii=False) + print(text) + if output: + Path(output).write_text(text + "\n", encoding="utf-8") + + +def _judge_contract(judge): + if not isinstance(judge, dict): + return "Judge output must be a JSON object" + if type(judge.get("passed")) is not bool: + return "Judge field passed must be a JSON boolean" + for key in ("score", "max_score"): + value = judge.get(key, 100 if key == "max_score" else None) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"Judge field {key} must be a finite number" + if not math.isfinite(float(value)): + return f"Judge field {key} must be a finite number" + score = float(judge["score"]) + max_score = float(judge.get("max_score", 100)) + if max_score <= 0: + return "Judge field max_score must be greater than zero" + if score < 0 or score > 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/ca777d845901e540_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/ca777d845901e540_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i<len(text): + ch=text[i] + if ch=='\\' and quote!="'" and i+1<len(text): + nxt=text[i+1] + if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__') + elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__') + else:out.extend((ch,nxt)) + i+=2;continue + if ch in "'\"": + if quote is None:quote=ch + elif quote==ch:quote=None + out.append(ch);i+=1;continue + if ch=='$': + if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue + m=variable.match(text,i) + if m: + value=constants.get(m.group(1)or m.group(2)) + if value is None:out.append(m.group(0)) + elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$')) + else:out.append(value) + i=m.end();continue + if ch=='~' and quote is not None: + out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue + out.append(ch);i+=1 + return ''.join(out) + +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 = _expand_known_variables(statement, constants) + 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/ca777d845901e540_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_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/ca777d845901e540_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/ca777d845901e540_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..46fa7a19b86e8fc0e64c9028b6c7c3dcf34022aa --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "ca777d845901e540_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "fedc23f62a5a38c4b6e8876e0f40abae8c3ed5e2c10a4b243d4f53be401178e4", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c00ad328f6ea5abed97a59e8033cf75e11e371a0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/instruction.md @@ -0,0 +1 @@ +We're finalizing the deployment plan for our Windows 11 hardening program across our Intune-managed fleet, covering pilot rings, Windows LAPS password rotation, and Controlled Folder Access enforcement. Before we write the plan, we need the agreed program values: the maximum password age to set for Windows LAPS, how many devices are in Ring 0 of the pilot ring methodology and what kind of devices they are, and how long Controlled Folder Access should run in audit mode before enforcement. Return one JSON object using this schema exactly once, with each placeholder replaced by the bare project-defined value: {"answers":{"q1":"string","q2":"string","q3":"string"}} diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d25d2fb5f6cec0b9d6062b155107abb0550e7877 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/skill/SKILL.md @@ -0,0 +1,162 @@ +--- +name: windows-11-security-baseline +description: "Guidance for the Windows 11 enterprise security baseline — Microsoft's recommended security settings deployed via Intune (Settings catalog / security baselines) or GPO. Covers core hardware-rooted controls (TPM 2.0, Secure Boot, virtualization-based security / VBS, Hypervisor-Protected Code Integrity / HVCI, Memory Integrity, Credential Guard, Local Security Authority protection), Windows LAPS (Microsoft's modern local admin password solution, replacement for legacy LAPS), Smart App Control, Personal Data Encryption (PDE), Windows Hello for Business deployment, controlled folder access, exploit protection, BitLocker baseline, app control with WDAC, removable storage controls, and integration with Intune compliance and Defender for Endpoint. WHEN: Windows 11 baseline, Windows security baseline, VBS HVCI Memory Integrity, Credential Guard, LSA protection, Windows LAPS, replace legacy LAPS, Smart App Control, WDAC, exploit protection, PDE Windows 11, Intune security baseline. DO NOT USE for endpoint EDR config (use defender-for-endpoint), Intune device management end-to-end (use intune-device-mgmt), or BitLocker design only (use bitlocker-design)." +license: MIT +metadata: + author: Microsoft + version: "0.1.0" +--- + +# Windows 11 Security Baseline + +The Windows 11 security baseline is Microsoft's curated set of recommended security +settings — hundreds of policies vetted for both security value and compatibility. The +baseline is delivered as Intune **security baselines** (settings catalog edition) or GPO +templates from the Microsoft Security Compliance Toolkit. + +This skill covers what to enable, the Windows 11-specific controls (LAPS, VBS/HVCI, +Credential Guard, Smart App Control, PDE), and the rollout pattern. + +## When to use +Hardening a Windows 11 fleet with Intune (or GPO for legacy estates), with focus on +the hardware-rooted and identity-protection capabilities specific to modern Windows. + +**Do not use this skill** for MDE policy authoring (`defender-for-endpoint`), generic +Intune device management (`intune-device-mgmt`), or BitLocker-only design +(`bitlocker-design`). + +## Core controls — turn on, in this order + +| Control | Why first | +|---|---| +| **Tamper Protection** (MDE) | Without it, all other controls are advisory | +| **Secure Boot + TPM 2.0** | Foundation for VBS/HVCI/Credential Guard; required for Win11 | +| **VBS / HVCI / Memory Integrity** | Kernel-mode code integrity in a hypervisor-isolated container | +| **Credential Guard** | LSASS isolation; defeats most credential-theft tooling | +| **LSA protection** | Prevents non-protected processes from injecting into LSASS | +| **BitLocker** | Disk encryption with TPM-bound startup | +| **Personal Data Encryption (PDE)** | Per-file encryption tied to user sign-in (kicks in after first sign-in) | +| **Windows Hello for Business** | Replaces password-based local sign-in | +| **Windows LAPS (modern)** | Local admin password rotation, Entra-backed | +| **Smart App Control** | Default-deny code execution on clean-installed Win11 | +| **WDAC / App Control for Business** | Mature app-control on managed estate | +| **Controlled Folder Access + Exploit Protection** | ASR-adjacent host hardening | +| **Removable storage policies** | USB exfil control | + +## Approach + +1. **Apply the Microsoft security baseline via Intune** at the device level. Use the + Settings catalog version (newer) or the named "Windows 11 security baseline" — the + newer Settings catalog is the forward-looking option. + +2. **Pilot ring methodology.** + - Ring 0 (50 IT devices): all baseline + new controls. + - Ring 1 (5% representative): same. + - Ring 2 (rest): after compatibility validation. + Don't treat the baseline as a one-shot deployment; some controls (Smart App + Control, WDAC, PDE) need staged rollout. + +3. **Hardware-rooted identity stack.** + - Verify **TPM 2.0** + **Secure Boot** at provisioning (Autopilot precondition). + - Enable **VBS** + **HVCI / Memory Integrity** via baseline; expect older drivers + to break — use the Driver Compatibility tool to find blockers pre-rollout. + - Enable **Credential Guard** + **LSA Protection** — together they end most + Mimikatz-style attacks against managed devices. + +4. **Windows LAPS** (the new built-in product, separate from legacy LAPS): + - **Entra-joined**: passwords stored in Entra ID, rotated via Intune policy. + - **Hybrid / AD-joined**: passwords stored in AD, schema extension required. + Migrate off legacy LAPS (deprecated). Cap password age 30 days. + +5. **Smart App Control** is **only available on clean-installed Win11** (kicks in + after a learning phase). For existing devices, use **WDAC / App Control for + Business** — bigger investment but works on upgraded fleets. Phase: audit-only + policy → enforce per device group → expand. + +6. **Personal Data Encryption (PDE)** requires Windows Hello for Business and + modern auth. Roll out with WHfB; not a replacement for BitLocker — it's + per-file encryption layered on top. + +7. **Windows Hello for Business** as the local sign-in (cert-trust or cloud Kerberos + trust). Pair with `passkeys-fido2` for the broader phishing-resistant strategy. + +8. **Controlled Folder Access + Exploit Protection.** CFA in audit mode for 14 days; + then enforce on user workstations only (not servers — breaks app file writes). + Exploit Protection profile from Microsoft baseline applied tenant-wide. + +9. **Removable storage controls.** Block writable USB by default for general + workforce; allowlist by hardware ID for legitimate use cases (designers, AV + teams). Combine with Defender for Endpoint device control for granular policies. + +10. **Compliance + Conditional Access.** Mark devices as compliant only when: + - BitLocker on, TPM healthy, Secure Boot on, Defender real-time on. + - Device risk = low (MDE). + - Baseline applied = Yes (via Intune compliance). + Tie compliance to Conditional Access for resource access. + +## Guardrails +- **Don't enable Memory Integrity / HVCI without driver compatibility check.** Old + printer / VPN / endpoint drivers break boot. +- **Smart App Control cannot be enabled on upgraded Win11.** Use WDAC for those + devices. +- **WDAC is high-value but operationally heavy.** Plan for the policy-management + function; this is not "set and forget." +- **Legacy LAPS is deprecated; new Windows LAPS is the path.** Don't deploy legacy + LAPS on greenfield Win11. +- **Credential Guard breaks some legacy auth scenarios** (Wi-Fi 802.1x with certain + TPM configs, third-party credential providers). Validate. +- **Don't run unsupported drivers / kernel-mode software** alongside Memory Integrity. +- **PDE requires WHfB.** Without Hello, PDE doesn't engage; data isn't protected + at the file level. +- **Intune Settings catalog vs classic baseline**: forward-looking is Settings catalog. + Don't run both for the same setting — conflicts. +- **CFA on servers breaks workloads.** Workstations only. +- **Removable storage block-all without allowlist** breaks legitimate users; have a + request workflow. + +## Common anti-patterns +- **"Applied baseline once, never updated"** — baseline updates ship quarterly; new + attacks add new settings. Re-baseline annually. +- **"Memory Integrity off because one driver complained"** — keep it on, replace the + driver. +- **"Legacy LAPS still running on Win11"** — deprecated; migrate to Windows LAPS. +- **"WDAC in audit forever"** — never enforced; not protecting anything. +- **"Smart App Control on upgraded devices"** — silently does nothing. +- **"Credential Guard off because of a 2018 third-party VPN"** — replace the VPN. +- **"USB block-all, no exceptions"** — engineering revolts and finds workarounds. + Allowlist legitimate use. +- **"Compliance signal not in Conditional Access"** — devices "compliant" but no + enforcement at access. +- **"Settings catalog and classic baseline both targeted at the same group"** — + policy conflicts; unpredictable enforcement. + +## Example prompts +- `Roll out the Windows 11 security baseline to a 30,000-device Intune-managed + estate with a 3-ring pilot.` +- `Migrate from legacy LAPS to Windows LAPS for a hybrid (Entra-joined + AD-joined) + estate.` +- `Driver compatibility readiness for VBS / HVCI / Memory Integrity rollout.` +- `WDAC policy authoring strategy: managed installer vs explicit allowlist; phased + enforcement.` +- `Personal Data Encryption rollout aligned with Windows Hello for Business and + passkey strategy.` +- `Removable storage policy: block USB write tenant-wide, allowlist by hardware ID + for designated groups, request workflow.` +- `Compliance policy + Conditional Access: bind the security baseline to access for + Microsoft 365 and Azure portal.` +- `Audit Smart App Control eligibility across the fleet and identify devices where + WDAC is the only viable path.` + +## Microsoft Learn +- Windows 11 security book: https://learn.microsoft.com/windows/security/book/ +- Security baselines for Windows 11: https://learn.microsoft.com/windows/security/operating-system-security/device-management/windows-security-configuration-framework/windows-security-baselines +- Intune security baselines: https://learn.microsoft.com/intune/intune-service/protect/security-baselines +- VBS / HVCI / Memory Integrity: https://learn.microsoft.com/windows/security/hardware-security/enable-virtualization-based-protection-of-code-integrity +- Credential Guard: https://learn.microsoft.com/windows/security/identity-protection/credential-guard/ +- LSA protection: https://learn.microsoft.com/windows-server/security/credentials-protection-and-management/configuring-additional-lsa-protection +- Windows LAPS: https://learn.microsoft.com/windows-server/identity/laps/laps-overview +- Smart App Control: https://learn.microsoft.com/windows/security/application-security/application-control/app-control-for-business/ +- WDAC / App Control for Business: https://learn.microsoft.com/windows/security/application-security/application-control/app-control-for-business/ +- Personal Data Encryption: https://learn.microsoft.com/windows/security/operating-system-security/data-protection/personal-data-encryption/ +- Controlled folder access: https://learn.microsoft.com/defender-endpoint/controlled-folders +- Microsoft Security Compliance Toolkit (GPO baselines): https://www.microsoft.com/download/details.aspx?id=55319 diff --git a/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/task.json b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..09d7b5de18ab46113238dd16997e96ce5d52e70e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ca777d845901e540_q1/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "ca777d845901e540", + "query_id": "ca777d845901e540_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "37fcf1400ecc7ea0ebe60414562a9e5cc131b182ae6bbe0b8eaa307e6d15a5d6", + "name": "windows-11-security-baseline", + "package_path": "skill", + "install_name": "windows-11-security-baseline-4afebb2d" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "37fcf1400ecc7ea0ebe60414562a9e5cc131b182ae6bbe0b8eaa307e6d15a5d6", + "files": { + "SKILL.md": "871c501e3b23bd5a93ba637e92cfdca4a543d996776f54f9f8eb0df4ff08e756" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "4afebb2dc222486f2afc55c2f72e67be3c5157b0bcf9008c1b056f1caf59d713" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/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/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..2df84dcd3c08cc141535e8515a30f27dd70ede59 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "6" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b990c000a9038f2df3ed8674ae078ba010751779 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/autograde_task_check.py @@ -0,0 +1,11 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import contextlib,io,json,runpy,sys +from pathlib import Path +HERE=Path(__file__).resolve().parent +buffer=io.StringIO() +with contextlib.redirect_stdout(buffer):runpy.run_path(str(HERE/'r10_base.py'),run_name='__main__') +body=next(json.loads(x)for x in reversed(buffer.getvalue().splitlines())if x.strip().startswith('{')and isinstance(json.loads(x),dict)and isinstance(json.loads(x).get('checks'),list)) +if '--view' not in sys.argv: + from r10_probes import augment + body=augment(body,316) +print(json.dumps(body,ensure_ascii=False)) diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_base.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ed22242256eee6367d1a3d2401c16d252cfcdcb9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_base.py @@ -0,0 +1,92 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import r10_runtime as _r10 +_r10.install_copy('worker.py') +import json, os, shutil, subprocess, sys, tempfile + +INBOX = { + "001.": '{"prompt": "hello world"}\n', + "002.": '{"agent_id": "a1", "reply_instruction": "send summary to channel ops"}\n', + "003.": '{"a2a_key": "k", "note": "no prompt here"}\n', +} + +def setup(d, names=None): + os.makedirs(os.path.join(d, "inbox"), exist_ok=True) + for n, c in INBOX.items(): + if names is None or n in names: + with open(os.path.join(d, "inbox", n), "w") as f: + f.write(c) + +def run_worker(d, args): + return subprocess.run([sys.executable, "worker.py"] + args, cwd=d, + capture_output=True, text=True, timeout=60) + +def read_json(p): + with open(p) as f: + return json.load(f) + +def evaluate(candidate_dir): + checks = [] + src = os.path.join(candidate_dir, "worker.py") + if not os.path.isfile(src): + return [{"id": str(i), "passed": False, "reason": "worker.py missing"} for i in range(7)] + std_ok=_r10.stdlib_gate('worker.py');std_reason=_r10.dependency('worker.py')[2] + d = tempfile.mkdtemp(dir="/tmp") + try: + shutil.copy(src, os.path.join(d, "worker.py")) + setup(d) + r = run_worker(d, []) + out = r.stdout + # criterion 0: processes all three, exits after two empty scans, idle per empty scan + c0 = r.returncode == 0 and sum(line.strip() == "idle" for line in out.splitlines()) == 2 + checks.append({"id": "0", "passed": c0, + "reason": "exit=%d, exact idle lines=%d (need exactly 2, once per empty scan)" % (r.returncode, sum(line.strip() == "idle" for line in out.splitlines()))}) + # criterion 1: done files exist, originals gone + ok = all(os.path.isfile(os.path.join(d, "inbox", n + ".done")) for n in INBOX) and \ + not any(os.path.exists(os.path.join(d, "inbox", n)) for n in INBOX) + checks.append({"id": "1", "passed": ok, + "reason": "all three .done files present and originals removed" if ok else "missing .done files or originals still present"}) + # criteria 2-4: reply files + exp = [("001.reply.", "echo: hello world", "001."), + ("002.reply.", "ack: send summary to channel ops", "002."), + ("003.reply.", "unknown task", "003.")] + for i, (fn, rep, srcname) in enumerate(exp, start=2): + p = os.path.join(d, "outbox", fn) + ok = False + reason = "outbox/%s missing or invalid JSON" % fn + if os.path.isfile(p): + try: + j = read_json(p) + if j.get("reply") == rep and j.get("source") == srcname: + ok = True; reason = "reply and source correct" + else: + reason = "got reply=%r source=%r" % (j.get("reply"), j.get("source")) + except Exception as e: + reason = "JSON parse error: %s" % e + checks.append({"id": str(i), "passed": ok, "reason": reason}) + # criterion 5: --once on fresh inbox with two items + d2 = tempfile.mkdtemp(dir="/tmp") + try: + shutil.copy(src, os.path.join(d2, "worker.py")) + setup(d2, {"001.", "002."}) + r2 = run_worker(d2, ["--once"]) + done = [f for f in os.listdir(os.path.join(d2, "inbox")) if f.endswith(".done")] + replies = os.listdir(os.path.join(d2, "outbox")) if os.path.isdir(os.path.join(d2, "outbox")) else [] + remaining = [f for f in os.listdir(os.path.join(d2, "inbox")) if not f.endswith(".done")] + ok = r2.returncode == 0 and len(done) == 1 and len(replies) == 1 and len(remaining) == 1 + checks.append({"id": "5", "passed": ok, + "reason": "--once processed exactly one item" if ok else + "done=%d replies=%d remaining=%d exit=%d" % (len(done), len(replies), len(remaining), r2.returncode)}) + finally: + shutil.rmtree(d2, ignore_errors=True) + checks.append({"id": "6", "passed": std_ok, + "reason": std_reason or "only stdlib imports"}) + finally: + shutil.rmtree(d, ignore_errors=True) + return checks + +cd = "/candidate" +if os.path.isdir(cd) and os.path.isfile(os.path.join(cd, "worker.py")): + res = evaluate(cd) +else: + res = [{"id": str(i), "passed": False, "reason": "worker.py not found in /candidate"} for i in range(7)] +print(json.dumps(_r10.finalize(res, {'6':'worker.py'}))) diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_probes.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_probes.py new file mode 100644 index 0000000000000000000000000000000000000000..ba44c690d441b64b3d9fbb22d97c3a20bc413dfc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_probes.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +"""Independent public-rule panels for R10. Imported only in offline Docker.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import contextlib,json,math,os,pathlib,shutil,subprocess,sys,tempfile +from r10_runtime import C,read_json,dependency +S=pathlib.Path('/source') +@contextlib.contextmanager +def fresh(remove=(),updates=None): + with tempfile.TemporaryDirectory(prefix='r10-panel-',dir='/tmp')as d: + w=pathlib.Path(d);shutil.copytree(C,w,dirs_exist_ok=True,symlinks=True) + task=json.loads((S/'task.json').read_text()) + for m in task.get('workspace',{}).get('input_mappings',[]): + src=S/m['source'];dst=w/m['workspace_target'];dst.parent.mkdir(parents=True,exist_ok=True) + if src.is_file():dst.write_bytes(src.read_bytes()) + for rel in remove: + p=w/rel + if p.is_dir()and not p.is_symlink():shutil.rmtree(p) + elif p.exists()or p.is_symlink():p.unlink() + for rel,value in(updates or{}).items(): + p=w/rel;p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(value if isinstance(value,bytes)else value.encode()) + yield w +def run(w,entry,args=()): + return subprocess.run([sys.executable,entry]+list(args),cwd=w,capture_output=True,text=True,timeout=60) +def tri(a,b):return False if a is False or b is False else None if a is None or b is None else True +def enforce(body,ids,good,reason): + for row in body['checks']: + if str(row['id'])in set(map(str,ids)): + row['passed']=tri(row.get('passed'),good);row['reason']=row.get('reason','')+'; R10: '+reason + body['scoreable']=all(type(x.get('passed'))is bool for x in body['checks']) + return body +def lifecycle(body): + name='add-export-csv';date='2026-01-15';rel='docs/security/'+name+'-r10-second.md';new='# Independent security report\n\nR10 preserved second-source content.\n' + with fresh(remove=('openspec/changes/archive','docs/archive'),updates={rel:new})as w: + sources=sorted(w.glob('docs/security/'+name+'-*.md'));before={p.name:p.read_text()for p in sources} + p=run(w,'lifecycle.py',[name,'--date',date]);out=w/'docs/archive'/date/name/'security.md' + text=out.read_text()if out.is_file()else'' + good=p.returncode==0 and len(before)>=2 and text.startswith('# Security reports — '+name)and all('## '+n in text and value.strip()in text and not(w/'docs/security'/n).exists()for n,value in before.items()) + return enforce(body,[7],good,'every one of multiple independent security files is concatenated and moved, not only the first glob result') +def worker(body): + updates={'inbox/002.':json.dumps({'prompt':'second'}),'inbox/001.':json.dumps({'prompt':'first'}),'inbox/000.txt':'ignore non-target suffix'} + with fresh(remove=('inbox','outbox'),updates=updates)as w: + p=run(w,'worker.py',['--once']);reply=w/'outbox/001.reply.' + doc=read_json(reply)if reply.is_file()else None + good=p.returncode==0 and(w/'inbox/001..done').is_file()and not(w/'inbox/001.').exists()and(w/'inbox/002.').is_file()and(w/'inbox/000.txt').is_file()and isinstance(doc,dict)and doc.get('source')=='001.'and doc.get('reply')=='echo: first'and len(list((w/'inbox').glob('*.done')))==1 + return enforce(body,[5],good,'--once selects the actual lexicographic first target despite reverse creation order and ignores a non-target suffix') +def citation_line(p,index): + authors=[] + for a in p.get('authors',[]): + last,first=(a.split(',',1)+[''])[:2];authors.append(' '.join(s[0]+'.'for s in first.strip().split())+' '+last.strip()) + author=authors[0]+' et al.'if len(authors)>3 else authors[0]if len(authors)==1 else ', '.join(authors[:-1])+', and '+authors[-1]if authors else'Unknown' + line=str(index)+'. '+author+', "'+p['title']+',"' + if p.get('journal'):line+=' *'+p['journal']+'*' + if p.get('volume'):line+=' **'+str(p['volume'])+'**,' + if p.get('pages'):line+=' '+str(p['pages']).split('-',1)[0] + line+=' ('+str(p.get('year')or'n.d.')+').' + if p.get('doi'):line+=' doi:'+p['doi'] + return line +def references(body): + papers=[dict(title='Independent Two Author Paper',authors=['First, Alice','Second, Bob Clark'],year=2031,journal='Test Journal',volume='7',pages='123-140',doi='10.test/r10'),dict(title='Changed Input',authors=['Miller, Cora'],year=2029,journal='',volume='',pages='',doi='')] + good=True + for panel in[papers,list(reversed(papers)),[]]: + with fresh(remove=('workspace/references.md',),updates={'data/papers.json':json.dumps(panel)})as w: + p=run(w,'format_refs.py');path=w/'workspace/references.md';actual=path.read_text()if path.is_file()else None;wanted=[citation_line(x,i)for i,x in enumerate(panel,1)] + good=good and p.returncode==0 and actual is not None and actual.splitlines()==wanted and p.stdout.strip()==actual.strip() + return enforce(body,[0,1,6],good,'two-author, reordered/changed fields and empty-array panels use independent formatted expectations, not four fixed strings') +def sitting(body): + panels=[(['sit on stool','sit on couch','sit on recliner'],{'seats':['BlueCouch','stoolSeat','stool'],'default':'stoolSeat'},['stool','BlueCouch','stoolSeat']),(['sit on toilet','','sit on couch'],{'seats':['toiletSeat','lounge'],'default':'lounge'},['toiletSeat','lounge']),([],{'seats':['quietSeat'],'default':'quietSeat'},[])] + good=True + for commands,seats,wanted in panels: + with fresh(remove=('actions.',),updates={'commands.txt':'\n'.join(commands)+'\n','seats.':json.dumps(seats)})as w: + p=run(w,'sit_planner.py');path=w/'actions.';out=read_json(path)if path.is_file()else None + valid=isinstance(out,list)and len(out)==len(wanted) + if valid: + for row,target in zip(out,wanted): + valid=valid and isinstance(row,dict)and row.get('moveTo')=={'target':target}and type(row.get('durationMs'))is int and 2000<=row['durationMs']<=3000 and row.get('pose')=={k:[90,0,0]for k in['LeftUpLeg','LeftLeg','RightUpLeg','RightLeg']}and isinstance(row.get('say'),str)and bool(row['say'].strip()) + good=good and p.returncode==0 and valid + enforce(body,[0,1,2,3,4,5],good,'commands/order/anchors/default vary independently, exact match beats fuzzy, empty input produces no actions') + return enforce(body,[6],dependency('sit_planner.py')[0],'complete entry and helper dependency closure') +PROBES={312:lifecycle,316:worker,320:references,366:sitting} +def augment(body,index): + try:return PROBES[index](body) + except (OSError,ValueError,TypeError,KeyError,subprocess.SubprocessError)as e: + return enforce(body,{'312':[7],'316':[5],'320':[0,1,6],'366':[0,1,2,3,4,5,6]}[str(index)],False,'independent public panel did not complete: '+type(e).__name__+': '+str(e)[:150]) diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_runtime.py b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d7872f5ef5e56b3e7c57f0f9a26ee4db4570e73b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/evaluator/r10_runtime.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""R10 grader helper. This file runs only inside an offline verifier container.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,os,pathlib,shutil +from dependency_scan import scan_stdlib +C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +_copies={};_deps={} +def dependency(entry): + key=str(entry) + if key not in _deps:_deps[key]=scan_stdlib(C,[key]) + return _deps[key] +def stdlib_gate(entry): + # Unknown is provisionally neutral; finalize() preserves it as unscored. + return dependency(entry)[0] is not False +def finalize(checks,owners): + for row in checks: + entry=owners.get(str(row['id'])) + if entry is None:continue + ok,_,why=dependency(entry) + if ok is False:row['passed']=False + elif ok is None and row.get('passed')is not False:row['passed']=None + row['reason']=row.get('reason','')+'; reachable dependency closure: '+why + return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks} +def strict_pairs(pairs): + out={} + for key,value in pairs: + if key in out:raise ValueError('duplicate JSON object key: '+key) + out[key]=value + return out +def read_json(path): + return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs, + parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x))) +def install_copy(entry): + """Complete authored dependencies without copying stale deliverables into fixtures.""" + if entry in _copies:return + _copies[entry]=True + try:task=json.loads(pathlib.Path('/source/task.json').read_text()) + except (OSError,ValueError):task={} + excluded=[] + for value in task.get('outputs',[]): + value=value.get('path')if isinstance(value,dict)else value + if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value)) + # Public fixture inputs come from the trusted source/fixture constructor, never + # from the candidate snapshot after a panel intentionally removes a file. + for mapping in task.get('workspace',{}).get('input_mappings',[]): + value=mapping.get('workspace_target') + if isinstance(value,str):excluded.append(pathlib.PurePosixPath(value)) + original_copy=shutil.copy;original_copyfile=shutil.copyfile + def extra(src,dst): + try: + source=pathlib.Path(src) + if source.name!=pathlib.Path(entry).name:return + source.resolve().relative_to(C.resolve()) + except (ValueError,TypeError,OSError):return + destination=pathlib.Path(dst) + if destination.is_dir():destination=destination/source.name + root=destination.parent + # Helpers keep the entry's authored relative directory context. + for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent + for dp,dn,fn in os.walk(str(C),followlinks=False): + dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')] + for name in fn: + p=pathlib.Path(dp)/name;rel=p.relative_to(C) + if any(rel==x or x in rel.parents for x in excluded):continue + if p.resolve()==source.resolve():continue + out=root/rel + if out.exists()or out.is_symlink():continue + out.parent.mkdir(parents=True,exist_ok=True) + if p.is_symlink():out.symlink_to(os.readlink(str(p))) + elif p.is_file():original_copyfile(str(p),str(out)) + def copy(src,dst,*args,**kwargs): + result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result + def copyfile(src,dst,*args,**kwargs): + result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result + shutil.copy=copy;shutil.copyfile=copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..28a280bbbc53c1a06495d5a2341690acaa4669eb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/grading/verified_config.json @@ -0,0 +1,108 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "ce60989a1328cf7b91e3e5c3", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "r10_probes.py": "b5159a8591e687e148f516ab410bdd3c789e586d0f9ba32939e63a1ac34a155a", + "r10_base.py": "e8ba4a55de7bfa9aa3e4473947191479f249bbc142e22bf2418d60170e392988", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "1a65fc0240a7dfb70ce8b58b4121d21b5bafa76215693d5dd1d201d6bd8951cc", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "ce32e155654a249b7e394e2dc9192de62d24f06981d112f3e6d1070ce5ea5d22", + "r10_runtime.py": "e4205af091a5c170ce2640089d77bfe7fe9e7b516c56c4a0b3886a69816cb3a2", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": false, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "cpu_memory_basis": "source_runtime_container_limits", + "cpus": 2, + "disk_mib": 10240, + "memory_mib": 4096, + "timeout_disk_basis": "advisory_not_measured_or_enforced", + "timeout_sec": 1200 + }, + "oracle": { + "basis": "advisory_reference_copy", + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": 60, + "max_steps": 16 + }, + "verifier": { + "basis": "original_python_evaluator_enforced_limits", + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 60, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/001. b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/001. new file mode 100644 index 0000000000000000000000000000000000000000..8aa939dde92d1bd8ce0db9b0fb85675971e5972a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/001. @@ -0,0 +1 @@ +{"prompt": "hello world"} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/002. b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/002. new file mode 100644 index 0000000000000000000000000000000000000000..234cbadd948b231c799a01ba2a2d3af3bb4ba4b7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/002. @@ -0,0 +1 @@ +{"agent_id": "a1", "reply_instruction": "send summary to channel ops"} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/003. b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/003. new file mode 100644 index 0000000000000000000000000000000000000000..e9036e16aba8b6a6eb98dfde52f72a9c9c028c99 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/inputs/inbox/003. @@ -0,0 +1 @@ +{"a2a_key": "k", "note": "no prompt here"} diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/instruction.md b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a20342ad0d11a75265e9afa525457a87645312e8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/instruction.md @@ -0,0 +1,6 @@ +Build a small offline inbox-driven worker in Python 3.12 (standard library only) named `worker.py`. It must scan the directory `inbox/` for files ending in `.`, sort them by filename, and process exactly one item per loop iteration: read the file as JSON, decide the task from its content, write a reply file into `outbox/` (create the directory if needed), then rename the processed inbox file to the same name with a `.done` suffix (e.g. `001.` -> `001..done`). Reply rules: (1) If the JSON has a `prompt` field, write `outbox/<same-basename>.reply.` containing {"reply": "echo: " + prompt}. (2) If it has a `reply_instruction` field, write a reply file whose `reply` value is the string `ack: ` + reply_instruction. (3) If the JSON has neither field, write a reply file with {"reply": "unknown task"}. Every reply file must also include the key `source` set to the original inbox filename (without the `.done` suffix). Processing must stop after the inbox is empty; print `idle` once per empty scan and exit after two consecutive empty scans. A `--once` flag must process at most one item then exit. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. Network operations in the observed Python invocation are disallowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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/ce60989a1328cf7b91e3e5c3/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..1a359188d186b9e5c535ca223aa322308065d6cf --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/skill/SKILL.md @@ -0,0 +1,76 @@ +--- +name: ai_proxy_skill +description: Use when working with this ai-agent-proxy project, especially to understand its HTTP endpoints, inbox-driven worker flow, and how requests are delivered to the local agent inbox. +--- + +# AI Proxy Skill + +Use this skill when you are working inside this `ai-agent-proxy` project. + +## Project Model + +This project is an inbox-driven proxy. + +- HTTP requests are accepted by the FastAPI server. +- The server writes the request JSON body into the local agent inbox. +- The worker should listen to the inbox and process pending files. +- Replies should follow the message instructions in the inbox item. + +## Inbox Flow + +- The worker inbox path is under the local workspace for this project. +- Listen to the inbox folder for new files. +- Read each inbox file as JSON. +- Process one inbox item at a time. +- After finishing one item, check the inbox again. +- When idle, keep checking the inbox files while waiting. + +## Endpoints + +### `POST /chat/completions` + +Use this endpoint for chat-style requests. + +- The server accepts the JSON request body. +- The server enqueues only the JSON body into the agent inbox. +- The server returns an empty chat-completion response immediately. +- If `stream=true`, the server returns an SSE-formatted empty completion response. + +### `POST /v1/chat/completions` + +This is the OpenAI-style alias for `/chat/completions`. + +- Behavior is the same as `/chat/completions`. +- The request body is written to the inbox as JSON only. + +### `POST /agent-inbox` + +Use this endpoint for direct agent-to-agent inbox delivery. + +- The server accepts a JSON body with fields such as `agent_id`, `reply_instruction`, `system_instruction`, `prompt`, and `a2a_key`. +- The server enqueues the JSON body into the agent inbox. +- The server returns a small JSON acknowledgement immediately. + +### `GET /v1/models` + +Returns the single advertised proxy model. + +### `GET /v1/models/{model_id}` + +Returns metadata for the requested model id. + +## Worker Guidance + +- Listen to the inbox. +- Treat inbox files as the work queue. +- Read the JSON body carefully. +- Figure out from the inbox content what the task is. +- Decide by yourself how to reply based on the inbox content and the current project context. +- Use the OpenClaw message CLI skill to send the reply. +- When building context for a large reply, use the context cache skill first. + +## Current Contract + +- The inbox file content is raw JSON only. +- Do not assume chat requests carry a derived channel id. +- If you need `channel` or `target` for outbound delivery, read them from the JSON body. diff --git a/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/task.json b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a1ffd2934ab5831154a7d96f292c08901122e3ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/ce60989a1328cf7b91e3e5c3/task.json @@ -0,0 +1,83 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "ce60989a1328cf7b91e3e5c3", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "ce60989a1328cf7b91e3e5c3", + "outputs": [ + "worker.py" + ], + "success_criteria": [ + "Running `python3 worker.py` processes all three inbox items and exits after two consecutive empty scans, printing `idle` at least once per empty scan.", + "After the run, `inbox/001..done`, `inbox/002..done`, and `inbox/003..done` exist and the original `.` files no longer exist.", + "`outbox/001.reply.` parses as JSON with reply == \"echo: hello world\" and source == \"001.\".", + "`outbox/002.reply.` parses as JSON with reply == \"ack: send summary to channel ops\" and source == \"002.\".", + "`outbox/003.reply.` parses as JSON with reply == \"unknown task\" and source == \"003.\".", + "Running `python3 worker.py --once` on a fresh inbox with two items processes exactly one item (one .done file, one reply) and exits.", + "worker.py uses only the Python standard library (no third-party imports). Dependency/resource checks apply only to the actual guarded Python invocations under the public bounded runtime policy, not to unused source or static closure inference." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "bfc528f58197308743a8361989f3e5ad4fabbf5e40ba6a4538d18e3f02da0b65", + "files": { + "SKILL.md": "5c2967f7490863dfcb62a812564c64f6e6840826c79bd87b97a3093b4f6f4120" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/inbox/001.", + "workspace_target": "inbox/001.", + "sha256": "8d1f23da992f50b0f687dffdacc3e5d4dce400dee35cafe239ba260f18440d2e" + }, + { + "source": "inputs/inbox/002.", + "workspace_target": "inbox/002.", + "sha256": "4a3cee6d46397f825b28f699cac77eb2075fb2263270180a6ae738d49860ab48" + }, + { + "source": "inputs/inbox/003.", + "workspace_target": "inbox/003.", + "sha256": "54e549ef662d3eaa87f997b836f6c11822917cef5b85322315e9e49bf18241ee" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "bfc528f58197308743a8361989f3e5ad4fabbf5e40ba6a4538d18e3f02da0b65" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "6" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "6" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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/cfb3a31856fef16cc68a9e5a/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/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/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..75b86b9cccb96ab1323ea5f9170b1e477d60c954 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/autograde_task_check.py @@ -0,0 +1,122 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json, os, subprocess, sys, tempfile, shutil +from collections import Counter + +EP = '{"tiers":["free","basic","standard","advanced","professional"],"endpoints":[{"name":"coin_ticker","min_tier":"free","category":"market"},{"name":"kline","min_tier":"free","category":"market"},{"name":"hot_coins","min_tier":"free","category":"market"},{"name":"exchanges","min_tier":"free","category":"market"},{"name":"pair_ticker","min_tier":"free","category":"features"},{"name":"news_rss","min_tier":"free","category":"news"},{"name":"api_key_info","min_tier":"free","category":"account"},{"name":"funding_rate","min_tier":"basic","category":"derivatives"},{"name":"ls_ratio","min_tier":"basic","category":"derivatives"},{"name":"flash_list","min_tier":"basic","category":"news"},{"name":"open_interest","min_tier":"professional","category":"derivatives"},{"name":"big_orders","min_tier":"standard","category":"whale"},{"name":"liquidation_map","min_tier":"advanced","category":"liquidation"},{"name":"stock_quotes","min_tier":"professional","category":"stocks"},{"name":"depth_grouped","min_tier":"advanced","category":"depth"}]}' + +def setup(mutate=None): + d = tempfile.mkdtemp(dir='/tmp') + shutil.copytree('/candidate',d,dirs_exist_ok=True,ignore=shutil.ignore_patterns('report.json','endpoints.json','__pycache__','*.pyc')) + data = json.loads(EP) + if mutate: mutate(data) + with open(os.path.join(d, 'endpoints.json'), 'w') as f: + json.dump(data, f) + # Entry and local helpers already copied; catalog comes from the trusted fixture. + return d + +def run(d, args): + p = subprocess.run([sys.executable, 'tier_check.py'] + args, cwd=d, + capture_output=True, text=True, timeout=30) + return p.returncode, p.stdout + +def read_report(d): + with open(os.path.join(d, 'report.json')) as f: + return json.load(f) + +checks = [] +def add(i, ok, reason): + checks.append({'id': str(i), 'passed': bool(ok), 'reason': reason}) + +# Check 0: runs, reads endpoints.json (detects hardcoding via perturbed catalog) +try: + def mut(data): + for e in data['endpoints']: + if e['name'] == 'kline': e['min_tier'] = 'advanced' + d = setup(mut) + rc, out = run(d, ['kline']) + lines = [l.strip() for l in out.splitlines() if l.strip()] + ok = (rc == 0 and 'kline -> advanced (PAID)' in lines) + add(0, ok, 'Script reflects a modified endpoints.json (kline -> advanced (PAID)); hardcoded data would fail' if ok else 'Script did not reflect modified endpoints.json (expected line "kline -> advanced (PAID)", got rc=%s, out=%r); endpoint data appears hardcoded or script fails to run' % (rc, out[:300])) +except Exception as e: + add(0, False, 'Could not run tier_check.py: %s' % e) + +# Check 1: three-endpoint run +try: + d = setup() + rc, out = run(d, ['kline', 'big_orders', 'funding_rate']) + lines = [l.strip() for l in out.splitlines() if l.strip()] + exp = ['kline -> free (FREE)', 'big_orders -> standard (PAID)', 'funding_rate -> basic (PAID)'] + ok = rc == 0 and lines == exp + add(1, ok, 'Prints the three expected lines in order and exits 0' if ok else 'Expected lines %r with exit 0; got exit %s, output %r' % (exp, rc, out[:300])) +except Exception as e: + add(1, False, 'Could not run tier_check.py: %s' % e) + +# Check 2: unknown name +try: + d = setup() + rc, out = run(d, ['kline', 'nope']) + lines = [l.strip() for l in out.splitlines() if l.strip()] + ok = rc == 2 and 'nope -> UNKNOWN' in lines + add(2, ok, 'Prints "nope -> UNKNOWN" and exits 2' if ok else 'Expected "nope -> UNKNOWN" line and exit code 2; got exit %s, output %r' % (rc, out[:300])) +except Exception as e: + add(2, False, 'Could not run tier_check.py: %s' % e) + +# Check 3: slash normalization +try: + d = setup() + rc, out = run(d, ['BTC/USDT']) + lines = [l.strip() for l in out.splitlines() if l.strip()] + ok = rc == 2 and lines == ['btc:usdt -> UNKNOWN'] + def normalized_catalog(data):data['endpoints'].append({'name':'btc:usdt','min_tier':'free','category':'symbol'}) + d2=setup(normalized_catalog) + rc2,out2=run(d2,['BTC/USDT']) + ok = ok and rc2==0 and out2.splitlines()==['btc:usdt -> free (FREE)'] and read_report(d2)=={'total':1,'free':1,'paid':0,'unknown':[]} + add(3, ok, 'Slash argument handled (normalized before lookup), prints UNKNOWN line, exits 2' if ok else 'Expected an UNKNOWN line for BTC/USDT and exit code 2; got exit %s, output %r' % (rc, out[:300])) +except Exception as e: + add(3, False, 'Could not run tier_check.py: %s' % e) + +# Check 4: report.json after three-endpoint run +try: + d = setup() + run(d, ['kline', 'big_orders', 'funding_rate']) + rep = read_report(d) + exp = {'total': 3, 'free': 1, 'paid': 2, 'unknown': []} + ok = (rep.get('total') == 3 and rep.get('free') == 1 and rep.get('paid') == 2 + and isinstance(rep.get('unknown'), list) and len(rep['unknown']) == 0 and all(type(rep.get(key)) is int for key in ('total','free','paid'))) + add(4, ok, 'report.json contains total=3, free=1, paid=2, unknown=[]' if ok else 'report.json expected %r; got %r' % (exp, rep)) +except Exception as e: + add(4, False, 'report.json missing or malformed after three-endpoint run: %s' % e) + +# Check 5: report.json after mixed run +try: + d = setup() + run(d, ['kline', 'nope', 'BTC/USDT']) + rep = read_report(d) + unk = rep.get('unknown') + ok = (rep.get('total') == 3 and rep.get('free') == 1 and rep.get('paid') == 0 + and isinstance(unk, list) and all(isinstance(name,str) for name in unk) and Counter(unk)==Counter(['nope','btc:usdt']) and all(type(rep.get(key)) is int for key in ('total','free','paid'))) + add(5, ok, 'report.json has total=3, free=1, paid=0, unknown containing exactly the requested unknown names with no duplicates/extras' if ok else 'Expected total=3, free=1, paid=0, unknown containing exactly the requested unknown names with no duplicates/extras; got %r' % rep) +except Exception as e: + add(5, False, 'report.json missing or malformed after mixed run: %s' % e) + +# R2: arguments are an ordered multiset; process names after the first unknown too. +try: + d = setup() + rc, out = run(d, ['nope', 'kline', 'kline', 'BTC/USDT', 'nope', 'funding_rate']) + expected_lines = ['nope -> UNKNOWN', 'kline -> free (FREE)', 'kline -> free (FREE)', 'btc:usdt -> UNKNOWN', 'nope -> UNKNOWN', 'funding_rate -> basic (PAID)'] + rep = read_report(d) + lines_ok = rc == 2 and [line.strip() for line in out.splitlines() if line.strip()] == expected_lines + counts_ok = isinstance(rep, dict) and all(type(rep.get(k)) is int for k in ('total', 'free', 'paid')) and rep.get('total') == 6 and rep.get('free') == 2 and rep.get('paid') == 1 + unknowns = rep.get('unknown') if isinstance(rep, dict) else None + counts_ok = counts_ok and isinstance(unknowns, list) and all(isinstance(n, str) for n in unknowns) and Counter(unknowns) == Counter(['nope', 'btc:usdt', 'nope']) +except (OSError, ValueError, TypeError, subprocess.SubprocessError): + lines_ok = counts_ok = False +for check in checks: + if check['id'] in ('1', '2', '3'): + check['passed'] = check['passed'] and lines_ok + check['reason'] += '; repeated/interleaved arguments preserve all six output lines and process after unknown' + if check['id'] in ('4', '5'): + check['passed'] = check['passed'] and counts_ok + check['reason'] += '; counts and unknown multiplicity reflect repeated arguments' + +print(json.dumps(__import__('r10_runtime').finalize(checks, {'0':'tier_check.py'}))) diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/r10_runtime.py b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/r10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d7872f5ef5e56b3e7c57f0f9a26ee4db4570e73b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/r10_runtime.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""R10 grader helper. This file runs only inside an offline verifier container.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,os,pathlib,shutil +from dependency_scan import scan_stdlib +C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +_copies={};_deps={} +def dependency(entry): + key=str(entry) + if key not in _deps:_deps[key]=scan_stdlib(C,[key]) + return _deps[key] +def stdlib_gate(entry): + # Unknown is provisionally neutral; finalize() preserves it as unscored. + return dependency(entry)[0] is not False +def finalize(checks,owners): + for row in checks: + entry=owners.get(str(row['id'])) + if entry is None:continue + ok,_,why=dependency(entry) + if ok is False:row['passed']=False + elif ok is None and row.get('passed')is not False:row['passed']=None + row['reason']=row.get('reason','')+'; reachable dependency closure: '+why + return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks} +def strict_pairs(pairs): + out={} + for key,value in pairs: + if key in out:raise ValueError('duplicate JSON object key: '+key) + out[key]=value + return out +def read_json(path): + return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs, + parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x))) +def install_copy(entry): + """Complete authored dependencies without copying stale deliverables into fixtures.""" + if entry in _copies:return + _copies[entry]=True + try:task=json.loads(pathlib.Path('/source/task.json').read_text()) + except (OSError,ValueError):task={} + excluded=[] + for value in task.get('outputs',[]): + value=value.get('path')if isinstance(value,dict)else value + if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value)) + # Public fixture inputs come from the trusted source/fixture constructor, never + # from the candidate snapshot after a panel intentionally removes a file. + for mapping in task.get('workspace',{}).get('input_mappings',[]): + value=mapping.get('workspace_target') + if isinstance(value,str):excluded.append(pathlib.PurePosixPath(value)) + original_copy=shutil.copy;original_copyfile=shutil.copyfile + def extra(src,dst): + try: + source=pathlib.Path(src) + if source.name!=pathlib.Path(entry).name:return + source.resolve().relative_to(C.resolve()) + except (ValueError,TypeError,OSError):return + destination=pathlib.Path(dst) + if destination.is_dir():destination=destination/source.name + root=destination.parent + # Helpers keep the entry's authored relative directory context. + for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent + for dp,dn,fn in os.walk(str(C),followlinks=False): + dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')] + for name in fn: + p=pathlib.Path(dp)/name;rel=p.relative_to(C) + if any(rel==x or x in rel.parents for x in excluded):continue + if p.resolve()==source.resolve():continue + out=root/rel + if out.exists()or out.is_symlink():continue + out.parent.mkdir(parents=True,exist_ok=True) + if p.is_symlink():out.symlink_to(os.readlink(str(p))) + elif p.is_file():original_copyfile(str(p),str(out)) + def copy(src,dst,*args,**kwargs): + result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result + def copyfile(src,dst,*args,**kwargs): + result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result + shutil.copy=copy;shutil.copyfile=copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..02eb7a0769331d15468a57a27d62f0cd75381419 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/evaluator/repair_manifest.json @@ -0,0 +1,54 @@ +{ + "query_id": "cfb3a31856fef16cc68a9e5a", + "sample_index": 784, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "original_count": 6, + "modified_check_ids": [ + "3", + "4", + "5" + ], + "root_cause": "mixed report未知名单只测包含,不测完整正确名单,多报不存在的unknown仍6/6。", + "public_semantics": "Summary unknown names must have exactly the argument-derived multiset, no invented or duplicated names. Slash normalization must actually precede catalog lookup, verified with a catalog entry at the normalized name. Preserve helpers and fresh reports.", + "source_hashes": { + "instruction.md": "cfa45297f69c61cab81ce79c24b2ff91b379523630a22b24fa3ba1c5403cff36", + "task.json": "aff4d2daad1ddd297cefa506412627e1f8442f4c8ec4a48515b36548e4e0bb77", + "evaluator/check.py": "0e088256300b96bb8a178801bf514e5f41bef1ceaa11e2f1dd43524d1c4d1da8", + "skill/SKILL.md": "2a12c793d124bc0be015a35dc42914ed4797840b65689293fddc0f1404f0b861", + "reference/answer.txt": "506f1c83d4c7c20eebfbb4696cb38a7a6d0302632b448241293fce333848a97e", + "inputs/endpoints.json": "8cc4e53389878a538be480dde185dd4a092e3b3731b06a4866325a55636b4784", + "reference/workspace/tier_check.py": "ae93cf6fa354d867386fd0c0b2a3399e74bee7bbbce9ef5fa9819c406c796e21", + "reference/workspace/report.json": "c731a1b7e3f2ed7876c35657fdc6fbbf45a0a69dfbcd29957371cd70a6b5dfb1" + }, + "reviewed_files": [ + "instruction.md", + "task.json", + "evaluator/check.py", + "skill/SKILL.md", + "reference/answer.txt", + "inputs/endpoints.json", + "reference/workspace/tier_check.py", + "reference/workspace/report.json" + ], + "required_historical_artifacts": [], + "checker_sha256": "25c180d24d4b74fc9c69d83299942032ecc4d276757091de2f6a3b41e90d3cd9", + "all_logic_sha256": { + "check.py": "25c180d24d4b74fc9c69d83299942032ecc4d276757091de2f6a3b41e90d3cd9" + }, + "reviewed_logic_file_sha256": { + "check.py": "25c180d24d4b74fc9c69d83299942032ecc4d276757091de2f6a3b41e90d3cd9" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "author": "repair_c", + "fresh_solver_runs": 0, + "historical_rescoring_by_author": false, + "validation": "AST parsed and compiled only; candidate and source checker never executed locally" +} diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..1bb2d216c04d9394ed8afc05160e3a6383bbbb90 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/grading/verified_config.json @@ -0,0 +1,39 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "cfb3a31856fef16cc68a9e5a", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "214e040f465a267372810209e890ee5f5f0085227e493fee86ff50ff98d8d428", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "d957d6b201da12f2a2fc08b3c382d014d988a6ab397c505d0a6806b90775406b", + "r10_runtime.py": "e4205af091a5c170ce2640089d77bfe7fe9e7b516c56c4a0b3886a69816cb3a2", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/inputs/endpoints.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/inputs/endpoints.json new file mode 100644 index 0000000000000000000000000000000000000000..74cd866339462995fc3e7bec9fc65adb65222bd8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/inputs/endpoints.json @@ -0,0 +1,20 @@ +{ + "tiers": ["free", "basic", "standard", "advanced", "professional"], + "endpoints": [ + {"name": "coin_ticker", "min_tier": "free", "category": "market"}, + {"name": "kline", "min_tier": "free", "category": "market"}, + {"name": "hot_coins", "min_tier": "free", "category": "market"}, + {"name": "exchanges", "min_tier": "free", "category": "market"}, + {"name": "pair_ticker", "min_tier": "free", "category": "features"}, + {"name": "news_rss", "min_tier": "free", "category": "news"}, + {"name": "api_key_info", "min_tier": "free", "category": "account"}, + {"name": "funding_rate", "min_tier": "basic", "category": "derivatives"}, + {"name": "ls_ratio", "min_tier": "basic", "category": "derivatives"}, + {"name": "flash_list", "min_tier": "basic", "category": "news"}, + {"name": "open_interest", "min_tier": "professional", "category": "derivatives"}, + {"name": "big_orders", "min_tier": "standard", "category": "whale"}, + {"name": "liquidation_map", "min_tier": "advanced", "category": "liquidation"}, + {"name": "stock_quotes", "min_tier": "professional", "category": "stocks"}, + {"name": "depth_grouped", "min_tier": "advanced", "category": "depth"} + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/instruction.md b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3451888bccd554368548926ba6181a1db27d1f50 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/instruction.md @@ -0,0 +1,6 @@ +We have a local snapshot of an API's endpoint catalog in endpoints.json (name, min_tier, category). Write a Python 3 script `tier_check.py` (standard library only) that: (1) loads endpoints.json; (2) builds a tier-ladder lookup and, for each endpoint given on the command line (e.g. `python3 tier_check.py kline big_orders funding_rate`), prints one line `NAME -> TIER (FREE)` or `NAME -> TIER (PAID)` where FREE means min_tier is 'free'; (3) if any requested endpoint name is not in the catalog, print `NAME -> UNKNOWN` and exit with code 2 after processing all names; otherwise exit 0; (4) additionally writes a summary file report.json containing {"total": N, "free": n_free, "paid": n_paid, "unknown": [names]} computed over the command-line arguments (unknown names counted in total but not in free/paid). Also implement symbol normalization: any argument containing '/' (like BTC/USDT) must first be converted to the colon format by lowercasing and replacing '/' with ':' before the catalog lookup — but note the catalog only contains endpoint names, so slash-arguments will normally be UNKNOWN unless they match after normalization. Do not hardcode the catalog contents in the script; read them from endpoints.json. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/cfb3a31856fef16cc68a9e5a/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..996f367500efc44b283dab927c1d05f95c6bea63 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/SKILL.md @@ -0,0 +1,233 @@ +--- +name: aicoin-market +description: "This skill should be used when the user asks about crypto prices, market data, K-line charts, funding rates, open interest, long/short ratios, whale orders, liquidation data, crypto news, newsflash, Twitter crypto tweets, trending coins, stock quotes, treasury holdings, or any crypto market query. Also use when user asks about configuring or checking AiCoin API key. Use when user says: 'BTC price', 'check price', 'show K-line', 'funding rate', 'open interest', 'whale orders', 'long/short ratio', 'crypto news', 'newsflash', 'trending coins', '查行情', '看价格', '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'liquidation map', '配置AiCoin key', 'AiCoin API key', 'AiCoin key安全吗'. Covers 200+ exchanges with real-time data. MUST run node scripts to fetch real data. NEVER generate fake prices or hallucinate market data. IMPORTANT — AiCoin API Key: When user asks about AiCoin API key (配置/检查/安全/能不能交易), run `node scripts/coin.mjs api_key_info` FIRST, show the security_notice to user. For exchange trading (buy/sell/balance), use aicoin-trading instead. For Freqtrade strategies/backtest, use aicoin-freqtrade. For Hyperliquid whale analytics, use aicoin-hyperliquid." +metadata: { "openclaw": { "primaryEnv": "AICOIN_ACCESS_KEY_ID", "requires": { "bins": ["node"] }, "homepage": "https://www.aicoin.com/opendata", "source": "https://github.com/aicoincom/coinos-skills", "license": "MIT" } } +--- + +# AiCoin Market + +Crypto market data toolkit powered by [AiCoin Open API](https://www.aicoin.com/opendata). Prices, K-lines, news, signals, whale orders, and more from 200+ exchanges. + +**Version:** 1.0.0 + +## Critical Rules + +1. **NEVER fabricate data.** Always run scripts to fetch real-time data. +2. **NEVER use curl, web_fetch, or browser** for crypto data. Always use these scripts. +3. **NEVER run `env` or `printenv`** — leaks API secrets into logs. +4. **Scripts auto-load `.env`** — never pass credentials inline. +5. **Reply in the user's language.** Chinese input = all-Chinese response (titles, headings, analysis). +6. **On 304/403 error — STOP, do NOT retry.** This is a paid feature. Follow the [Paid Feature Guide](#paid-feature-guide) to help the user upgrade. + +## Quick Reference + +| Task | Command | Min Tier | +|------|---------|----------| +| **API Key Info** | `node scripts/coin.mjs api_key_info` — **When user asks about AiCoin API key (配置/安全/能不能下单), ALWAYS run this first.** | Free | +| BTC price | `node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'` | Free | +| K-line | `node scripts/market.mjs kline '{"symbol":"btcusdt:okex","period":"3600","size":"100"}'` | Free | +| Funding rate | `node scripts/coin.mjs funding_rate '{"symbol":"BTC"}'` | Basic | +| Long/short ratio | `node scripts/features.mjs ls_ratio` | Basic | +| Whale orders | `node scripts/features.mjs big_orders '{"symbol":"btcswapusdt:binance"}'` | Standard | +| News flash | `node scripts/news.mjs flash_list '{"language":"cn"}'` | Basic | +| Trending coins | `node scripts/market.mjs hot_coins '{"key":"defi"}'` | Free | +| Open interest | `node scripts/coin.mjs open_interest '{"symbol":"BTC","interval":"15m"}'` | Professional | +| Liquidation map | `node scripts/coin.mjs liquidation_map '{"dbkey":"btcswapusdt:binance","cycle":"24h"}'` | Advanced | + +**Symbol shortcuts:** `BTC`, `ETH`, `SOL`, `DOGE`, `XRP` auto-resolve in coin.mjs. + +**Chinese Slang:** 大饼=BTC, 姨太=ETH, 狗狗=DOGE, 瑞波=XRP, 索拉纳=SOL. + +## Free vs Paid Endpoints + +**Free (built-in key, no config needed):** `coin_ticker`, `kline`, `hot_coins`, `exchanges`, `pair_ticker`, `news_rss` — only 6 endpoints. + +**Basic ($29/mo) adds:** `coin_list`, `coin_config`, `funding_rate`, `trade_data`, `ticker`, `futures_interest`, `ls_ratio`, `nav`, `pair_by_market`, `pair_list`, `news_list`, `flash_list`, `twitter/latest`, `twitter/search`, `newsflash/search`, `newsflash/list` + +**Standard ($79/mo) adds:** `big_orders`, `agg_trades`, `grayscale_trust`, `gray_scale`, `signal_alert`, `signal_config`, `strategy_signal`, `change_signal`, `depth_latest`, `newsflash`, `news_detail`, `twitter/members`, `twitter/interaction_stats`, `newsflash/detail` + +**Advanced ($299/mo) adds:** `liquidation_map`, `liquidation_history`, `liquidation`, `indicator_kline`, `indicator_pairs`, `index_list`, `index_price`, `index_info`, `depth_full`, `depth_grouped` + +**Professional ($699/mo) adds:** `ai_analysis`, `open_interest`, `estimated_liquidation`, `historical_depth`, `super_depth`, `funding_rate`(weighted), `stock_quotes`, `stock_top_gainer`, `stock_company`, `treasury_*`, `stock_market`, `signal_alert_list`, `exchange_listing` + +Full tier table: `docs/api-tiers.md` + +## Setup + +Scripts work out of the box with a built-in free key (6 endpoints). For more endpoints, add your API key to `.env`: + +``` +AICOIN_ACCESS_KEY_ID=your-key +AICOIN_ACCESS_SECRET=your-secret +``` + +**安全说明:** AiCoin API Key 仅用于获取市场数据(行情、K线、新闻等),无法进行任何交易操作,也无法读取你在交易所的信息。如需交易功能,需单独到交易所申请交易 API Key(见 aicoin-trading skill)。所有密钥仅保存在本地设备 `.env` 文件中,不会上传到任何服务器。 + +`.env` is auto-loaded from: cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env` + +## Scripts + +All scripts: `node scripts/<name>.mjs <action> [json-params]` + +### scripts/coin.mjs — Coin Data + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `api_key_info` | **AiCoin API Key status + security notice. Run when user asks about key config/safety.** | Free | None | +| `coin_ticker` | Real-time prices | Free | `{"coin_list":"bitcoin,ethereum"}` | +| `coin_list` | List all coins | Basic | None | +| `coin_config` | Coin profile | Basic | `{"coin_list":"bitcoin"}` | +| `funding_rate` | Funding rate (BTC only, aggregated) | Basic | `{"symbol":"BTC","interval":"8h"}` Weighted: add `"weighted":"true"` (Pro). For per-exchange real-time rates, use **aicoin-trading**: `node scripts/exchange.mjs funding_rate '{"exchange":"binance","symbol":"BTC/USDT:USDT"}'` | +| `trade_data` | Trade data | Basic | `{"symbol":"btcswapusdt:okcoinfutures"}` | +| `ai_analysis` | AI analysis & prediction | Pro | `{"coin_keys":"[\"bitcoin\"]","language":"CN"}` | +| `open_interest` | Open interest | Pro | `{"symbol":"BTC","interval":"15m"}` Coin-margined: add `"margin_type":"coin"` | +| `liquidation_map` | Liquidation heatmap | Adv | `{"symbol":"btcswapusdt:binance","cycle":"24h"}` | +| `liquidation_history` | Liquidation history | Adv | `{"symbol":"btcswapusdt:binance","interval":"1m"}` | +| `estimated_liquidation` | Estimated liquidation | Pro | `{"symbol":"btcswapusdt:binance","cycle":"24h"}` | +| `historical_depth` | Historical depth | Pro | `{"symbol":"btcswapusdt:okcoinfutures"}` | +| `super_depth` | Large order depth >$10k | Pro | `{"symbol":"btcswapusdt:okcoinfutures"}` | + +### scripts/market.mjs — Market Data + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `kline` | Standard K-line | Free | `{"symbol":"btcusdt:okex","period":"3600","size":"100"}` period: 900/3600/14400/86400 | +| `hot_coins` | Trending coins | Free | `{"key":"defi"}` key: gamefi/anonymous/market/web/newcoin/stable/defi | +| `exchanges` | Exchange list | Free | None | +| `ticker` | Exchange tickers | Basic | `{"market_list":"okex,binance"}` | +| `futures_interest` | Futures OI ranking | Basic | `{"language":"cn"}` | +| `depth_latest` | Real-time depth | Std | `{"symbol":"btcswapusdt:binance"}` | +| `indicator_kline` | Indicator K-line | Adv | `{"symbol":"btcswapusdt:binance","indicator_key":"fundflow","period":"3600"}` | +| `indicator_pairs` | Indicator pairs | Adv | `{"indicator_key":"fundflow"}` | +| `index_list` | Index list | Adv | None | +| `index_price` | Index price | Adv | `{"key":"i:diniw:ice"}` | +| `index_info` | Index details | Adv | `{"key":"i:diniw:ice"}` | +| `depth_full` | Full order book | Adv | `{"symbol":"btcswapusdt:binance"}` | +| `depth_grouped` | Grouped depth | Adv | `{"symbol":"btcswapusdt:binance","groupSize":"100"}` | +| `stock_quotes` | Stock quotes | Pro | `{"tickers":"i:mstr:nasdaq"}` | +| `stock_top_gainer` | Top gainers | Pro | `{"us_stock":"true"}` | +| `stock_company` | Company details | Pro | `{"symbol":"i:mstr:nasdaq"}` | +| `treasury_entities` | Holding entities | Pro | `{"coin":"BTC"}` | +| `treasury_history` | Transaction history | Pro | `{"coin":"BTC"}` | +| `treasury_accumulated` | Accumulated holdings | Pro | `{"coin":"BTC"}` | +| `treasury_latest_entities` | Latest entities | Pro | `{"coin":"BTC"}` | +| `treasury_latest_history` | Latest history | Pro | `{"coin":"BTC"}` | +| `treasury_summary` | Holdings overview | Pro | `{"coin":"BTC"}` | + +### scripts/features.mjs — Features & Signals + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `pair_ticker` | Pair ticker | Free | `{"key_list":"btcusdt:okex,btcusdt:huobipro"}` | +| `ls_ratio` | Long/short ratio | Basic | None | +| `nav` | Market navigation | Basic | `{"language":"cn"}` | +| `pair_by_market` | Pairs by exchange | Basic | `{"market":"binance"}` | +| `pair_list` | Pair list | Basic | `{"market":"binance","currency":"USDT"}` | +| `grayscale_trust` | Grayscale trust | Std | None | +| `gray_scale` | Grayscale holdings | Std | `{"coins":"btc,eth"}` | +| `signal_alert` | Signal alerts | Std | None | +| `signal_config` | Alert config | Std | `{"language":"cn"}` | +| `strategy_signal` | Strategy signal | Std | `{"signal_key":"depth_win_one"}` | +| `change_signal` | Anomaly signal | Std | `{"type":"1"}` | +| `big_orders` | Whale orders | Std | `{"symbol":"btcswapusdt:binance"}` | +| `agg_trades` | Aggregated large trades | Std | `{"symbol":"btcswapusdt:binance"}` | +| `liquidation` | Liquidation data | Adv | `{"type":"1","coinKey":"bitcoin"}` | +| `signal_alert_list` | Alert list | Pro | None | +| `stock_market` | Crypto stocks | Pro | None | +| `delete_signal` | Delete alert | Pro | `{"id":"xxx"}` | + +### scripts/news.mjs — News & Content + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `news_rss` | RSS news feed | Free | `{"page":"1"}` | +| `news_list` | News list | Basic | `{"page":"1","page_size":"20"}` | +| `flash_list` | Industry flash news | Basic | `{"language":"cn"}` | +| `newsflash` | AiCoin flash news | Std | `{"language":"cn"}` | +| `news_detail` | News detail | Std | `{"id":"xxx"}` | +| `exchange_listing` | Exchange listing announcements | Pro | `{"memberIds":"477,1509"}` | + +### scripts/twitter.mjs — Twitter/X Crypto Tweets + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `latest` | Latest crypto tweets | Basic | `{"language":"cn","page_size":"20"}` | +| `search` | Search tweets | Basic | `{"keyword":"bitcoin","language":"cn","page_size":"20"}` | +| `members` | Search KOL/users | Std | `{"keyword":"elon","page":"1","page_size":"20"}` | +| `interaction_stats` | Tweet engagement stats | Std | `{"flash_ids":"123,456,789"}` | + +### scripts/newsflash.mjs — Newsflash (OpenData) + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `search` | Search newsflash | Basic | `{"keyword":"bitcoin","page":"1","page_size":"20"}` | +| `list` | Newsflash list with filters | Basic | `{"page_size":"20","language":"cn"}` | +| `detail` | Newsflash full content | Std | `{"flash_id":"123456"}` | + +### scripts/airdrop.mjs — Airdrop (OpenData) + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `list` | Airdrop projects list (multi-source) | Basic | `{"source":"all","status":"ongoing","page":"1","page_size":"20","exchange":"binance"}` | +| `detail` | Airdrop detail (hodler/xlaunch) | Std | `{"type":"hodler","token":"SIGN"}` | +| `banner` | Hot airdrop banners | Basic | `{"limit":"5"}` | +| `exchanges` | Available exchanges and activity types | Basic | `{"lan":"cn"}` | +| `calendar` | Airdrop calendar (year+month required) | Std | `{"year":"2026","month":"3"}` | + +**Source options for list:** `all`(default), `hodler`, `xlaunch`, `earncoin`, `alpha`, `bitget_launchpool`, `bitget_poolx` + +### scripts/drop_radar.mjs — Drop Radar (OpenData) + +| Action | Description | Min Tier | Params | +|--------|-------------|----------|--------| +| `list` | Project list with filters | Basic | `{"page":"1","page_size":"20","status":"CONFIRMED","keyword":"airdrop"}` | +| `detail` | Project detail | Basic | `{"airdrop_id":"xxx"}` | +| `widgets` | Statistics overview | Basic | `{"lan":"cn"}` | +| `filters` | Available filter options | Basic | `{"lan":"cn"}` | +| `events` | Project event calendar | Std | `{"airdrop_id":"xxx"}` | +| `team` | Project team members | Std | `{"airdrop_id":"xxx"}` | +| `x_following` | Project X following list | Std | `{"airdrop_id":"xxx"}` | +| `status_changes` | Recent status changes | Std | `{"days":"7","page":"1","page_size":"20"}` | +| `tweets` | Search project tweets | Std | `{"keywords":"bitcoin,airdrop","page_size":"20"}` | + +## Cross-Skill References + +| Need | Use | +|------|-----| +| Exchange trading (buy/sell/balance) | **aicoin-trading** | +| Freqtrade strategies/backtest/deploy | **aicoin-freqtrade** | +| Hyperliquid whale tracking | **aicoin-hyperliquid** | + +## Common Errors + +- `errorCode 304 / HTTP 403` — Paid feature. Follow [Paid Feature Guide](#paid-feature-guide) below. +- `Invalid symbol` — Check format: AiCoin uses `btcusdt:okex`, not `BTC/USDT` +- `Rate limit exceeded` — Wait 1-2s between requests; use batch queries + +## Paid Feature Guide + +When a script returns 304 or 403, this endpoint requires a higher API tier. **Do NOT retry the same call.** + +Tell the user (in their language): + +1. **What happened**: This feature needs a paid AiCoin API subscription. +2. **How to get a key**: Visit https://www.aicoin.com/opendata to register and create an API key. +3. **Tier options**: + +| Tier | Price | Highlights | +|------|-------|------------| +| Free | $0 | Prices, K-lines, trending coins (6 endpoints) | +| Basic | $29/mo | + Funding rate, L/S ratio, news, twitter (24 endpoints) | +| Standard | $79/mo | + Whale orders, signals, grayscale (38 endpoints) | +| Advanced | $299/mo | + Liquidation map, indicator K-lines, index, depth (49 endpoints) | +| Professional | $699/mo | All 63 endpoints: AI analysis, OI, stocks, treasury | + +4. **How to configure**: After getting a key, add to `.env` file: +``` +AICOIN_ACCESS_KEY_ID=your-key-id +AICOIN_ACCESS_SECRET=your-secret +``` +Scripts auto-load `.env` from cwd, `~/.openclaw/workspace/.env`, or `~/.openclaw/.env`. + +5. **After configuring**: The same script command will work. No code changes needed. +6. **MUST tell the user**: AiCoin API Key 仅用于获取市场数据(行情、K线、新闻等),无法进行任何交易操作,也无法读取你在交易所的任何信息。如需在交易所下单,需要单独到交易所申请交易 API Key(见 aicoin-trading skill)。所有密钥仅保存在你的本地设备 `.env` 文件中,不会上传到任何服务器。 diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ar.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ar.txt new file mode 100644 index 0000000000000000000000000000000000000000..88323795f580831a184145de97ed6255b7725313 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ar.txt @@ -0,0 +1 @@ +يجب استخدام هذه المهارة عندما يسأل المستخدم عن أسعار العملات المشفرة، وبيانات السوق، ومخططات K-line، ومعدلات التمويل، والفائدة المفتوحة، والنسب الطويلة/القصيرة، وأوامر الحيتان، وبيانات التصفية، وأخبار العملات المشفرة، والأخبار العاجلة، وتغريدات العملات المشفرة على تويتر، والعملات المتداولة، وأسعار الأسهم، وحيازات الخزانة، أو أي استعلام عن سوق العملات المشفرة. يُستخدم أيضًا عندما يسأل المستخدم عن تكوين أو التحقق من مفتاح AiCoin API. يُستخدم عندما يقول المستخدم: "سعر BTC"، "التحقق من السعر"، "إظهار K-line"، "معدل التمويل"، "الفائدة المفتوحة"، "أوامر الحيتان"، "نسبة طويلة/قصيرة"، "أخبار التشفير"، "newsflash"، "العملات المتداولة"، "查行情"، "看价格"، "大饼多少钱"، "K线"، "资金费率"، "多空比"، "鲸鱼单"، "新闻快讯"، "热门币"، "خريطة التصفية"، "مفتاح AiCoin"، "مفتاح AiCoin API"، "AiCoin" مفتاح ". يغطي أكثر من 200 عملية تبادل مع البيانات في الوقت الفعلي. يجب تشغيل البرامج النصية للعقدة لجلب البيانات الحقيقية. لا تقم أبدًا بإنشاء أسعار زائفة أو تهلوس بيانات السوق. هام — مفتاح AiCoin API: عندما يسأل المستخدم عن مفتاح AiCoin API (配置/检查/安全/能不能交易)، قم بتشغيل "node scripts/coin.mjs api_key_info" أولاً، وأظهر إشعار الأمان للمستخدم. لتداول العملات (شراء/بيع/رصيد)، استخدم aicoin-trading بدلاً من ذلك. بالنسبة لاستراتيجيات Freqtrade/backtest، استخدم aicoin-freqtrade. بالنسبة لتحليلات الحيتان مفرطة السيولة، استخدم aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_cn.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_cn.txt new file mode 100644 index 0000000000000000000000000000000000000000..805156c5460cdc2164358f2dc4cc08563e958508 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_cn.txt @@ -0,0 +1 @@ +当用户询问加密货币价格、市场数据、K线图、融资利率、未平仓合约、多头/空头比率、鲸鱼订单、清算数据、加密货币新闻、新闻快讯、Twitter加密推文、趋势币、股票报价、国库持有或任何加密货币市场查询时,应该使用此技能。当用户询问配置或检查 AiCoin API 密钥时也可使用。当用户说:“BTC价格”、“查看价格”、“显示K线”、“资金费率”、“持仓量”、“鲸鱼订单”、“多空比”、“加密新闻”、“快讯”、“热门币种”、“查行情”、“看价格”、“大饼多少钱”、“K线”、“资金费率”、“多空比”时使用‘鲸鱼单’、‘新闻快讯’、‘热门币’、‘清算图’、‘配置AiCoin key’、‘AiCoin API key’、‘AiCoin key安全吗’。覆盖200+交易所的实时数据。必须运行节点脚本来获取真实数据。切勿生成虚假价格或幻觉市场数据。重要 — AiCoin API 密钥:当用户询问 AiCoin API 密钥(配置/检查/安全/不能交易)时,请首先运行 `node script/coin.mjs api_key_info`,向用户显示 security_notice。对于交易所交易(买入/卖出/余额),请使用 aicoin-trading。对于 Freqtrade 策略/回测,请使用 aicoin-freqtrade。对于 Hyperliquid 鲸鱼分析,请使用 aicoin-hyperliquid。 diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_de.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_de.txt new file mode 100644 index 0000000000000000000000000000000000000000..31726297e1885aa62f9250c10ca5e168b0f7fabc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_de.txt @@ -0,0 +1 @@ +Diese Fähigkeit sollte verwendet werden, wenn der Benutzer Fragen zu Kryptopreisen, Marktdaten, K-Line-Diagrammen, Finanzierungsraten, offenen Positionen, Long/Short-Verhältnissen, Walaufträgen, Liquidationsdaten, Kryptonachrichten, Newsflash, Twitter-Krypto-Tweets, Trendmünzen, Aktienkursen, Staatsanleihenbeständen oder anderen Fragen zum Kryptomarkt stellt. Verwenden Sie es auch, wenn der Benutzer nach der Konfiguration oder Überprüfung des AiCoin-API-Schlüssels fragt. Wird verwendet, wenn der Benutzer sagt: „BTC-Preis“, „Preis prüfen“, „K-Linie anzeigen“, „Finanzierungsrate“, „Open Interest“, „Walaufträge“, „Long/Short-Verhältnis“, „Krypto-Nachrichten“, „Newsflash“, „Trendmünzen“, „查行情“, „看价格“, „大饼多少钱“, „K线“, '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'Liquidation Map', '配置AiCoin Key', 'AiCoin API Key', 'AiCoin Key安全吗'. Deckt mehr als 200 Börsen mit Echtzeitdaten ab. MÜSSEN Knotenskripte ausführen, um echte Daten abzurufen. Generieren Sie NIEMALS gefälschte Preise oder halluzinieren Sie Marktdaten. WICHTIG – AiCoin-API-Schlüssel: Wenn der Benutzer nach dem AiCoin-API-Schlüssel (配置/检查/安全/能不能交易) fragt, führen Sie ZUERST „node scripts/coin.mjs api_key_info“ aus und zeigen Sie dem Benutzer den security_notice. Für den Börsenhandel (Kauf/Verkauf/Balance) verwenden Sie stattdessen aicoin-trading. Für Freqtrade-Strategien/Backtests verwenden Sie aicoin-freqtrade. Verwenden Sie für die Analyse von Hyperliquid-Walen aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_en.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_en.txt new file mode 100644 index 0000000000000000000000000000000000000000..97a4a617c02380aee13c03fb2f764d446a4c895d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_en.txt @@ -0,0 +1 @@ +This skill should be used when the user asks about crypto prices, market data, K-line charts, funding rates, open interest, long/short ratios, whale orders, liquidation data, crypto news, newsflash, Twitter crypto tweets, trending coins, stock quotes, treasury holdings, or any crypto market query. Also use when user asks about configuring or checking AiCoin API key. Use when user says: 'BTC price', 'check price', 'show K-line', 'funding rate', 'open interest', 'whale orders', 'long/short ratio', 'crypto news', 'newsflash', 'trending coins', '查行情', '看价格', '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'liquidation map', '配置AiCoin key', 'AiCoin API key', 'AiCoin key安全吗'. Covers 200+ exchanges with real-time data. MUST run node scripts to fetch real data. NEVER generate fake prices or hallucinate market data. IMPORTANT — AiCoin API Key: When user asks about AiCoin API key (配置/检查/安全/能不能交易), run `node scripts/coin.mjs api_key_info` FIRST, show the security_notice to user. For exchange trading (buy/sell/balance), use aicoin-trading instead. For Freqtrade strategies/backtest, use aicoin-freqtrade. For Hyperliquid whale analytics, use aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_es.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_es.txt new file mode 100644 index 0000000000000000000000000000000000000000..36eac820c94c86779e6048334b096fe184f89353 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_es.txt @@ -0,0 +1 @@ +Esta habilidad debe usarse cuando el usuario pregunta sobre precios de criptomonedas, datos de mercado, gráficos de líneas K, tasas de financiación, interés abierto, ratios largos/cortos, órdenes de ballenas, datos de liquidación, noticias sobre criptomonedas, noticias de última hora, tweets sobre criptomonedas en Twitter, monedas de tendencia, cotizaciones de acciones, tenencias de tesorería o cualquier consulta sobre el mercado de criptomonedas. Utilícelo también cuando el usuario pregunte sobre la configuración o verificación de la clave API de AiCoin. Úselo cuando el usuario diga: 'precio BTC', 'comprobar precio', 'mostrar línea K', 'tasa de financiación', 'interés abierto', 'órdenes de ballenas', 'relación larga/corta', 'noticias criptográficas', 'noticias de última hora', 'monedas de tendencia', '查行情', '看价格', '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'mapa de liquidación', '配置AiCoin key', 'AiCoin API key', 'AiCoin key安全吗'. Cubre más de 200 intercambios con datos en tiempo real. DEBE ejecutar scripts de nodo para obtener datos reales. NUNCA generes precios falsos ni alucines con datos de mercado. IMPORTANTE - Clave API de AiCoin: cuando el usuario pregunta sobre la clave API de AiCoin (配置/检查/安全/能不能交易), ejecute `node scripts/coin.mjs api_key_info` PRIMERO, muestre el aviso de seguridad al usuario. Para operaciones de intercambio (compra/venta/equilibrio), utilice aicoin-trading en su lugar. Para estrategias/backtest de Freqtrade, utilice aicoin-freqtrade. Para análisis de ballenas Hyperliquid, utilice aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_fr.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_fr.txt new file mode 100644 index 0000000000000000000000000000000000000000..f65b00cb896c8910b9fff149ebc126e29f4b97d6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_fr.txt @@ -0,0 +1 @@ +Cette compétence doit être utilisée lorsque l'utilisateur pose des questions sur les prix des cryptomonnaies, les données de marché, les graphiques K-line, les taux de financement, les intérêts ouverts, les ratios long/short, les ordres de baleines, les données de liquidation, les actualités cryptographiques, les flashs d'information, les tweets cryptographiques Twitter, les tendances des pièces, les cotations boursières, les avoirs de trésorerie ou toute requête sur le marché cryptographique. À utiliser également lorsque l'utilisateur demande comment configurer ou vérifier la clé API AiCoin. À utiliser lorsque l'utilisateur dit : "Prix BTC", "Vérifier le prix", "afficher la ligne K", "taux de financement", "intérêt ouvert", "ordres de baleines", "ratio long/short", "actualités crypto", "newsflash", "pièces tendance", "查行情", "看价格", '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'carte de liquidation', '配置AiCoin clé', 'Clé API AiCoin', 'Clé AiCoin安全吗'. Couvre plus de 200 échanges avec des données en temps réel. DOIT exécuter des scripts de nœud pour récupérer des données réelles. NE JAMAIS générer de faux prix ni halluciner les données du marché. IMPORTANT — Clé API AiCoin : lorsque l'utilisateur pose des questions sur la clé API AiCoin (配置/检查/安全/能不能交易), exécutez EN PREMIER `node scripts/coin.mjs api_key_info`, affichez l'avis de sécurité à l'utilisateur. Pour le trading en bourse (achat/vente/solde), utilisez plutôt aicoin-trading. Pour les stratégies/backtest Freqtrade, utilisez aicoin-freqtrade. Pour l’analyse des baleines hyperliquides, utilisez aicoin-hyperliquide. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_it.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_it.txt new file mode 100644 index 0000000000000000000000000000000000000000..1af355f692f3dfcbed6c2c6fd9aa65313656382f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_it.txt @@ -0,0 +1 @@ +Questa abilità dovrebbe essere utilizzata quando l'utente chiede informazioni su prezzi delle criptovalute, dati di mercato, grafici della linea K, tassi di finanziamento, interessi aperti, rapporti lungo/corto, ordini di balene, dati di liquidazione, notizie sulle criptovalute, notizie flash, tweet sulle criptovalute di Twitter, monete di tendenza, quotazioni azionarie, titoli di tesoreria o qualsiasi domanda sul mercato delle criptovalute. Da utilizzare anche quando l'utente chiede informazioni sulla configurazione o sul controllo della chiave API AiCoin. Da utilizzare quando l'utente dice: "Prezzo BTC", "controlla prezzo", "mostra linea K", "tasso di finanziamento", "interesse aperto", "ordini balena", "rapporto lungo/corto", "notizie cripto", "newsflash", "monete di tendenza", "查行情", "看价格", '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', 'mappa di liquidazione', '配置AiCoin chiave', 'Chiave API AiCoin', 'Chiave AiCoin安全吗'. Copre oltre 200 scambi con dati in tempo reale. DEVE eseguire gli script del nodo per recuperare dati reali. Non generare MAI prezzi falsi o dati di mercato allucinanti. IMPORTANTE — Chiave API AiCoin: quando l'utente chiede la chiave API AiCoin (配置/检查/安全/能不能交易), esegui PRIMA `node scripts/coin.mjs api_key_info`, mostra security_notice all'utente. Per il trading in borsa (acquisto/vendita/saldo), utilizza invece aicoin-trading. Per le strategie/backtest di Freqtrade, utilizzare aicoin-freqtrade. Per l'analisi delle balene iperliquide, utilizzare aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ja.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ja.txt new file mode 100644 index 0000000000000000000000000000000000000000..aead8ab50da70190fdaa9772acff3755b23e676a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ja.txt @@ -0,0 +1 @@ +このスキルは、ユーザーが仮想通貨価格、市場データ、K ライン チャート、資金調達率、建玉、ロング/ショート レシオ、クジラ注文、清算データ、仮想通貨ニュース、ニュースフラッシュ、Twitter 仮想通貨ツイート、トレンド コイン、株価、財務省保有株、または任意の仮想通貨市場に関する質問について質問するときに使用する必要があります。ユーザーが AiCoin API キーの設定や確認について尋ねる場合にも使用します。ユーザーが言うときに使用します: 「BTC 価格」、「価格を確認」、「K ラインを表示」、「ファンディング レート」、「建玉」、「クジラ注文」、「ロング/ショート レシオ」、「暗号ニュース」、「ニュースフラッシュ」、「トレンド コイン」、「查行情」、「看价格」、「大饼何钱」、「Kline」、 '资金费率'、'多空比'、'鲸鱼单'、'新闻快讯'、'热门币'、'清算マップ'、'配置AiCoinキー'、'AiCoin APIキー'、'AiCoinキー安全吗'。リアルタイム データで 200 以上の交換をカバーします。実際のデータをフェッチするにはノード スクリプトを実行しなければなりません。偽の価格を生成したり、幻覚の市場データを作成したりしないでください。重要 — AiCoin API キー: ユーザーが AiCoin API キー (配置/检查/安全/能交易) について尋ねたら、最初に `node scripts/coin.mjs api_key_info` を実行し、ユーザーに security_notice を表示します。取引所取引 (購入/販売/残高) の場合は、代わりに aicoin-trading を使用してください。 Freqtrade 戦略/バックテストについては、aicoin-freqtrade を使用してください。 Hyperliquid クジラ分析には、aicoin-hyperliquid を使用します。 diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ko.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ko.txt new file mode 100644 index 0000000000000000000000000000000000000000..019c6d5a2f8f6bfadf280cf140ac038618193717 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ko.txt @@ -0,0 +1 @@ +이 기술은 사용자가 암호화폐 가격, 시장 데이터, K-라인 차트, 자금 조달 요율, 미결제약정, 장/단기 비율, 고래 주문, 청산 데이터, 암호화폐 뉴스, 뉴스 속보, 트위터 암호화폐 트윗, 동향 동전, 주식 시세, 국채 보유 또는 암호화폐 시장 쿼리에 대해 질문할 때 사용해야 합니다. 또한 사용자가 AiCoin API 키 구성 또는 확인에 대해 문의할 때 사용합니다. 사용자가 다음과 같이 말할 때 사용: 'BTC 가격', '가격 확인', 'K-라인 표시', '펀딩 비율', '미결제약정', '고래 주문', '롱/숏 비율', '암호화폐 뉴스', '뉴스플래시', '트렌딩 코인', '查行情', '看价格', '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '新闻快讯', '热门币', '청산 맵', '配置AiCoin 키', 'AiCoin API 키', 'AiCoin 키안전확보'. 실시간 데이터로 200개 이상의 교환을 처리합니다. 실제 데이터를 가져오려면 노드 스크립트를 실행해야 합니다. 절대로 가짜 가격을 생성하거나 시장 데이터에 환각을 일으키지 마십시오. 중요 — AiCoin API 키: 사용자가 AiCoin API 키(配置/检查/안전/能不能交易)에 대해 문의하면 먼저 `node scripts/coin.mjs api_key_info`를 실행하고 사용자에게 security_notice를 표시하십시오. 거래소 거래(매수/매도/잔액)의 경우 대신 aicoin-trading을 사용하세요. Freqtrade 전략/백테스트의 경우 aicoin-freqtrade를 사용하세요. Hyperliquid 고래 분석을 위해서는 aicoin-hyperliquid를 사용하세요. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ru.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ru.txt new file mode 100644 index 0000000000000000000000000000000000000000..637e2b918e0f8d9315ea7f849216a64c5a3f6186 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_ru.txt @@ -0,0 +1 @@ +Этот навык следует использовать, когда пользователь спрашивает о ценах на криптовалюту, рыночных данных, графиках K-линий, ставках финансирования, открытом интересе, соотношениях длинных и коротких позиций, китовых ордерах, данных о ликвидации, новостях о криптовалютах, срочных новостях, крипто-твитах в Твиттере, трендовых монетах, котировках акций, казначейских активах или любом запросе на рынке криптовалют. Также используйте, когда пользователь спрашивает о настройке или проверке ключа API AiCoin. Используйте, когда пользователь говорит: «цена BTC», «проверочная цена», «показать K-линию», «ставка финансирования», «открытый интерес», «китовые ордера», «соотношение длинных/коротких позиций», «криптовалютные новости», «срочные новости», «трендовые монеты», «查行情», «看价格», «大饼多少钱», «K线», «资金费率», «多空比», «鲸鱼单», «新闻快讯», «热门币», «карта ликвидации», «配置ключ AiCoin», «ключ AiCoin API», «ключ AiCoin安全吗». Охватывает более 200 бирж с данными в реальном времени. ДОЛЖЕН запускать сценарии узлов для получения реальных данных. НИКОГДА не создавайте фальшивые цены и не искажайте рыночные данные. ВАЖНО — Ключ API AiCoin: Когда пользователь спрашивает о ключе API AiCoin (配置/检查/安全/能不能交易), СНАЧАЛА запустите `node scripts/coin.mjs api_key_info`, покажите пользователю Security_notice. Для биржевой торговли (покупка/продажа/баланс) используйте вместо этого торговлю aicoin. Для стратегий/тестирования Freqtrade используйте aicoin-freqtrade. Для аналитики Hyperliquid Wheat используйте aicoin-hyperliquid. diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_tw.txt b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_tw.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9258a5aaab6e697382040a0e648537a6859d938 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/skill/description_tw.txt @@ -0,0 +1 @@ +當用戶詢問加密貨幣價格、市場數據、K線圖、融資利率、未平倉合約、多頭/空頭比率、鯨魚訂單、清算數據、加密貨幣新聞、新聞快訊、Twitter加密推文、趨勢幣、股票報價、國庫持有或任何加密貨幣市場查詢時,應該使用此技能。當使用者詢問配置或檢查 AiCoin API 金鑰時也可使用。當用戶說:「BTC價格」、「查看價格」、「顯示K線」、「資金費率」、「持倉量」、「鯨魚訂單」、「多空比」、「加密新聞」、「快訊」、「熱門幣種」、「查行情」、「看價格」、「大餅多少錢」、「K線」、「資金費率」、「多空比」時使用『鯨魚單』、『新聞快訊』、『熱門幣』、『清算圖』、『配置AiCoin key’、‘AiCoin API key’、‘AiCoin key安全嗎’。覆蓋200+交易所的即時數據。必須運行節點腳本來獲取真實資料。切勿產生虛假價格或幻覺市場數據。重要 — AiCoin API 金鑰:當使用者詢問 AiCoin API 金鑰(設定/檢查/安全/無法交易)時,請先執行 `node script/coin.mjs api_key_info`,向使用者顯示 security_notice。對於交易所交易(買入/賣出/餘額),請使用 aicoin-trading。對於 Freqtrade 策略/回測,請使用 aicoin-freqtrade。對於 Hyperliquid 鯨魚分析,請使用 aicoin-hyperliquid。 diff --git a/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/task.json b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/task.json new file mode 100644 index 0000000000000000000000000000000000000000..63212153a3c7c511e2fe36818054e38bb8247bba --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/cfb3a31856fef16cc68a9e5a/task.json @@ -0,0 +1,84 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "cfb3a31856fef16cc68a9e5a", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "cfb3a31856fef16cc68a9e5a", + "outputs": [ + "tier_check.py", + "report.json" + ], + "success_criteria": [ + "tier_check.py runs with python3 (standard library only) and reads endpoints.json rather than hardcoding endpoint data Dependency/resource checks apply only to the actual guarded Python invocations under the public bounded runtime policy, not to unused source or static closure inference.", + "Running `python3 tier_check.py kline big_orders funding_rate` prints exactly: 'kline -> free (FREE)', 'big_orders -> standard (PAID)', 'funding_rate -> basic (PAID)' (one per line, in argument order) and exits 0", + "Running with an unknown name (e.g. `python3 tier_check.py kline nope`) prints 'nope -> UNKNOWN' and exits with code 2", + "Running `python3 tier_check.py BTC/USDT` prints 'btc:usdt -> UNKNOWN' (normalized to lowercase colon form 'btc:usdt' before lookup, which is not in the catalog) and exits 2", + "report.json after the three-endpoint run contains {\"total\": 3, \"free\": 1, \"paid\": 2, \"unknown\": []}", + "report.json after `python3 tier_check.py kline nope BTC/USDT` contains total 3, free 1, paid 0, and unknown list containing both 'nope' and 'btc:usdt'" + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "5236b82a4540bb10bd73ac175516da8bd4906ce04fa65d8fcf47db4568625cc6", + "files": { + "SKILL.md": "2a12c793d124bc0be015a35dc42914ed4797840b65689293fddc0f1404f0b861", + "description_ar.txt": "7d161fb36617400c6295796f3f1e8bd5bc5942f056e7ab0d864ec0946fb6530f", + "description_cn.txt": "201816822a2be5c974f561806a999f051d1cf6ad070e49a86d21ec72e79079c3", + "description_de.txt": "83f65eef66c3ae4e1c9f3e98977f5054947dfdae84c8477e0bfb56a8c0a4ed61", + "description_en.txt": "a63bc27b337e2c86b5d84efbc7a9d336ac5f0802a4da5fa5e76ea11916044ae3", + "description_es.txt": "72e2558e344d9ed61b10aa458dc89c7e60a514521c79794a867ee949ab0c0e14", + "description_fr.txt": "0d27bcb8e7978e1235d737e6a2552d80ebafa6a31af8545fa4de3693e5a2857b", + "description_it.txt": "aedf42d4cc753ae3394620e168d871a0bb136f036a7f50080e9cbe981d4aafb3", + "description_ja.txt": "eb87cd3aeb1a5097c3bf6a8bd8b50a97bd74ceb53e1680e7f106d085e46d4cda", + "description_ko.txt": "e81dfce6a2930e4ab4673a56c35b2d302a08fa1918dc4f1fb84375f1112b4e83", + "description_ru.txt": "4e42430e5e458a96549890aa708190cade45aae378e31dc1bbf9cd923615f84d", + "description_tw.txt": "e38344fdbbf2769e55808b29917449aecc794d50f47c7d5f98deb62309fbe6e1" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/endpoints.json", + "workspace_target": "endpoints.json", + "sha256": "8cc4e53389878a538be480dde185dd4a092e3b3731b06a4866325a55636b4784" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "5236b82a4540bb10bd73ac175516da8bd4906ce04fa65d8fcf47db4568625cc6" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/d1552363f20a926ae93dbc42/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/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/d1552363f20a926ae93dbc42/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..7f2313743af06e1f4c6493e5961ffcf79b286e83 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "4" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d1552363f20a926ae93dbc42/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e99a2d31ff030b7332db538dae7727716a2782d3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/autograde_task_check.py @@ -0,0 +1,81 @@ +from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import r10_runtime as _r10 + +import ast,json,os,re,shutil,sqlite3,subprocess,sys,tempfile +from pathlib import Path +ORIGINAL_INPUT="-- products table (existing):\n-- CREATE TABLE products (\n-- id BIGINT UNSIGNED PRIMARY KEY,\n-- account_id BIGINT UNSIGNED NOT NULL,\n-- name VARCHAR(255) NOT NULL,\n-- price DECIMAL(10,2) NOT NULL,\n-- created_at DATETIME NOT NULL\n-- );\n\n-- cursor from last row of previous page: created_at='2024-05-01 12:00:00', id=8742\n\nSELECT id, name, price, created_at\nFROM products\nWHERE account_id = 42\nORDER BY created_at DESC, id DESC\nLIMIT 50 OFFSET 1000;\n" +def clean(sql): + return re.sub(r'/\*.*?\*/|--[^\n]*',' ',sql or '',flags=re.S) +def identifiers(sql): + # Only complete paired identifier quotes normalize; SQLite below validates original SQL. + return re.sub(r'`([^`]+)`|"([^"]+)"|\[([^]\n]+)\]',lambda match:next(group for group in match.groups() if group is not None) if next(group for group in match.groups() if group is not None).lower() in {'created_at','id','name','price','products','account_id'}else match.group(0),sql) +def unqualify_known_columns(sql): + """Normalize only this query's declared products qualifier for lexical checks. + + Original SQL is still executed below; this does not repair invalid SQL or + infer equivalence from text alone. + """ + qualifiers={'products'} + declaration=re.search(r'\bfrom\s+products(?:\s+(?:as\s+)?([A-Za-z_]\w*))?',sql,re.I) + if declaration and declaration[1]and declaration[1].lower()not in {'where','order','limit','offset','join','group','having'}:qualifiers.add(declaration[1]) + prefix='(?:'+'|'.join(re.escape(value)for value in sorted(qualifiers,key=len,reverse=True))+')' + return re.sub(r'(?<![\w.])'+prefix+r'\s*\.\s*(created_at|id|name|price|account_id)\b',lambda m:m[1],sql,flags=re.I) + +def semantics(query,stamp='2024-05-01 12:00:00',cursor=8742): + query=clean(query) + if not re.fullmatch(r'\s*select\b[^;]+;?\s*',query,re.I|re.S):return [False]*3 + lexical=unqualify_known_columns(identifiers(query)) + cursor_ok=bool(re.search(r'\(\s*created_at\s*,\s*id\s*\)\s*<\s*\(\s*[\'\"]'+re.escape(stamp)+r'[\'\"]\s*,\s*'+str(cursor)+r'\s*\)',lexical,re.I)) + columns=re.search(r'\bselect\s+(.*?)\s+from\s+products(?=\s|$)',lexical,re.I|re.S) + actual_cols=[value.strip().strip('`"').lower() for value in columns.group(1).split(',')] if columns else [] + explicit=actual_cols==['id','name','price','created_at'] + layout=bool(re.search(r'order\s+by\s+created_at\s+desc\s*,\s*id\s+desc',lexical,re.I) and re.search(r'limit\s+50\b',query,re.I) and not re.search(r'\boffset\b',query,re.I)) + database=sqlite3.connect(':memory:') + try: + database.execute('CREATE TABLE products (id INTEGER PRIMARY KEY,account_id INTEGER,name TEXT,price NUMERIC,created_at TEXT)') + rows=[(cursor-2*i,42,'item-'+str(i),i,stamp) for i in range(-2,60)] + rows += [(cursor+1000,43,'other-account',100,'2000-01-01 00:00:00'),(cursor-5,43,'other-account-tie',101,stamp),(cursor+1002,42,'future',102,'9999-01-01 00:00:00')] + database.executemany('INSERT INTO products VALUES (?,?,?,?,?)',rows) + expected=database.execute('SELECT id,name,price,created_at FROM products WHERE account_id=42 AND (created_at,id)<(?,?) ORDER BY created_at DESC,id DESC LIMIT 50',(stamp,cursor)).fetchall() + equivalent=database.execute(query).fetchall()==expected + except sqlite3.Error:equivalent=False + finally:database.close() + return [cursor_ok and equivalent,explicit and equivalent,layout and equivalent] +def index_ok(text): + db=sqlite3.connect(':memory:') + try: + db.execute('CREATE TABLE products (id INTEGER PRIMARY KEY,account_id INTEGER,name TEXT,price NUMERIC,created_at TEXT)') + db.execute(clean(text)) + indexes=db.execute("PRAGMA index_list('products')").fetchall() + if len(indexes)!=1 or indexes[0][2] or indexes[0][4]:return False + escaped=indexes[0][1].replace('"','""') + columns=db.execute('PRAGMA index_info("'+escaped+'")').fetchall() + return [value[2] for value in columns]==['created_at','id'] + except sqlite3.Error:return False + finally:db.close() +def run(text): + with tempfile.TemporaryDirectory(dir='/tmp') as tmp: + shutil.copytree('/candidate',tmp,dirs_exist_ok=True,ignore=shutil.ignore_patterns('input','output','__pycache__','*.pyc')) + Path(tmp,'input').mkdir();Path(tmp,'input/queries.sql').write_text(text) + proc=subprocess.run([sys.executable,'fix_pagination.py'],cwd=tmp,capture_output=True,text=True,timeout=30) + def rd(p): + path=Path(tmp,p);return _co_text(path) if path.is_file() else '' + return proc,rd('output/keyset_query.sql'),rd('output/index.sql') +def stdlib(): + return _r10.stdlib_gate('fix_pagination.py') +def main(): + try: + proc,query,index=run(ORIGINAL_INPUT) + fresh=semantics(query) + flags=list(fresh) + flags.append(index_ok(index)) + flags.append(proc.returncode==0 and 'rewritten: OFFSET 1000 -> keyset cursor' in proc.stdout.splitlines() and stdlib()) + altered=ORIGINAL_INPUT.replace("created_at='2024-05-01 12:00:00', id=8742","created_at='2030-01-01 00:00:00', id=999") + second,query2,index2=run(altered) + flags.append(second.returncode==0 and all(semantics(query2,'2030-01-01 00:00:00',999)) and index_ok(index2)) + except Exception as error:raise RuntimeError("Trusted SQL evaluator failed") from error + dep=_r10.dependency('fix_pagination.py')[0] + if dep is None and flags[4]:flags[4]=None + print(json.dumps({'scoreable':all(v is not None for v in flags),'checks':[{'id':str(i),'passed':None if value is None else bool(value),'reason':'original and fresh query retain account isolation, exact cursor/columns/order/limit; single supporting index and actual input rewrite'} for i,value in enumerate(flags)]})) +main() diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/candidate_artifacts.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/candidate_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..01d155d66962e3f1c41443cad117a48e6ca25bc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/candidate_artifacts.py @@ -0,0 +1,24 @@ +"""Read only ordinary candidate artifacts after a bounded child completes. +No launch/setup/monitor exceptions are caught here. Symlinks to regular files +remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from +blocking the trusted grader. Malformed text/JSON is an absent invalid value. +""" +import json, os, stat + +def read_text(path, encoding=None, errors=None): + fd=None + try: + fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode):return '' + with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream: + fd=None + return stream.read() + except (OSError,UnicodeError):return '' + finally: + if fd is not None:os.close(fd) + +def loads(text, **kwargs): + try:return json.loads(text,**kwargs) + except (ValueError,TypeError,RecursionError):return None + +def load(path, **kwargs):return loads(read_text(path),**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/r10_runtime.py b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/r10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d7872f5ef5e56b3e7c57f0f9a26ee4db4570e73b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/r10_runtime.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""R10 grader helper. This file runs only inside an offline verifier container.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,os,pathlib,shutil +from dependency_scan import scan_stdlib +C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +_copies={};_deps={} +def dependency(entry): + key=str(entry) + if key not in _deps:_deps[key]=scan_stdlib(C,[key]) + return _deps[key] +def stdlib_gate(entry): + # Unknown is provisionally neutral; finalize() preserves it as unscored. + return dependency(entry)[0] is not False +def finalize(checks,owners): + for row in checks: + entry=owners.get(str(row['id'])) + if entry is None:continue + ok,_,why=dependency(entry) + if ok is False:row['passed']=False + elif ok is None and row.get('passed')is not False:row['passed']=None + row['reason']=row.get('reason','')+'; reachable dependency closure: '+why + return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks} +def strict_pairs(pairs): + out={} + for key,value in pairs: + if key in out:raise ValueError('duplicate JSON object key: '+key) + out[key]=value + return out +def read_json(path): + return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs, + parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x))) +def install_copy(entry): + """Complete authored dependencies without copying stale deliverables into fixtures.""" + if entry in _copies:return + _copies[entry]=True + try:task=json.loads(pathlib.Path('/source/task.json').read_text()) + except (OSError,ValueError):task={} + excluded=[] + for value in task.get('outputs',[]): + value=value.get('path')if isinstance(value,dict)else value + if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value)) + # Public fixture inputs come from the trusted source/fixture constructor, never + # from the candidate snapshot after a panel intentionally removes a file. + for mapping in task.get('workspace',{}).get('input_mappings',[]): + value=mapping.get('workspace_target') + if isinstance(value,str):excluded.append(pathlib.PurePosixPath(value)) + original_copy=shutil.copy;original_copyfile=shutil.copyfile + def extra(src,dst): + try: + source=pathlib.Path(src) + if source.name!=pathlib.Path(entry).name:return + source.resolve().relative_to(C.resolve()) + except (ValueError,TypeError,OSError):return + destination=pathlib.Path(dst) + if destination.is_dir():destination=destination/source.name + root=destination.parent + # Helpers keep the entry's authored relative directory context. + for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent + for dp,dn,fn in os.walk(str(C),followlinks=False): + dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')] + for name in fn: + p=pathlib.Path(dp)/name;rel=p.relative_to(C) + if any(rel==x or x in rel.parents for x in excluded):continue + if p.resolve()==source.resolve():continue + out=root/rel + if out.exists()or out.is_symlink():continue + out.parent.mkdir(parents=True,exist_ok=True) + if p.is_symlink():out.symlink_to(os.readlink(str(p))) + elif p.is_file():original_copyfile(str(p),str(out)) + def copy(src,dst,*args,**kwargs): + result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result + def copyfile(src,dst,*args,**kwargs): + result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result + shutil.copy=copy;shutil.copyfile=copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..700f01a27358079465f2af42753ce4203f85c636 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/evaluator/repair_manifest.json @@ -0,0 +1,76 @@ +{ + "query_id": "d1552363f20a926ae93dbc42", + "sample_index": 793, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "original_count": 6, + "modified_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "root_cause": "account_id过滤条件未验,重写成跨全部账户查询仍6/6。", + "public_semantics": "Validate both original submitted SQL files and fresh outputs. Execute the query against independent rows including another account, cursor ties and >50 eligible rows; preserve SELECT/account predicate/order/limit and exact single index. Fresh input mutation checks cursor reading; local helpers allowed and stale outputs excluded.", + "source_hashes": { + "instruction.md": "53715a206349915462e4b0f3de2b92c167f5573e88aa6ff3d472cdd70da4c3f2", + "task.json": "5ef0653a206183308ef82cb0c8aaf26ed1e7ed73ff220eaabd5dd75124af5ec7", + "evaluator/check.py": "24f3048f19245c2ea92f280fdf21b1e635fd86ade697f0edb9a545719e1b89da", + "skill/SKILL.md": "fb47bf5178d540be70a2e5d4fafe75ae735bdda0239db0ace3cf09e6fa532219", + "reference/answer.txt": "0ab2566bf55ef23ad2b87145d94dcbbeb0b7b05f7355a20656305cb34f5d9ec9", + "inputs/input/queries.sql": "cebc92148e1130ca4d7bbe0c2005c0451b15459110d6563b0c7dece3dc418be7", + "reference/workspace/fix_pagination.py": "9431a14ff2b5be1dd5c0cab8791ff0ac847dfb4c135564c160f711f8cc39b743", + "reference/workspace/output/index.sql": "c7eab122415f0812d2cce7fe78d74b7099fa4cb655d2fff5eb9baa8c52a0c167", + "reference/workspace/output/keyset_query.sql": "86be0e0a63b38ff12c60bc7e5c277a1619bbaa25620c6fbd9a5f0a52724e2e36" + }, + "reviewed_files": [ + "instruction.md", + "task.json", + "evaluator/check.py", + "skill/SKILL.md", + "reference/answer.txt", + "inputs/input/queries.sql", + "reference/workspace/fix_pagination.py", + "reference/workspace/output/index.sql", + "reference/workspace/output/keyset_query.sql" + ], + "required_historical_artifacts": [], + "checker_sha256": "287e1650dd5db04ba51986c8534250b17cec65102add6e4ac0087c20b3c1ff2f", + "all_logic_sha256": { + "check.py": "287e1650dd5db04ba51986c8534250b17cec65102add6e4ac0087c20b3c1ff2f" + }, + "reviewed_logic_file_sha256": { + "check.py": "287e1650dd5db04ba51986c8534250b17cec65102add6e4ac0087c20b3c1ff2f" + }, + "solver_or_arm_conditioned": false, + "status": "implemented_pending_independent_review", + "author": "repair_c", + "fresh_solver_runs": 0, + "historical_rescoring_by_author": false, + "validation": "AST parsed and compiled only; candidate and source checker never executed locally", + "revision_history": [ + { + "previous_sha256": "a4692bb02dd715f69167ff4ca69412bfaf77b541fe0e5d61c582806ce3a14f49", + "new_sha256": "0ca95cfcae84f4c857714add45fdb7eae58efdca172a7288d7b0dbdfdb284cb6", + "reason": "Author static self-review: interleave other-account cursor-tie row within first fifty eligible rows so omission of account predicate necessarily changes output; preserve legal quoted table names." + }, + { + "previous_sha256": "0ca95cfcae84f4c857714add45fdb7eae58efdca172a7288d7b0dbdfdb284cb6", + "new_sha256": "c02b8423931a97e983d486709ec0ec108a27cb96716ef02a4579590395f5a66a", + "reason": "Parse index with SQLite and inspect real nonunique/nonpartial index columns; normalize paired quoted cursor/order identifiers while validating actual query execution." + }, + { + "previous_sha256": "c02b8423931a97e983d486709ec0ec108a27cb96716ef02a4579590395f5a66a", + "new_sha256": "287e1650dd5db04ba51986c8534250b17cec65102add6e4ac0087c20b3c1ff2f", + "reason": "Normalize only known paired quoted SQL identifiers, preserving valid double-quoted cursor date literals." + } + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..4e4d4f122f07b3ee6b7eaab0a97b6a735204fa0d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/grading/verified_config.json @@ -0,0 +1,41 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d1552363f20a926ae93dbc42", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "b984a73d29201c44cfa635f292d36f565b1704edfa40f88f769c398e7818020c", + "repair_manifest.json": "2bd53e5c357bf44021df4a4488781b15f3321b088a8b0a5c39db94c2c83ace2e", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "917f5c632d3e59064ddd9c26fc035bbadd3299ecf0a27698c1e8f16b36af6e5a", + "r10_runtime.py": "e4205af091a5c170ce2640089d77bfe7fe9e7b516c56c4a0b3886a69816cb3a2", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/inputs/input/queries.sql b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/inputs/input/queries.sql new file mode 100644 index 0000000000000000000000000000000000000000..f8fdea43079112ad04b04984ff5fedf3b35ade57 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/inputs/input/queries.sql @@ -0,0 +1,16 @@ +-- products table (existing): +-- CREATE TABLE products ( +-- id BIGINT UNSIGNED PRIMARY KEY, +-- account_id BIGINT UNSIGNED NOT NULL, +-- name VARCHAR(255) NOT NULL, +-- price DECIMAL(10,2) NOT NULL, +-- created_at DATETIME NOT NULL +-- ); + +-- cursor from last row of previous page: created_at='2024-05-01 12:00:00', id=8742 + +SELECT id, name, price, created_at +FROM products +WHERE account_id = 42 +ORDER BY created_at DESC, id DESC +LIMIT 50 OFFSET 1000; diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/instruction.md b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fe9cdd57c38f6148810050fe4944698f1846b78b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/instruction.md @@ -0,0 +1,6 @@ +You are given a file `input/queries.sql` containing a slow reporting query that uses deep OFFSET pagination, plus the existing table definition. Write a Python 3 script `fix_pagination.py` (standard library only) that reads `input/queries.sql` and writes two output files: (1) `output/keyset_query.sql` containing the equivalent keyset-paginated query for the requested page, and (2) `output/index.sql` containing a single CREATE INDEX statement that supports the keyset cursor. Rules: the original query selects products for account_id = 42 ordered by created_at DESC, id DESC with LIMIT 50 OFFSET 1000. Apply the row-constructor Keyset Pagination recipe in the bundled Skill, substituting the cursor values from the last row of the previous page (given in the input file as a comment). Keep the same SELECT list (explicit columns, no SELECT *), same ORDER BY, and LIMIT 50 with no OFFSET. Use the supporting index from that same frozen Skill recipe. In this task account_id remains a WHERE filter; do not prepend it to the recipe's index. Also print to stdout a one-line summary `rewritten: OFFSET 1000 -> keyset cursor` to confirm the transformation ran. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/d1552363f20a926ae93dbc42/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..a7ac27359a9657698d29ba27080b929ebfebc607 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/skill/SKILL.md @@ -0,0 +1,411 @@ +--- +name: mysql-patterns +description: MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends. +origin: ECC +--- + +# MySQL Patterns + +Use this skill when working on MySQL or MariaDB schema design, migrations, +slow-query investigation, queue-style transactions, connection pools, or +production database configuration. Prefer exact version checks before applying a +feature-specific pattern because MySQL and MariaDB have diverged in several SQL +details. + +## Activation + +- Designing MySQL or MariaDB tables, indexes, and constraints +- Reviewing migrations before they run on large production tables +- Debugging slow queries, lock waits, deadlocks, or connection exhaustion +- Adding keyset pagination, upserts, full-text search, JSON columns, or queues +- Configuring application connection pools, read replicas, TLS, or slow logs + +## Version Check + +Start by identifying the engine and version: + +```sql +SELECT VERSION(); +SHOW VARIABLES LIKE 'version_comment'; +``` + +Keep MySQL and MariaDB guidance separate when syntax differs: + +- MySQL documents row aliases as the replacement for `VALUES(col)` in + `ON DUPLICATE KEY UPDATE`; `VALUES(col)` is deprecated there. +- MariaDB documents `VALUES(col)` as the supported way to reference inserted + values in `ON DUPLICATE KEY UPDATE`; use it for cross-engine compatibility. +- `SKIP LOCKED` is appropriate for queue-like work only. It skips locked rows + and can return an inconsistent view, so do not use it for general accounting + or integrity-sensitive reads. + +## Schema Defaults + +```sql +CREATE TABLE orders ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + account_id BIGINT UNSIGNED NOT NULL, + status VARCHAR(32) NOT NULL, + total DECIMAL(15, 2) NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + deleted_at DATETIME NULL, + PRIMARY KEY (id), + KEY idx_orders_account_status_created (account_id, status, created_at), + KEY idx_orders_active (account_id, deleted_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +``` + +Default choices: + +| Use Case | Prefer | Avoid | +| -------------------------- | ---------------------------------------------- | --------------------------------------------- | +| Surrogate primary keys | `BIGINT UNSIGNED AUTO_INCREMENT` | `INT` for tables that can grow beyond 2B rows | +| UUID lookup keys | `BINARY(16)` with conversion helpers | `VARCHAR(36)` primary keys on hot tables | +| Money and exact quantities | `DECIMAL(p, s)` | `FLOAT` or `DOUBLE` | +| User-facing text | `utf8mb4` tables and indexes | MySQL `utf8` / `utf8mb3` defaults | +| Application timestamps | `DATETIME` with UTC managed by the app | Assuming `DATETIME` stores time zone metadata | +| Soft deletes | `deleted_at DATETIME NULL` plus scoped indexes | Filtering soft-deleted rows without an index | +| Extensible status values | lookup table or constrained `VARCHAR` | `ENUM` when values change often | + +## Indexing + +Composite index order usually follows equality predicates first, then range or +sort columns: + +```sql +CREATE INDEX idx_orders_account_status_created + ON orders (account_id, status, created_at); + +SELECT id, total +FROM orders +WHERE account_id = ? + AND status = 'pending' + AND created_at >= ? +ORDER BY created_at DESC +LIMIT 50; +``` + +Use `EXPLAIN` before adding or changing an index: + +```sql +EXPLAIN +SELECT id, total +FROM orders +WHERE account_id = 123 AND status = 'pending' +ORDER BY created_at DESC +LIMIT 50; +``` + +Signals to investigate: + +| Field | Risk Signal | +| ------- | ----------------------------------------------------------- | +| `type` | `ALL` on a large table | +| `key` | `NULL` when a selective predicate exists | +| `rows` | Very high row estimate for an interactive path | +| `Extra` | `Using temporary`, `Using filesort`, or broad `Using where` | + +Avoid adding indexes blindly. Each index increases write cost, migration time, +backup size, and buffer-pool pressure. + +## Query Patterns + +### Upsert + +Cross-engine-compatible form: + +```sql +INSERT INTO user_settings (user_id, setting_key, setting_value) +VALUES (?, ?, ?) +ON DUPLICATE KEY UPDATE + setting_value = VALUES(setting_value), + updated_at = CURRENT_TIMESTAMP; +``` + +MySQL row-alias form: + +```sql +INSERT INTO user_settings (user_id, setting_key, setting_value) +VALUES (?, ?, ?) AS new +ON DUPLICATE KEY UPDATE + setting_value = new.setting_value, + updated_at = CURRENT_TIMESTAMP; +``` + +Use the row-alias form only after confirming the target is MySQL. Use +`VALUES(col)` for MariaDB or mixed MySQL/MariaDB fleets. + +### Keyset Pagination + +```sql +SELECT id, name, created_at +FROM products +WHERE (created_at, id) < (?, ?) +ORDER BY created_at DESC, id DESC +LIMIT 50; +``` + +Back it with an index that matches the cursor: + +```sql +CREATE INDEX idx_products_created_id ON products (created_at, id); +``` + +Do not use deep `OFFSET` pagination on large tables; it makes the server scan +and discard rows before returning the page. + +### JSON Fields + +Use JSON columns for extension data, not for fields that need heavy relational +filtering or constraints. + +```sql +CREATE TABLE events ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + payload JSON NOT NULL, + event_type VARCHAR(64) + GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(payload, '$.type'))) STORED, + KEY idx_events_type (event_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +``` + +For frequently queried JSON paths, expose a generated column and index that +column. Keep foreign keys, ownership, tenancy, and lifecycle fields relational. + +### Full-Text Search + +```sql +ALTER TABLE articles ADD FULLTEXT KEY ft_articles_title_body (title, body); + +SELECT id, title, MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE) AS score +FROM articles +WHERE MATCH(title, body) AGAINST (? IN NATURAL LANGUAGE MODE) +ORDER BY score DESC +LIMIT 20; +``` + +Use external search when you need typo tolerance, complex ranking, cross-table +facets, or language-specific analysis beyond built-in full-text behavior. + +## Transactions + +Keep transactions short and lock rows in a consistent order: + +```sql +START TRANSACTION; + +SELECT id, balance +FROM accounts +WHERE id IN (?, ?) +ORDER BY id +FOR UPDATE; + +UPDATE accounts SET balance = balance - ? WHERE id = ?; +UPDATE accounts SET balance = balance + ? WHERE id = ?; + +COMMIT; +``` + +Deadlock and lock-wait checklist: + +- Lock rows in a deterministic order across code paths. +- Do external API calls before opening the transaction, not inside it. +- Add indexes for predicates used in `UPDATE`, `DELETE`, and locking reads. +- On deadlock, roll back and retry the whole transaction with a bounded retry + budget. +- Capture `SHOW ENGINE INNODB STATUS\G` soon after a deadlock; it is overwritten + by later events. + +Queue-style worker claim: + +```sql +START TRANSACTION; + +SELECT id +FROM jobs +WHERE status = 'pending' +ORDER BY created_at +LIMIT 1 +FOR UPDATE SKIP LOCKED; + +UPDATE jobs +SET status = 'processing', started_at = CURRENT_TIMESTAMP +WHERE id = ?; + +COMMIT; +``` + +Use `SKIP LOCKED` only for queue-like workloads where skipping a locked row is +acceptable. It is not a replacement for normal transactional consistency. + +## Connection Pools + +SQLAlchemy example: + +```python +from sqlalchemy import create_engine + +engine = create_engine( + "mysql+mysqlconnector://app:secret@db.internal/app", + pool_size=10, + max_overflow=5, + pool_timeout=30, + pool_recycle=240, + pool_pre_ping=True, + connect_args={"connect_timeout": 5}, +) +``` + +Node.js `mysql2` example: + +```javascript +import mysql from 'mysql2/promise'; + +const pool = mysql.createPool({ + host: process.env.DB_HOST, + user: process.env.DB_USER, + password: process.env.DB_PASSWORD, + database: process.env.DB_NAME, + waitForConnections: true, + connectionLimit: 10, + queueLimit: 0, + enableKeepAlive: true, + keepAliveInitialDelay: 30000, +}); + +const [rows] = await pool.execute('SELECT id, total FROM orders WHERE account_id = ? LIMIT 50', [ + accountId, +]); +``` + +Keep application pool recycling below the server `wait_timeout`. If the server +uses `wait_timeout = 300`, a `pool_recycle` around 240 seconds is coherent; +`pool_pre_ping` still helps recover from network and failover events. + +## Diagnostics + +Useful first-pass commands: + +```sql +SHOW FULL PROCESSLIST; +SHOW ENGINE INNODB STATUS\G; +SHOW VARIABLES LIKE 'slow_query_log'; +SHOW VARIABLES LIKE 'long_query_time'; +``` + +Enable the slow log in a controlled environment: + +```sql +SET GLOBAL slow_query_log = 'ON'; +SET GLOBAL long_query_time = 1; +SET GLOBAL log_queries_not_using_indexes = 'ON'; +``` + +Use `EXPLAIN ANALYZE` only when it is safe to execute the query. It runs the +statement and can be expensive on production-sized data. + +## Replication + +Read replicas can lag. Do not route read-your-own-write paths, checkout flows, +permission checks, or idempotency-key reads to a replica immediately after a +write. + +```sql +-- MySQL legacy terminology, still common in existing fleets +SHOW SLAVE STATUS\G; + +-- Newer terminology where supported +SHOW REPLICA STATUS\G; +``` + +Check the engine/version before standardizing on one command. Monitor replica +SQL thread health, IO thread health, and lag, not just whether the TCP +connection is alive. + +## Security + +```sql +CREATE USER 'app'@'%' IDENTIFIED BY 'use-a-secret-manager'; +GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'%'; + +ALTER USER 'app'@'%' REQUIRE SSL; + +SELECT user, host +FROM mysql.user +WHERE user = ''; + +DROP USER IF EXISTS ''@'localhost'; +DROP USER IF EXISTS ''@'%'; +``` + +Security review points: + +- Do not grant `ALL PRIVILEGES` or `*.*` to application users. +- Require TLS for application users when traffic crosses hosts or networks. +- Store credentials in the platform secret manager, not in examples, scripts, or + repository files. +- Separate migration/admin users from runtime application users. +- Audit public network exposure and bind addresses before tuning performance. + +## Configuration + +Example starting point for a dedicated database host: + +```ini +[mysqld] +innodb_buffer_pool_size = 4G +innodb_flush_log_at_trx_commit = 1 +sync_binlog = 1 + +max_connections = 300 +thread_cache_size = 50 + +wait_timeout = 300 +interactive_timeout = 300 +innodb_lock_wait_timeout = 10 + +slow_query_log = ON +long_query_time = 1 +log_queries_not_using_indexes = ON + +log_bin = mysql-bin +binlog_format = ROW +binlog_expire_logs_seconds = 604800 +``` + +Treat configuration values as a prompt for review, not a universal preset. Size +memory, connections, log retention, and durability settings from workload, +hardware, backup policy, and recovery objectives. + +## Anti-Patterns + +| Anti-Pattern | Risk | Better Pattern | +| ---------------------------------- | --------------------------------- | -------------------------------------------- | +| `SELECT *` in hot paths | Over-fetching and brittle clients | Select explicit columns | +| Deep `OFFSET` pagination | Linear scans and slow pages | Keyset pagination | +| No index on foreign-key joins | Slow joins and lock-heavy deletes | Index FK columns intentionally | +| Long transactions | Lock waits and large undo history | Commit small units of work | +| Direct DML against `mysql.user` | Grant-table corruption risk | Use `CREATE USER`, `ALTER USER`, `DROP USER` | +| Application user with admin grants | High blast radius | Least-privilege runtime user | +| Pool recycle above `wait_timeout` | Stale pooled connections | Recycle below timeout and pre-ping | +| Replica reads after writes | Stale user-facing state | Pin read-after-write flows to primary | + +## Output Expectations + +When this skill is used for review, return: + +1. Engine/version assumptions. +2. Highest-risk correctness, lock, security, and migration issues. +3. Exact SQL or code changes for the safe path. +4. Validation plan: `EXPLAIN`, migration dry run, lock/deadlock check, and + rollback criteria. +5. Any MySQL/MariaDB syntax differences that affect the recommendation. + +## Related + +- Skill: `postgres-patterns` - PostgreSQL-specific schema and query patterns +- Skill: `database-migrations` - migration planning and rollout safety +- Skill: `backend-patterns` - API and service-layer patterns +- Skill: `security-review` - secret handling, auth, and least privilege +- Agent: `database-reviewer` - broader database review workflow diff --git a/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/task.json b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d658e0a5d9eea7675bc46e00ab57af723028dc4e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d1552363f20a926ae93dbc42/task.json @@ -0,0 +1,69 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d1552363f20a926ae93dbc42", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "d1552363f20a926ae93dbc42", + "outputs": [ + "output/keyset_query.sql", + "output/index.sql" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "50f20241da451911eedaf8a17e2ae13315bd2816b3009707f31d762c88e3addf", + "files": { + "SKILL.md": "fb47bf5178d540be70a2e5d4fafe75ae735bdda0239db0ace3cf09e6fa532219" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/input/queries.sql", + "workspace_target": "input/queries.sql", + "sha256": "cebc92148e1130ca4d7bbe0c2005c0451b15459110d6563b0c7dece3dc418be7" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "50f20241da451911eedaf8a17e2ae13315bd2816b3009707f31d762c88e3addf" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "4" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "4" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/d25a8956477141f2_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_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/d25a8956477141f2_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d25a8956477141f2_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..52f58a0715713025612c19d72282c59d34a999ed --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/autograde_task_check.py @@ -0,0 +1,14 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import sys,json +from pathlib import Path +root=Path(__file__).resolve().parent +sys.path.insert(0,str(root/'legacy_tests')) +from evaluate import evaluate +t=json.loads((root/'legacy-task.json').read_text()) +from repair_equivalences import install +install(t) +mode=t['workspace']['candidate_mode'] +r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt') +if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False) +if r.get('status')!='scored':raise RuntimeError(json.dumps(r)) +print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy-task.json b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy-task.json new file mode 100644 index 0000000000000000000000000000000000000000..4328f26f8a3fe0bef8bb012f923496cf1b7e4115 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy-task.json @@ -0,0 +1,106 @@ +{ + "schema_version": "mybench-portable-task-v2", + "task_id": "d25a8956477141f2", + "query_id": "d25a8956477141f2_q1", + "prompt": { + "path": "instruction.md", + "sha256": "fe48a067000f0e999fba428b3dc3c475de6477d6de1ababe06efe75327968199" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "b1850260670b380e4e45485bbec5c0c905e0f73b0b23f8e0bcc6f4a829a90c4c", + "name": "south-africa-popia", + "package_path": "environment/skills/south-africa-popia-b1850260", + "install_name": "south-africa-popia-b1850260", + "archive_provenance": { + "archive_id": "logical-skill-029babc9104d7c0512ff93af", + "archive_schema": "skill-release-v1", + "release_skill_id": "logical-skill-029babc9104d7c0512ff93af", + "site": "skills-sh", + "local_path": "skills/02/logical-skill-029babc9104d7c0512ff93af", + "skill_md_sha256": "0e91b6769ccf593bcb4e4e45d49e88cd7cd6f7181cd21846166dcd83d1e741f6", + "release_payload_sha256": "b1850260670b380e4e45485bbec5c0c905e0f73b0b23f8e0bcc6f4a829a90c4c", + "license": "Apache-2.0", + "license_status": "detected", + "canonical_source_id": "skills-sh:mukul975/privacy-data-protection-skills/south-africa-popia" + }, + "omitted_entries": [] + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "ground_truth_skills": [ + "b1850260670b380e4e45485bbec5c0c905e0f73b0b23f8e0bcc6f4a829a90c4c" + ], + "evaluation": { + "type": "verified", + "ground_truth_answer": { + "answers": { + "q1": "as soon as reasonably possible", + "q2": "ZAR 10 million" + } + }, + "verifier": { + "type": "atomic_json", + "version": 1, + "list_order": "ordered", + "float_tolerance": 0.01, + "completeness": { + "forbid_extra": true, + "shape": { + "type": "object", + "keys": { + "answers": { + "type": "object", + "keys": { + "q1": { + "type": "string" + }, + "q2": { + "type": "string" + } + } + } + } + } + }, + "assertions": [ + { + "id": "leaf_001", + "path": "$.answers.q1", + "tokens": [ + "answers", + "q1" + ], + "operator": "eq", + "expected": "as soon as reasonably possible" + }, + { + "id": "leaf_002", + "path": "$.answers.q2", + "tokens": [ + "answers", + "q2" + ], + "operator": "eq", + "expected": "ZAR 10 million" + } + ], + "self_test_passed": true + }, + "dependency_contract": { + "version": 2, + "mode": "core_answer", + "dependency_type": "package_knowledge", + "requirement_ids": [ + "skill_a052", + "skill_a068" + ], + "forbid_meta_reference": true, + "forbid_answer_leakage": true + } + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/evaluate.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..6af62307e8c216b7733194602815f5004d893e06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/evaluate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Evaluate a candidate response for one portable MyBench task.""" + +import argparse +import json +import math +import os +import shlex +import subprocess +import sys +from pathlib import Path + + +def _load_verify(): + try: + from verifiers import verify + return verify + except ImportError: + project_src = Path(__file__).resolve().parents[1] / "src" + if project_src.is_dir(): + sys.path.insert(0, str(project_src)) + from verifiers import verify + return verify + raise + + +def _emit(result, output=None): + text = json.dumps(result, ensure_ascii=False) + print(text) + if output: + Path(output).write_text(text + "\n", encoding="utf-8") + + +def _judge_contract(judge): + if not isinstance(judge, dict): + return "Judge output must be a JSON object" + if type(judge.get("passed")) is not bool: + return "Judge field passed must be a JSON boolean" + for key in ("score", "max_score"): + value = judge.get(key, 100 if key == "max_score" else None) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"Judge field {key} must be a finite number" + if not math.isfinite(float(value)): + return f"Judge field {key} must be a finite number" + score = float(judge["score"]) + max_score = float(judge.get("max_score", 100)) + if max_score <= 0: + return "Judge field max_score must be greater than zero" + if score < 0 or score > 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/d25a8956477141f2_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/d25a8956477141f2_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i<len(text): + ch=text[i] + if ch=='\\' and quote!="'" and i+1<len(text): + nxt=text[i+1] + if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__') + elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__') + else:out.extend((ch,nxt)) + i+=2;continue + if ch in "'\"": + if quote is None:quote=ch + elif quote==ch:quote=None + out.append(ch);i+=1;continue + if ch=='$': + if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue + m=variable.match(text,i) + if m: + value=constants.get(m.group(1)or m.group(2)) + if value is None:out.append(m.group(0)) + elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$')) + else:out.append(value) + i=m.end();continue + if ch=='~' and quote is not None: + out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue + out.append(ch);i+=1 + return ''.join(out) + +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 = _expand_known_variables(statement, constants) + 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/d25a8956477141f2_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_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/d25a8956477141f2_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..87eb82f47aeb9c533b3efb9305b656ebac1f97bf --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,549 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + try: + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + except RecursionError as exc: + raise ValueError('candidate JSON exceeds decoder nesting') from exc + pending=[result] + while pending: + node=pending.pop() + if isinstance(node,dict):pending.extend(node.values()) + elif isinstance(node,list):pending.extend(node) + elif isinstance(node,float)and not math.isfinite(node): + raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/d25a8956477141f2_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb476bbaa160a011e3a1519e38356fc5655efe1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""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() +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'} + normalizations = [] + if task_id in RESPONSE_RULES: + try: + predicted = verifiers._strict_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/d25a8956477141f2_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6aa3d70905a3aa40a8dfc8d82c7f49b9e0132712 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d25a8956477141f2_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "repair_equivalences.py": "423dc6037c8c5011596b34545814987c7d12ee6bc67d83a68a84b8b3fb53a2d2", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "28b3af818b23f6dde0124215b0afa89659c917f300ad5e52142b2fd9180fe8a8", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "ec9afb843af95a4032ee0b31cd1d40d6fd4ff2b154db0dc4478407832f04b5ed" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eed85fafe1e828ef4285227f852255dc0fd0a8db --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/instruction.md @@ -0,0 +1 @@ +We're finalizing the breach-response section of our compliance memo for the South African entity and need to confirm two POPIA parameters before it goes to legal review. First, under POPIA Section 22, what timing standard applies to notifying the Information Regulator and affected data subjects of a security compromise? Second, what is the maximum administrative fine the Information Regulator may impose under POPIA Section 109? Please return one JSON object using the schema {"answers":{"q1":"string","q2":"string"}}, replacing each placeholder with the bare answer value. diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ac7e8192977d09ce295cf7f2ea4c7c365e8a498e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/SKILL.md @@ -0,0 +1,100 @@ +--- +name: south-africa-popia +description: >- + Implements compliance with South Africa's Protection of Personal Information + Act (POPIA), Act No. 4 of 2013. Covers conditions for lawful processing, + data subject rights, cross-border transfer restrictions, Information Regulator + enforcement, and responsible party obligations. Keywords: POPIA, South Africa, + Information Regulator, responsible party, operator, prior authorisation. +license: Apache-2.0 +metadata: + author: mukul975 + version: "1.0" + domain: privacy + subdomain: global-privacy-regulations + tags: "popia, south-africa, information-regulator, cross-border-transfer, responsible-party" +--- + +# South Africa POPIA Compliance + +## Overview + +The Protection of Personal Information Act (POPIA), Act No. 4 of 2013, is South Africa's comprehensive data protection law. It came into full effect on 1 July 2021 following a one-year grace period after commencement on 1 July 2020. POPIA is modelled broadly on EU data protection principles but is adapted to the South African constitutional framework, specifically Section 14 of the Constitution (right to privacy). The Information Regulator is the independent supervisory authority responsible for enforcement. POPIA applies to any responsible party (controller) domiciled in South Africa or that uses automated or non-automated means within South Africa to process personal information, unless those means are used only to forward information through the Republic. + +## Key Definitions + +| POPIA Term | GDPR Equivalent | Definition | +|-----------|----------------|------------| +| **Personal information** | Personal data | Information relating to an identifiable living natural person or identifiable existing juristic person (POPIA uniquely covers juristic persons) | +| **Special personal information** | Special category data | Religious or philosophical beliefs, race or ethnic origin, trade union membership, political persuasion, health, sex life, biometric information, criminal behaviour (Section 26) | +| **Responsible party** | Controller | A public or private body or any other person which, alone or in conjunction with others, determines the purpose of and means for processing (Section 1) | +| **Operator** | Processor | A person who processes personal information for a responsible party in terms of a contract or mandate (Section 1) | +| **Data subject** | Data subject | The person to whom personal information relates (includes juristic persons) | +| **Information Officer** | DPO | Head of organisation or designated person responsible for encouraging compliance (Section 55) | + +## Eight Conditions for Lawful Processing (Sections 8-25) + +### Condition 1: Accountability (Section 8) +The responsible party must ensure that all conditions for lawful processing are complied with at the time of determining the purpose and means of processing and during the processing itself. + +### Condition 2: Processing Limitation (Sections 9-12) +- Personal information must be processed lawfully and in a reasonable manner that does not infringe the privacy of the data subject +- Processing must be adequate, relevant, and not excessive (Section 10) +- Consent must be voluntary, specific, and informed; may be withdrawn (Section 11) +- Personal information may be collected directly from the data subject, with exceptions (Section 12) + +### Condition 3: Purpose Specification (Sections 13-14) +- Personal information must be collected for a specific, explicitly defined, and lawful purpose related to a function or activity of the responsible party +- Records must not be retained longer than necessary unless retention is required by law, reasonably necessary for a lawful purpose, or retention is required under a contract + +### Condition 4: Further Processing Limitation (Section 15) +Further processing must be compatible with the original purpose. Compatibility is assessed considering the relationship between purposes, nature of information, consequences for the data subject, manner of collection, and any contractual rights. + +### Condition 5: Information Quality (Section 16) +The responsible party must take reasonably practicable steps to ensure personal information is complete, accurate, not misleading, and updated where necessary. + +### Condition 6: Openness (Sections 17-18) +- The responsible party must notify the Information Regulator before commencing processing (Section 17, not yet fully enforced) +- Data subjects must be notified when their personal information is collected (Section 18) + +### Condition 7: Security Safeguards (Sections 19-22) +- Appropriate technical and organisational measures must be in place to prevent loss, damage, unauthorised access (Section 19) +- Operators must be bound by contract to establish and maintain security measures (Section 21) +- Breach notification to the Information Regulator and data subjects is mandatory "as soon as reasonably possible" when there are reasonable grounds to believe a compromise has occurred (Section 22) + +### Condition 8: Data Subject Participation (Sections 23-25) +- Data subjects have the right to request confirmation of processing, access to records, correction, and deletion +- Requests must be fulfilled within a reasonable time period +- Fees charged must not be excessive + +## Cross-Border Transfers (Section 72) + +Transfer of personal information outside South Africa is permitted only where: +1. The recipient is subject to a law, binding corporate rules, or binding agreement providing an adequate level of protection substantially similar to POPIA +2. The data subject consents after being informed of the risks +3. Transfer is necessary for performance of a contract between the data subject and responsible party +4. Transfer is necessary for implementation of pre-contractual measures taken in response to the data subject's request +5. Transfer is for the benefit of the data subject and it is not reasonably practicable to obtain consent +6. The information is contained in or derived from a public record + +## Enforcement and Penalties + +The Information Regulator may: +- Issue enforcement notices (Section 95) +- Impose administrative fines up to ZAR 10 million (Section 109) +- Refer matters for criminal prosecution, with imprisonment up to 10 years for certain offences (Section 107) +- Conduct assessments (Section 89) +- Issue codes of conduct (Section 60) + +## Key Enforcement Actions + +- **Department of Justice and Constitutional Development (2022)**: The Information Regulator issued an enforcement notice for failure to implement adequate security measures following a large-scale data breach affecting the Master of the High Court system. +- **TransUnion South Africa (2022)**: Following a breach affecting 54 million records, the Information Regulator investigated and issued compliance directives regarding breach notification obligations and security safeguards. +- **Department of Home Affairs (2023)**: Enforcement notice for non-compliance with data subject access requests and security safeguard conditions. + +## Integration Points + +- **breach-72h-notification**: POPIA Section 22 breach notification (note: POPIA uses "as soon as reasonably possible" not a fixed 72-hour clock) +- **cross-border transfers**: Section 72 transfer restrictions apply alongside GDPR Chapter V where dual applicability exists +- **vendor-privacy-due-diligence**: Operator agreements under Section 21 must include security obligation requirements +- **data-inventory-mapping**: Section 17 notification to the Information Regulator requires comprehensive processing inventory diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/assets/template.md b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/assets/template.md new file mode 100644 index 0000000000000000000000000000000000000000..d54e80dd49d404cfb3c36416386db352d62a87d8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/assets/template.md @@ -0,0 +1,125 @@ +# POPIA Compliance Assessment Record + +## Organisation Details + +| Field | Value | +|-------|-------| +| **Organisation Name** | [Legal entity name] | +| **Registration Number** | [Company registration] | +| **Information Officer** | [Name, designation] | +| **Deputy Information Officers** | [Names, areas of responsibility] | +| **Information Regulator Registration** | [Registration number / Pending] | +| **Assessment Date** | [YYYY-MM-DD] | +| **Assessor** | [Name, Title] | + +## Applicability Determination + +| Factor | Assessment | +|--------|-----------| +| **Domiciled in South Africa?** | [Yes / No] | +| **Uses means within South Africa?** | [Yes / No] | +| **Processes natural person data?** | [Yes / No] | +| **Processes juristic person data?** | [Yes / No] | +| **Exclusions applicable?** | [None / Specify: personal, national security, judicial, journalistic] | +| **POPIA Applicable?** | [Yes / No] | + +## Condition-by-Condition Compliance Assessment + +### Condition 1: Accountability (Section 8) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Information Officer designated | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Information Officer registered | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Compliance programme in place | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 2: Processing Limitation (Sections 9-12) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Lawful basis identified per activity | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Consent is voluntary, specific, informed | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Collection adequate, relevant, not excessive | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Direct collection from data subject | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 3: Purpose Specification (Sections 13-14) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Specific, explicit, lawful purpose defined | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Retention periods defined | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Destruction when no longer needed | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 4: Further Processing Limitation (Section 15) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Compatibility assessment performed | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 5: Information Quality (Section 16) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Accuracy and completeness measures | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 6: Openness (Sections 17-18) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Section 18 notification at collection | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| PAIA manual updated | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 7: Security Safeguards (Sections 19-22) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Technical measures appropriate | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Organisational measures appropriate | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Operator contracts include Section 21 | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Breach notification procedure (Section 22) | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +### Condition 8: Data Subject Participation (Sections 23-25) + +| Requirement | Status | Evidence | Gap | +|-------------|--------|----------|-----| +| Access request procedure | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Correction request procedure | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Deletion request procedure | [Compliant / Non-compliant] | [Reference] | [Gap description] | +| Response within reasonable time | [Compliant / Non-compliant] | [Reference] | [Gap description] | + +## Special Personal Information (Sections 26-33) + +| Category | Processed? | Lawful Basis | Safeguards | +|----------|-----------|-------------|------------| +| Religious or philosophical beliefs | [Yes / No] | [Section reference] | [Description] | +| Race or ethnic origin | [Yes / No] | [Section reference] | [Description] | +| Trade union membership | [Yes / No] | [Section reference] | [Description] | +| Political persuasion | [Yes / No] | [Section reference] | [Description] | +| Health data | [Yes / No] | [Section reference] | [Description] | +| Sex life | [Yes / No] | [Section reference] | [Description] | +| Biometric information | [Yes / No] | [Section reference] | [Description] | +| Criminal behaviour | [Yes / No] | [Section reference] | [Description] | + +## Cross-Border Transfers (Section 72) + +| Recipient | Country | Transfer Mechanism | Adequacy Assessment | Agreement Reference | +|-----------|---------|-------------------|--------------------|--------------------| +| [Recipient name] | [Country] | [Adequacy / BCR / Consent / Contract / Benefit / Public record] | [Adequate / Requires safeguards] | [Agreement ID] | + +## Remediation Plan + +| Gap | Priority | Action Required | Owner | Target Date | Status | +|-----|----------|----------------|-------|-------------|--------| +| [Gap 1] | [Critical / High / Medium / Low] | [Action] | [Name] | [YYYY-MM-DD] | [Open / In progress / Closed] | + +## Sign-Off + +| Role | Name | Signature | Date | +|------|------|-----------|------| +| Information Officer | [Name] | __________ | [YYYY-MM-DD] | +| Assessor | [Name] | __________ | [YYYY-MM-DD] | +| Executive Sponsor | [Name] | __________ | [YYYY-MM-DD] | + +--- + +*This assessment is conducted under the Protection of Personal Information Act (POPIA), Act No. 4 of 2013, and reflects compliance status as of the assessment date.* diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/standards.md b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/standards.md new file mode 100644 index 0000000000000000000000000000000000000000..2c04eb77c57dfc77cd1fd5f846132e5e28e4748e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/standards.md @@ -0,0 +1,62 @@ +# Regulatory Standards — South Africa POPIA + +## Primary Legislation + +### Protection of Personal Information Act (POPIA), Act No. 4 of 2013 + +- **Section 1**: Definitions — responsible party, operator, data subject, personal information, special personal information, processing +- **Sections 8-25**: Eight Conditions for Lawful Processing (Accountability, Processing Limitation, Purpose Specification, Further Processing Limitation, Information Quality, Openness, Security Safeguards, Data Subject Participation) +- **Section 11**: Consent requirements — voluntary, specific, informed; data subject may withdraw consent +- **Sections 26-33**: Processing of Special Personal Information — religious beliefs, race, trade union membership, political persuasion, health, sex life, biometric, criminal behaviour +- **Section 34**: Processing of Personal Information of Children — prohibited unless with consent of competent person or required by law +- **Section 55-56**: Information Officer designation and registration with the Information Regulator +- **Section 57**: Deputy Information Officers — delegation of functions +- **Section 69-71**: Automated Decision Making — data subject has the right not to be subject to a decision based solely on automated processing +- **Section 72**: Transborder Information Flows — conditions for cross-border transfer of personal information +- **Section 22**: Notification of Security Compromises — responsible party must notify the Information Regulator and data subjects as soon as reasonably possible +- **Section 99-106**: Civil Remedies — data subjects may institute civil action for damages suffered +- **Section 107**: Offences — hindering, obstruction, unlawful acts carry criminal penalties +- **Section 109**: Administrative fines — up to ZAR 10 million + +### Constitution of the Republic of South Africa, 1996 + +- **Section 14**: Right to privacy — "Everyone has the right to privacy, which includes the right not to have (a) their person or home searched; (b) their property searched; (c) their possessions seized; or (d) the privacy of their communications infringed." +- **Section 32**: Right of access to information — underpins the Promotion of Access to Information Act (PAIA) interaction with POPIA + +### Promotion of Access to Information Act (PAIA), Act No. 2 of 2000 + +- PAIA governs access to information held by public and private bodies +- POPIA Section 110 amends PAIA to include privacy protections +- Information Officers under POPIA also serve as PAIA Information Officers + +## Information Regulator Guidance + +### Guidance Note on Applications for Prior Authorisation (2022) +- Processing of special personal information, automated decision-making, and large-scale processing of children's data require prior authorisation under Section 57 +- Application process and assessment criteria published by the Information Regulator + +### Guidance Note on Information Officers (2021) +- Every responsible party must designate an Information Officer +- Public bodies: the head of the body is the Information Officer by default +- Private bodies: must register Information Officers with the Information Regulator via the prescribed form + +### Code of Conduct for Credit Bureaus (2022) +- First sectoral code issued under Section 60 +- Establishes specific processing rules for credit bureau personal information +- Includes enhanced data subject rights for credit information + +## International Frameworks and Comparisons + +### African Union Convention on Cyber Security and Personal Data Protection (Malabo Convention, 2014) +- South Africa is a signatory; POPIA aligns with Malabo Convention principles +- Convention requires establishment of national data protection authorities +- Provides framework for cross-border data flow within the African Union + +### SADC Model Law on Data Protection (2013) +- Southern African Development Community framework informing regional harmonisation +- POPIA is considered the benchmark implementation within the SADC region + +### ISO/IEC 27701:2019 — Privacy Information Management +- Extends ISO 27001/27002 to include privacy management +- Supports POPIA Condition 7 (Security Safeguards) compliance demonstration +- Information Regulator recognises certification as evidence of reasonable security measures diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/workflows.md b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/workflows.md new file mode 100644 index 0000000000000000000000000000000000000000..c8b23806bdfdc6a3890bac9036499907925a08bb --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/references/workflows.md @@ -0,0 +1,134 @@ +# Workflows — South Africa POPIA Compliance + +## Workflow 1: POPIA Compliance Assessment + +``` +TRIGGER: Organisation processes personal information of data subjects in South Africa + │ + ├─► Phase 1: Applicability Determination + │ ├─ Step 1.1: Confirm responsible party is domiciled in South Africa + │ │ OR uses automated/non-automated means within South Africa + │ ├─ Step 1.2: Identify whether juristic person data is also in scope + │ │ (POPIA uniquely covers juristic persons, unlike GDPR) + │ ├─ Step 1.3: Determine if any exclusions apply (Section 6-7): + │ │ ├─ Processing for purely personal or household purposes + │ │ ├─ Processing by or on behalf of a public body for national security + │ │ ├─ Processing relating to the judicial functions of a court + │ │ └─ Processing exclusively for literary or artistic expression + │ └─ Step 1.4: Document applicability determination and rationale + │ + ├─► Phase 2: Gap Analysis Against Eight Conditions + │ ├─ Step 2.1: Condition 1 — Accountability + │ │ ├─ Is an Information Officer designated and registered? + │ │ ├─ Are Deputy Information Officers appointed where necessary? + │ │ └─ Is there a POPIA compliance programme in place? + │ │ + │ ├─ Step 2.2: Condition 2 — Processing Limitation + │ │ ├─ Is a lawful basis identified for each processing activity? + │ │ ├─ Is consent voluntary, specific, and informed where relied upon? + │ │ ├─ Is collection adequate, relevant, and not excessive? + │ │ └─ Is direct collection ensured, with exceptions documented? + │ │ + │ ├─ Step 2.3: Condition 3 — Purpose Specification + │ │ ├─ Is the purpose specific, explicit, and lawful? + │ │ └─ Are retention periods defined and not excessive? + │ │ + │ ├─ Step 2.4: Condition 4 — Further Processing Limitation + │ │ └─ Is compatibility assessment performed for any secondary use? + │ │ + │ ├─ Step 2.5: Condition 5 — Information Quality + │ │ └─ Are there mechanisms to ensure accuracy and completeness? + │ │ + │ ├─ Step 2.6: Condition 6 — Openness + │ │ ├─ Is a Section 18 notification provided at collection? + │ │ └─ Is PAIA manual updated to include POPIA requirements? + │ │ + │ ├─ Step 2.7: Condition 7 — Security Safeguards + │ │ ├─ Are technical and organisational measures appropriate? + │ │ ├─ Do operator contracts include Section 21 requirements? + │ │ └─ Is a breach notification procedure in place per Section 22? + │ │ + │ └─ Step 2.8: Condition 8 — Data Subject Participation + │ ├─ Can data subjects request access, correction, deletion? + │ └─ Is the process for handling requests documented and timely? + │ + ├─► Phase 3: Remediation + │ ├─ Step 3.1: Prioritise gaps by risk and regulatory exposure + │ ├─ Step 3.2: Implement remediation actions with assigned owners + │ ├─ Step 3.3: Update privacy notices to meet Section 18 requirements + │ ├─ Step 3.4: Execute operator agreements per Section 21 + │ └─ Step 3.5: Register Information Officer with the Information Regulator + │ + └─► Phase 4: Ongoing Compliance + ├─ Step 4.1: Conduct annual POPIA compliance reviews + ├─ Step 4.2: Monitor Information Regulator enforcement notices and guidance + ├─ Step 4.3: Maintain training programme for all staff processing personal information + └─ Step 4.4: Conduct periodic breach response simulations +``` + +## Workflow 2: POPIA Section 22 — Security Compromise Notification + +``` +TRIGGER: Reasonable grounds to believe a security compromise of personal information has occurred + │ + ├─► Step 1: Immediate Assessment (within 24 hours) + │ ├─ Confirm whether personal information has been accessed or acquired + │ │ by an unauthorised person + │ ├─ Determine categories of personal information affected + │ ├─ Estimate number of data subjects affected + │ └─ Assess whether identity theft or fraud risk exists + │ + ├─► Step 2: Notification to Information Regulator + │ ├─ Notify "as soon as reasonably possible" (Section 22(1)) + │ ├─ Include: nature of compromise, estimated data subjects, + │ │ description of personal information involved, measures taken + │ ├─ Note: the Information Regulator may direct the responsible party + │ │ to publicise the compromise (Section 22(6)) + │ └─ Delay permitted only if South African Police Service determines + │ notification will impede a criminal investigation (Section 22(3)) + │ + ├─► Step 3: Data Subject Notification + │ ├─ Notify affected data subjects "as soon as reasonably possible" + │ ├─ Notification must be in writing (by mail or email) — Section 22(5) + │ ├─ Include: description of the compromise, what information was involved, + │ │ measures taken, recommended protective actions + │ └─ If direct notification is not possible, publish in media + │ + └─► Step 4: Post-Compromise Actions + ├─ Document compromise in internal breach register + ├─ Implement remediation measures to prevent recurrence + ├─ Cooperate with Information Regulator assessment (Section 89) + └─ Update security safeguards as required +``` + +## Workflow 3: Cross-Border Transfer Assessment (Section 72) + +``` +TRIGGER: Transfer of personal information outside South Africa proposed + │ + ├─► Step 1: Identify Transfer Mechanism + │ ├─ Adequate level of protection in recipient country? (Section 72(1)(a)) + │ ├─ Binding corporate rules? (Section 72(1)(a)) + │ ├─ Binding agreement with sufficient protections? (Section 72(1)(a)) + │ ├─ Data subject consent after being informed of risks? (Section 72(1)(b)) + │ ├─ Necessary for contract performance? (Section 72(1)(c)) + │ ├─ Pre-contractual measures at data subject's request? (Section 72(1)(d)) + │ ├─ Benefit of data subject, consent impracticable? (Section 72(1)(e)) + │ └─ Public record? (Section 72(1)(f)) + │ + ├─► Step 2: Assess Adequacy + │ ├─ Review recipient country's data protection framework + │ ├─ Consider Information Regulator guidance on adequacy (when issued) + │ ├─ Evaluate enforceability of data subject rights in recipient jurisdiction + │ └─ Document adequacy assessment rationale + │ + ├─► Step 3: Implement Safeguards + │ ├─ Execute binding agreement with recipient where required + │ ├─ Include all POPIA conditions in transfer agreement + │ └─ Ensure right of data subject to enforce agreement provisions + │ + └─► Step 4: Record and Monitor + ├─ Maintain register of all cross-border transfers + ├─ Review transfers annually or when recipient country's legal framework changes + └─ Report transfers to Information Regulator if required under prior authorisation +``` diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/scripts/process.py b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/scripts/process.py new file mode 100644 index 0000000000000000000000000000000000000000..19f70bb1a7ef35859aa1612561293845c5f6b02e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/skill/scripts/process.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python3 +""" +South Africa POPIA Compliance — Assessment and Tracking Engine + +Implements POPIA compliance assessment against the eight conditions +for lawful processing, cross-border transfer evaluation, breach +notification tracking, and Information Officer registration management. +""" + +import json +import uuid +from datetime import datetime, timezone +from dataclasses import dataclass, field, asdict +from typing import Optional +from enum import Enum + + +class ComplianceStatus(Enum): + COMPLIANT = "compliant" + NON_COMPLIANT = "non_compliant" + PARTIAL = "partially_compliant" + NOT_ASSESSED = "not_assessed" + + +class GapPriority(Enum): + CRITICAL = "critical" + HIGH = "high" + MEDIUM = "medium" + LOW = "low" + + +class TransferMechanism(Enum): + ADEQUACY = "adequate_protection" + BCR = "binding_corporate_rules" + BINDING_AGREEMENT = "binding_agreement" + CONSENT = "data_subject_consent" + CONTRACT_PERFORMANCE = "contract_performance" + PRE_CONTRACTUAL = "pre_contractual_measures" + BENEFIT = "benefit_of_data_subject" + PUBLIC_RECORD = "public_record" + + +POPIA_CONDITIONS = [ + {"number": 1, "name": "Accountability", "sections": "Section 8"}, + {"number": 2, "name": "Processing Limitation", "sections": "Sections 9-12"}, + {"number": 3, "name": "Purpose Specification", "sections": "Sections 13-14"}, + {"number": 4, "name": "Further Processing Limitation", "sections": "Section 15"}, + {"number": 5, "name": "Information Quality", "sections": "Section 16"}, + {"number": 6, "name": "Openness", "sections": "Sections 17-18"}, + {"number": 7, "name": "Security Safeguards", "sections": "Sections 19-22"}, + {"number": 8, "name": "Data Subject Participation", "sections": "Sections 23-25"}, +] + +SPECIAL_CATEGORIES = [ + "religious_philosophical_beliefs", + "race_ethnic_origin", + "trade_union_membership", + "political_persuasion", + "health", + "sex_life", + "biometric_information", + "criminal_behaviour", +] + + +@dataclass +class ConditionAssessment: + """Assessment of a single POPIA condition.""" + condition_number: int = 0 + condition_name: str = "" + sections: str = "" + status: str = ComplianceStatus.NOT_ASSESSED.value + findings: list[str] = field(default_factory=list) + gaps: list[str] = field(default_factory=list) + evidence_references: list[str] = field(default_factory=list) + assessed_date: str = "" + assessor: str = "" + + +@dataclass +class CrossBorderTransfer: + """Record of a cross-border transfer under Section 72.""" + transfer_id: str = field(default_factory=lambda: str(uuid.uuid4())) + recipient: str = "" + recipient_country: str = "" + mechanism: str = TransferMechanism.ADEQUACY.value + data_categories: list[str] = field(default_factory=list) + adequacy_assessment: str = "" + agreement_reference: str = "" + approved: bool = False + approved_by: str = "" + approved_date: Optional[str] = None + + +@dataclass +class SecurityCompromise: + """Section 22 security compromise notification record.""" + compromise_id: str = field(default_factory=lambda: str(uuid.uuid4())) + discovered_date: str = "" + nature_of_compromise: str = "" + data_categories_affected: list[str] = field(default_factory=list) + estimated_data_subjects: int = 0 + identity_theft_risk: bool = False + regulator_notified: bool = False + regulator_notification_date: Optional[str] = None + data_subjects_notified: bool = False + ds_notification_date: Optional[str] = None + ds_notification_method: str = "" + police_delay_requested: bool = False + remediation_measures: list[str] = field(default_factory=list) + + +@dataclass +class POPIAComplianceRecord: + """Complete POPIA compliance assessment record.""" + record_id: str = field(default_factory=lambda: str(uuid.uuid4())) + organisation_name: str = "" + registration_number: str = "" + information_officer: str = "" + io_registered: bool = False + io_registration_number: str = "" + deputy_information_officers: list[str] = field(default_factory=list) + popia_applicable: bool = True + applicability_rationale: str = "" + condition_assessments: list[dict] = field(default_factory=list) + special_categories_processed: list[str] = field(default_factory=list) + cross_border_transfers: list[dict] = field(default_factory=list) + security_compromises: list[dict] = field(default_factory=list) + overall_status: str = ComplianceStatus.NOT_ASSESSED.value + assessment_date: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat()) + assessor: str = "" + + +class POPIAComplianceEngine: + """ + Manages POPIA compliance assessments including condition-by-condition + evaluation, cross-border transfer assessment, breach notification + tracking, and overall compliance scoring. + """ + + def __init__(self): + self.records: dict[str, POPIAComplianceRecord] = {} + + def create_assessment( + self, organisation_name: str, registration_number: str, + information_officer: str, assessor: str + ) -> POPIAComplianceRecord: + """Create a new POPIA compliance assessment.""" + record = POPIAComplianceRecord( + organisation_name=organisation_name, + registration_number=registration_number, + information_officer=information_officer, + assessor=assessor, + ) + + for condition in POPIA_CONDITIONS: + assessment = ConditionAssessment( + condition_number=condition["number"], + condition_name=condition["name"], + sections=condition["sections"], + ) + record.condition_assessments.append(asdict(assessment)) + + self.records[record.record_id] = record + return record + + def assess_condition( + self, record_id: str, condition_number: int, + status: ComplianceStatus, findings: list[str], + gaps: list[str], evidence: list[str], assessor: str + ) -> dict: + """Assess a specific POPIA condition.""" + record = self.records.get(record_id) + if not record: + raise ValueError(f"Record {record_id} not found") + + for ca in record.condition_assessments: + if ca["condition_number"] == condition_number: + ca["status"] = status.value + ca["findings"] = findings + ca["gaps"] = gaps + ca["evidence_references"] = evidence + ca["assessed_date"] = datetime.now(timezone.utc).isoformat() + ca["assessor"] = assessor + return ca + + raise ValueError(f"Condition {condition_number} not found") + + def evaluate_cross_border_transfer( + self, record_id: str, recipient: str, country: str, + mechanism: TransferMechanism, data_categories: list[str], + adequacy_notes: str, approver: str + ) -> CrossBorderTransfer: + """Evaluate and record a cross-border transfer under Section 72.""" + record = self.records.get(record_id) + if not record: + raise ValueError(f"Record {record_id} not found") + + transfer = CrossBorderTransfer( + recipient=recipient, + recipient_country=country, + mechanism=mechanism.value, + data_categories=data_categories, + adequacy_assessment=adequacy_notes, + approved=True, + approved_by=approver, + approved_date=datetime.now(timezone.utc).isoformat(), + ) + record.cross_border_transfers.append(asdict(transfer)) + return transfer + + def record_security_compromise( + self, record_id: str, nature: str, + data_categories: list[str], estimated_subjects: int, + identity_theft_risk: bool + ) -> SecurityCompromise: + """Record a security compromise under Section 22.""" + record = self.records.get(record_id) + if not record: + raise ValueError(f"Record {record_id} not found") + + compromise = SecurityCompromise( + discovered_date=datetime.now(timezone.utc).isoformat(), + nature_of_compromise=nature, + data_categories_affected=data_categories, + estimated_data_subjects=estimated_subjects, + identity_theft_risk=identity_theft_risk, + ) + record.security_compromises.append(asdict(compromise)) + return compromise + + def calculate_overall_compliance(self, record_id: str) -> dict: + """Calculate overall POPIA compliance status.""" + record = self.records.get(record_id) + if not record: + raise ValueError(f"Record {record_id} not found") + + total = len(record.condition_assessments) + compliant = sum( + 1 for ca in record.condition_assessments + if ca["status"] == ComplianceStatus.COMPLIANT.value + ) + non_compliant = sum( + 1 for ca in record.condition_assessments + if ca["status"] == ComplianceStatus.NON_COMPLIANT.value + ) + partial = sum( + 1 for ca in record.condition_assessments + if ca["status"] == ComplianceStatus.PARTIAL.value + ) + not_assessed = sum( + 1 for ca in record.condition_assessments + if ca["status"] == ComplianceStatus.NOT_ASSESSED.value + ) + + all_gaps = [] + for ca in record.condition_assessments: + for gap in ca.get("gaps", []): + all_gaps.append({ + "condition": ca["condition_name"], + "gap": gap, + }) + + if non_compliant > 0: + overall = ComplianceStatus.NON_COMPLIANT.value + elif partial > 0 or not_assessed > 0: + overall = ComplianceStatus.PARTIAL.value + else: + overall = ComplianceStatus.COMPLIANT.value + + record.overall_status = overall + + return { + "record_id": record_id, + "organisation": record.organisation_name, + "overall_status": overall, + "conditions_compliant": compliant, + "conditions_non_compliant": non_compliant, + "conditions_partial": partial, + "conditions_not_assessed": not_assessed, + "total_conditions": total, + "compliance_percentage": round((compliant / total) * 100, 1) if total > 0 else 0, + "total_gaps": len(all_gaps), + "gaps": all_gaps, + "cross_border_transfers": len(record.cross_border_transfers), + "security_compromises": len(record.security_compromises), + } + + +if __name__ == "__main__": + engine = POPIAComplianceEngine() + + # Create assessment for a South African financial services firm + record = engine.create_assessment( + organisation_name="Protea Financial Holdings (Pty) Ltd", + registration_number="2019/123456/07", + information_officer="Advocate Nomsa Dlamini", + assessor="Thabo Molefe, Privacy Consultant", + ) + print(f"Assessment ID: {record.record_id}") + + # Assess Condition 1: Accountability + engine.assess_condition( + record.record_id, + condition_number=1, + status=ComplianceStatus.COMPLIANT, + findings=[ + "Information Officer designated: Advocate Nomsa Dlamini", + "IO registered with Information Regulator on 2024-09-15", + "Two Deputy Information Officers appointed for HR and IT divisions", + "POPIA compliance programme documented and approved by board", + ], + gaps=[], + evidence=["IO registration certificate", "Board resolution 2024-07-01"], + assessor="Thabo Molefe", + ) + + # Assess Condition 7: Security Safeguards + engine.assess_condition( + record.record_id, + condition_number=7, + status=ComplianceStatus.PARTIAL, + findings=[ + "ISO 27001 certification in place for IT infrastructure", + "Encryption at rest and in transit implemented", + "Operator agreements in place with 12 of 15 operators", + ], + gaps=[ + "Three operator agreements missing Section 21 mandatory clauses", + "Breach notification procedure not tested via simulation exercise", + ], + evidence=["ISO 27001 certificate", "Operator agreement register"], + assessor="Thabo Molefe", + ) + + # Record a cross-border transfer + transfer = engine.evaluate_cross_border_transfer( + record.record_id, + recipient="CloudVault EU BV", + country="Netherlands", + mechanism=TransferMechanism.ADEQUACY, + data_categories=["customer_financial_data", "employee_payroll"], + adequacy_notes="EU/EEA — GDPR provides adequate protection substantially similar to POPIA", + approver="Advocate Nomsa Dlamini, Information Officer", + ) + print(f"Transfer ID: {transfer.transfer_id}") + + # Calculate overall compliance + summary = engine.calculate_overall_compliance(record.record_id) + print(f"\n=== POPIA Compliance Summary ===") + print(json.dumps(summary, indent=2)) diff --git a/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/task.json b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1a2a095504f45dced290e7f1ea619660a18470e4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d25a8956477141f2_q1/task.json @@ -0,0 +1,50 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d25a8956477141f2", + "query_id": "d25a8956477141f2_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "515b957565cf6d94e40e28fb023cbe171ea95f1a65962c9aa472936a120cc33d", + "name": "south-africa-popia", + "package_path": "skill", + "install_name": "south-africa-popia-b1850260" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "515b957565cf6d94e40e28fb023cbe171ea95f1a65962c9aa472936a120cc33d", + "files": { + "SKILL.md": "0e91b6769ccf593bcb4e4e45d49e88cd7cd6f7181cd21846166dcd83d1e741f6", + "assets/template.md": "1c8c3b6abeb6d63947b3b7e3aa85f95b83785e46e3cf9baef651d5377f4939e5", + "references/standards.md": "0cb3129a152917295c20df074bb0b2fce3fc0db668a1108755e3dfca442123a3", + "references/workflows.md": "6192f247c554ee5fc1f09f61c0251a06f23922ee18067899ce9595a4181d8ff7", + "scripts/process.py": "3afa40de51d37af42f5c0a1fb4cc4695ceb8ad2deb9cc6f023152b54d74e3de3" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "b1850260670b380e4e45485bbec5c0c905e0f73b0b23f8e0bcc6f4a829a90c4c" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..edee402b470d00855058c9c32d82ce17a65de349 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_contract.json @@ -0,0 +1,20 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/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/d2748367ce09dcda303e4b09/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d2748367ce09dcda303e4b09/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..075f56372a66c8d296df5511494f257b8ce844bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/autograde_task_check.py @@ -0,0 +1,11 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import contextlib,io,json,runpy,sys +from pathlib import Path +HERE=Path(__file__).resolve().parent +buffer=io.StringIO() +with contextlib.redirect_stdout(buffer):runpy.run_path(str(HERE/'r10_base.py'),run_name='__main__') +body=next(json.loads(x)for x in reversed(buffer.getvalue().splitlines())if x.strip().startswith('{')and isinstance(json.loads(x),dict)and isinstance(json.loads(x).get('checks'),list)) +if '--view' not in sys.argv: + from r10_probes import augment + body=augment(body,320) +print(json.dumps(body,ensure_ascii=False)) diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/candidate_artifacts.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/candidate_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..01d155d66962e3f1c41443cad117a48e6ca25bc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/candidate_artifacts.py @@ -0,0 +1,24 @@ +"""Read only ordinary candidate artifacts after a bounded child completes. +No launch/setup/monitor exceptions are caught here. Symlinks to regular files +remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from +blocking the trusted grader. Malformed text/JSON is an absent invalid value. +""" +import json, os, stat + +def read_text(path, encoding=None, errors=None): + fd=None + try: + fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode):return '' + with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream: + fd=None + return stream.read() + except (OSError,UnicodeError):return '' + finally: + if fd is not None:os.close(fd) + +def loads(text, **kwargs): + try:return json.loads(text,**kwargs) + except (ValueError,TypeError,RecursionError):return None + +def load(path, **kwargs):return loads(read_text(path),**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/original_check.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/original_check.py new file mode 100644 index 0000000000000000000000000000000000000000..af79958571f4dc0d011b2813a424e81941285c72 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/original_check.py @@ -0,0 +1,62 @@ +from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import r10_runtime as _r10 +import json, os, shutil, subprocess, sys, tempfile, ast + +EXPECTED = [ + '1. A. Vaswani, N. Shazeer, and N. Parmar, "Attention Is All You Need," *Advances in Neural Information Processing Systems* **30**, 5998 (2017). doi:10.48550/arXiv.1706.03762', + '2. J. A. Smith et al., "Deep Learning for Turbulence Modeling," *Journal of Fluid Mechanics* **955**, A21 (2023). doi:10.1017/jfm.2023.100', + '3. T. B. Nguyen, "A Single-Author Study on DNS Methods," *Physics of Fluids* **36**, 015101 (2024).', + '4. Unknown, "Untitled Survey," (n.d.).', +] + +def run_candidate(): + tmp = tempfile.mkdtemp(dir='/tmp') + try: + if not os.path.exists('/candidate/format_refs.py'): + return None, None, 'format_refs.py not found in /candidate' + if not os.path.exists('/candidate/data/papers.json'): + return None, None, 'data/papers.json not found in /candidate' + shutil.copy('/candidate/format_refs.py', os.path.join(tmp, 'format_refs.py')) + os.makedirs(os.path.join(tmp, 'data'), exist_ok=True) + shutil.copy('/candidate/data/papers.json', os.path.join(tmp, 'data', 'papers.json')) + p = subprocess.run([sys.executable, 'format_refs.py'], cwd=tmp, capture_output=True, text=True, timeout=60) + refpath = os.path.join(tmp, 'workspace', 'references.md') + content = _co_text(refpath) if os.path.isfile(refpath) else None + err = None if p.returncode == 0 else 'script exited with code %d: %s' % (p.returncode, p.stderr[-300:]) + return content, p.stdout, err + except subprocess.TimeoutExpired:return None,None,'candidate timeout' + except Exception as e:raise RuntimeError('Trusted references launcher/fixture failed') from e + finally: + shutil.rmtree(tmp, ignore_errors=True) + +def stdlib_only(): + return _r10.stdlib_gate('format_refs.py'),_r10.dependency('format_refs.py')[2] + +def main(): + checks = [] + content, stdout, err = run_candidate() + lines = [l for l in content.splitlines() if l.strip()] if content is not None else None + + ok, msg = stdlib_only() + if err: + ok, msg = False, err + elif ok and content is None: + ok, msg = False, 'workspace/references.md was not created' + checks.append({'id': '0', 'passed': ok, 'reason': msg or 'script runs with stdlib only and created the output file'}) + + ok = lines is not None and len(lines) == 4 and all(lines[i].startswith('%d. ' % (i+1)) for i in range(4)) + reason = 'exactly 4 non-empty lines with 1.-4. prefixes in order' if ok else ('references.md missing' if lines is None else 'expected 4 lines starting with 1. - 4., got %d lines' % len(lines)) + checks.append({'id': '1', 'passed': ok, 'reason': reason}) + + for idx in range(4): + ok = lines is not None and len(lines) > idx and lines[idx].strip() == EXPECTED[idx] + checks.append({'id': str(idx + 2), 'passed': ok, + 'reason': ('line %d matches expected reference' % (idx+1)) if ok else ('line %d mismatch; expected: %s' % (idx+1, EXPECTED[idx]))}) + + ok = stdout is not None and content is not None and stdout.strip() == content.strip() + checks.append({'id': '6', 'passed': ok, 'reason': 'stdout matches references.md content' if ok else 'stdout does not match the file content (or script produced no stdout)'}) + + print(json.dumps(_r10.finalize(checks, {'0':'format_refs.py'}))) + +main() diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_base.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e928dba207cf3c6b2fe757b478f723e4d82cd398 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_base.py @@ -0,0 +1,187 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import r10_runtime as _r10 +_r10.install_copy('format_refs.py') +"""Preserve program tests and independently score frozen submitted deliverables. + +No condition labels, scores, skill identities, or selected trajectories enter +this grader. Both views use the original check IDs and criterion weights. +""" +import contextlib +import io +import json +import os +import re +from pathlib import Path +import runpy +import shutil +import subprocess +import sys +import tempfile + +HERE=Path(__file__).resolve().parent +CONFIG=json.loads((HERE/'repair.json').read_text()) +CANDIDATE=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +ANSWER=Path(os.environ.get('MYBENCH_ANSWER','/answer.txt')) + +def evaluate_view(mode, frozen): + """Run a fresh grader process; keep monkeypatches away from aggregation.""" + with tempfile.TemporaryDirectory(prefix='evaluation-view-') as td: + clone=Path(td)/'candidate' + shutil.copytree(CANDIDATE,clone,symlinks=True) + for rel in CONFIG.get('fresh_artifacts',[]): + p=clone/rel + if p.is_symlink() or p.is_file():p.unlink() + elif p.is_dir():shutil.rmtree(p) + answer=Path(td)/'answer.txt' + if ANSWER.is_file():shutil.copyfile(ANSWER,answer) + env=dict(os.environ, MYBENCH_VIEW=mode, MYBENCH_FROZEN=str(frozen), + MYBENCH_CANDIDATE=str(clone),MYBENCH_ANSWER=str(answer)) + p=subprocess.run([sys.executable,str(HERE/'check.py'),'--view'],env=env, + cwd=clone,capture_output=True,text=True, + timeout=CONFIG.get('timeout',360)) + for line in reversed(p.stdout.splitlines()): + try: + obj=json.loads(line) + if isinstance(obj,dict) and isinstance(obj.get('checks'),list):return obj + except (ValueError,TypeError):pass + raise RuntimeError('grader view failed: rc=%s %s'%(p.returncode,p.stderr[-1500:])) + +def run_inner(): + mode=os.environ['MYBENCH_VIEW'] + frozen=Path(os.environ['MYBENCH_FROZEN']) + original_run=subprocess.run + count=0 + entries={int(k):v for k,v in CONFIG.get('runs',{}).items()} + fresh_missing=[] + def run_with_delivery(*args,**kwargs): + nonlocal count + idx=count;count+=1 + p=original_run(*args,**kwargs) + if idx in entries and CONFIG.get('require_fresh_generated'): + cwd=Path(kwargs.get('cwd') or os.getcwd()) + command=args[0] if args else kwargs.get('args') + for item in entries[idx]: + if item.get('stream'):continue + if 'output_arg' in item:destination=Path(command[item['output_arg']]) + elif 'directory_arg' in item:destination=Path(command[item['directory_arg']])/item['generated'] + else:destination=cwd/item['generated'] + if not destination.exists() and not destination.is_symlink():fresh_missing.append(str(destination)) + if mode=='delivery' and idx in entries: + cwd=Path(kwargs.get('cwd') or os.getcwd()) + for item in entries[idx]: + submitted=frozen/item['submitted'] + if item.get('stream'): + val=submitted.read_bytes() if submitted.is_file() else b'' + old=getattr(p,item['stream']) + setattr(p,item['stream'],val.decode('utf-8',errors='replace') if isinstance(old,str) else val) + else: + command=args[0] if args else kwargs.get('args') + if 'output_arg' in item: + destination=Path(command[item['output_arg']]) + elif 'directory_arg' in item: + destination=Path(command[item['directory_arg']])/item['generated'] + else:destination=cwd/item['generated'] + if destination.is_symlink() or (destination.exists() and not destination.is_dir()):destination.unlink() + elif destination.is_dir():shutil.rmtree(destination) + if submitted.exists() or submitted.is_symlink(): + destination.parent.mkdir(parents=True,exist_ok=True) + if submitted.is_symlink():destination.symlink_to(os.readlink(submitted)) + elif submitted.is_dir():shutil.copytree(submitted,destination,symlinks=True) + else: + shutil.copy2(submitted,destination) + if item.get('json_path_arg') is not None: + data=json.loads(destination.read_text()) + given=Path(command[item['json_path_arg']]) + actual=data.get('path') + if isinstance(actual,str) and Path(actual).name==given.name: + data['path']=str(given) + destination.write_text(json.dumps(data)) + for rel in CONFIG.get('must_be_absent',[]): + destination=cwd/rel + if not (CANDIDATE/rel).exists() and not (CANDIDATE/rel).is_symlink(): + if destination.is_dir():shutil.rmtree(destination) + elif destination.exists() or destination.is_symlink():destination.unlink() + else: + destination.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(frozen/rel,destination) + return p + subprocess.run=run_with_delivery + code=(HERE/'original_check.py').read_text() + # The candidate root is a runtime input, never a solver-condition marker. + code=code.replace('/candidate',str(CANDIDATE)).replace('/answer.txt',str(ANSWER)) + scope={'__name__':'__main__','__file__':str(HERE/'original_check.py')} + captured=io.StringIO() + with contextlib.redirect_stdout(captured): + exec(compile(code,str(HERE/'original_check.py'),'exec'),scope) + body=None + for line in reversed(captured.getvalue().splitlines()): + try: + obj=json.loads(line) + if isinstance(obj,dict) and isinstance(obj.get('checks'),list):body=obj;break + except (ValueError,TypeError):pass + if body is None:raise RuntimeError('original checker did not emit its checks schema') + if fresh_missing: + for c in body['checks']: + if str(c['id']) in CONFIG.get('presence_check_ids',[]): + c['passed']=False;c['reason']=c.get('reason','')+'; no fresh generated file(s): '+repr(fresh_missing) + print(json.dumps(body)) + +def main(): + if not (CANDIDATE/'format_refs.py').is_file(): + print(json.dumps({'checks':[{'id':str(cid),'passed':False,'reason':'Required submitted entry format_refs.py is missing or not a regular file'} for cid in CONFIG['check_ids']]})) + return + if '--view' in sys.argv:return run_inner() + with tempfile.TemporaryDirectory(prefix='submitted-delivery-') as td: + frozen=Path(td) + required=CONFIG.get('submitted_artifacts',[]) + present={} + for rel in required+CONFIG.get('must_be_absent',[]): + src=CANDIDATE/rel;dst=frozen/rel + present[rel]=src.is_file() or src.is_dir() or src.is_symlink() + if present[rel]: + dst.parent.mkdir(parents=True,exist_ok=True) + if src.is_symlink():dst.symlink_to(os.readlink(src)) + elif src.is_dir():shutil.copytree(src,dst,symlinks=True) + else:shutil.copy2(src,dst) + try: + behavior=evaluate_view('behavior',frozen) + delivered=evaluate_view('delivery',frozen) + bchecks=behavior['checks']; dchecks={str(c['id']):c for c in delivered['checks']} + missing=[p for p in required if not present.get(p)] + absent_wrong=[p for p in CONFIG.get('must_be_absent',[]) if present.get(p)] + invalid_required=[] + for rel,values in CONFIG.get('json_required_values',{}).items(): + try: + obj=json.loads((frozen/rel).read_text()) + if not isinstance(obj,dict) or any(obj.get(k)!=v for k,v in values.items()):invalid_required.append(rel) + except Exception:invalid_required.append(rel) + special={} + if CONFIG.get('special_delivery')=='adls_arbitrary_test_values': + try: + conf=(frozen/'conf_output.txt').read_text().splitlines() + match=re.fullmatch(r'fs\.azure\.account\.auth\.type\.([A-Za-z0-9_-]+\.dfs\.core\.windows\.net) = OAuth',conf[0]) + host=match.group(1) if match else None + pfx=['fs.azure.account.auth.type.','fs.azure.account.oauth.provider.type.','fs.azure.account.oauth2.client.id.','fs.azure.account.oauth2.client.secret.','fs.azure.account.oauth2.client.endpoint.'] + fields=[] + for line,prefix in zip(conf,pfx): + m=re.fullmatch(re.escape(prefix+(host or '')+' = ')+r'(.+)',line) + fields.append(m.group(1) if m else None) + good=bool(host and len(conf)==6 and len(fields)==5 and all(fields) and fields[0]=='OAuth' and fields[1]=='org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider' and re.fullmatch(r'https://login\.microsoftonline\.com/[^/]+/oauth2/token',fields[4])) + uri_good=good and re.fullmatch(r'abfss://[^@\s]+@'+re.escape(host)+r'/\S+',conf[5]) is not None + secret=fields[3] if len(fields)>3 else None + forbidden='\n'.join(conf[:3]+conf[4:])+(frozen/'missing_output.txt').read_text()+(frozen/'check_output.txt').read_text() + special={'1':bool(good),'2':bool(uri_good),'4':bool(good and secret and secret not in forbidden)} + except Exception:special={'1':False,'2':False,'4':False} + checks=[] + for c in bchecks: + cid=str(c['id']); dc=dchecks.get(cid,{}) + ok=False if c.get('passed')is False or dc.get('passed')is False else None if c.get('passed')is None or dc.get('passed')is None else True + if cid in special:ok=ok and special[cid] + if cid in CONFIG.get('presence_check_ids',[]):ok=ok and not missing and not absent_wrong and not invalid_required + checks.append(dict(c,passed=ok,reason='behavior: %s; submitted delivery: %s%s'%(c.get('reason',''),dc.get('reason','missing check'),'; missing='+repr(missing) if missing else '; forbidden state='+repr(absent_wrong) if absent_wrong else ''))) + if set(dchecks)!={str(c['id']) for c in bchecks}:raise RuntimeError('check ID schema changed between views') + print(json.dumps({'scoreable':all(type(c.get('passed'))is bool for c in checks),'checks':checks})) + except Exception as e: + raise RuntimeError('Trusted independent delivery view failed: '+str(e)) from e + +if __name__=='__main__':main() diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_probes.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_probes.py new file mode 100644 index 0000000000000000000000000000000000000000..7172b4644c9f091b295fbc07871fd714cf93b807 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_probes.py @@ -0,0 +1,84 @@ +from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json +# -*- coding: utf-8 -*- +"""Independent public-rule panels for R10. Imported only in offline Docker.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import contextlib,json,math,os,pathlib,shutil,subprocess,sys,tempfile +from r10_runtime import C,read_json,dependency +S=pathlib.Path('/source') +@contextlib.contextmanager +def fresh(remove=(),updates=None): + with tempfile.TemporaryDirectory(prefix='r10-panel-',dir='/tmp')as d: + w=pathlib.Path(d);shutil.copytree(C,w,dirs_exist_ok=True,symlinks=True) + task=json.loads((S/'task.json').read_text()) + for m in task.get('workspace',{}).get('input_mappings',[]): + src=S/m['source'];dst=w/m['workspace_target'];dst.parent.mkdir(parents=True,exist_ok=True) + if src.is_file():dst.write_bytes(src.read_bytes()) + for rel in remove: + p=w/rel + if p.is_dir()and not p.is_symlink():shutil.rmtree(p) + elif p.exists()or p.is_symlink():p.unlink() + for rel,value in(updates or{}).items(): + p=w/rel;p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(value if isinstance(value,bytes)else value.encode()) + yield w +def run(w,entry,args=()): + try:return subprocess.run([sys.executable,entry]+list(args),cwd=w,capture_output=True,text=True,timeout=60) + except subprocess.TimeoutExpired:return subprocess.CompletedProcess([],124,'','') +def tri(a,b):return False if a is False or b is False else None if a is None or b is None else True +def enforce(body,ids,good,reason): + for row in body['checks']: + if str(row['id'])in set(map(str,ids)): + row['passed']=tri(row.get('passed'),good);row['reason']=row.get('reason','')+'; R10: '+reason + body['scoreable']=all(type(x.get('passed'))is bool for x in body['checks']) + return body +def lifecycle(body): + name='add-export-csv';date='2026-01-15';rel='docs/security/'+name+'-r10-second.md';new='# Independent security report\n\nR10 preserved second-source content.\n' + with fresh(remove=('openspec/changes/archive','docs/archive'),updates={rel:new})as w: + sources=sorted(w.glob('docs/security/'+name+'-*.md'));before={p.name:p.read_text()for p in sources} + p=run(w,'lifecycle.py',[name,'--date',date]);out=w/'docs/archive'/date/name/'security.md' + text=out.read_text()if out.is_file()else'' + good=p.returncode==0 and len(before)>=2 and text.startswith('# Security reports — '+name)and all('## '+n in text and value.strip()in text and not(w/'docs/security'/n).exists()for n,value in before.items()) + return enforce(body,[7],good,'every one of multiple independent security files is concatenated and moved, not only the first glob result') +def worker(body): + updates={'inbox/002.':json.dumps({'prompt':'second'}),'inbox/001.':json.dumps({'prompt':'first'}),'inbox/000.txt':'ignore non-target suffix'} + with fresh(remove=('inbox','outbox'),updates=updates)as w: + p=run(w,'worker.py',['--once']);reply=w/'outbox/001.reply.' + doc=read_json(reply)if reply.is_file()else None + good=p.returncode==0 and(w/'inbox/001..done').is_file()and not(w/'inbox/001.').exists()and(w/'inbox/002.').is_file()and(w/'inbox/000.txt').is_file()and isinstance(doc,dict)and doc.get('source')=='001.'and doc.get('reply')=='echo: first'and len(list((w/'inbox').glob('*.done')))==1 + return enforce(body,[5],good,'--once selects the actual lexicographic first target despite reverse creation order and ignores a non-target suffix') +def citation_line(p,index): + authors=[] + for a in p.get('authors',[]): + last,first=(a.split(',',1)+[''])[:2];authors.append(' '.join(s[0]+'.'for s in first.strip().split())+' '+last.strip()) + author=authors[0]+' et al.'if len(authors)>3 else authors[0]if len(authors)==1 else ', '.join(authors[:-1])+', and '+authors[-1]if authors else'Unknown' + line=str(index)+'. '+author+', "'+p['title']+',"' + if p.get('journal'):line+=' *'+p['journal']+'*' + if p.get('volume'):line+=' **'+str(p['volume'])+'**,' + if p.get('pages'):line+=' '+str(p['pages']).split('-',1)[0] + line+=' ('+str(p.get('year')or'n.d.')+').' + if p.get('doi'):line+=' doi:'+p['doi'] + return line +def references(body): + papers=[dict(title='Independent Two Author Paper',authors=['First, Alice','Second, Bob Clark'],year=2031,journal='Test Journal',volume='7',pages='123-140',doi='10.test/r10'),dict(title='Changed Input',authors=['Miller, Cora'],year=2029,journal='',volume='',pages='',doi='')] + good=True + for panel in[papers,list(reversed(papers)),[]]: + with fresh(remove=('workspace/references.md',),updates={'data/papers.json':json.dumps(panel)})as w: + p=run(w,'format_refs.py');path=w/'workspace/references.md';actual=_co_text(path)if path.is_file()else None;wanted=[citation_line(x,i)for i,x in enumerate(panel,1)] + good=good and p.returncode==0 and actual is not None and [line for line in actual.splitlines()if line.strip()]==wanted and p.stdout.strip()==actual.strip() + return enforce(body,[0,1,6],good,'two-author, reordered/changed fields and empty-array panels use independent formatted expectations, not four fixed strings') +def sitting(body): + panels=[(['sit on stool','sit on couch','sit on recliner'],{'seats':['BlueCouch','stoolSeat','stool'],'default':'stoolSeat'},['stool','BlueCouch','stoolSeat']),(['sit on toilet','','sit on couch'],{'seats':['toiletSeat','lounge'],'default':'lounge'},['toiletSeat','lounge']),([],{'seats':['quietSeat'],'default':'quietSeat'},[])] + good=True + for commands,seats,wanted in panels: + with fresh(remove=('actions.',),updates={'commands.txt':'\n'.join(commands)+'\n','seats.':json.dumps(seats)})as w: + p=run(w,'sit_planner.py');path=w/'actions.';out=read_json(path)if path.is_file()else None + valid=isinstance(out,list)and len(out)==len(wanted) + if valid: + for row,target in zip(out,wanted): + valid=valid and isinstance(row,dict)and row.get('moveTo')=={'target':target}and type(row.get('durationMs'))is int and 2000<=row['durationMs']<=3000 and row.get('pose')=={k:[90,0,0]for k in['LeftUpLeg','LeftLeg','RightUpLeg','RightLeg']}and isinstance(row.get('say'),str)and bool(row['say'].strip()) + good=good and p.returncode==0 and valid + enforce(body,[0,1,2,3,4,5],good,'commands/order/anchors/default vary independently, exact match beats fuzzy, empty input produces no actions') + return enforce(body,[6],dependency('sit_planner.py')[0],'complete entry and helper dependency closure') +PROBES={312:lifecycle,316:worker,320:references,366:sitting} +def augment(body,index): + return PROBES[index](body) diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_runtime.py b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d7872f5ef5e56b3e7c57f0f9a26ee4db4570e73b --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/r10_runtime.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""R10 grader helper. This file runs only inside an offline verifier container.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,os,pathlib,shutil +from dependency_scan import scan_stdlib +C=pathlib.Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) +_copies={};_deps={} +def dependency(entry): + key=str(entry) + if key not in _deps:_deps[key]=scan_stdlib(C,[key]) + return _deps[key] +def stdlib_gate(entry): + # Unknown is provisionally neutral; finalize() preserves it as unscored. + return dependency(entry)[0] is not False +def finalize(checks,owners): + for row in checks: + entry=owners.get(str(row['id'])) + if entry is None:continue + ok,_,why=dependency(entry) + if ok is False:row['passed']=False + elif ok is None and row.get('passed')is not False:row['passed']=None + row['reason']=row.get('reason','')+'; reachable dependency closure: '+why + return {'scoreable':all(type(row.get('passed'))is bool for row in checks),'checks':checks} +def strict_pairs(pairs): + out={} + for key,value in pairs: + if key in out:raise ValueError('duplicate JSON object key: '+key) + out[key]=value + return out +def read_json(path): + return json.loads(pathlib.Path(path).read_bytes(),object_pairs_hook=strict_pairs, + parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON: '+x))) +def install_copy(entry): + """Complete authored dependencies without copying stale deliverables into fixtures.""" + if entry in _copies:return + _copies[entry]=True + try:task=json.loads(pathlib.Path('/source/task.json').read_text()) + except (OSError,ValueError):task={} + excluded=[] + for value in task.get('outputs',[]): + value=value.get('path')if isinstance(value,dict)else value + if isinstance(value,str)and not value.endswith(('.py','.sh')):excluded.append(pathlib.PurePosixPath(value)) + # Public fixture inputs come from the trusted source/fixture constructor, never + # from the candidate snapshot after a panel intentionally removes a file. + for mapping in task.get('workspace',{}).get('input_mappings',[]): + value=mapping.get('workspace_target') + if isinstance(value,str):excluded.append(pathlib.PurePosixPath(value)) + original_copy=shutil.copy;original_copyfile=shutil.copyfile + def extra(src,dst): + try: + source=pathlib.Path(src) + if source.name!=pathlib.Path(entry).name:return + source.resolve().relative_to(C.resolve()) + except (ValueError,TypeError,OSError):return + destination=pathlib.Path(dst) + if destination.is_dir():destination=destination/source.name + root=destination.parent + # Helpers keep the entry's authored relative directory context. + for unused in pathlib.PurePosixPath(entry).parts[:-1]:root=root.parent + for dp,dn,fn in os.walk(str(C),followlinks=False): + dn[:]=[n for n in dn if n not in ('skills','skill','.git','.venv','venv','__pycache__')] + for name in fn: + p=pathlib.Path(dp)/name;rel=p.relative_to(C) + if any(rel==x or x in rel.parents for x in excluded):continue + if p.resolve()==source.resolve():continue + out=root/rel + if out.exists()or out.is_symlink():continue + out.parent.mkdir(parents=True,exist_ok=True) + if p.is_symlink():out.symlink_to(os.readlink(str(p))) + elif p.is_file():original_copyfile(str(p),str(out)) + def copy(src,dst,*args,**kwargs): + result=original_copy(src,dst,*args,**kwargs);extra(src,result);return result + def copyfile(src,dst,*args,**kwargs): + result=original_copyfile(src,dst,*args,**kwargs);extra(src,result);return result + shutil.copy=copy;shutil.copyfile=copyfile diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/repair.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/repair.json new file mode 100644 index 0000000000000000000000000000000000000000..d696347662ce596cfec8d939daf4aa883fe00814 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/evaluator/repair.json @@ -0,0 +1,35 @@ +{ + "query_id": "d2748367ce09dcda303e4b09", + "repair_kind": "independent_submitted_artifact_semantics", + "submitted_artifacts": [ + "workspace/references.md" + ], + "fresh_artifacts": [], + "runs": { + "0": [ + { + "submitted": "workspace/references.md", + "generated": "workspace/references.md" + } + ] + }, + "require_fresh_generated": true, + "check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "presence_check_ids": [ + "0" + ], + "timeout": 360, + "instruction_sha256": "d934398ac0b16df32ebf1bb44eec4df763495a3e915bb19e71216bc24392a6a9", + "original_checker_sha256": "9e99daeb7b14b7f63300daab3ca149825ffd14908773f06a9a9d9d9c1bbd843a", + "public_delivery_contract": "You are given a JSON file `data/papers.json` containing metadata for several papers (title, authors as 'Last, First' strings, year, journal, volume, pages, doi). Write a Python 3 script `format_refs.py` (standard library only) that reads this JSON and writes a Markdown reference list to `workspace/references.md` using the following numbered citation style: authors formatted as initials followed by last name (e.g. 'A. Vaswani'); if there is exactly 1 author use that author alone; if there are 2 or 3 authors join all with ', ' and put ', and ' before the last one; if there are more than 3 authors use only the first author followed by ' et al.'; if the author list is empty use 'Unknown'. Then the reference is: `<authors>, \"<title>,\"` followed by the journal in Markdown italics (`*Journal*`) if present, followed by the volume in bold (`**30**,`) if present, followed by the first page number only (text before the first '-') if pages are present, followed by ` (<year>).` (use 'n.d.' if year is missing), followed by ` doi:<doi>` if a doi is present. Each reference is prefixed with its 1-based index and a period and space (e.g. `1. ...`), one per line, in the same order as the JSON array. Run the script with bash so the output file is created, and also print the resulting Markdown to stdout.", + "preserve_ids_and_weights": true, + "no_condition_or_score_input": true +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..12100f8b71e416c81bee9652f1360c00d11962ea --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/grading/verified_config.json @@ -0,0 +1,116 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d2748367ce09dcda303e4b09", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "r10_probes.py": "75db6d83a8206aad64bba57e34d2e2daf9226213b35c0aedf1cfa4206f787469", + "r10_base.py": "584305e615e0f574ab1530e463c53531a8c778ec770039a0d611928b07f3cceb", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "original_check.py": "16bd405aa4e1b5d131460128c053d8660da1b3989d4788b5be462694d44c5b4d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "08a9a547638d54fa92d2659195a5f1b433195a1c1628a62b945eca2275b817ff", + "r10_runtime.py": "e4205af091a5c170ce2640089d77bfe7fe9e7b516c56c4a0b3886a69816cb3a2", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "repair.json": "779794797b1ebc269c327ce60dbbbea6fe3067cbb1b90d9b4be4327cc4c7191a", + "auto_contract.json": "cd1a3cf8f6adc127040758d67438be38f63486fb5c9c9d0faad4d4c7328dc67e" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": false, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "cpu_memory_basis": "source_runtime_container_limits", + "cpus": 2, + "disk_mib": 10240, + "memory_mib": 4096, + "timeout_disk_basis": "advisory_not_measured_or_enforced", + "timeout_sec": 1200 + }, + "oracle": { + "basis": "advisory_reference_copy", + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": 60, + "max_steps": 16 + }, + "verifier": { + "basis": "original_python_evaluator_enforced_limits", + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 60, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_ANSWER", + "MYBENCH_CANDIDATE", + "MYBENCH_FROZEN", + "MYBENCH_VIEW" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/inputs/data/papers.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/inputs/data/papers.json new file mode 100644 index 0000000000000000000000000000000000000000..272c412e8eba37ada9e83c7ca6ca5f4807066cd3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/inputs/data/papers.json @@ -0,0 +1,38 @@ +[ + { + "title": "Attention Is All You Need", + "authors": ["Vaswani, Ashish", "Shazeer, Noam", "Parmar, Niki"], + "year": 2017, + "journal": "Advances in Neural Information Processing Systems", + "volume": "30", + "pages": "5998-6008", + "doi": "10.48550/arXiv.1706.03762" + }, + { + "title": "Deep Learning for Turbulence Modeling", + "authors": ["Smith, John A.", "Doe, Jane", "Lee, Min", "Chen, Wei"], + "year": 2023, + "journal": "Journal of Fluid Mechanics", + "volume": "955", + "pages": "A21-A40", + "doi": "10.1017/jfm.2023.100" + }, + { + "title": "A Single-Author Study on DNS Methods", + "authors": ["Nguyen, Thao B."], + "year": 2024, + "journal": "Physics of Fluids", + "volume": "36", + "pages": "015101-015112", + "doi": "" + }, + { + "title": "Untitled Survey", + "authors": [], + "year": null, + "journal": "", + "volume": "", + "pages": "", + "doi": "" + } +] diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/instruction.md b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e4fc8d48eff71df74d6d8299d042a5f29d2da1ad --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/instruction.md @@ -0,0 +1,8 @@ +You are given `data/papers.json`, an array of paper metadata (title, authors as 'Last, First' strings, year, journal, volume, pages, doi). Write a Python 3 standard-library program `format_refs.py` that implements the bundled Skill's JCP numbered-reference `format_ref` example. Read that frozen example for author abbreviation/count rules, fallback strings, punctuation, Markdown styling, first-page handling, DOI rendering and numbering; do not retrieve an external style guide or install scholaraio. + +Write `workspace/references.md` in input array order, invoking the style with a 1-based index and one reference per line. Use the example's metadata keys and formatting for supplied fields. Empty authors must render as the literal Unknown; handle that case before the example's <=3-author branch (its sample code would otherwise index an empty list). Missing year uses n.d.; missing optional journal/volume/pages/doi is omitted. Run with bash so the file is created, and also print the resulting Markdown to stdout. This is an offline formatting task, not literature search. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/d2748367ce09dcda303e4b09/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b8613e3c035b97b72aa2d52bcba9d419e13971d8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/skill/SKILL.md @@ -0,0 +1,234 @@ +--- +name: export +description: Use when the user needs BibTeX, RIS, Markdown reference lists, filtered citation exports, custom citation styles, or a Markdown-to-DOCX export for sharing. +--- +# 导出论文与文档 + +将本地论文库导出为标准引用格式,或将任意 Markdown 内容转换为 Word 文件。 + +## 支持的导出格式 + +| 格式 | 命令 | 用途 | +|------|------|------| +| BibTeX `.bib` | `export bibtex` | LaTeX 写作引用 | +| RIS `.ris` | `export ris` | Zotero / Endnote / Mendeley 导入 | +| Markdown 文献列表 | `export markdown` | 直接粘贴到文档、综述草稿 | +| Word DOCX | `export docx` | 分享给同事、导师,任意 Markdown 内容 | + +--- + +## BibTeX 导出 + +```bash +# 导出全部论文到屏幕 +scholaraio export bibtex --all + +# 导出全部论文到文件 +scholaraio export bibtex --all -o workspace/library.bib + +# 导出指定论文 +scholaraio export bibtex "Smith-2023-Turbulence" "Doe-2024-DNS" + +# 按年份筛选导出 +scholaraio export bibtex --all --year 2020-2024 -o workspace/recent.bib + +# 按期刊筛选导出 +scholaraio export bibtex --all --journal "Fluid Mechanics" -o workspace/jfm.bib +``` + +## RIS 导出(Zotero / Endnote / Mendeley) + +```bash +# 导出全部论文 +scholaraio export ris --all -o workspace/library.ris + +# 导出指定论文 +scholaraio export ris "Smith-2023-Turbulence" "Doe-2024-DNS" -o workspace/refs.ris + +# 按年份筛选 +scholaraio export ris --all --year 2022-2024 -o workspace/recent.ris +``` + +导出后可直接在 Zotero 中:File → Import → 选择 .ris 文件 + +## Markdown 文献列表导出 + +### 内置格式(--style) + +| 格式名 | 说明 | 典型场景 | +|--------|------|----------| +| `apa`(默认) | APA 7th 作者-年份 | 社科、心理、教育 | +| `vancouver` | Vancouver/ICMJE 编号 | 医学、生命科学 | +| `chicago-author-date` | Chicago 17 作者-年份 | 人文、社科 | +| `mla` | MLA 9th | 文学、语言学 | +| `<自定义>` | 期刊专属格式 | 见下方「自定义格式」 | + +```bash +# 导出全部论文(APA 风格,默认) +scholaraio export markdown --all + +# 指定引用格式 +scholaraio export markdown --all --style vancouver +scholaraio export markdown --all --style chicago-author-date +scholaraio export markdown --all --style jcp # 自定义格式 + +# 导出到文件 +scholaraio export markdown --all --style apa -o workspace/references.md + +# 无序列表 +scholaraio export markdown --all --bullet + +# 按年份筛选 +scholaraio export markdown --all --year 2020-2024 -o workspace/recent_refs.md +``` + +### 查看可用格式 + +```bash +scholaraio style list # 列出全部格式(内置 + 自定义) +scholaraio style show jcp # 查看某个自定义格式的代码 +``` + +--- + +## 自定义期刊引用格式(Agent 精确控制) + +### 原理 + +自定义格式以 Python 文件存储在配置的 citation styles 目录中。fresh 默认是 +`data/libraries/citation_styles/<name>.py`。如果用户仍有旧版 +`data/citation_styles/` 内容,先通过 `scholaraio migrate upgrade --migration-id <id> --confirm` +迁移后再导出。格式文件必须实现一个函数: + +```python +def format_ref(meta: dict, idx: int | None = None) -> str: + """ + meta 字段:title, authors (list), year, journal, volume, issue, + pages, doi, publisher, paper_type, ... + idx: 有序列表的编号(None = 无序/bullet) + 返回:格式化后的 Markdown 引用字符串 + """ +``` + +### Agent 工作流:为指定期刊生成格式 + +当用户说「导出成 JCP 格式」「帮我按 Physical Review Letters 格式导出」: + +1. **检查是否已有缓存** + ```bash + scholaraio style list + ``` + 如果已有 `jcp` 或目标格式名,直接跳到第 4 步。 + +2. **获取期刊官方格式说明** + - 搜索:`<journal name> citation style guide` 或 `<journal name> reference format` + - 或从 CSL 仓库获取标准定义: + `https://raw.githubusercontent.com/citation-style-language/styles/master/<slug>.csl` + - CSL 搜索:`https://github.com/citation-style-language/styles/`(支持 10,000+ 期刊) + +3. **写 Python 格式化函数并保存** + - 根据格式说明写 `format_ref(meta, idx)` 函数 + - 保存到当前 `cfg.citation_styles_dir / "<name>.py"`(fresh 默认 `data/libraries/citation_styles/<name>.py`) + - 可同时保存同目录的 `<name>.json`(记录来源和示例) + +4. **导出** + ```bash + scholaraio export markdown --all --style <name> -o workspace/refs.md + ``` + +### 示例:JCP 格式文件(fresh 默认 data/libraries/citation_styles/jcp.py) + +```python +# Journal of Chemical Physics / AIP Publishing 编号格式 +# 来源:https://publishing.aip.org/wp-content/uploads/2021/05/JCP_Style_Guide.pdf + +def format_ref(meta: dict, idx: int | None = None) -> str: + authors = meta.get("authors") or [] + + def _fmt(name): + parts = name.split(",", 1) + if len(parts) == 2: + last, first = parts[0].strip(), parts[1].strip() + initials = " ".join(f"{w[0]}." for w in first.split() if w) + return f"{initials} {last}" + return name + + if len(authors) == 1: + author_str = _fmt(authors[0]) + elif len(authors) <= 3: + fmt = [_fmt(a) for a in authors] + author_str = ", ".join(fmt[:-1]) + f", and {fmt[-1]}" + elif authors: + author_str = _fmt(authors[0]) + " et al." + else: + author_str = "Unknown" + + title = meta.get("title") or "Untitled" + journal = meta.get("journal") or "" + volume = meta.get("volume") or "" + pages = meta.get("pages") or "" + year = meta.get("year") or "n.d." + doi = meta.get("doi") or "" + start_page = pages.split("-")[0].strip() if pages else "" + + ref = f'{author_str}, "{title},"' + if journal: ref += f" *{journal}*" + if volume: ref += f" **{volume}**," + if start_page: ref += f" {start_page}" + ref += f" ({year})." + if doi: ref += f" doi:{doi}" + + prefix = f"{idx}. " if idx is not None else "- " + return prefix + ref +``` + +输出示例: +``` +1. A. Vaswani et al., "Attention Is All You Need," *Advances in Neural Information Processing Systems* **30**, 5998 (2017). doi:10.48550/arXiv.1706.03762 +``` + +--- + +## DOCX 导出(任意 Markdown → Word) + +```bash +# 将 Markdown 文件导出为 Word +scholaraio export docx --input workspace/literature_review.md --output workspace/review.docx + +# 添加文档标题 +scholaraio export docx --input workspace/report.md --output workspace/report.docx --title "研究报告" + +# 从 stdin 读取(配合 Claude 生成内容直接导出) +echo "# 标题\n内容..." | scholaraio export docx --output workspace/doc.docx +``` + +支持的 Markdown 元素:标题(H1-H9)、段落、**粗体**、*斜体*、列表、表格、代码块、引用块 + +**依赖**:需安装 `pip install python-docx` + +> **高级排版**:`export docx` 仅做简单 Markdown → Word 转换。需要自定义样式、嵌入图片、表格等高级排版时,请使用 `/document` skill(直接调用 python-docx API)。 + +--- + +## 示例 + +用户说:"把我所有论文导出成 BibTeX" +→ 执行 `export bibtex --all` + +用户说:"导出成 RIS,我要导入 Zotero" +→ 执行 `export ris --all -o workspace/library.ris` + +用户说:"给我一份 Markdown 格式的参考文献列表" +→ 执行 `export markdown --all` + +用户说:"按 Vancouver 格式导出文献列表" +→ 执行 `export markdown --all --style vancouver` + +用户说:"按 JCP 格式导出,我要投 Journal of Chemical Physics" +→ 先 `style list` 检查,若无则获取 JCP 格式说明、写入当前 citation styles 目录(fresh 默认 `data/libraries/citation_styles/jcp.py`),再 `export markdown --all --style jcp` + +用户说:"把这篇文献综述导出成 Word 文件" +→ 执行 `export docx --input workspace/review.md --output workspace/review.docx` + +用户说:"导出 DNS 相关的论文引用" +→ 先用 `usearch "DNS"` 搜索,从结果中提取目录名,再 `export markdown <dir1> <dir2> ...` diff --git a/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/task.json b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/task.json new file mode 100644 index 0000000000000000000000000000000000000000..469c931707b4d8408f4cd54b3e185eef28e6ee82 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d2748367ce09dcda303e4b09/task.json @@ -0,0 +1,69 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d2748367ce09dcda303e4b09", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "d2748367ce09dcda303e4b09", + "outputs": [ + "format_refs.py", + "workspace/references.md" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "fad15b85e4d19073c9c441af198b201577c3132ab21cf4285fbf88654eba8140", + "files": { + "SKILL.md": "e51a5a2d36551a69d63c79c28aecda10759e758f192b3c0c2b700499eda5f7c1" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/data/papers.json", + "workspace_target": "data/papers.json", + "sha256": "ee935f59e0eef888366eb305670b1388afcf5c10aa9aaaa4f2b5a7915ca1ef71" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "fad15b85e4d19073c9c441af198b201577c3132ab21cf4285fbf88654eba8140" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/d31ddb6d11deef56_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_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/d31ddb6d11deef56_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d31ddb6d11deef56_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..52f58a0715713025612c19d72282c59d34a999ed --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/autograde_task_check.py @@ -0,0 +1,14 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import sys,json +from pathlib import Path +root=Path(__file__).resolve().parent +sys.path.insert(0,str(root/'legacy_tests')) +from evaluate import evaluate +t=json.loads((root/'legacy-task.json').read_text()) +from repair_equivalences import install +install(t) +mode=t['workspace']['candidate_mode'] +r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt') +if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False) +if r.get('status')!='scored':raise RuntimeError(json.dumps(r)) +print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy-task.json b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy-task.json new file mode 100644 index 0000000000000000000000000000000000000000..84f9e69ccf2f42be9ea6606ff8b00bad9d9fe947 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy-task.json @@ -0,0 +1,155 @@ +{ + "schema_version": "mybench-portable-task-v2", + "task_id": "d31ddb6d11deef56", + "query_id": "d31ddb6d11deef56_q1", + "prompt": { + "path": "instruction.md", + "sha256": "462179749397abee2f103ce5013ba925ea65977d17c84ad5c14fbbc7414535d7" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "38add14f1fa5914bacf065f63b780b1e813b3b2851edeed1d0735f5e1965ad67", + "name": "healthcheck", + "package_path": "environment/skills/healthcheck-38add14f", + "install_name": "healthcheck-38add14f", + "archive_provenance": { + "archive_id": "logical-skill-a90fba99c0bad3d5292dc965", + "archive_schema": "skill-release-v1", + "release_skill_id": "logical-skill-a90fba99c0bad3d5292dc965", + "site": "skills-2m", + "local_path": "skills/a9/logical-skill-a90fba99c0bad3d5292dc965", + "skill_md_sha256": "b719702f8e27de241dc738f240e173bd8cc403f7cab01a6b42086a6746f5d73b", + "release_payload_sha256": "38add14f1fa5914bacf065f63b780b1e813b3b2851edeed1d0735f5e1965ad67", + "license": "Apache-2.0", + "license_status": "detected", + "canonical_source_id": "changling:6a01fec1cc5b45a153faf0bfd6ed333c" + }, + "omitted_entries": [] + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "ground_truth_skills": [ + "38add14f1fa5914bacf065f63b780b1e813b3b2851edeed1d0735f5e1965ad67" + ], + "evaluation": { + "type": "verified", + "ground_truth_answer": { + "files": [ + { + "path": "output/baseline_healthcheck.sh", + "content": "#!/usr/bin/env bash\nset -euo pipefail\nopenclaw security audit --deep\nopenclaw update status\nopenclaw cron list\n" + } + ] + }, + "verifier": { + "type": "workspace_objective", + "version": 15, + "output_mode": "workspace", + "reference_files": [ + { + "path": "output/baseline_healthcheck.sh", + "format": "shell", + "content": "#!/usr/bin/env bash\nset -euo pipefail\nopenclaw security audit --deep\nopenclaw update status\nopenclaw cron list\n" + } + ], + "checks": [ + { + "id": "workspace_file_set", + "type": "workspace_file_set", + "paths": [ + "output/baseline_healthcheck.sh" + ], + "roots": [ + "output" + ] + }, + { + "id": "file_001", + "type": "file_exists", + "path": "output/baseline_healthcheck.sh" + }, + { + "id": "shell_001", + "type": "shell_syntax", + "path": "output/baseline_healthcheck.sh" + }, + { + "id": "shell_001_001", + "type": "shell_command", + "path": "output/baseline_healthcheck.sh", + "value": "openclaw security audit --deep" + }, + { + "id": "shell_001_002", + "type": "shell_command", + "path": "output/baseline_healthcheck.sh", + "value": "openclaw update status" + }, + { + "id": "shell_001_003", + "type": "shell_command", + "path": "output/baseline_healthcheck.sh", + "value": "openclaw cron list" + }, + { + "id": "shell_001_sequence", + "type": "shell_command_sequence", + "path": "output/baseline_healthcheck.sh", + "values": [ + "openclaw security audit --deep", + "openclaw update status", + "openclaw cron list" + ] + }, + { + "id": "shell_001_unconditional", + "type": "shell_unconditional_commands", + "path": "output/baseline_healthcheck.sh", + "values": [ + "openclaw security audit --deep", + "openclaw update status", + "openclaw cron list" + ] + }, + { + "id": "shell_001_failure_propagation", + "type": "shell_failure_propagation", + "path": "output/baseline_healthcheck.sh", + "values": [ + "openclaw security audit --deep", + "openclaw update status", + "openclaw cron list" + ] + }, + { + "id": "shell_straight_line_001", + "type": "shell_straight_line", + "path": "output/baseline_healthcheck.sh", + "allowed_commands": [ + "openclaw security audit --deep", + "openclaw update status", + "openclaw cron list" + ], + "exact_operation_count": 3 + } + ], + "self_test_passed": true + }, + "dependency_contract": { + "version": 2, + "mode": "core_answer", + "dependency_type": "project_command_convention", + "requirement_ids": [ + "skill_a064", + "skill_a074", + "skill_a147" + ], + "forbid_meta_reference": true, + "forbid_answer_leakage": true + } + } +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/evaluate.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..6af62307e8c216b7733194602815f5004d893e06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/evaluate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Evaluate a candidate response for one portable MyBench task.""" + +import argparse +import json +import math +import os +import shlex +import subprocess +import sys +from pathlib import Path + + +def _load_verify(): + try: + from verifiers import verify + return verify + except ImportError: + project_src = Path(__file__).resolve().parents[1] / "src" + if project_src.is_dir(): + sys.path.insert(0, str(project_src)) + from verifiers import verify + return verify + raise + + +def _emit(result, output=None): + text = json.dumps(result, ensure_ascii=False) + print(text) + if output: + Path(output).write_text(text + "\n", encoding="utf-8") + + +def _judge_contract(judge): + if not isinstance(judge, dict): + return "Judge output must be a JSON object" + if type(judge.get("passed")) is not bool: + return "Judge field passed must be a JSON boolean" + for key in ("score", "max_score"): + value = judge.get(key, 100 if key == "max_score" else None) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"Judge field {key} must be a finite number" + if not math.isfinite(float(value)): + return f"Judge field {key} must be a finite number" + score = float(judge["score"]) + max_score = float(judge.get("max_score", 100)) + if max_score <= 0: + return "Judge field max_score must be greater than zero" + if score < 0 or score > 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/d31ddb6d11deef56_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/d31ddb6d11deef56_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..c03f64348caa714a2797a7d6488d9a515c65d380 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,455 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i<len(text): + ch=text[i] + if ch=='\\' and quote!="'" and i+1<len(text): + nxt=text[i+1] + if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__') + elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__') + else:out.extend((ch,nxt)) + i+=2;continue + if ch in "'\"": + if quote is None:quote=ch + elif quote==ch:quote=None + out.append(ch);i+=1;continue + if ch=='$': + if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue + m=variable.match(text,i) + if m: + value=constants.get(m.group(1)or m.group(2)) + if value is None:out.append(m.group(0)) + elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$')) + else:out.append(value) + i=m.end();continue + if ch=='~' and quote is not None: + out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue + out.append(ch);i+=1 + return ''.join(out) + + +# Ordinary assignment/parameter defaults are not shell control flow. This +# recognizer never evaluates their text or assumes the inherited value is empty. +_DEFAULT_STATE_NAMES = frozenset({ + 'PATH', 'IFS', 'ENV', 'BASH_ENV', 'SHELLOPTS', 'BASHOPTS', 'CDPATH', + 'GLOBIGNORE', 'FIGNORE', 'POSIXLY_CORRECT', 'BASH_COMPAT', + 'PROMPT_COMMAND', 'PS0', 'PS1', 'PS2', 'PS4', 'UID', 'EUID', 'PPID', + 'SHELL', 'RANDOM', 'SRANDOM', 'SECONDS', 'LINENO', 'OPTIND', 'OPTARG', + '_', 'HOME', 'PWD', 'OLDPWD', 'PIPESTATUS', 'DIRSTACK', 'GROUPS', + 'FUNCNAME', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME', +}) + +def _ordinary_parameter_default(statement): + """Recognize X=${Y:-literal}, ${Y-literal}, ${Y:=literal}, ${Y=literal}. + + Optional export and double quotes do not change the assignment semantics. + Both names must be ordinary variables, the nonempty fallback must be literal, + and no nested expansion/command substitution is allowed. Return every name + which can be assigned; their effective values remain unknown. Reading Y in + '-' variants does not erase an earlier known Y value; '=' variants may write + Y, so both Y and X lose any previously inferred constant. + """ + match = re.fullmatch( + r'(?:export\s+(?:--\s+)?)?([A-Za-z_][A-Za-z0-9_]*)=' + r'("?)\$\{([A-Za-z_][A-Za-z0-9_]*)(:?[-=])' + r'[A-Za-z0-9_./:+-]+\}\2', statement) + if not match: + return None + target, _, source, operator = match.groups() + if any(name in _DEFAULT_STATE_NAMES or + name.startswith(('BASH_', 'BASH_FUNC_', 'LD_', 'DYLD_')) + for name in (target, source)): + return None + return (target, source) if '=' in operator else (target,) + +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 + default_names = _ordinary_parameter_default(statement) + if default_names is not None: + for default_name in default_names: + constants.pop(default_name, None) + index += 1 + continue + statement = _expand_known_variables(statement, constants) + 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/d31ddb6d11deef56_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_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/d31ddb6d11deef56_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/d31ddb6d11deef56_q1/evaluator/repair_equivalences.py b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/repair_equivalences.py new file mode 100644 index 0000000000000000000000000000000000000000..4df26c2ffaf32ee54a18bcb00381e1aef3ec640d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/evaluator/repair_equivalences.py @@ -0,0 +1,240 @@ +"""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() +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'} + 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/d31ddb6d11deef56_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a4a2633c3cce091fede08d4c0c96835947ace7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/grading/verified_config.json @@ -0,0 +1,100 @@ +{ + "engine": "portable_verified_v1", + "grader_file_sha256": { + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "a1a80dfb4a0a220270ed06cc5b56f5de10545c496d3499a593afaa6cbf8b7d3d", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "ad9a68c999f2d69b8da5f09f353532d46d5038a22f0a67fbe0a8cb5c83badb36", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "6746a616cb27fda304fa7efeacbe1a49ab596a75b920079b2c7ca624d17dfab5", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70", + "repair_equivalences.py": "7af5aa61343c0582148d5c2d67b11606bc5afc92ce508e44298aeee3f90d17af" + }, + "query_id": "d31ddb6d11deef56_q1", + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "criterion_weights": { + "0": 1 + }, + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "grader_timeout_seconds": 600, + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ] + }, + "schema": "audited-verified-grader-v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e99326c1ef4717f722c3f4b50d4d0c2e1337d4e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/instruction.md @@ -0,0 +1 @@ +Our OpenClaw gateway host just went through its first hardening pass and I want a baseline maintenance script before we settle on an audit cadence. Please create output/baseline_healthcheck.sh that runs the baseline deep security audit and version check for the gateway, and also lists the existing scheduled cron jobs so we can review what periodic audits are already configured. Keep it a straight-line maintenance script: all commands at the top level, no conditionals or loops. It should be read-only in effect (just the baseline checks and the cron inventory). If any command fails, the script must stop immediately and exit with a nonzero status — don't continue past a failure or suppress it. diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/.skillfish.json b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/.skillfish.json new file mode 100644 index 0000000000000000000000000000000000000000..40b2f22df513d1f03f2de780778c728257963868 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/.skillfish.json @@ -0,0 +1,10 @@ +{ + "version": 2, + "name": "healthcheck", + "owner": "openclaw", + "repo": "openclaw", + "path": "skills/healthcheck", + "branch": "main", + "sha": "5582aa49acc8ad1fb5f89508c94705c806dbfcca", + "source": "manual" +} \ No newline at end of file diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..494c4d1b16e27645f79f5f76b2e9440f3f092ca5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/skill/SKILL.md @@ -0,0 +1,245 @@ +--- +name: healthcheck +description: Audit and harden hosts running OpenClaw for SSH, firewall, updates, exposure, cron checks, and risk posture. +--- + +# OpenClaw Host Hardening + +## Overview + +Assess and harden the host running OpenClaw, then align it to a user-defined risk tolerance without breaking access. Use OpenClaw security tooling as a first-class signal, but treat OS hardening as a separate, explicit set of steps. + +## Core rules + +- Recommend running this skill with a state-of-the-art model (e.g., Opus 4.5, GPT 5.2+). The agent should self-check the current model and suggest switching if below that level; do not block execution. +- Require explicit approval before any state-changing action. +- Do not modify remote access settings without confirming how the user connects. +- Prefer reversible, staged changes with a rollback plan. +- Never claim OpenClaw changes the host firewall, SSH, or OS updates; it does not. +- If role/identity is unknown, provide recommendations only. +- Formatting: every set of user choices must be numbered so the user can reply with a single digit. +- System-level backups are recommended; try to verify status. + +## Workflow (follow in order) + +### 0) Model self-check (non-blocking) + +Before starting, check the current model. If it is below state-of-the-art (e.g., Opus 4.5, GPT 5.2+), recommend switching. Do not block execution. + +### 1) Establish context (read-only) + +Try to infer 1–5 from the environment before asking. Prefer simple, non-technical questions if you need confirmation. + +Determine (in order): + +1. OS and version (Linux/macOS/Windows), container vs host. +2. Privilege level (root/admin vs user). +3. Access path (local console, SSH, RDP, tailnet). +4. Network exposure (public IP, reverse proxy, tunnel). +5. OpenClaw gateway status and bind address. +6. Backup system and status (e.g., Time Machine, system images, snapshots). +7. Deployment context (local mac app, headless gateway host, remote gateway, container/CI). +8. Disk encryption status (FileVault/LUKS/BitLocker). +9. OS automatic security updates status. + Note: these are not blocking items, but are highly recommended, especially if OpenClaw can access sensitive data. +10. Usage mode for a personal assistant with full access (local workstation vs headless/remote vs other). + +First ask once for permission to run read-only checks. If granted, run them by default and only ask questions for items you cannot infer or verify. Do not ask for information already visible in runtime or command output. Keep the permission ask as a single sentence, and list follow-up info needed as an unordered list (not numbered) unless you are presenting selectable choices. + +If you must ask, use non-technical prompts: + +- “Are you using a Mac, Windows PC, or Linux?” +- “Are you logged in directly on the machine, or connecting from another computer?” +- “Is this machine reachable from the public internet, or only on your home/network?” +- “Do you have backups enabled (e.g., Time Machine), and are they current?” +- “Is disk encryption turned on (FileVault/BitLocker/LUKS)?” +- “Are automatic security updates enabled?” +- “How do you use this machine?” + Examples: + - Personal machine shared with the assistant + - Dedicated local machine for the assistant + - Dedicated remote machine/server accessed remotely (always on) + - Something else? + +Only ask for the risk profile after system context is known. + +If the user grants read-only permission, run the OS-appropriate checks by default. If not, offer them (numbered). Examples: + +1. OS: `uname -a`, `sw_vers`, `cat /etc/os-release`. +2. Listening ports: + - Linux: `ss -ltnup` (or `ss -ltnp` if `-u` unsupported). + - macOS: `lsof -nP -iTCP -sTCP:LISTEN`. +3. Firewall status: + - Linux: `ufw status`, `firewall-cmd --state`, `nft list ruleset` (pick what is installed). + - macOS: `/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate` and `pfctl -s info`. +4. Backups (macOS): `tmutil status` (if Time Machine is used). + +### 2) Run OpenClaw security audits (read-only) + +As part of the default read-only checks, run `openclaw security audit --deep`. Only offer alternatives if the user requests them: + +1. `openclaw security audit` (faster, non-probing) +2. `openclaw security audit --json` (structured output) + +Offer to apply OpenClaw safe defaults (numbered): + +1. `openclaw security audit --fix` + +Be explicit that `--fix` only tightens OpenClaw defaults and file permissions. It does not change host firewall, SSH, or OS update policies. + +If browser control is enabled, recommend that 2FA be enabled on all important accounts, with hardware keys preferred and SMS not sufficient. + +### 3) Check OpenClaw version/update status (read-only) + +As part of the default read-only checks, run `openclaw update status`. + +Report the current channel and whether an update is available. + +### 4) Determine risk tolerance (after system context) + +Ask the user to pick or confirm a risk posture and any required open services/ports (numbered choices below). +Do not pigeonhole into fixed profiles; if the user prefers, capture requirements instead of choosing a profile. +Offer suggested profiles as optional defaults (numbered). Note that most users pick Home/Workstation Balanced: + +1. Home/Workstation Balanced (most common): firewall on with reasonable defaults, remote access restricted to LAN or tailnet. +2. VPS Hardened: deny-by-default inbound firewall, minimal open ports, key-only SSH, no root login, automatic security updates. +3. Developer Convenience: more local services allowed, explicit exposure warnings, still audited. +4. Custom: user-defined constraints (services, exposure, update cadence, access methods). + +### 5) Produce a remediation plan + +Provide a plan that includes: + +- Target profile +- Current posture summary +- Gaps vs target +- Step-by-step remediation with exact commands +- Access-preservation strategy and rollback +- Risks and potential lockout scenarios +- Least-privilege notes (e.g., avoid admin usage, tighten ownership/permissions where safe) +- Credential hygiene notes (location of OpenClaw creds, prefer disk encryption) + +Always show the plan before any changes. + +### 6) Offer execution options + +Offer one of these choices (numbered so users can reply with a single digit): + +1. Do it for me (guided, step-by-step approvals) +2. Show plan only +3. Fix only critical issues +4. Export commands for later + +### 7) Execute with confirmations + +For each step: + +- Show the exact command +- Explain impact and rollback +- Confirm access will remain available +- Stop on unexpected output and ask for guidance + +### 8) Verify and report + +Re-check: + +- Firewall status +- Listening ports +- Remote access still works +- OpenClaw security audit (re-run) + +Deliver a final posture report and note any deferred items. + +## Required confirmations (always) + +Require explicit approval for: + +- Firewall rule changes +- Opening/closing ports +- SSH/RDP configuration changes +- Installing/removing packages +- Enabling/disabling services +- User/group modifications +- Scheduling tasks or startup persistence +- Update policy changes +- Access to sensitive files or credentials + +If unsure, ask. + +## Periodic checks + +After OpenClaw install or first hardening pass, run at least one baseline audit and version check: + +- `openclaw security audit` +- `openclaw security audit --deep` +- `openclaw update status` + +Ongoing monitoring is recommended. Use the OpenClaw cron tool/CLI to schedule periodic audits (Gateway scheduler). Do not create scheduled tasks without explicit approval. Store outputs in a user-approved location and avoid secrets in logs. +When scheduling headless cron runs, include a note in the output that instructs the user to call `healthcheck` so issues can be fixed. + +### Required prompt to schedule (always) + +After any audit or hardening pass, explicitly offer scheduling and require a direct response. Use a short prompt like (numbered): + +1. “Do you want me to schedule periodic audits (e.g., daily/weekly) via `openclaw cron add`?” + +If the user says yes, ask for: + +- cadence (daily/weekly), preferred time window, and output location +- whether to also schedule `openclaw update status` + +Use a stable cron job name so updates are deterministic. Prefer exact names: + +- `healthcheck:security-audit` +- `healthcheck:update-status` + +Before creating, `openclaw cron list` and match on exact `name`. If found, `openclaw cron edit <id> ...`. +If not found, `openclaw cron add --name <name> ...`. + +Also offer a periodic version check so the user can decide when to update (numbered): + +1. `openclaw update status` (preferred for source checkouts and channels) +2. `npm view openclaw version` (published npm version) + +## OpenClaw command accuracy + +Use only supported commands and flags: + +- `openclaw security audit [--deep] [--fix] [--json]` +- `openclaw status` / `openclaw status --deep` +- `openclaw health --json` +- `openclaw update status` +- `openclaw cron add|list|runs|run` + +Do not invent CLI flags or imply OpenClaw enforces host firewall/SSH policies. + +## Logging and audit trail + +Record: + +- Gateway identity and role +- Plan ID and timestamp +- Approved steps and exact commands +- Exit codes and files modified (best effort) + +Redact secrets. Never log tokens or full credential contents. + +## Memory writes (conditional) + +Only write to memory files when the user explicitly opts in and the session is a private/local workspace +(per `docs/reference/templates/AGENTS.md`). Otherwise provide a redacted, paste-ready summary the user can +decide to save elsewhere. + +Follow the durable-memory prompt format used by OpenClaw compaction: + +- Write lasting notes to `memory/YYYY-MM-DD.md`. + +After each audit/hardening run, if opted-in, append a short, dated summary to `memory/YYYY-MM-DD.md` +(what was checked, key findings, actions taken, any scheduled cron jobs, key decisions, +and all commands executed). Append-only: never overwrite existing entries. +Redact sensitive host details (usernames, hostnames, IPs, serials, service names, tokens). +If there are durable preferences or decisions (risk posture, allowed ports, update policy), +also update `MEMORY.md` (long-term memory is optional and only used in private sessions). + +If the session cannot write to the workspace, ask for permission or provide exact entries +the user can paste into the memory files. diff --git a/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/task.json b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e1e1b24d6abd4ee7381bd601ab6795b9d88dcd3c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d31ddb6d11deef56_q1/task.json @@ -0,0 +1,49 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d31ddb6d11deef56", + "query_id": "d31ddb6d11deef56_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/baseline_healthcheck.sh" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "2f996bb134e4d3191ae3311a00e46821f36900939329f78c058267b758ece963", + "name": "healthcheck", + "package_path": "skill", + "install_name": "healthcheck-38add14f" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "2f996bb134e4d3191ae3311a00e46821f36900939329f78c058267b758ece963", + "files": { + ".skillfish.json": "8977282d72d6a30d3fc07aec705ec4c4e17df9d21b0576d326265048d2e9e20e", + "SKILL.md": "b719702f8e27de241dc738f240e173bd8cc403f7cab01a6b42086a6746f5d73b" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "38add14f1fa5914bacf065f63b780b1e813b3b2851edeed1d0735f5e1965ad67" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_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/d39a46c29e19038d_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d39a46c29e19038d_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..73010dcb3d7fb71f338bfc1817e393eda4dc2697 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/autograde_task_check.py @@ -0,0 +1,12 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import sys,json +from pathlib import Path +root=Path(__file__).resolve().parent +sys.path.insert(0,str(root/'legacy_tests')) +from evaluate import evaluate +t=json.loads((root/'legacy-task.json').read_text()) +mode=t['workspace']['candidate_mode'] +r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt') +if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False) +if r.get('status')!='scored':raise RuntimeError(json.dumps(r)) +print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy-task.json b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy-task.json new file mode 100644 index 0000000000000000000000000000000000000000..5281bed632fa5d60c57b826770c753d096b034a3 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy-task.json @@ -0,0 +1,101 @@ +{ + "schema_version": "mybench-portable-task-v2", + "task_id": "d39a46c29e19038d", + "query_id": "d39a46c29e19038d_q1", + "prompt": { + "path": "instruction.md", + "sha256": "81aceb7054fe3ecd13adff38282d3fada3bad8b7edf0bbe2fa4c9ee0ac22f0c4" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "b5d3f09eb4322d068ed3f4658977da6bc3cefeaac5548ff50b88a7f3c6bbd357", + "name": "training-check", + "package_path": "environment/skills/training-check-b5d3f09e", + "install_name": "training-check-b5d3f09e", + "archive_provenance": { + "archive_id": "logical-skill-03434db3eb00da72fc561147", + "archive_schema": "skill-release-v1", + "release_skill_id": "logical-skill-03434db3eb00da72fc561147", + "site": "skills-sh", + "local_path": "skills/03/logical-skill-03434db3eb00da72fc561147", + "skill_md_sha256": "b912cc10a6227211bdce83c51ed0ba2f6143b108e6b733daaeca809f59588654", + "release_payload_sha256": "b5d3f09eb4322d068ed3f4658977da6bc3cefeaac5548ff50b88a7f3c6bbd357", + "license": "MIT", + "license_status": "detected", + "canonical_source_id": "skills-sh:wanshuiyin/auto-claude-code-research-in-sleep/training-check" + }, + "omitted_entries": [] + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "ground_truth_skills": [ + "b5d3f09eb4322d068ed3f4658977da6bc3cefeaac5548ff50b88a7f3c6bbd357" + ], + "evaluation": { + "type": "verified", + "ground_truth_answer": { + "files": [ + { + "path": "output/codex_escalation.json", + "content": "{\n \"config\": {\n \"model_reasoning_effort\": \"xhigh\"\n },\n \"model\": \"gpt-5.6-sol\"\n}\n" + } + ] + }, + "verifier": { + "type": "workspace_objective", + "version": 15, + "output_mode": "workspace", + "reference_files": [ + { + "path": "output/codex_escalation.json", + "format": "json", + "content": "{\n \"config\": {\n \"model_reasoning_effort\": \"xhigh\"\n },\n \"model\": \"gpt-5.6-sol\"\n}\n" + } + ], + "checks": [ + { + "id": "workspace_file_set", + "type": "workspace_file_set", + "paths": [ + "output/codex_escalation.json" + ], + "roots": [ + "output" + ] + }, + { + "id": "file_001", + "type": "file_exists", + "path": "output/codex_escalation.json" + }, + { + "id": "json_001", + "type": "json_exact", + "path": "output/codex_escalation.json", + "expected": { + "model": "gpt-5.6-sol", + "config": { + "model_reasoning_effort": "xhigh" + } + } + } + ], + "self_test_passed": true + }, + "dependency_contract": { + "version": 2, + "mode": "core_answer", + "dependency_type": "project_configuration", + "requirement_ids": [ + "skill_a051", + "skill_a052" + ], + "forbid_meta_reference": true, + "forbid_answer_leakage": true + } + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/evaluate.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..6af62307e8c216b7733194602815f5004d893e06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/evaluate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Evaluate a candidate response for one portable MyBench task.""" + +import argparse +import json +import math +import os +import shlex +import subprocess +import sys +from pathlib import Path + + +def _load_verify(): + try: + from verifiers import verify + return verify + except ImportError: + project_src = Path(__file__).resolve().parents[1] / "src" + if project_src.is_dir(): + sys.path.insert(0, str(project_src)) + from verifiers import verify + return verify + raise + + +def _emit(result, output=None): + text = json.dumps(result, ensure_ascii=False) + print(text) + if output: + Path(output).write_text(text + "\n", encoding="utf-8") + + +def _judge_contract(judge): + if not isinstance(judge, dict): + return "Judge output must be a JSON object" + if type(judge.get("passed")) is not bool: + return "Judge field passed must be a JSON boolean" + for key in ("score", "max_score"): + value = judge.get(key, 100 if key == "max_score" else None) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"Judge field {key} must be a finite number" + if not math.isfinite(float(value)): + return f"Judge field {key} must be a finite number" + score = float(judge["score"]) + max_score = float(judge.get("max_score", 100)) + if max_score <= 0: + return "Judge field max_score must be greater than zero" + if score < 0 or score > 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/d39a46c29e19038d_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..9f9c41ce4b8f1e69585b64acbaea591e0d156f27 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1337 @@ +"""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 math +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 + + + +def _r10_unique_pairs(pairs): + result={} + for key,value in pairs: + if key in result:raise ValueError('duplicate JSON object key: '+key) + result[key]=value + return result + +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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"), object_pairs_hook=_r10_unique_pairs, parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x))) + passed = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/d39a46c29e19038d_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i<len(text): + ch=text[i] + if ch=='\\' and quote!="'" and i+1<len(text): + nxt=text[i+1] + if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__') + elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__') + else:out.extend((ch,nxt)) + i+=2;continue + if ch in "'\"": + if quote is None:quote=ch + elif quote==ch:quote=None + out.append(ch);i+=1;continue + if ch=='$': + if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue + m=variable.match(text,i) + if m: + value=constants.get(m.group(1)or m.group(2)) + if value is None:out.append(m.group(0)) + elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$')) + else:out.append(value) + i=m.end();continue + if ch=='~' and quote is not None: + out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue + out.append(ch);i+=1 + return ''.join(out) + +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 = _expand_known_variables(statement, constants) + 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/d39a46c29e19038d_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_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/d39a46c29e19038d_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/d39a46c29e19038d_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..3cdcaadec2fd8085d8b10e109560b86b9f50a3a8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d39a46c29e19038d_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "6655e32ed1926a0e3efaa153462937fad0ccaa8af9a0592f71bd3aae59e7134e", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "ca01231938f79d2c66c7a0ba8013bd215d79fe35850d10514fa740c38307b00b", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "workspace", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a841462f8440ca641c5d85d8867f35ed11ac5051 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/instruction.md @@ -0,0 +1,10 @@ +Our training health checker only escalates the Unsure cases — e.g. loss that looks flat but isn't clearly diverging, or metrics too noisy to call — to an external reviewer. I need to set up that reviewer call as a JSON config file. Please create output/codex_escalation.json following this repo's conventions for reviewer escalation configs, with exactly this shape and no extra keys: + +{ + "model": "<reviewer model>", + "config": { + "model_reasoning_effort": "<reasoning effort>" + } +} + +Fill in the model and reasoning effort values appropriate for this project's reviewer setup. Don't substitute a prose explanation for the file. For `output/codex_escalation.json`, use exactly this JSON shape: {"model":"string","config":{"model_reasoning_effort":"string"}}. The quoted type names are placeholders; replace each with its project-defined native JSON value of that type and add no other keys. diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..4f2039e073ce149be0bf5149d4fd239cacd8331c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/skill/SKILL.md @@ -0,0 +1,132 @@ +--- +name: training-check +description: Periodically check WandB metrics during training to catch problems early (NaN, loss divergence, idle GPUs). Avoids wasting GPU hours on broken runs. Use when training is running and you want automated health checks. +argument-hint: "[wandb-run-path]" +allowed-tools: Bash(*), Read, Grep, Glob, Write, Edit, mcp__codex__codex, mcp__codex__codex-reply +--- + +# Training Check + +Periodically read WandB metrics during training to catch problems early. Do not wait until training finishes to discover it was a waste of GPU time. + +> ⏱ This skill is **correctly** cron-wired (see below): it polls +> machine-checkable training health (NaN / divergence / idle GPU) — the additive +> external-wait shape in +> [`shared-references/external-cadence.md`](../shared-references/external-cadence.md). +> The occasional Codex call for an ambiguous metric is a **one-shot** check per +> tick, not a multi-round verdict loop, so it stays additive — it never grows +> into a wrapped verdict skill. + +## Context: $ARGUMENTS + +## Constants + +- WANDB_ENTITY and WANDB_PROJECT: read from CLAUDE.md or passed as argument (format: `entity/project/run_id`) +- CHECK_INTERVAL: starts at 10 minutes, then gradually increases if consistently healthy: 10 min → 20 min → 30 min → 60 min (cap) +- REVIEWER_MODEL = `gpt-5.6-sol` — used via Codex MCP for ambiguous cases only + +## When to Use + +- After training is confirmed running (session alive, loss decreasing for first few steps) +- Set up via CronCreate to fire periodically during training +- **This skill checks training QUALITY, not process HEALTH.** Process health (session alive, GPU utilization) is [watchdog.py](../../tools/watchdog.py)'s job. + +## Workflow + +### Step 1: Read WandB Metrics + +```python +import wandb +api = wandb.Api() +run = api.run("<entity>/<project>/<run_id>") +history = run.history() +``` + +If WandB is unreachable (API error, network issue), fall back to reading the log file directly via SSH: +```bash +ssh server "tail -100 /path/to/training.log" +``` + +Check these signals: +- **Loss trend**: Is training loss decreasing over the last N steps? +- **Eval metrics**: Are evaluation metrics improving (or at least not degrading)? +- **NaN / Inf**: Any NaN or Inf values in loss or gradients? +- **Spikes**: Sudden large jumps in loss (>10x normal variance)? +- **Learning rate**: Is the schedule behaving as expected? +- **Gradient norm**: Exploding or vanishing? + +### Step 2: Judgment + +| Signal | Judgment | Action | +|--------|----------|--------| +| NaN/Inf in loss | **Clearly bad** | Stop training, investigate | +| Loss diverging (increasing for >N steps) | **Clearly bad** | Stop training, investigate | +| Eval metrics significantly worse than baseline | **Clearly bad** | Stop training, investigate | +| Loss decreasing, metrics improving | **Clearly fine** | Continue, increase check interval | +| Loss flat but not diverging | **Unsure** | → Step 3 (Codex judgment) | +| Metrics noisy, can't tell trend | **Unsure** | → Step 3 (Codex judgment) | +| Slightly worse than baseline but still early | **Unsure** | → Step 3 (Codex judgment) | + +### Step 3: Codex Judgment (only when unsure) + +Only escalate to Codex when the signal is ambiguous. For clearly good or clearly bad signals, act directly. + +``` +mcp__codex__codex: + model: gpt-5.6-sol + config: {"model_reasoning_effort": "xhigh"} + prompt: | + TRAINING HEALTH CHECK — need your judgment on ambiguous metrics. + + Run: <entity>/<project>/<run_id> + Current epoch/step: X / Y total + Training loss (last 10 checkpoints): [values] + Eval metrics (last 3 evals): [values] + Baseline reference: [numbers from paper/reproduction] + + What I'm unsure about: [specific concern] + + Please respond with exactly one of: + - STOP: clearly problematic, should kill training + - CONTINUE: looks fine, check again next interval + - WAIT: not enough data to judge, check again sooner +``` + +### Step 4: Act + +| Decision | Action | +|----------|--------| +| **Stop** | Kill the training session. Save the WandB run URL, key metrics, and reason for stopping. Log to project notes for debugging. | +| **Continue** | Do nothing. Will be invoked again at next interval (increase interval if consistently healthy). | +| **Wait** | Do nothing but keep the current short interval (don't increase). | + +## Integration with Watchdog + +Training-check and [watchdog.py](../../tools/watchdog.py) operate at different levels: + +| Layer | Tool | What it checks | Frequency | +|-------|------|----------------|-----------| +| Process health | watchdog.py | Session alive? GPU active? | Every 60s (continuous) | +| Training quality | training-check | Loss trend? Metrics improving? | Every 10-60 min (periodic) | + +Use both together: +- Watchdog catches crashes and idle GPUs immediately +- Training-check catches subtle quality issues (loss plateau, metric degradation) + +## Rules + +- Do not stop training on first sign of noise — some loss spikes are normal. Look at **trends over multiple checkpoints**. +- When stopping training, always save the WandB run URL and key metrics as evidence. +- If both WandB and log files are unreachable, report the connectivity issue and try again next interval. Do not assume training is broken. +- Gradually increase check interval when healthy (10 → 20 → 30 → 60 min). Reset to 10 min after any anomaly. +- This skill is meant to be automated via CronCreate — do not ask the user whether to set it up. Just set it. + +## CronCreate Setup Example + +``` +After training is confirmed stable: + CronCreate (recurring, every 10 minutes initially): + "Run /training-check for wandb run <entity>/<project>/<run_id>" +``` + +As the check interval increases, delete the old CronCreate job and create a new one with the longer interval. diff --git a/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/task.json b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..90c25112b758fe29f2e1836fd1023e2bbbf655c9 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d39a46c29e19038d_q1/task.json @@ -0,0 +1,48 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d39a46c29e19038d", + "query_id": "d39a46c29e19038d_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [ + "output/codex_escalation.json" + ], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "0e4695422583ca0f8130476fd5d1ab0dbdb2a05808f7f153ccb847eabc8e2cb3", + "name": "training-check", + "package_path": "skill", + "install_name": "training-check-b5d3f09e" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "workspace" + }, + "source_skill": { + "sha256": "0e4695422583ca0f8130476fd5d1ab0dbdb2a05808f7f153ccb847eabc8e2cb3", + "files": { + "SKILL.md": "b912cc10a6227211bdce83c51ed0ba2f6143b108e6b733daaeca809f59588654" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "b5d3f09eb4322d068ed3f4658977da6bc3cefeaac5548ff50b88a7f3c6bbd357" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..cae2448b64c62dd8cddab9b29492acc3d49f4b7c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_contract.json @@ -0,0 +1,8 @@ +{ + "expected_check_ids": [ + "0" + ], + "criterion_weights": { + "0": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_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/d3b492c190ff2216_q1/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d3b492c190ff2216_q1/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..73010dcb3d7fb71f338bfc1817e393eda4dc2697 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/autograde_task_check.py @@ -0,0 +1,12 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import sys,json +from pathlib import Path +root=Path(__file__).resolve().parent +sys.path.insert(0,str(root/'legacy_tests')) +from evaluate import evaluate +t=json.loads((root/'legacy-task.json').read_text()) +mode=t['workspace']['candidate_mode'] +r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt') +if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False) +if r.get('status')!='scored':raise RuntimeError(json.dumps(r)) +print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy-task.json b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy-task.json new file mode 100644 index 0000000000000000000000000000000000000000..5285366bce144dc5aafaca25ff962bf98270efb6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy-task.json @@ -0,0 +1,105 @@ +{ + "schema_version": "mybench-portable-task-v2", + "task_id": "d3b492c190ff2216", + "query_id": "d3b492c190ff2216_q1", + "prompt": { + "path": "instruction.md", + "sha256": "73faa96b453d511cb4dae349a5f90ef5a11ccf7a203c46bca83a0b44be84bc20" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "0af7cc1813a426caff7efa00a9a6f8bea90ed94b9b65742be236d9ac47266810", + "name": "strategy-compare", + "package_path": "environment/skills/strategy-compare-0af7cc18", + "install_name": "strategy-compare-0af7cc18", + "archive_provenance": { + "archive_id": "logical-skill-0618a718dabb33198d3e2e57", + "archive_schema": "skill-release-v1", + "release_skill_id": "logical-skill-0618a718dabb33198d3e2e57", + "site": "skills-sh", + "local_path": "skills/06/logical-skill-0618a718dabb33198d3e2e57", + "skill_md_sha256": "38bf3c9d68e6e389484ed3d11f82d87ccbaff9308ae0d91961741644f1bdd50c", + "release_payload_sha256": "0af7cc1813a426caff7efa00a9a6f8bea90ed94b9b65742be236d9ac47266810", + "license": "none", + "license_status": "none", + "canonical_source_id": "skills-sh:marketcalls/vectorbt-backtesting-skills/strategy-compare" + }, + "omitted_entries": [] + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "ground_truth_skills": [ + "0af7cc1813a426caff7efa00a9a6f8bea90ed94b9b65742be236d9ac47266810" + ], + "evaluation": { + "type": "verified", + "ground_truth_answer": { + "answers": { + "q1": "0.00111", + "q2": "20" + } + }, + "verifier": { + "type": "atomic_json", + "version": 1, + "list_order": "ordered", + "float_tolerance": 0.01, + "completeness": { + "forbid_extra": true, + "shape": { + "type": "object", + "keys": { + "answers": { + "type": "object", + "keys": { + "q1": { + "type": "string" + }, + "q2": { + "type": "string" + } + } + } + } + } + }, + "assertions": [ + { + "id": "leaf_001", + "path": "$.answers.q1", + "tokens": [ + "answers", + "q1" + ], + "operator": "eq", + "expected": "0.00111" + }, + { + "id": "leaf_002", + "path": "$.answers.q2", + "tokens": [ + "answers", + "q2" + ], + "operator": "eq", + "expected": "20" + } + ], + "self_test_passed": true + }, + "dependency_contract": { + "version": 2, + "mode": "core_answer", + "dependency_type": "package_knowledge", + "requirement_ids": [ + "skill_a025" + ], + "forbid_meta_reference": true, + "forbid_answer_leakage": true + } + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/evaluate.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..6af62307e8c216b7733194602815f5004d893e06 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/evaluate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Evaluate a candidate response for one portable MyBench task.""" + +import argparse +import json +import math +import os +import shlex +import subprocess +import sys +from pathlib import Path + + +def _load_verify(): + try: + from verifiers import verify + return verify + except ImportError: + project_src = Path(__file__).resolve().parents[1] / "src" + if project_src.is_dir(): + sys.path.insert(0, str(project_src)) + from verifiers import verify + return verify + raise + + +def _emit(result, output=None): + text = json.dumps(result, ensure_ascii=False) + print(text) + if output: + Path(output).write_text(text + "\n", encoding="utf-8") + + +def _judge_contract(judge): + if not isinstance(judge, dict): + return "Judge output must be a JSON object" + if type(judge.get("passed")) is not bool: + return "Judge field passed must be a JSON boolean" + for key in ("score", "max_score"): + value = judge.get(key, 100 if key == "max_score" else None) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return f"Judge field {key} must be a finite number" + if not math.isfinite(float(value)): + return f"Judge field {key} must be a finite number" + score = float(judge["score"]) + max_score = float(judge.get("max_score", 100)) + if max_score <= 0: + return "Judge field max_score must be greater than zero" + if score < 0 or score > 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/d3b492c190ff2216_q1/evaluator/legacy_tests/objective_evaluators.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/objective_evaluators.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3bad880c48278be1ed5bd3fc84cc5214e90634 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/objective_evaluators.py @@ -0,0 +1,1329 @@ +"""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 math +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 _same_native_json_types(actual, expected): + if type(expected)is float: + return type(actual)in(int,float)and math.isfinite(actual) + if type(actual)is not type(expected):return False + if isinstance(expected,dict): + return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected) + if isinstance(expected,list): + return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected)) + if isinstance(actual,float):return math.isfinite(actual) + return True + +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 = (_same_native_json_types(actual, check.get("expected")) and + _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)) + if check.get("require_straight_line"): + passed = passed and _shell_is_straight_line(source) + 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) + if "allowed_commands" in check: + calls = shell_invocations(source) + allowed = check["allowed_commands"] + passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and + all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls)) + 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/d3b492c190ff2216_q1/evaluator/legacy_tests/shell_invocations.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/shell_invocations.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0221d237c1f7bc91355f053b7257e419ad5858 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/shell_invocations.py @@ -0,0 +1,265 @@ +"""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 _expand_known_variables(text, constants): + """Preserve quote/escape expansion semantics in the bounded shell grammar. + + Active unknown variables stay symbolic. A quoted/escaped literal dollar or + tilde has a separate token, so it cannot satisfy an expanding shell call. + This is parsing only; no shell command is evaluated. + """ + out,quote,i=[],None,0 + variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)') + while i<len(text): + ch=text[i] + if ch=='\\' and quote!="'" and i+1<len(text): + nxt=text[i+1] + if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__') + elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__') + else:out.extend((ch,nxt)) + i+=2;continue + if ch in "'\"": + if quote is None:quote=ch + elif quote==ch:quote=None + out.append(ch);i+=1;continue + if ch=='$': + if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue + m=variable.match(text,i) + if m: + value=constants.get(m.group(1)or m.group(2)) + if value is None:out.append(m.group(0)) + elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$')) + else:out.append(value) + i=m.end();continue + if ch=='~' and quote is not None: + out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue + out.append(ch);i+=1 + return ''.join(out) + +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 = _expand_known_variables(statement, constants) + 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/d3b492c190ff2216_q1/evaluator/legacy_tests/test.sh b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9456b50378732ef42842ccf150839d0aa8b9b31f --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_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/d3b492c190ff2216_q1/evaluator/legacy_tests/verifiers.py b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/verifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c2dda9005abedd83fb90cef8f99a3cea8f0655 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/evaluator/legacy_tests/verifiers.py @@ -0,0 +1,544 @@ +"""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 math +import posixpath +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] + return json.loads(text) + + + +def _strict_json_value(value): + """Atomic answer contract: one complete JSON value, no extra prose/keys.""" + def unique(pairs): + d={} + for k,v in pairs: + if k in d:raise ValueError('duplicate JSON key: '+k) + d[k]=v + return d + def invalid(s):raise ValueError('non-finite JSON number: '+s) + result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid) + if isinstance(value,str) else value) + def finite(v): + if isinstance(v,dict):return all(finite(x)for x in v.values()) + if isinstance(v,list):return all(finite(x)for x in v) + return not isinstance(v,float)or math.isfinite(v) + if not finite(result):raise ValueError('non-finite JSON number') + return result + +def _path_equal(actual, expected): + if not isinstance(actual,str)or not isinstance(expected,str):return False + # A trailing slash is not a harmless spelling for a named file. + suffix=posixpath.splitext(expected.rstrip('/'))[1] + if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False + return _path_value(actual)==_path_value(expected) + +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("\\", "/") + text = posixpath.normpath(text) if text else text + 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": + pred = _atomic_prepare(_strict_json_value(solver_output), + verifier.get("list_order", "ordered")) + 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"], _atomic_shape(pred)) + 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_equal(actual, 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/d3b492c190ff2216_q1/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..2ebb50d6dec3a40eeb97e7d39b8c29b920c136e1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/grading/verified_config.json @@ -0,0 +1,99 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d3b492c190ff2216_q1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "legacy-task.json": "2d0f898b6bdc887e83eb2fa0e58d3c26cb8720d94c989b2618a51a02aeed2c65", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37", + "legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089", + "legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1", + "legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a", + "legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc", + "legacy_tests/verifiers.py": "170f6c86b91adfb8c10f0f1833ed5219d814b8723ee0e605327c31fdbf64fb70" + }, + "runtime_requirements": { + "candidate_mode": "response", + "candidate_snapshot_copy_to_ephemeral_app": true, + "container_private_entry": "/grader/check.py", + "environment": { + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_ANSWER": "/answer.txt", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1", + "MYBENCH_RUN_METADATA": "/run_metadata.json", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source" + }, + "expected_check_ids": [ + "0" + ], + "external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer", + "external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored", + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "image_included": false, + "legacy_adapter": true, + "mounts_readonly": [ + "/candidate", + "/source", + "/grader", + "/answer.txt" + ], + "network": "none", + "original_declared_resources": { + "agent": { + "basis": "advisory_not_measured", + "cpus": 2, + "memory_mib": 4096, + "timeout_sec": 1200 + }, + "oracle": { + "timeout_sec": 120 + }, + "source_agent": { + "command_timeout_sec": null, + "max_steps": null + }, + "verifier": { + "cpus": 1, + "memory_mib": 1024, + "pids": 64, + "timeout_sec": 900, + "tmpfs_mib": 128 + } + }, + "private_entry": "evaluator/check.py", + "private_tree_environment_tokens": [ + "MYBENCH_CANDIDATE_FILE", + "MYBENCH_OPEN_JUDGE_COMMAND", + "MYBENCH_OPEN_JUDGE_TIMEOUT", + "MYBENCH_TASK_JSON" + ], + "trusted_trace_environment_aliases": [ + "MYBENCH_TOOL_TRAJECTORY", + "MYBENCH_TRUSTED_TRACE", + "TOOL_TRAJECTORY", + "TOOL_TRAJECTORY_FILE" + ], + "trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256", + "working_directory": "/candidate", + "writable_ephemeral_roots": [ + "/app", + "/workspace", + "/tmp" + ], + "criterion_weights": { + "0": 1 + }, + "grader_timeout_seconds": 600, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "portable_verified_v1" +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/instruction.md b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b05168b08cb987d1572c98db5258eec504b6edd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/instruction.md @@ -0,0 +1 @@ +We're setting up VectorBT backtests for Indian equity delivery trades and need to lock in the project's mandated fee settings so all our results stay consistent. Two questions: what value must the fees rate parameter be set to for Indian delivery equity backtests, and what value must the fixed_fees parameter be set to? Please answer with exactly one JSON object matching {"answers":{"q1":"string","q2":"string"}}, replacing each placeholder with the bare project-defined scalar value for that item. diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..e4a17dd501189fef9c8f5fa6f925e856a0829520 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/skill/SKILL.md @@ -0,0 +1,45 @@ +--- +name: strategy-compare +description: Compare multiple strategies or directions (long vs short vs both) on the same symbol. Generates side-by-side stats table. +argument-hint: "[symbol] [strategies...]" +allowed-tools: Read, Write, Edit, Bash, Glob, Grep +--- + +Create a strategy comparison script. + +## Arguments + +Parse `$ARGUMENTS` as: symbol followed by strategy names + +- `$0` = symbol (e.g., SBIN, RELIANCE, NIFTY) +- Remaining args = strategies to compare (e.g., ema-crossover rsi donchian) + +If only a symbol is given with no strategies, compare: ema-crossover, rsi, donchian, supertrend. +If "long-vs-short" is one of the strategies, compare longonly vs shortonly vs both for the first real strategy. + +## Instructions + +1. Read the vectorbt-expert skill rules for reference patterns +2. Create `backtesting/strategy_comparison/` directory if it doesn't exist (on-demand) +3. Create a `.py` file in `backtesting/strategy_comparison/` named `{symbol}_strategy_comparison.py` +3. The script must: + - Fetch data once via OpenAlgo + - If user provides a DuckDB path, load data directly via `duckdb.connect(path, read_only=True)`. See vectorbt-expert `rules/duckdb-data.md`. + - If `openalgo.ta` is not importable (standalone DuckDB), use inline `exrem()` fallback. + - **Use OpenAlgo ta for ALL indicators by default** (never VectorBT built-in). Only switch to TA-Lib if the user explicitly says "talib"/"TA-Lib" + - **Always use OpenAlgo ta** for specialty indicators (Supertrend, Donchian, etc.) - no TA-Lib equivalent exists + - Clean signals with `ta.exrem()` (always `.fillna(False)` before exrem) + - Run each strategy on the same data + - **Indian delivery fees**: `fees=0.00111, fixed_fees=20` for delivery equity + - Collect key metrics from each into a side-by-side DataFrame + - **Include NIFTY benchmark** in the comparison table (via OpenAlgo `NSE_INDEX`) + - **Print Strategy vs Benchmark comparison table**: Total Return, Sharpe, Sortino, Max DD, Win Rate, Trades, Profit Factor + - **Explain results** in plain language - which strategy performed best and why + - Plot overlaid equity curves for all strategies using Plotly (`template="plotly_dark"`) + - Save comparison to CSV +4. Never use icons/emojis in code or logger output + +## Example Usage + +`/strategy-compare RELIANCE ema-crossover rsi donchian` +`/strategy-compare SBIN long-vs-short ema-crossover` diff --git a/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/task.json b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/task.json new file mode 100644 index 0000000000000000000000000000000000000000..88218e63ba9903a137f91c2477f04edd02728052 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3b492c190ff2216_q1/task.json @@ -0,0 +1,46 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d3b492c190ff2216", + "query_id": "d3b492c190ff2216_q1", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "outputs": [], + "success_criteria": [ + "Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "workspace": { + "input_mappings": [], + "skill_packages": [ + { + "content_hash": "9b8f8252260564f2a436cce3bae4e19532d67c60d5e52b93a03bbfb155a1aeb1", + "name": "strategy-compare", + "package_path": "skill", + "install_name": "strategy-compare-0af7cc18" + } + ], + "default_skill_target": ".claude/skills", + "candidate_mode": "response" + }, + "source_skill": { + "sha256": "9b8f8252260564f2a436cce3bae4e19532d67c60d5e52b93a03bbfb155a1aeb1", + "files": { + "SKILL.md": "38bf3c9d68e6e389484ed3d11f82d87ccbaff9308ae0d91961741644f1bdd50c" + } + }, + "migration": { + "source_schema": "mybench-portable-task-v2", + "legacy_task_json": "provenance/legacy-package/task.json", + "historical_gain_protocol": "legacy; not Harbor certified", + "reference_available": true, + "skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task", + "original_skill_content_hashes": [ + "0af7cc1813a426caff7efa00a9a6f8bea90ed94b9b65742be236d9ac47266810" + ] + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..3ed04aa38181e433e1551f63c886feb57f2b613c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_contract.json @@ -0,0 +1,18 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/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/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..a84f00994e1ed87e6407bae462ceedf6daf382f1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "5" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e868c6627e8aa27a74eaa2b3d4f6985c16b84f56 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/autograde_task_check.py @@ -0,0 +1,172 @@ +from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json, os, re, shutil, subprocess, sys, tempfile +from dependency_scan import scan_stdlib + +CONFIGS = { + "team.json": {"team_name":"review-auth-flow","agent_type":"claude","workers":3,"task":"review the auth module for security issues","panes":{"worker-1":"review-auth-flow:0.0","worker-2":"review-auth-flow:0.1","worker-3":"review-auth-flow:0.2"}}, + "experimental.json": {"team_name":"ui-redesign","agent_type":"expert","workers":12,"task":"redesign UI components","panes":{}} +} +PANES = { + "worker-1.txt": " \n \u273b Cascading\u2026 (5m 34s \u00b7 \u2193 3.0k tokens \u00b7 thinking)\n \n \u23fa Read(src/auth/session.py)\n \u23bf Read 84 lines\n \u23fa Grep(pattern=\"password\", path=\"src/auth\")\n \u23bf 12 matches\n \n \u273b Verifying\u2026 (1m 02s \u00b7 \u2193 0.4k tokens \u00b7 thinking)\n \n \u2776\n", + "worker-2.txt": " \u23fa Write(tests/auth/test_session.py)\n \u23bf Wrote 42 lines\n \u23fa Bash(pytest tests/auth -q)\n \u23bf 12 passed in 1.3s\n \n Baked for 3m 12s\n \u2776\n", + "worker-3.txt": " \u23fa Edit(src/auth/token.py)\n \u23bf Edited 1 line\n \n Running\u2026 timeout 300s\n \n \u2776\n" +} +STATUS = { + "worker-1.json": {"state":"BUSY","seconds_since_update":45}, + "worker-2.json": {"state":"IDLE","seconds_since_update":600}, + "worker-3.json": {"state":"BUSY","seconds_since_update":310} +} +EXPECTED_PANES = {"worker-1":"review-auth-flow:0.0","worker-2":"review-auth-flow:0.1","worker-3":"review-auth-flow:0.2"} +EXPECTED_STATES = {"worker-1":"WORKING","worker-2":"COMPLETED","worker-3":"WORKING"} +NUDGE_MSG = "Nudge: check worker status files and resume stalled work." + +def setup(tmp): + os.makedirs(os.path.join(tmp,"configs")) + os.makedirs(os.path.join(tmp,"panes")) + os.makedirs(os.path.join(tmp,"status")) + for n,c in CONFIGS.items(): + open(os.path.join(tmp,"configs",n),"w").write(json.dumps(c)) + for n,t in PANES.items(): + open(os.path.join(tmp,"panes",n),"w").write(t) + for n,s in STATUS.items(): + open(os.path.join(tmp,"status",n),"w").write(json.dumps(s)) + + +import ast, shlex +from pathlib import Path + +CANDIDATE=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate')) + +def commands_valid(commands,pane): + if not isinstance(commands,list) or len(commands)!=3 or not all(isinstance(s,str) for s in commands): return False + try: args=[shlex.split(s) for s in commands] + except ValueError: return False + first=['tmux','send-keys','-t',pane,'-l','--',NUDGE_MSG] + last=['tmux','send-keys','-t',pane,'Enter'] + return args[0]==first and args[2]==last and len(args[1])==2 and args[1][0]=='sleep' and bool(re.fullmatch(r'(?:0?\.10*|0\.1)',args[1][1])) + +def inspect_report(report,stdout=None): + checks=[] + def add(i,ok,why):checks.append({'id':str(i),'passed':bool(ok),'reason':why}) + if not isinstance(report,dict): + return [{'id':str(i),'passed':False,'reason':'report.json missing or malformed'} for i in range(5)] + add(0,all(k in report for k in ('config_validation','workers','nudges')),'required report sections') + cv=report.get('config_validation');valid=isinstance(cv,dict) and set(cv)==set(CONFIGS) + if valid: + for filename,config in CONFIGS.items(): + errors=cv[filename] + if not isinstance(errors,list) or not all(isinstance(e,str) and e.strip() for e in errors):valid=False;continue + expected=[] + if config.get('agent_type')not in {'claude','codex','gemini'}:expected.append('AGENT_TYPE') + workers=config.get('workers') + if type(workers)is not int or not 1<=workers<=10:expected.append('WORKERS') + for key in ('team_name','task'): + if not isinstance(config.get(key),str)or not config[key].strip():expected.append(key.upper()) + valid=valid and errors==expected + add(1,valid,'all independently invalid config fields must be identified') + workers=report.get('workers');valid=isinstance(workers,list) and len(workers)==len(EXPECTED_STATES) + if valid: + names=[w.get('name') if isinstance(w,dict) else None for w in workers] + valid=all(isinstance(n,str) for n in names) and len(set(names))==len(EXPECTED_STATES) and set(names)==set(EXPECTED_STATES) + for w in workers: + if not isinstance(w,dict):valid=False;continue + n=w.get('name');ev=w.get('evidence');state=w.get('state') + source=PANES.get(str(n)+'.txt','') + actual=isinstance(ev,str)and(ev==''if state=='UNKNOWN'else ev.strip()in[l.strip()for l in source.splitlines()if l.strip()]) + support=False + if actual: + if state=='UNKNOWN':support=ev=='' + elif state=='WORKING':support=bool(re.search(r'[✻✶✳✽✾]\s*[A-Za-z]+[^\n]*\([^)]*\d+(?:m|s)|Running…',ev)) or pending_tool_evidence(ev,source) + elif state=='COMPLETED':support=bool(re.search(r'Baked for|Sautéed for',ev)) + elif state=='QUEUED':support='Press up to edit queued messages' in ev + elif state=='IDLE':support='❯' in ev + valid=valid and n in EXPECTED_STATES and state==EXPECTED_STATES.get(n) and w.get('pane')==EXPECTED_PANES.get(n) and actual and support + add(2,valid,'unique workers with correct panes, states and actual supporting evidence lines') + wanted={EXPECTED_PANES[name]for name in EXPECTED_STATES if STATUS.get(name+'.json',{}).get('state')=='BUSY'and STATUS[name+'.json'].get('seconds_since_update',0)>120} + nudges=report.get('nudges');valid=isinstance(nudges,list)and len(nudges)==len(wanted)and all(isinstance(x,dict)for x in nudges) + actual=[x.get('pane')for x in nudges]if valid else[] + valid=valid and all(isinstance(pane,str) for pane in actual) and len(set(actual))==len(actual)and set(actual)==wanted + add(3,valid,'exact independent BUSY and age>120 target set') + add(4,valid and all(commands_valid(x.get('commands'),x.get('pane'))for x in nudges),'each actual stalled pane receives literal message/sleep/separate Enter in order') + return checks + +def stdlib_only(path): + ok,modules,why=scan_stdlib(CANDIDATE,[str(path.relative_to(CANDIDATE))]) + return None if why.startswith('unknown:')else ok + +def pending_tool_evidence(evidence,source): + prefixes=('Bash(','Read(','Edit(','Write(','Grep(','Glob(') + lines=source.splitlines() + for index,line in enumerate(lines): + if line.strip()!=evidence.strip() or not any(p in line for p in prefixes):continue + complete=False + for following in lines[index+1:]: + if any(p in following for p in prefixes):break + if '⎿' in following:complete=True;break + if not complete:return True + return False + +def load_report(path): + try:return _co_loads(_co_text(path)) + except Exception:return None + +def run(): + scripts=[CANDIDATE/'monitor_team.py'] if (CANDIDATE/'monitor_team.py').is_file() else list(CANDIDATE.rglob('monitor_team.py')) + if len(scripts)!=1: + print(json.dumps({'scoreable':True,'checks':[{'id':str(i),'passed':False,'reason':'required monitor_team.py missing or ambiguous'}for i in range(6)]}));return + script=scripts[0];checks=[];stdout='';rc=None;error='' + with tempfile.TemporaryDirectory(prefix='monitor-grader-') as temp: + shutil.copytree(CANDIDATE,temp,dirs_exist_ok=True,symlinks=True,ignore=shutil.ignore_patterns('configs','panes','status','report.json','__pycache__')) + setup(temp) + for source in CANDIDATE.rglob('*.py'): + dest=Path(temp)/source.relative_to(CANDIDATE);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy(source,dest) + shutil.copy(script,os.path.join(temp,'monitor_team.py')) + try: + p=subprocess.run([sys.executable,'-B','-S','monitor_team.py'],cwd=temp,capture_output=True,text=True,timeout=60) + rc=p.returncode;stdout=p.stdout;error=p.stderr[-1000:] + except (OSError,subprocess.SubprocessError) as e:raise RuntimeError('Trusted monitor candidate launcher failed') from e + checks=inspect_report(load_report(Path(temp)/'report.json')) + lines=[l.strip() for l in stdout.splitlines()] + summary=all(len([l for l in lines if re.match(re.escape(n)+r':',l)]) == 1 and any(re.match(re.escape(n)+r':\s*'+state+r'\b',l) for l in lines) for n,state in EXPECTED_STATES.items()) + dep=stdlib_only(script) + checks.append({'id':'5','passed':False if rc!=0 or not summary or dep is False else None if dep is None else True,'reason':'successful stdlib execution and per-worker summaries; '+error}) + print(json.dumps({'checks':checks})) + + +import contextlib as _rv_contextlib,io as _rv_io +_rv_original_main=run +_rv_variants=["_rv_is_variant=True;PANES['worker-1.txt']='Press up to edit queued messages\\n❯\\n';PANES['worker-2.txt']='❯\\n';EXPECTED_STATES.update({'worker-1':'QUEUED','worker-2':'IDLE'});CONFIGS['missing-fields.json']={'agent_type':'claude','workers':1,'team_name':' ','task':'','panes':{}}", '_rv_is_variant=True;CONFIGS={\'team.json\': {\'team_name\': \'review-auth-flow\', \'agent_type\': \'claude\', \'workers\': 3, \'task\': \'review the auth module for security issues\', \'panes\': {\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'}}, \'experimental.json\': {\'team_name\': \'ui-redesign\', \'agent_type\': \'expert\', \'workers\': 12, \'task\': \'redesign UI components\', \'panes\': {}}};PANES={\'alpha.txt\': \' \\n ✻ Cascading… (5m 34s · ↓ 3.0k tokens · thinking)\\n \\n ⏺ Read(src/auth/session.py)\\n ⎿ Read 84 lines\\n ⏺ Grep(pattern="password", path="src/auth")\\n ⎿ 12 matches\\n \\n ✻ Verifying… (1m 02s · ↓ 0.4k tokens · thinking)\\n \\n ❶\\n\', \'beta.txt\': \' ⏺ Write(tests/auth/test_session.py)\\n ⎿ Wrote 42 lines\\n ⏺ Bash(pytest tests/auth -q)\\n ⎿ 12 passed in 1.3s\\n \\n Baked for 3m 12s\\n ❶\\n\', \'gamma.txt\': \' ⏺ Edit(src/auth/token.py)\\n ⎿ Edited 1 line\\n \\n Running… timeout 300s\\n \\n ❶\\n\'};STATUS={\'alpha.json\': {\'state\': \'BUSY\', \'seconds_since_update\': 120}, \'beta.json\': {\'state\': \'BUSY\', \'seconds_since_update\': 121}, \'gamma.json\': {\'state\': \'IDLE\', \'seconds_since_update\': 999}};EXPECTED_PANES={\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'};EXPECTED_STATES={\'alpha\': \'WORKING\', \'beta\': \'COMPLETED\', \'gamma\': \'WORKING\'}', '_rv_is_variant=True;CONFIGS={\'team.json\': {\'team_name\': \'review-auth-flow\', \'agent_type\': \'claude\', \'workers\': 3, \'task\': \'review the auth module for security issues\', \'panes\': {\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'}}, \'experimental.json\': {\'team_name\': \'ui-redesign\', \'agent_type\': \'expert\', \'workers\': 12, \'task\': \'redesign UI components\', \'panes\': {}}};PANES={\'alpha.txt\': \' \\n ✻ Cascading… (5m 34s · ↓ 3.0k tokens · thinking)\\n \\n ⏺ Read(src/auth/session.py)\\n ⎿ Read 84 lines\\n ⏺ Grep(pattern="password", path="src/auth")\\n ⎿ 12 matches\\n \\n ✻ Verifying… (1m 02s · ↓ 0.4k tokens · thinking)\\n \\n ❶\\n\', \'beta.txt\': \' ⏺ Write(tests/auth/test_session.py)\\n ⎿ Wrote 42 lines\\n ⏺ Bash(pytest tests/auth -q)\\n ⎿ 12 passed in 1.3s\\n \\n Baked for 3m 12s\\n ❶\\n\', \'gamma.txt\': \' ⏺ Edit(src/auth/token.py)\\n ⎿ Edited 1 line\\n \\n Running… timeout 300s\\n \\n ❶\\n\'};STATUS={\'alpha.json\': {\'state\': \'BUSY\', \'seconds_since_update\': 121}, \'beta.json\': {\'state\': \'BUSY\', \'seconds_since_update\': 120}, \'gamma.json\': {\'state\': \'BUSY\', \'seconds_since_update\': 121}};EXPECTED_PANES={\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'};EXPECTED_STATES={\'alpha\': \'WORKING\', \'beta\': \'COMPLETED\', \'gamma\': \'WORKING\'}', '_rv_is_variant=True;CONFIGS={\'team.json\': {\'team_name\': \'review-auth-flow\', \'agent_type\': \'claude\', \'workers\': 3, \'task\': \'review the auth module for security issues\', \'panes\': {\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'}}, \'experimental.json\': {\'team_name\': \'ui-redesign\', \'agent_type\': \'expert\', \'workers\': 12, \'task\': \'redesign UI components\', \'panes\': {}}};PANES={\'alpha.txt\': \' \\n ✻ Cascading… (5m 34s · ↓ 3.0k tokens · thinking)\\n \\n ⏺ Read(src/auth/session.py)\\n ⎿ Read 84 lines\\n ⏺ Grep(pattern="password", path="src/auth")\\n ⎿ 12 matches\\n \\n ✻ Verifying… (1m 02s · ↓ 0.4k tokens · thinking)\\n \\n ❶\\n\', \'beta.txt\': \' ⏺ Write(tests/auth/test_session.py)\\n ⎿ Wrote 42 lines\\n ⏺ Bash(pytest tests/auth -q)\\n ⎿ 12 passed in 1.3s\\n \\n Baked for 3m 12s\\n ❶\\n\', \'gamma.txt\': \' ⏺ Edit(src/auth/token.py)\\n ⎿ Edited 1 line\\n \\n Running… timeout 300s\\n \\n ❶\\n\'};STATUS={\'alpha.json\': {\'state\': \'IDLE\', \'seconds_since_update\': 999}, \'beta.json\': {\'state\': \'IDLE\', \'seconds_since_update\': 121}, \'gamma.json\': {\'state\': \'IDLE\', \'seconds_since_update\': 999}};EXPECTED_PANES={\'alpha\': \'new-session:2.4\', \'beta\': \'new-session:2.5\', \'gamma\': \'new-session:2.6\'};EXPECTED_STATES={\'alpha\': \'WORKING\', \'beta\': \'COMPLETED\', \'gamma\': \'WORKING\'}'] +_rv_owners=[['1', '2', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']] +# Independent pending-call evidence and configuration type/range boundaries. +_rv_variants.append("_rv_is_variant=True;PANES={name+'.txt':'❯\\n ⏺ Bash(sleep 60)\\n' for name in EXPECTED_PANES};EXPECTED_STATES={name:'WORKING' for name in EXPECTED_PANES}") +_rv_owners.append(['2','5']) +_rv_variants.append("_rv_is_variant=True;CONFIGS.update({'bad-bool.json':{'agent_type':'codex','workers':True,'team_name':'t','task':'x','panes':{}},'bad-zero.json':{'agent_type':'gemini','workers':0,'team_name':'t','task':'x','panes':{}},'codex-ten.json':{'agent_type':'codex','workers':10,'team_name':'t','task':'x','panes':{}},'gemini-one.json':{'agent_type':'gemini','workers':1,'team_name':'t','task':'x','panes':{}}})") +_rv_owners.append(['1','5']) +_rv_variants.append("_rv_is_variant=True;PANES={name+'.txt':'No recognized activity in this capture\\n' for name in EXPECTED_PANES};EXPECTED_STATES={name:'UNKNOWN' for name in EXPECTED_PANES}") +_rv_owners.append(['2','5']) +# R2: worker cardinality comes from the config, not the original three-worker fixture. +for _r2_count in (1, 4): + _r2_names = ['member-'+str(i) for i in range(_r2_count)] + _r2_panes = {n:'varied-team:0.'+str(i) for i,n in enumerate(_r2_names)} + _r2_config = {'team.json':{'team_name':'varied-team','agent_type':'claude','workers':_r2_count,'task':'review varied team','panes':_r2_panes}} + _rv_variants.append('_rv_is_variant=True;CONFIGS='+repr(_r2_config)+';EXPECTED_PANES='+repr(_r2_panes)+';EXPECTED_STATES='+repr({n:'IDLE' for n in _r2_names})+';PANES='+repr({n+'.txt':'❯\n' for n in _r2_names})+';STATUS='+repr({n+'.json':{'state':'IDLE','seconds_since_update':0} for n in _r2_names})) + _rv_owners.append(['0','1','2','3','4','5']) +def _rv_capture(): + buffer=_rv_io.StringIO() + with _rv_contextlib.redirect_stdout(buffer):_rv_original_main() + return json.loads(buffer.getvalue().strip().splitlines()[-1]) +def _rv_run(): + base=_rv_capture();by={str(c['id']):c for c in base['checks']} + for index,setup in enumerate(_rv_variants): + exec(setup,globals()) + value=_rv_capture() + for c in value['checks']: + key=str(c['id']) + if _rv_owners is None or key in _rv_owners[index]: + by[key]['passed']=False if by[key]['passed'] is False or c['passed'] is False else None if by[key]['passed'] is None or c['passed'] is None else True + if not c['passed']:by[key]['reason']+='; changed public input panel '+str(index)+': '+c.get('reason','failed') + base['scoreable']=all(c.get('passed') is not None for c in base['checks']) + print(json.dumps(base,ensure_ascii=False)) +try:_rv_run() +except Exception as error:print(json.dumps({'scoreable':False,'checks':[dict(id=str(i),passed=None,reason='unresolved grader observation: '+type(error).__name__)for i in range(6)]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/candidate_artifacts.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/candidate_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..01d155d66962e3f1c41443cad117a48e6ca25bc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/candidate_artifacts.py @@ -0,0 +1,24 @@ +"""Read only ordinary candidate artifacts after a bounded child completes. +No launch/setup/monitor exceptions are caught here. Symlinks to regular files +remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from +blocking the trusted grader. Malformed text/JSON is an absent invalid value. +""" +import json, os, stat + +def read_text(path, encoding=None, errors=None): + fd=None + try: + fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode):return '' + with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream: + fd=None + return stream.read() + except (OSError,UnicodeError):return '' + finally: + if fd is not None:os.close(fd) + +def loads(text, **kwargs): + try:return json.loads(text,**kwargs) + except (ValueError,TypeError,RecursionError):return None + +def load(path, **kwargs):return loads(read_text(path),**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..a8371f353ad4817102528b7e851c80fe763d4457 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/grading/verified_config.json @@ -0,0 +1,129 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d3cdbad82b42ceaf3187f97c", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "9ebe9f6e50e4aeebaa50167411c4288dee2e01291120b019137f2c56d198e160", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "34973c86b5e6826e6e14dd914cbb3d5b9712085618672584870a12d10ffe193a", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002" + }, + "runtime_requirements": { + "family": "verified_multi10_public_contract", + "container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "read_only_mounts": [ + "task:/source", + "task:/task", + "evaluator:/grader", + "candidate:/candidate", + "answer:/answer.txt" + ], + "writable_tmpfs": [ + "/app", + "/workspace", + "/tmp" + ], + "copy_completed_candidate_children_to_app_before_grader": true, + "entrypoint": [ + "python3", + "/grader/check.py" + ], + "working_directory": "/candidate", + "environment": { + "MYBENCH_CANDIDATE": "/candidate", + "MYBENCH_CANDIDATE_PATH": "/candidate", + "CANDIDATE_DIR": "/candidate", + "CANDIDATE_ROOT": "/candidate", + "MYBENCH_SOURCE_TASK": "/source", + "SOURCE_TASK_DIR": "/source", + "MYBENCH_ANSWER_FILE": "/answer.txt", + "MYBENCH_EPHEMERAL_APP": "1", + "MYBENCH_EPHEMERAL_WORKSPACE": "1" + }, + "environment_names_detected": [ + "MYBENCH_CANDIDATE" + ], + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_count": 6, + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1 + }, + "actual_original_success_criteria_count": 6, + "original_task_metadata_must_not_define_override_criterion_count": false, + "requires_external_actual_native_trace": false, + "requires_external_trusted_snapshot_binding": false, + "fresh_native_binding_must_not_require_historical_run_id": true, + "checker_can_execute_candidate_subprocesses": true, + "host_execution_forbidden": true, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair.", + "docker_image_payload_in_source_tree": false, + "runtime_missing": [], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "grader_timeout_seconds": 600 + }, + "engine": "portable_verified_v1", + "retired_semantic_criterion_adapter": { + "schema": "semantic-adapter-inlined-v2", + "original_semantic_criterion_adapter": { + "schema": "semantic-fixed-panel-v1", + "adapter_sha256": "4e966ab2ef58591fe3cca2b243db7b162882b94f53fd41eacc7a60b543e8a7dd", + "policy_sha256": "313398696b79abba944ec7b5443e258b734862f4104ab92f790d7255a048b5d9", + "groups": { + "0": [ + "0", + "submitted-0" + ], + "1": [ + "1", + "submitted-1" + ], + "2": [ + "2", + "submitted-2" + ], + "3": [ + "3", + "submitted-3" + ], + "4": [ + "4", + "submitted-4" + ], + "5": [ + "5" + ] + }, + "all_necessary_subchecks_retained": true, + "criterion_weights_changed": false, + "source": "Previously applied benchmark grading repair; fresh-entry wiring only" + }, + "new_raw_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5" + ], + "criterion_weights_changed": false, + "reason": "Replacement checker AND-folds fresh and saved submitted reports into canonical IDs 0..4 and keeps original ID5, preserving all original subchecks without double application." + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/experimental.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/experimental.json new file mode 100644 index 0000000000000000000000000000000000000000..8be1297afa4bc63abc984da57bf1c92ae8132ec8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/experimental.json @@ -0,0 +1,7 @@ +{ + "team_name": "ui-redesign", + "agent_type": "expert", + "workers": 12, + "task": "redesign UI components", + "panes": {} +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/team.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/team.json new file mode 100644 index 0000000000000000000000000000000000000000..10de06e1f567613d432af3021daa8ae7707e7990 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/configs/team.json @@ -0,0 +1,11 @@ +{ + "team_name": "review-auth-flow", + "agent_type": "claude", + "workers": 3, + "task": "review the auth module for security issues", + "panes": { + "worker-1": "review-auth-flow:0.0", + "worker-2": "review-auth-flow:0.1", + "worker-3": "review-auth-flow:0.2" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-1.txt b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-1.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a0d93b44191caf132fd613d2509b3595cdae03e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-1.txt @@ -0,0 +1,11 @@ + + ✻ Cascading… (5m 34s · ↓ 3.0k tokens · thinking) + + ⏺ Read(src/auth/session.py) + ⎿ Read 84 lines + ⏺ Grep(pattern="password", path="src/auth") + ⎿ 12 matches + + ✻ Verifying… (1m 02s · ↓ 0.4k tokens · thinking) + + ❯ diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-2.txt b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-2.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c119002eef6bc78e64773a5c2437888a85eea19 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-2.txt @@ -0,0 +1,7 @@ + ⏺ Write(tests/auth/test_session.py) + ⎿ Wrote 42 lines + ⏺ Bash(pytest tests/auth -q) + ⎿ 12 passed in 1.3s + + Baked for 3m 12s + ❯ diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-3.txt b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-3.txt new file mode 100644 index 0000000000000000000000000000000000000000..532636ed9030195b08c6c7eaa101c68a6c87733c --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/panes/worker-3.txt @@ -0,0 +1,6 @@ + ⏺ Edit(src/auth/token.py) + ⎿ Edited 1 line + + Running… timeout 300s + + ❯ diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-1.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-1.json new file mode 100644 index 0000000000000000000000000000000000000000..05179fe90c17192c3d440cfb84b1fdd2610efeae --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-1.json @@ -0,0 +1,4 @@ +{ + "state": "BUSY", + "seconds_since_update": 45 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-2.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-2.json new file mode 100644 index 0000000000000000000000000000000000000000..294675b443ab7b377c3bc4664ba5d00d6620d1e4 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-2.json @@ -0,0 +1,4 @@ +{ + "state": "IDLE", + "seconds_since_update": 600 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-3.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-3.json new file mode 100644 index 0000000000000000000000000000000000000000..839819b3b4b1afe0b7a1ab68fdf19d7d41d041a7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/inputs/status/worker-3.json @@ -0,0 +1,4 @@ +{ + "state": "BUSY", + "seconds_since_update": 310 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/instruction.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db1affac8e8f3474d35a4b21cd663dae0730b9d5 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/instruction.md @@ -0,0 +1,24 @@ +You are monitoring a CLI worker team that runs in tmux. Write a Python 3 script `monitor_team.py` (standard library only) and run it. It must do the following: + +1. Validate team configurations. For each JSON file in `configs/`, check: `agent_type` must be one of `claude`, `codex`, `gemini` (anything else is an unsupported external CLI worker type and must be reported as an error, not executed); `workers` must be an integer from 1 to 10; `team_name` and `task` must be non-empty strings. Collect all validation errors per config file. + +2. For the valid config, classify each worker's state from its captured tmux pane transcript (files in `panes/`, named `<worker>.txt`, each representing the last 20 lines of `tmux capture-pane -p -S -20`). Apply these rules in order: + - WORKING if the transcript contains a Unicode activity indicator (any of ✻ ✶ ✳ ✽ ✾) followed by an action word and a duration in parentheses, OR a line containing `Running…`, OR an in-progress tool call (`Bash(`, `Read(`, `Edit(`, `Write(`, `Grep(`, `Glob(`). + - COMPLETED if it contains `Baked for` or `Sautéed for`. + - QUEUED if it contains `Press up to edit queued messages`. + - IDLE if a `❯` prompt appears with none of the above indicators anywhere in the captured 20 lines (a visible `❯` alone does NOT mean idle — you must check the full capture). + Record for each worker the pane target (`session:window.pane` from the config), the classified state, and the matching evidence line. + +3. Detect stalled workers: read `status/<worker>.json`; a worker is stalled if its `state` is `BUSY` and `seconds_since_update` is greater than 120. + +4. For each stalled worker, emit a nudge plan in `report.json`: the pane target plus the exact three-command safe-send sequence from bundled skill/members/M002/SKILL.md, Sending Input Safely. Substitute the configured pane and the literal message "Nudge: check worker status files and resume stalled work." into that frozen recipe, retaining its literal-send flag, brief delay, and separate Enter send. + +5. Write `report.json` with sections `config_validation` (object mapping config filename to error list, empty list if valid), `workers` (list of {name, pane, state, evidence}), and `nudges` (list of {pane, commands}). Also print a one-line summary per worker like `worker-1: WORKING` to stdout. + +Deterministic validation/evidence details: each config error list contains only the codes `AGENT_TYPE`, `WORKERS`, `TEAM_NAME`, `TASK`, in that order, once per failed field; a JSON boolean is not a workers integer. The state rules examine the entire capture (the provided files already contain the last20 lines). A completed tool call has a following `⎿` result line before the next tool-call line; such a call is not in progress. A tool-call line lacking that result is in progress. An activity line must contain an activity indicator, an alphabetic action word, and a parenthesized duration containing digits plus m or s. Use the first state in the public priority order that has a supporting line; evidence must be one actual complete supporting source line (leading/trailing whitespace may be normalized). If none matches, use state `UNKNOWN` and evidence `""`. Do not query live tmux or wall-clock time: these are captured files and seconds_since_update is authoritative. Nudge commands are plans only and must never be executed. Fresh invocations are graded, rather than any historical tool transcript. + + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/d3cdbad82b42ceaf3187f97c/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..ba0a0fbae2e3be4c89215ebb267b8c02e139bbdc --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/SKILL.md @@ -0,0 +1,3 @@ +# Multi-skill source bundle + +Private source bundle wrapper. The original skills are in members/. diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M000/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M000/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..2d5aa4f65ecca0662ed38ab161f3149b5bc0c2a1 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M000/SKILL.md @@ -0,0 +1,163 @@ +--- +name: omc-teams +description: CLI-team runtime for claude, codex, or gemini workers in tmux panes when you need process-based parallel execution +aliases: [] +level: 4 +--- + +# OMC Teams Skill + +Spawn N CLI worker processes in tmux panes to execute tasks in parallel. Supports `claude`, `codex`, and `gemini` agent types. + +`/omc-teams` is a legacy compatibility skill for the CLI-first runtime: use `omc team ...` commands (not deprecated MCP runtime tools). + +## Usage + +```bash +/startup-harness:omc-teams N:claude "task description" +/startup-harness:omc-teams N:codex "task description" +/startup-harness:omc-teams N:gemini "task description" +``` + +### Parameters + +- **N** - Number of CLI workers (1-10) +- **agent-type** - `claude` (Claude CLI), `codex` (OpenAI Codex CLI), or `gemini` (Google Gemini CLI) +- **task** - Task description to distribute across all workers + +### Examples + +```bash +/omc-teams 2:claude "implement auth module with tests" +/omc-teams 2:codex "review the auth module for security issues" +/omc-teams 3:gemini "redesign UI components for accessibility" +``` + +## Requirements + +- **tmux binary** must be installed and discoverable (`command -v tmux`) +- **Classic tmux session optional** for in-place pane splitting (`$TMUX` set). Inside cmux or a plain terminal, `omc team` falls back to a detached tmux session instead of splitting the current surface. +- **claude** CLI: `npm install -g @anthropic-ai/claude-code` +- **codex** CLI: `npm install -g @openai/codex` +- **gemini** CLI: `npm install -g @google/gemini-cli` + +## Workflow + +### Phase 0: Verify prerequisites + +Check tmux explicitly before claiming it is missing: + +```bash +command -v tmux >/dev/null 2>&1 +``` + +- If this fails, report that **tmux is not installed** and stop. +- If `$TMUX` is set, `omc team` can reuse the current tmux window/panes directly. +- If `$TMUX` is empty but `CMUX_SURFACE_ID` is set, report that the user is running inside **cmux**. Do **not** say tmux is missing or that they are "not inside tmux"; `omc team` will launch a **detached tmux session** for workers instead of splitting the cmux surface. +- If neither `$TMUX` nor `CMUX_SURFACE_ID` is set, report that the user is in a **plain terminal**. `omc team` can still launch a **detached tmux session**, but if they specifically want in-place pane/window topology they should start from a classic tmux session first. +- If you need to confirm the active tmux session, use: + +```bash +tmux display-message -p '#S' +``` + +### Phase 1: Parse + validate input + +Extract: + +- `N` — worker count (1–10) +- `agent-type` — `claude|codex|gemini` +- `task` — task description + +Validate before decomposing or running anything: + +- Reject unsupported agent types up front. `/omc-teams` only supports **`claude`**, **`codex`**, and **`gemini`**. +- If the user asks for an unsupported type such as `expert`, explain that `/omc-teams` launches external CLI workers only. +- For native Claude Code team agents/roles, direct them to **`/startup-harness:team`** instead. + +### Phase 2: Decompose task + +Break work into N independent subtasks (file- or concern-scoped) to avoid write conflicts. + +### Phase 3: Start CLI team runtime + +Activate mode state (recommended): + +```text +state_write(mode="team", current_phase="team-exec", active=true) +``` + +Start workers via CLI: + +```bash +omc team <N>:<claude|codex|gemini> "<task>" +``` + +Team name defaults to a slug from the task text (example: `review-auth-flow`). + +After launch, verify the command actually executed instead of assuming Enter fired. Check pane output and confirm the command or worker bootstrap text appears in pane history: + +```bash +tmux list-panes -a -F '#{session_name}:#{window_index}.#{pane_index} #{pane_id} #{pane_current_command}' +tmux capture-pane -pt <pane-id> -S -20 +``` + +Do not claim the team started successfully unless pane output shows the command was submitted. + +### Phase 4: Monitor + lifecycle API + +```bash +omc team status <team-name> +omc team api list-tasks --input '{"team_name":"<team-name>"}' --json +``` + +Use `omc team api ...` for task claiming, task transitions, mailbox delivery, and worker state updates. + +### Phase 5: Shutdown (only when needed) + +```bash +omc team shutdown <team-name> +omc team shutdown <team-name> --force +``` + +Use shutdown for intentional cancellation or stale-state cleanup. Prefer non-force shutdown first. + +### Phase 6: Report + state close + +Report task results with completion/failure summary and any remaining risks. + +```text +state_write(mode="team", current_phase="complete", active=false) +``` + +## Deprecated Runtime Note + +Legacy MCP runtime tools are deprecated for execution: + +- `omc_run_team_start` +- `omc_run_team_status` +- `omc_run_team_wait` +- `omc_run_team_cleanup` + +If encountered, switch to `omc team ...` CLI commands. + +## Error Reference + +| Error | Cause | Fix | +| ---------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------- | +| `not inside tmux` | Requested in-place pane topology from a non-tmux surface | Start tmux and rerun, or let `omc team` use its detached-session fallback | +| `cmux surface detected` | Running inside cmux without `$TMUX` | Use the normal `omc team ...` flow; OMC will launch a detached tmux session | +| `Unsupported agent type` | Requested agent is not claude/codex/gemini | Use `claude`, `codex`, or `gemini`; for native Claude Code agents use `/startup-harness:team` | +| `codex: command not found` | Codex CLI not installed | `npm install -g @openai/codex` | +| `gemini: command not found` | Gemini CLI not installed | `npm install -g @google/gemini-cli` | +| `Team <name> is not running` | stale or missing runtime state | `omc team status <team-name>` then `omc team shutdown <team-name> --force` if stale | +| `status: failed` | Workers exited with incomplete work | inspect runtime output, narrow scope, rerun | + +## Relationship to `/team` + +| Aspect | `/team` | `/omc-teams` | +| ------------ | ----------------------------------------- | ---------------------------------------------------- | +| Worker type | Claude Code native team agents | claude / codex / gemini CLI processes in tmux | +| Invocation | `TeamCreate` / `Task` / `SendMessage` | `omc team [N:agent]` + `status` + `shutdown` + `api` | +| Coordination | Native team messaging and staged pipeline | tmux worker runtime + CLI API state files | +| Use when | You want Claude-native team orchestration | You want external CLI worker execution | diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M001/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M001/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..08b9dc23efc28562d2d5970fe39ef1deb938da69 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M001/SKILL.md @@ -0,0 +1,57 @@ +--- +name: AO Session Monitor +description: Properly inspect AO worker tmux sessions to detect working vs idle state +--- + +# AO Session Monitor Skill + +## How to check if an AO worker session is active + +Claude Code renders the `❯` prompt at the bottom of the tmux pane **while the model is thinking above it**. Checking only the last 5-6 lines will produce false "idle" reports. + +### Correct detection method + +1. Capture at least 20 lines: `tmux capture-pane -t <session> -p -S -20` +2. Look for **Unicode activity indicators**: `✻ ✶ ✳ ✽ ✾` followed by an action word and duration + - Examples: `✻ Cascading… (5m 34s · ↓ 3.0k tokens · thinking)` + - Examples: `✶ Germinating… (2m 21s · ↓ 1.2k tokens · thought for 7s)` +3. Look for **tool use in progress**: `Bash(`, `Read(`, `Edit(`, `Write(`, `Grep(`, `Glob(` +4. Look for **"Running…"** — a Bash command is executing + +### State classification + +| Indicator | State | Meaning | +|---|---|---| +| `✻✶✳✽✾` + duration | **WORKING** | Model is thinking or executing tools | +| `Running…` or `timeout` | **WORKING** | Shell command in progress | +| `Baked for Xm` or `Sautéed for Xm` | **COMPLETED** | Finished, went idle | +| `❯` with no activity indicators in 20 lines | **IDLE** | Actually waiting for input | +| `Press up to edit queued messages` | **QUEUED** | Has pending message from lifecycle-worker | +| `+uncommitted` in status bar | **HAS WORK** | Edited files but hasn't committed/pushed | + +### Common false positives + +- **`❯` visible = idle**: WRONG. The prompt renders below the thinking indicator. Always check 20+ lines. +- **No `Bash` in last 6 lines = not working**: WRONG. The model may be in a long thinking phase between commands. +- **Session shows old output = dead**: WRONG. The model may be mid-thought. Check for activity indicators. + +### Shell one-liner for monitoring + +```bash +for s in $(tmux list-sessions 2>/dev/null | grep "ao-[0-9]" | cut -d: -f1); do + name=${s##*-} + last=$(tmux capture-pane -t "$s" -p -S -20 2>/dev/null) + pr=$(echo "$last" | grep -oE "PR: #[0-9]+" | head -1) + uc=""; echo "$last" | grep -q "uncommitted" && uc="+uc" + activity=$(echo "$last" | grep -oE "[✻✶✳✽✾] [A-Za-z]+…[^)]*\)" | tail -1) + if [ -n "$activity" ]; then + echo " $name: WORKING $pr $uc ($activity)" + elif echo "$last" | grep -qE "Baked|Sautéed"; then + echo " $name: completed $pr" + elif echo "$last" | grep -q "queued"; then + echo " $name: QUEUED $pr" + else + echo " $name: idle $pr $uc" + fi +done +``` diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..bd144e100ed60ad7d8bef03d8a59ba44ebb9b6ad --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/SKILL.md @@ -0,0 +1,155 @@ +--- +name: tmux +description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output. +origin: + source: openclaw + url: https://github.com/openclaw/openclaw + version: 90eb5b073f +--- + +# tmux Session Control + +Control tmux sessions by sending keystrokes and reading output. Essential for managing Claude Code sessions. + +## When to Use + +✅ **USE this skill when:** + +- Monitoring Claude/Codex sessions in tmux +- Sending input to interactive terminal applications +- Scraping output from long-running processes in tmux +- Navigating tmux panes/windows programmatically +- Checking on background work in existing sessions + +## When NOT to Use + +❌ **DON'T use this skill when:** + +- Running one-off shell commands → use `exec` tool directly +- Starting new background processes → use `exec` with `background:true` +- Non-interactive scripts → use `exec` tool +- The process isn't in tmux +- You need to create a new tmux session → use `exec` with `tmux new-session` + +## Example Sessions + +| Session | Purpose | +| ----------------------- | --------------------------- | +| `shared` | Primary interactive session | +| `worker-2` - `worker-8` | Parallel worker sessions | + +## Common Commands + +### List Sessions + +```bash +tmux list-sessions +tmux ls +``` + +### Capture Output + +```bash +# Last 20 lines of pane +tmux capture-pane -t shared -p | tail -20 + +# Entire scrollback +tmux capture-pane -t shared -p -S - + +# Specific pane in window +tmux capture-pane -t shared:0.0 -p +``` + +### Send Keys + +```bash +# Send text (doesn't press Enter) +tmux send-keys -t shared "hello" + +# Send text + Enter +tmux send-keys -t shared "y" Enter + +# Send special keys +tmux send-keys -t shared Enter +tmux send-keys -t shared Escape +tmux send-keys -t shared C-c # Ctrl+C +tmux send-keys -t shared C-d # Ctrl+D (EOF) +tmux send-keys -t shared C-z # Ctrl+Z (suspend) +``` + +### Window/Pane Navigation + +```bash +# Select window +tmux select-window -t shared:0 + +# Select pane +tmux select-pane -t shared:0.1 + +# List windows +tmux list-windows -t shared +``` + +### Session Management + +```bash +# Create new session +tmux new-session -d -s newsession + +# Kill session +tmux kill-session -t sessionname + +# Rename session +tmux rename-session -t old new +``` + +## Sending Input Safely + +For interactive TUIs (Claude Code, Codex, etc.), split text and Enter into separate sends to avoid paste/multiline edge cases: + +```bash +tmux send-keys -t shared -l -- "Please apply the patch in src/foo.ts" +sleep 0.1 +tmux send-keys -t shared Enter +``` + +## Claude Code Session Patterns + +### Check if Session Needs Input + +```bash +# Look for prompts +tmux capture-pane -t worker-3 -p | tail -10 | grep -E "❯|Yes.*No|proceed|permission" +``` + +### Approve Claude Code Prompt + +```bash +# Send 'y' and Enter +tmux send-keys -t worker-3 'y' Enter + +# Or select numbered option +tmux send-keys -t worker-3 '2' Enter +``` + +### Check All Sessions Status + +```bash +for s in shared worker-2 worker-3 worker-4 worker-5 worker-6 worker-7 worker-8; do + echo "=== $s ===" + tmux capture-pane -t $s -p 2>/dev/null | tail -5 +done +``` + +### Send Task to Session + +```bash +tmux send-keys -t worker-4 "Fix the bug in auth.js" Enter +``` + +## Notes + +- Use `capture-pane -p` to print to stdout (essential for scripting) +- `-S -` captures entire scrollback history +- Target format: `session:window.pane` (e.g., `shared:0.0`) +- Sessions persist across SSH disconnects diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/find-sessions.sh b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/find-sessions.sh new file mode 100644 index 0000000000000000000000000000000000000000..314cc6020b80614acd68115802312fe9e4f38428 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/find-sessions.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern] + +List tmux sessions on a socket (default tmux socket if none provided). + +Options: + -L, --socket tmux socket name (passed to tmux -L) + -S, --socket-path tmux socket path (passed to tmux -S) + -A, --all scan all sockets under OPENCLAW_TMUX_SOCKET_DIR + -q, --query case-insensitive substring to filter session names + -h, --help show this help +USAGE +} + +socket_name="" +socket_path="" +query="" +scan_all=false +socket_dir="${OPENCLAW_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/openclaw-tmux-sockets}" + +while [[ $# -gt 0 ]]; do + case "$1" in + -L|--socket) socket_name="${2-}"; shift 2 ;; + -S|--socket-path) socket_path="${2-}"; shift 2 ;; + -A|--all) scan_all=true; shift ;; + -q|--query) query="${2-}"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) echo "Unknown option: $1" >&2; usage; exit 1 ;; + esac +done + +if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then + echo "Cannot combine --all with -L or -S" >&2 + exit 1 +fi + +if [[ -n "$socket_name" && -n "$socket_path" ]]; then + echo "Use either -L or -S, not both" >&2 + exit 1 +fi + +if ! command -v tmux >/dev/null 2>&1; then + echo "tmux not found in PATH" >&2 + exit 1 +fi + +list_sessions() { + local label="$1"; shift + local tmux_cmd=(tmux "$@") + + if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then + echo "No tmux server found on $label" >&2 + return 1 + fi + + if [[ -n "$query" ]]; then + sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)" + fi + + if [[ -z "$sessions" ]]; then + echo "No sessions found on $label" + return 0 + fi + + echo "Sessions on $label:" + printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do + attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached") + printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created" + done +} + +if [[ "$scan_all" == true ]]; then + if [[ ! -d "$socket_dir" ]]; then + echo "Socket directory not found: $socket_dir" >&2 + exit 1 + fi + + shopt -s nullglob + sockets=("$socket_dir"/*) + shopt -u nullglob + + if [[ "${#sockets[@]}" -eq 0 ]]; then + echo "No sockets found under $socket_dir" >&2 + exit 1 + fi + + exit_code=0 + for sock in "${sockets[@]}"; do + if [[ ! -S "$sock" ]]; then + continue + fi + list_sessions "socket path '$sock'" -S "$sock" || exit_code=$? + done + exit "$exit_code" +fi + +tmux_cmd=(tmux) +socket_label="default socket" + +if [[ -n "$socket_name" ]]; then + tmux_cmd+=(-L "$socket_name") + socket_label="socket name '$socket_name'" +elif [[ -n "$socket_path" ]]; then + tmux_cmd+=(-S "$socket_path") + socket_label="socket path '$socket_path'" +fi + +list_sessions "$socket_label" "${tmux_cmd[@]:1}" diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/wait-for-text.sh b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/wait-for-text.sh new file mode 100644 index 0000000000000000000000000000000000000000..56354be835459c7614bfc96b5526e92dc1dbde5d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M002/scripts/wait-for-text.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: wait-for-text.sh -t target -p pattern [options] + +Poll a tmux pane for text and exit when found. + +Options: + -t, --target tmux target (session:window.pane), required + -p, --pattern regex pattern to look for, required + -F, --fixed treat pattern as a fixed string (grep -F) + -T, --timeout seconds to wait (integer, default: 15) + -i, --interval poll interval in seconds (default: 0.5) + -l, --lines number of history lines to inspect (integer, default: 1000) + -h, --help show this help +USAGE +} + +target="" +pattern="" +grep_flag="-E" +timeout=15 +interval=0.5 +lines=1000 + +while [[ $# -gt 0 ]]; do + case "$1" in + -t|--target) target="${2-}"; shift 2 ;; + -p|--pattern) pattern="${2-}"; shift 2 ;; + -F|--fixed) grep_flag="-F"; shift ;; + -T|--timeout) timeout="${2-}"; shift 2 ;; + -i|--interval) interval="${2-}"; shift 2 ;; + -l|--lines) lines="${2-}"; shift 2 ;; + -h|--help) usage; exit 0 ;; + *) echo "Unknown option: $1" >&2; usage; exit 1 ;; + esac +done + +if [[ -z "$target" || -z "$pattern" ]]; then + echo "target and pattern are required" >&2 + usage + exit 1 +fi + +if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then + echo "timeout must be an integer number of seconds" >&2 + exit 1 +fi + +if ! [[ "$lines" =~ ^[0-9]+$ ]]; then + echo "lines must be an integer" >&2 + exit 1 +fi + +if ! command -v tmux >/dev/null 2>&1; then + echo "tmux not found in PATH" >&2 + exit 1 +fi + +# End time in epoch seconds (integer, good enough for polling) +start_epoch=$(date +%s) +deadline=$((start_epoch + timeout)) + +while true; do + # -J joins wrapped lines, -S uses negative index to read last N lines + pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)" + + if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then + exit 0 + fi + + now=$(date +%s) + if (( now >= deadline )); then + echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2 + echo "Last ${lines} lines from $target:" >&2 + printf '%s\n' "$pane_text" >&2 + exit 1 + fi + + sleep "$interval" +done diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..781f929a7f67d50eed7421598aa650269b3d5674 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md @@ -0,0 +1,20 @@ +--- +name: doey-nudge +description: Cascading nudge — wake stalled Claude instances across all teams. Use when workers seem stuck, idle, or unresponsive. +--- + +- Session config: !`cat $(tmux show-environment DOEY_RUNTIME 2>/dev/null | cut -d= -f2-)/session.env 2>/dev/null || true` + +Send a nudge cascade to Taskmaster, who will propagate it to all team Subtaskmasters and their Workers. + +```bash +RD=$(tmux show-environment DOEY_RUNTIME 2>/dev/null | cut -d= -f2-) +source "${RD}/session.env" +_TM_PANE=$(grep '^TASKMASTER_PANE=' "${RD}/session.env" 2>/dev/null | cut -d= -f2-) +TASKMASTER_PANE="${SESSION_NAME}:${_TM_PANE:-1.0}" + +NUDGE_MSG="Nudge cascade requested. Check all team Subtaskmasters and ensure work is progressing. For each team window W in [${TEAM_WINDOWS}], send-keys to W.0 telling the Subtaskmaster to check worker status files and nudge any stalled workers (BUSY with no status update in >120s). Use copy-mode -q before each send-keys. Fire and forget." + +source "$HOME/.local/bin/doey-send.sh" 2>/dev/null || true +doey_send_verified "$TASKMASTER_PANE" "$NUDGE_MSG" && echo "Nudge sent to Taskmaster (${TASKMASTER_PANE})" || echo "Nudge delivery failed" +``` diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md.tmpl b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md.tmpl new file mode 100644 index 0000000000000000000000000000000000000000..f6c8e4da728816aa7629a4a22b4b5b54eb220607 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/skill/members/M003/SKILL.md.tmpl @@ -0,0 +1,20 @@ +--- +name: doey-nudge +description: Cascading nudge — wake stalled Claude instances across all teams. Use when workers seem stuck, idle, or unresponsive. +--- + +- Session config: !`cat $(tmux show-environment DOEY_RUNTIME 2>/dev/null | cut -d= -f2-)/session.env 2>/dev/null || true` + +Send a nudge cascade to {{DOEY_ROLE_COORDINATOR}}, who will propagate it to all team {{DOEY_ROLE_TEAM_LEAD}}s and their {{DOEY_ROLE_WORKER}}s. + +```bash +RD=$(tmux show-environment DOEY_RUNTIME 2>/dev/null | cut -d= -f2-) +source "${RD}/session.env" +_TM_PANE=$(grep '^TASKMASTER_PANE=' "${RD}/session.env" 2>/dev/null | cut -d= -f2-) +TASKMASTER_PANE="${SESSION_NAME}:${_TM_PANE:-1.0}" + +NUDGE_MSG="Nudge cascade requested. Check all team {{DOEY_ROLE_TEAM_LEAD}}s and ensure work is progressing. For each team window W in [${TEAM_WINDOWS}], send-keys to W.0 telling the {{DOEY_ROLE_TEAM_LEAD}} to check worker status files and nudge any stalled workers (BUSY with no status update in >120s). Use copy-mode -q before each send-keys. Fire and forget." + +source "$HOME/.local/bin/doey-send.sh" 2>/dev/null || true +doey_send_verified "$TASKMASTER_PANE" "$NUDGE_MSG" && echo "Nudge sent to {{DOEY_ROLE_COORDINATOR}} (${TASKMASTER_PANE})" || echo "Nudge delivery failed" +``` diff --git a/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/task.json b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/task.json new file mode 100644 index 0000000000000000000000000000000000000000..29248de48298e4d90f5bc19f0f29464006b1c282 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3cdbad82b42ceaf3187f97c/task.json @@ -0,0 +1,222 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d3cdbad82b42ceaf3187f97c", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "d3cdbad82b42ceaf3187f97c", + "outputs": [ + "report.json" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "8b5f2d5957d41fe5f282a0fe6723d36e6099a505e25752180cdca41b9559c03b", + "files": { + "SKILL.md": "c026851d0b60cc1e9687b03a24dfadf626b1e352c79c1d0b3ee85fc61ff4766c", + "members/M000/SKILL.md": "0c24cb922edec3c5d38eb3eeb5d69679b49294eb874bc79d4b27118e747795b3", + "members/M001/SKILL.md": "e646265625c977fc7c18c0f8f76bb1e57d01627c54646616c5598e26962cdfd1", + "members/M002/SKILL.md": "69f0077b4d3b9c61bc59bb979a99bf213ddea217fb7dcc5bbbff9f9cfb84d3cc", + "members/M002/scripts/find-sessions.sh": "4c4552ce0adb2754080969f00b761c1c118766771e0595b8c9b416ee0842fbae", + "members/M002/scripts/wait-for-text.sh": "96bc42702f7353c32233c223d61dd11f2f99033267aeefac838aea8983a67735", + "members/M003/SKILL.md": "96610e10405fdc5244edc5fd09519f6fa51e7068e6a090d41db01ffc3c3af868", + "members/M003/SKILL.md.tmpl": "fdda2d93c291188211a2a1105a286e098b76e641d93a391f6bf2fb85634f986c" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/configs/team.json", + "workspace_target": "configs/team.json", + "sha256": "e3751c70ffd608df6d17c67a2ed48d0ca545b695a308cfa9ebf3251d617adf76" + }, + { + "source": "inputs/configs/experimental.json", + "workspace_target": "configs/experimental.json", + "sha256": "f193cf67576dc79a734e22bd8d2c7c153356554a27be9a5392a4fe9809ac835d" + }, + { + "source": "inputs/panes/worker-1.txt", + "workspace_target": "panes/worker-1.txt", + "sha256": "655fd7930587a0a4a4482ad9abf0e17b0ac109be9684fc6447e1a50a0fec509f" + }, + { + "source": "inputs/panes/worker-2.txt", + "workspace_target": "panes/worker-2.txt", + "sha256": "ff6a4fc8606810afd3eb0a8e757d2ee8864c75c635465733bdf9486ef90c3308" + }, + { + "source": "inputs/panes/worker-3.txt", + "workspace_target": "panes/worker-3.txt", + "sha256": "fa694754818608bb6caa5d756ecca0d74841ea7c4f8abb133dfb6e2b58876599" + }, + { + "source": "inputs/status/worker-1.json", + "workspace_target": "status/worker-1.json", + "sha256": "37dda05413afb4d084a8f810f89dc55f30543b4c5c680171e17ba0cf9abdd496" + }, + { + "source": "inputs/status/worker-2.json", + "workspace_target": "status/worker-2.json", + "sha256": "15e6e49456ef1b3150cf568c343cf98fb21185df73e13f704ce22f7d5a55f0be" + }, + { + "source": "inputs/status/worker-3.json", + "workspace_target": "status/worker-3.json", + "sha256": "890fa9a5705e75f99518e234e2ee672fdd3de54b777cb3a38a5a1cab5513630d" + } + ], + "skill_packages": [ + { + "package_path": "skill/members/M000", + "content_hash": "dee706be5ff1990d830044d7de3472a0ec2fee7fd6ae0a70d0aaea3d3a918750", + "member_id": "M000" + }, + { + "package_path": "skill/members/M001", + "content_hash": "4154387f505f62a35ea6991373d258a9d11aa9382124c0a9db6fce11d7d30eed", + "member_id": "M001" + }, + { + "package_path": "skill/members/M002", + "content_hash": "dabb19ab938913d92e6dca82f09745a6d18f7b081604dfc626a93ff3e0de0819", + "member_id": "M002" + }, + { + "package_path": "skill/members/M003", + "content_hash": "add15572ca0666ae2c3957b084976b94101f92046a4226ece406cb519da35330", + "member_id": "M003" + } + ] + }, + "source_group": { + "schema_version": "multi-skill-source-v1", + "group_id": "ff069d9e1732ea13cc01c415", + "members": [ + { + "skill_id": "skill-5604b538f1ec09ab6b36c788", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/56/skill-5604b538f1ec09ab6b36c788", + "snapshot": { + "sha256": "dee706be5ff1990d830044d7de3472a0ec2fee7fd6ae0a70d0aaea3d3a918750", + "files": { + "SKILL.md": "0c24cb922edec3c5d38eb3eeb5d69679b49294eb874bc79d4b27118e747795b3" + }, + "bytes": 6961 + }, + "skill_md_sha256": "0c24cb922edec3c5d38eb3eeb5d69679b49294eb874bc79d4b27118e747795b3", + "member_id": "M000", + "package_path": "members/M000" + }, + { + "skill_id": "skill-58052cd82966a2b3a3260361", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/58/skill-58052cd82966a2b3a3260361", + "snapshot": { + "sha256": "4154387f505f62a35ea6991373d258a9d11aa9382124c0a9db6fce11d7d30eed", + "files": { + "SKILL.md": "e646265625c977fc7c18c0f8f76bb1e57d01627c54646616c5598e26962cdfd1" + }, + "bytes": 2537 + }, + "skill_md_sha256": "e646265625c977fc7c18c0f8f76bb1e57d01627c54646616c5598e26962cdfd1", + "member_id": "M001", + "package_path": "members/M001" + }, + { + "skill_id": "skill-b6202096867f9720192fa37c", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/b6/skill-b6202096867f9720192fa37c", + "snapshot": { + "sha256": "dabb19ab938913d92e6dca82f09745a6d18f7b081604dfc626a93ff3e0de0819", + "files": { + "SKILL.md": "69f0077b4d3b9c61bc59bb979a99bf213ddea217fb7dcc5bbbff9f9cfb84d3cc", + "scripts/find-sessions.sh": "4c4552ce0adb2754080969f00b761c1c118766771e0595b8c9b416ee0842fbae", + "scripts/wait-for-text.sh": "96bc42702f7353c32233c223d61dd11f2f99033267aeefac838aea8983a67735" + }, + "bytes": 8553 + }, + "skill_md_sha256": "69f0077b4d3b9c61bc59bb979a99bf213ddea217fb7dcc5bbbff9f9cfb84d3cc", + "member_id": "M002", + "package_path": "members/M002" + }, + { + "skill_id": "skill-e6cc6fb4677b3ed9a4f668a3", + "store_id": "skill-release", + "original_package_path": "skill-release-archive/skills/e6/skill-e6cc6fb4677b3ed9a4f668a3", + "snapshot": { + "sha256": "add15572ca0666ae2c3957b084976b94101f92046a4226ece406cb519da35330", + "files": { + "SKILL.md": "96610e10405fdc5244edc5fd09519f6fa51e7068e6a090d41db01ffc3c3af868", + "SKILL.md.tmpl": "fdda2d93c291188211a2a1105a286e098b76e641d93a391f6bf2fb85634f986c" + }, + "bytes": 2416 + }, + "skill_md_sha256": "96610e10405fdc5244edc5fd09519f6fa51e7068e6a090d41db01ffc3c3af868", + "member_id": "M003", + "package_path": "members/M003" + } + ] + }, + "label_scope": { + "comparison": "none_vs_all_members", + "unit": "skill_group", + "individual_member_necessity_tested": false + }, + "member_contributions": [ + { + "member_id": "M000", + "contribution": "Validation rules for a CLI team launch: worker count N must be 1–10 and agent-type restricted to claude/codex/gemini, with unsupported types rejected up front before any work", + "relationship": "Defines step 1 of the task: the monitor validates each team config before classifying or nudging, mirroring the runtime's parse-and-validate phase" + }, + { + "member_id": "M001", + "contribution": "Pane-state classification rules: capture at least 20 lines, treat Unicode activity indicators / Running… / tool calls as WORKING, 'Baked/Sautéed for' as COMPLETED, queued-message text as QUEUED, and only classify IDLE when a ❯ prompt appears with no activity indicators in the full 20-line capture", + "relationship": "Supplies the exact state-detection method the script applies to each worker's captured pane transcript in step 2, including the false-positive warning that a visible prompt alone is not idle" + }, + { + "member_id": "M002", + "contribution": "tmux pane targeting format (session:window.pane) and the safe send-keys pattern for interactive TUIs: send literal text with -l first, then send Enter as a separate keystroke", + "relationship": "Provides the command syntax used in step 4 to construct the nudge delivery commands for stalled workers' panes" + }, + { + "member_id": "M003", + "contribution": "Stalled-worker rule: a worker that is BUSY with no status update for more than 120 seconds should be nudged to check worker status files and resume work", + "relationship": "Defines the stall threshold and nudge message semantics that determine which classified workers receive a nudge plan in step 3–4" + } + ], + "autograde_contract_revision": "deterministic-v1", + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "5" + ], + "require_execution": true + }, + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "5" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..40cb7b630ecd82d183f8f920421937dab375d13d --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_contract.json @@ -0,0 +1,28 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1, + "10": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/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/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6fa188ccf1e0fe090f3cdeda9c40268cb02093c6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy.json @@ -0,0 +1,13 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..4df4caaa98f65583a6ef445057e18b5c00462195 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/autograde_task_check.py @@ -0,0 +1,51 @@ +from candidate_artifacts import read_text as _co_text, loads as _co_loads, load as _co_json +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,subprocess,sys +from pathlib import Path +from workspace_copy import workspace +from dependency_scan import scan_stdlib +PANELS=json.loads((Path(__file__).parent/'input_snapshots/panels.json').read_text()) +IDS=list(map(str,range(11))) +def tri(values):return False if any(v is False for v in values)else None if any(v is None for v in values)else True +def number(value):return type(value)in(int,float) +def results_of(report): + if isinstance(report.get('results'),list):return report['results'] + choices=[v for v in report.values()if isinstance(v,list)and all(isinstance(x,dict)and all(k in x for k in ('index','op','ok','errors'))for x in v)] + return choices[0]if len(choices)==1 else None +def grade(report,panel): + if not isinstance(report,dict):return[False]*11 + rows=results_of(report);summary=report.get('summary');ops=panel['ops'];values=[True]+[False]*10 + if not isinstance(rows,list):return values + def row(index): + found=[r for r in rows if isinstance(r,dict)and number(r.get('index')) and r['index']==index] + return found[0]if len(found)==1 else None + for owner,specs in panel['domains'].items(): + good=True + for spec in specs: + found=row(spec['index']);errors=found.get('errors')if found else None + good=good and found is not None and found.get('ok')is spec['ok']and isinstance(errors,list)and (errors==[]if spec['ok']else len(errors)>0)and all(reason in errors for reason in spec['reasons']) + values[int(owner)]=good + n_ok=sum(1 for r in rows if isinstance(r,dict)and r.get('ok')is True) + values[9]=isinstance(summary,dict)and all(number(summary.get(k))for k in ('total','passed','failed'))and summary.get('total')==len(ops)and summary.get('passed')==n_ok and summary.get('failed')==len(rows)-n_ok and len(rows)==len(ops) + values[10]=isinstance(summary,dict)and all(k in summary for k in ('total','passed','failed'))and len(rows)==len(ops)and all(isinstance(row,dict)and number(row.get('index'))and row['index']in range(len(ops))and row.get('op')==ops[int(row['index'])]['op']and type(row.get('ok'))is bool and isinstance(row.get('errors'),list)and all(isinstance(error,str)and error.strip()for error in row['errors'])and (row['ok']==(row['errors']==[]))for row in rows) + if values[10]:values[10]=len({row['index']for row in rows})==len(ops) + return values +def once(panel): + with workspace(remove=['report.','report.json']): + work=Path('/app');(work/'ops.').write_text(json.dumps(panel['ops']),encoding='utf-8') + try:process=subprocess.run([sys.executable,'validate_timeline.py'],cwd=work,capture_output=True,timeout=30) + except subprocess.TimeoutExpired:return [False]*11 + except OSError as error:raise RuntimeError("Trusted timeline launcher failed") from error + if process.returncode<0:return [False]*11 + try:report=_co_loads(_co_text(work/'report.', encoding='utf-8')) + except(OSError,UnicodeError,ValueError):return[False]*11 + return grade(report,panel) +def main(): + root=Path('/candidate') + if not(root/'validate_timeline.py').is_file():return{k:False for k in IDS} + ok,_,detail=scan_stdlib(root,['validate_timeline.py']);dep=None if detail.startswith('unknown:')else ok + rows=[once(panel)for panel in PANELS];values={str(n):tri([None if row is None else row[n]for row in rows])for n in range(11)};values['0']=tri([values['0'],dep]);return values +if __name__=='__main__': + try:values=main();reason='Original11timeline domains, literalops./report., sourcebound original+typedboundarypanel, fullapp/stdlibclosure/bytes. No Unity action or privateexit0/priorRun.' + except Exception as error:values={k:None for k in IDS};reason='Unresolved trusted preparation: '+str(error) + print(json.dumps({'scoreable':all(type(v)is bool for v in values.values()),'checks':[dict(id=k,passed=values[k],reason=reason)for k in IDS]})) diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/candidate_artifacts.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/candidate_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..01d155d66962e3f1c41443cad117a48e6ca25bc6 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/candidate_artifacts.py @@ -0,0 +1,24 @@ +"""Read only ordinary candidate artifacts after a bounded child completes. +No launch/setup/monitor exceptions are caught here. Symlinks to regular files +remain usable. Nonblocking open + fstat prevents a candidate-created FIFO from +blocking the trusted grader. Malformed text/JSON is an absent invalid value. +""" +import json, os, stat + +def read_text(path, encoding=None, errors=None): + fd=None + try: + fd=os.open(os.fspath(path),os.O_RDONLY|os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode):return '' + with os.fdopen(fd,'r',encoding=encoding or 'utf-8',errors=errors or 'strict') as stream: + fd=None + return stream.read() + except (OSError,UnicodeError):return '' + finally: + if fd is not None:os.close(fd) + +def loads(text, **kwargs): + try:return json.loads(text,**kwargs) + except (ValueError,TypeError,RecursionError):return None + +def load(path, **kwargs):return loads(read_text(path),**kwargs) diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/input_snapshots/panels.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/input_snapshots/panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b6e07a3427d9904b2e56468d61ada89cd10d330e --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/input_snapshots/panels.json @@ -0,0 +1,751 @@ +[ + { + "ops": [ + { + "op": "add_animation_track", + "trackName": "Hero Move" + }, + { + "op": "create", + "name": "IntroCutscene" + }, + { + "op": "add_animation_track", + "trackName": "Hero Move" + }, + { + "op": "add_audio_track", + "trackName": "Music" + }, + { + "op": "add_keyframe", + "trackName": "Hero Move", + "time": 1.5 + }, + { + "op": "add_clip", + "trackName": "Hero Move", + "start": 0, + "duration": 2.5 + }, + { + "op": "add_clip", + "trackName": "Music", + "start": -1, + "duration": 3 + }, + { + "op": "set_duration", + "duration": 5, + "wrapMode": "Loop" + }, + { + "op": "set_duration", + "wrapMode": "Repeat" + }, + { + "op": "play", + "action": "rewind" + }, + { + "op": "play" + }, + { + "op": "remove_track", + "trackName": "Music" + }, + { + "op": "remove_track", + "trackName": "Music" + }, + { + "op": "set_binding", + "trackName": "Hero Move" + }, + { + "op": "set_binding", + "trackName": "Hero Move", + "bindingObjectName": "Hero" + }, + { + "op": "list_tracks" + } + ], + "domains": { + "1": [ + { + "index": 0, + "ok": false, + "reasons": [ + "no_timeline" + ] + } + ], + "2": [ + { + "index": 4, + "ok": false, + "reasons": [ + "unknown_op" + ] + } + ], + "3": [ + { + "index": 6, + "ok": false, + "reasons": [] + } + ], + "4": [ + { + "index": 8, + "ok": false, + "reasons": [] + } + ], + "5": [ + { + "index": 9, + "ok": false, + "reasons": [] + } + ], + "6": [ + { + "index": 11, + "ok": true, + "reasons": [] + }, + { + "index": 12, + "ok": false, + "reasons": [ + "track_not_found" + ] + } + ], + "7": [ + { + "index": 13, + "ok": false, + "reasons": [] + } + ], + "8": [ + { + "index": 1, + "ok": true, + "reasons": [] + }, + { + "index": 2, + "ok": true, + "reasons": [] + }, + { + "index": 3, + "ok": true, + "reasons": [] + }, + { + "index": 5, + "ok": true, + "reasons": [] + }, + { + "index": 7, + "ok": true, + "reasons": [] + }, + { + "index": 10, + "ok": true, + "reasons": [] + }, + { + "index": 14, + "ok": true, + "reasons": [] + }, + { + "index": 15, + "ok": true, + "reasons": [] + } + ] + } + }, + { + "ops": [ + { + "op": "bogus" + }, + { + "op": "create" + }, + { + "op": "create", + "name": "NewSequence" + }, + { + "op": "add_activation_track", + "trackName": "Active" + }, + { + "op": "add_control_track", + "trackName": "Control" + }, + { + "op": "add_signal_track", + "trackName": "Signal" + }, + { + "op": "add_clip", + "trackName": "Active", + "start": true + }, + { + "op": "add_clip", + "trackName": "Active", + "duration": null + }, + { + "op": "add_clip", + "duration": 1 + }, + { + "op": "add_clip", + "trackName": "Active" + }, + { + "op": "set_duration" + }, + { + "op": "set_duration", + "wrapMode": "loop" + }, + { + "op": "set_duration", + "wrapMode": "Hold" + }, + { + "op": "play", + "action": "pause" + }, + { + "op": "play", + "action": "" + }, + { + "op": "set_binding", + "trackName": "Active" + }, + { + "op": "set_binding", + "bindingObjectName": "Actor" + }, + { + "op": "remove_track", + "trackName": "Signal" + }, + { + "op": "remove_track", + "trackName": "Signal" + }, + { + "op": "list_tracks" + }, + { + "op": "add_track" + }, + { + "op": "play", + "action": "stop" + }, + { + "op": "remove_track" + }, + { + "op": "set_binding", + "trackName": "Active", + "bindingObjectName": "Actor" + }, + { + "op": "set_duration", + "wrapMode": null + }, + { + "op": "set_duration", + "wrapMode": "" + }, + { + "op": "set_duration", + "wrapMode": "None" + } + ], + "domains": { + "1": [ + { + "index": 0, + "ok": false, + "reasons": [ + "no_timeline" + ] + } + ], + "2": [ + { + "index": 0, + "ok": false, + "reasons": [ + "unknown_op" + ] + }, + { + "index": 20, + "ok": false, + "reasons": [ + "unknown_op" + ] + } + ], + "3": [ + { + "index": 6, + "ok": false, + "reasons": [] + }, + { + "index": 7, + "ok": false, + "reasons": [] + }, + { + "index": 8, + "ok": false, + "reasons": [] + } + ], + "4": [ + { + "index": 11, + "ok": false, + "reasons": [] + }, + { + "index": 24, + "ok": false, + "reasons": [] + }, + { + "index": 25, + "ok": false, + "reasons": [] + } + ], + "5": [ + { + "index": 14, + "ok": false, + "reasons": [] + } + ], + "6": [ + { + "index": 17, + "ok": true, + "reasons": [] + }, + { + "index": 18, + "ok": false, + "reasons": [ + "track_not_found" + ] + }, + { + "index": 22, + "ok": false, + "reasons": [] + } + ], + "7": [ + { + "index": 15, + "ok": false, + "reasons": [] + }, + { + "index": 16, + "ok": false, + "reasons": [] + } + ], + "8": [ + { + "index": 1, + "ok": false, + "reasons": [] + }, + { + "index": 2, + "ok": true, + "reasons": [] + }, + { + "index": 3, + "ok": true, + "reasons": [] + }, + { + "index": 4, + "ok": true, + "reasons": [] + }, + { + "index": 5, + "ok": true, + "reasons": [] + }, + { + "index": 9, + "ok": true, + "reasons": [] + }, + { + "index": 10, + "ok": true, + "reasons": [] + }, + { + "index": 12, + "ok": true, + "reasons": [] + }, + { + "index": 13, + "ok": true, + "reasons": [] + }, + { + "index": 19, + "ok": true, + "reasons": [] + }, + { + "index": 21, + "ok": true, + "reasons": [] + }, + { + "index": 23, + "ok": true, + "reasons": [] + }, + { + "index": 26, + "ok": true, + "reasons": [] + } + ] + } + }, + { + "ops": [ + { + "op": "bogus" + }, + { + "op": "create" + }, + { + "op": "create", + "name": "NewSequence" + }, + { + "op": "add_activation_track", + "trackName": "Active" + }, + { + "op": "add_control_track", + "trackName": "Control" + }, + { + "op": "add_signal_track", + "trackName": "Signal" + }, + { + "op": "add_clip", + "trackName": "Active", + "start": true + }, + { + "op": "add_clip", + "trackName": "Active", + "duration": null + }, + { + "op": "add_clip", + "duration": 1 + }, + { + "op": "add_clip", + "trackName": "Active" + }, + { + "op": "set_duration" + }, + { + "op": "set_duration", + "wrapMode": "loop" + }, + { + "op": "set_duration", + "wrapMode": "Hold" + }, + { + "op": "play", + "action": "pause" + }, + { + "op": "play", + "action": "" + }, + { + "op": "set_binding", + "trackName": "Active" + }, + { + "op": "set_binding", + "bindingObjectName": "Actor" + }, + { + "op": "remove_track", + "trackName": "Signal" + }, + { + "op": "remove_track", + "trackName": "Signal" + }, + { + "op": "list_tracks" + }, + { + "op": "add_track" + }, + { + "op": "play", + "action": "stop" + }, + { + "op": "remove_track" + }, + { + "op": "set_binding", + "trackName": "Active", + "bindingObjectName": "Actor" + }, + { + "op": "set_duration", + "wrapMode": null + }, + { + "op": "set_duration", + "wrapMode": "" + }, + { + "op": "set_duration", + "wrapMode": "None" + }, + { + "op": "add_clip", + "trackName": "public-duration-boundary", + "start": 0, + "duration": -1 + }, + { + "op": "add_clip", + "trackName": "public-duration-boundary", + "start": 0, + "duration": -0.5 + } + ], + "domains": { + "1": [ + { + "index": 0, + "ok": false, + "reasons": [ + "no_timeline" + ] + } + ], + "2": [ + { + "index": 0, + "ok": false, + "reasons": [ + "unknown_op" + ] + }, + { + "index": 20, + "ok": false, + "reasons": [ + "unknown_op" + ] + } + ], + "3": [ + { + "index": 6, + "ok": false, + "reasons": [] + }, + { + "index": 7, + "ok": false, + "reasons": [] + }, + { + "index": 8, + "ok": false, + "reasons": [] + }, + { + "index": 27, + "ok": false, + "reasons": [] + }, + { + "index": 28, + "ok": false, + "reasons": [] + } + ], + "4": [ + { + "index": 11, + "ok": false, + "reasons": [] + }, + { + "index": 24, + "ok": false, + "reasons": [] + }, + { + "index": 25, + "ok": false, + "reasons": [] + } + ], + "5": [ + { + "index": 14, + "ok": false, + "reasons": [] + } + ], + "6": [ + { + "index": 17, + "ok": true, + "reasons": [] + }, + { + "index": 18, + "ok": false, + "reasons": [ + "track_not_found" + ] + }, + { + "index": 22, + "ok": false, + "reasons": [] + } + ], + "7": [ + { + "index": 15, + "ok": false, + "reasons": [] + }, + { + "index": 16, + "ok": false, + "reasons": [] + } + ], + "8": [ + { + "index": 1, + "ok": false, + "reasons": [] + }, + { + "index": 2, + "ok": true, + "reasons": [] + }, + { + "index": 3, + "ok": true, + "reasons": [] + }, + { + "index": 4, + "ok": true, + "reasons": [] + }, + { + "index": 5, + "ok": true, + "reasons": [] + }, + { + "index": 9, + "ok": true, + "reasons": [] + }, + { + "index": 10, + "ok": true, + "reasons": [] + }, + { + "index": 12, + "ok": true, + "reasons": [] + }, + { + "index": 13, + "ok": true, + "reasons": [] + }, + { + "index": 19, + "ok": true, + "reasons": [] + }, + { + "index": 21, + "ok": true, + "reasons": [] + }, + { + "index": 23, + "ok": true, + "reasons": [] + }, + { + "index": 26, + "ok": true, + "reasons": [] + } + ] + } + } +] diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/repair_manifest.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/repair_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..73f3153ad6aa595c7ec843f9664202d36e1d78d7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/repair_manifest.json @@ -0,0 +1,313 @@ +{ + "query_id": "d3ce3afb97a91cfa9ec6e68f", + "sample_index": 305, + "canonical_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "original_count": 11, + "revision": 2, + "repair_scope": "grader_only_round4_20261018", + "status": "implemented_pending_independent_review", + "root_cause": "grader", + "public_semantics": "Preserve11oldtypedTimeline domains, literalpaths/fullapp/helper/stdclosure/bytes; original+oneboundarypanel, no privateparameterreason/rc0/priorRun.", + "checker_sha256": "c47b9a3eaa90da428b11eb6d2bcca9d07b85c7c98b80f86cc59d86a6040c200f", + "actual_authors": [ + "c" + ], + "canonical_sha256": "fa9ec26b1922b1f467b46b3efe464aa9cccf2184d8dfcfaebdbf8ee59cf3c0eb", + "source_binding": { + "evaluator/check.py": { + "source_sha256": "924f9b025a624c4d1f710f06f9703b34844c6fc6072d9306481b534a043c219e", + "view_sha256": "924f9b025a624c4d1f710f06f9703b34844c6fc6072d9306481b534a043c219e" + }, + "inputs/ops.": { + "source_sha256": "ac82330057e41744c53cc9154ed2b4aa180df306d61411e71f514c69c7963063", + "view_sha256": "ac82330057e41744c53cc9154ed2b4aa180df306d61411e71f514c69c7963063" + }, + "instruction.md": { + "source_sha256": "6c357a42cb2b900ec2fe84e901c0714bb73582f4666192f2052a1a8166977337", + "view_sha256": "6c357a42cb2b900ec2fe84e901c0714bb73582f4666192f2052a1a8166977337" + }, + "reference/answer.txt": { + "source_sha256": "b19dad4d6c4b16ce45de000b478fd957ada69f3f3ac0cdc9f5464a4a65c9dd69", + "view_sha256": "b19dad4d6c4b16ce45de000b478fd957ada69f3f3ac0cdc9f5464a4a65c9dd69" + }, + "reference/workspace/instruction.md": { + "source_sha256": "6c357a42cb2b900ec2fe84e901c0714bb73582f4666192f2052a1a8166977337", + "view_sha256": "6c357a42cb2b900ec2fe84e901c0714bb73582f4666192f2052a1a8166977337" + }, + "reference/workspace/ops.": { + "source_sha256": "ac82330057e41744c53cc9154ed2b4aa180df306d61411e71f514c69c7963063", + "view_sha256": "ac82330057e41744c53cc9154ed2b4aa180df306d61411e71f514c69c7963063" + }, + "reference/workspace/report.json": { + "source_sha256": "289ab42c214b28f6626947e389cdcb7cee6dfa78d25d201ee9f6d86eae010d2e", + "view_sha256": "289ab42c214b28f6626947e389cdcb7cee6dfa78d25d201ee9f6d86eae010d2e" + }, + "reference/workspace/validate_timeline.py": { + "source_sha256": "78d46f09802cf7ea855a6f213c11615fe56aa96956173c5a456dc0da4946baf2", + "view_sha256": "78d46f09802cf7ea855a6f213c11615fe56aa96956173c5a456dc0da4946baf2" + }, + "skill/SKILL.md": { + "source_sha256": "0c17a81d705fb588b0cb34a02e22597b5f510dd833b12f26f666e4b6253c93b0", + "view_sha256": "0c17a81d705fb588b0cb34a02e22597b5f510dd833b12f26f666e4b6253c93b0" + }, + "task.json": { + "source_sha256": "728fac1920203c65628e955c6e6a0083c50076f21ca672b2c02eec031f525427", + "view_sha256": "728fac1920203c65628e955c6e6a0083c50076f21ca672b2c02eec031f525427" + } + }, + "contract_audit": { + "cause": "grader", + "task_verdict": "sound", + "grader_verdict": "repaired", + "execution_chain_verdict": "public_wiring_sound", + "canonical_ids_sound": true, + "no_extra_contract_requirements": true, + "reviewed_source_paths": [ + "instruction.md", + "task.json", + "evaluator/check.py", + "skill/SKILL.md", + "reference/answer.txt", + "inputs/ops.", + "reference/workspace/instruction.md", + "reference/workspace/ops.", + "reference/workspace/report.json", + "reference/workspace/validate_timeline.py" + ], + "obligations": [ + { + "id": "program_report", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Named stdlibPython3 script readsops. andwritesreport. JSON, no priorRun/exit0 assumption", + "material": true, + "check_ids": [ + "0" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "no_order_guard_nonstdlib" + ] + }, + { + "id": "ordering", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Any noncreate beforefirstcreate hasno_timeline", + "material": true, + "check_ids": [ + "1" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "no_order_guard_nonstdlib" + ] + }, + { + "id": "whitelist", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Onlypublicwhitelist operations accepted and unknown_op reported", + "material": true, + "check_ids": [ + "2" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "clip", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "add_clip requires trackName and numericnonbool start/duration>=0; optionaldefaults valid", + "material": true, + "check_ids": [ + "3" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "wrapmode", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "set_duration wrapMode ifpresent Hold/Loop/None; omissiondefault allowed", + "material": true, + "check_ids": [ + "4" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations", + "present_null_empty_wrapmode_treated_as_omitted" + ] + }, + { + "id": "play", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "play actionifpresent play/pause/stop; omissiondefaultplay", + "material": true, + "check_ids": [ + "5" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "remove", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "remove_track requiresname andonlycurrentlypresent previousaddedtrack; repeatedremove fails", + "material": true, + "check_ids": [ + "6" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "binding", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "set_binding requiresbothtrackName andbindingObjectName", + "material": true, + "check_ids": [ + "7" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "valid_defaults_create", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Validtypedops/defaults pass; create requiresname", + "material": true, + "check_ids": [ + "8" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "accepts_all_operations" + ] + }, + { + "id": "summary", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Summary exact nonbool numericcounts correct for actualinputandrowbooleans; equal JSON16/16.0 accepted", + "material": true, + "check_ids": [ + "9" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "frozen_original_report" + ] + }, + { + "id": "shape", + "source_path": "instruction.md", + "source_lines": [ + 1 + ], + "requirement": "Everyop exactlyone unique numericindex/op/strictbool/errorslist row, outputorder unrestricted, reportsummary/errorsconsistent", + "material": true, + "check_ids": [ + "10" + ], + "positive_controls": [ + "authored_literal_output_and_present_values", + "combined_helper_app_unused_bytes_nonzero" + ], + "negative_controls": [ + "frozen_original_report" + ] + } + ], + "task_analysis": "Task isoffline JSONvalidator only, no actualUnity editor/network/approvalaction. Primary namedliteral ops./report. remains authoritative versus reference report.json. Public parameter types applywhenpresent, defaultsonlyomitted; no successrc0 or priorRun obligation.", + "grader_analysis": "11 oldowners retained. Original16ops preserved, one24op panel covers absentname/defaults/remainingtypedwhitelist/multipleknownorderingerrors/bool+nullnumeric/presentemptyaction/missingbindingfields. Nonfixedparameter reasoncodes not imposed. Reference minimalpositivechanges outputfilename andpresentvaluefallback only. Sevenfullvectors handderived; no modeloracle. Unique2 resolves completeFIRSTF1/F2: count/index nonbool numeric equivalence and uniqueindex coverage/opbinding independent resultlistorder; combinedhelperpositive reversedrecords/floatingcountandindex. Freshpanel extends24to27 onlywithpresentnull/emptywrapModeinvalid andliteralNonevalid. Everyold7map rederived unchanged; newfocusedwrapfallbacknegative only4False.", + "execution_chain_analysis": "Fullclone actualapp with publicterminaldotinput andoutput, oldreports cleared, exactnamedPythonCLI. Bytes streamsunused, exit7allowed, launch/timeout/signalunknown. stdlibclosure under0; originalRunartifactnotrequired. No candidate/checker/model/referenceexecution orprivatehistoryread." + }, + "substantive_change": "OnlycompleteFIRSTF1/F2: equalnumericcounts/index+unorderedindexedrows andpresence-basedwrapModeenum,3focusedrows+1negative;combinedexistingpositive exerciseslegalequivalents.", + "historical_scores_seen": false, + "score_exposure_scope": null, + "solver_or_arm_conditioned": false, + "new_solver_executions": 0, + "notes": [ + "All8completevectors manuallyrederived. Original7expectedmaps unchanged, unaffectedoriginalref/frozen/allok/signal payloads stable; positive/noorder/combined actualproducerwrapfixexplicitlyreviewable. No candidate/checker/reference/model execution or privatehistoryread." + ] +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/workspace_copy.py b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/workspace_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..92b57ae29e6fd3e02487af3d613d7dccb07e08bd --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/evaluator/workspace_copy.py @@ -0,0 +1,24 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +from contextlib import contextmanager +from pathlib import Path +import shutil + +def clean(root): + for path in root.iterdir(): + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + else:path.unlink() + +@contextmanager +def workspace(remove=()): + roots=[Path('/workspace'),Path('/app')] + try: + for root in roots: + root.mkdir(exist_ok=True);clean(root);shutil.copytree('/candidate',root,dirs_exist_ok=True,symlinks=True) + for name in remove: + path=root/name + if path.is_dir() and not path.is_symlink():shutil.rmtree(path) + elif path.exists() or path.is_symlink():path.unlink() + yield roots[0] + finally: + for root in roots: + if root.exists():clean(root) diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/grading/verified_config.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/grading/verified_config.json new file mode 100644 index 0000000000000000000000000000000000000000..ac6a6f5f4328ae00d0a2272d9b35bd91e4c607f0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/grading/verified_config.json @@ -0,0 +1,51 @@ +{ + "schema": "audited-verified-grader-v1", + "query_id": "d3ce3afb97a91cfa9ec6e68f", + "runtime_requirements": { + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10" + ], + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none", + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1, + "10": 1 + }, + "result_policy": "Completed ordinary candidates yield fixed Boolean checks and normalized weighted score; candidate schema/execution failures are scored failures; trusted evaluator/environment errors yield evaluation_error with no score and must be retried after repair." + }, + "engine": "verified514_offline_v1", + "selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "grader_file_sha256": { + "auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa", + "workspace_copy.py": "99e435a77c4f789572fec68c896669a9caac680b6f8df8928a6accbe4cfc24d3", + "candidate_artifacts.py": "1857e74fae0bffb9f16f194dc9124135b17ca23a1bb3ed56d8e868f37b23e185", + "check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703", + "auto_policy.json": "f6e4a3b5fbc38e0a6fb6c20df2996b628e42c8cd56f32b06155fc08e0b85e0dc", + "repair_manifest.json": "221f7e41764bf13f4dad87de59c28dd1097708df78180418fb04706d87292b43", + "dependency_scan.py": "e828073332857154e4a1aba28ae0a6e68810fe353e7c7e7e28f0af2fa5317c50", + "auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0", + "autograde_task_check.py": "b6ee2feaf1908a0931a2ea2e95c9169bdb261ab8cb78fec677532da15a3a97c8", + "auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932", + "auto_contract.json": "849b17327d7eb151740cb1af5cade2f38a02f85c905797e3fec58c57b2053479", + "input_snapshots/panels.json": "e8e0020714ed5ca0503561fe31b2d73a69a7e1d48863232901b2abe5a81d0128" + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/inputs/ops. b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/inputs/ops. new file mode 100644 index 0000000000000000000000000000000000000000..21c954543434332594dc01bf3eefbaee8ba02abe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/inputs/ops. @@ -0,0 +1,18 @@ +[ + {"op": "add_animation_track", "trackName": "Hero Move"}, + {"op": "create", "name": "IntroCutscene"}, + {"op": "add_animation_track", "trackName": "Hero Move"}, + {"op": "add_audio_track", "trackName": "Music"}, + {"op": "add_keyframe", "trackName": "Hero Move", "time": 1.5}, + {"op": "add_clip", "trackName": "Hero Move", "start": 0, "duration": 2.5}, + {"op": "add_clip", "trackName": "Music", "start": -1, "duration": 3}, + {"op": "set_duration", "duration": 5, "wrapMode": "Loop"}, + {"op": "set_duration", "wrapMode": "Repeat"}, + {"op": "play", "action": "rewind"}, + {"op": "play"}, + {"op": "remove_track", "trackName": "Music"}, + {"op": "remove_track", "trackName": "Music"}, + {"op": "set_binding", "trackName": "Hero Move"}, + {"op": "set_binding", "trackName": "Hero Move", "bindingObjectName": "Hero"}, + {"op": "list_tracks"} +] diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/instruction.md b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..946c31337f587207f8c60c97940329e17f76d5a8 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/instruction.md @@ -0,0 +1,14 @@ +A game team wrote a JSON array of planned Unity Timeline operations in `ops.` (copied from inputs/ops.). Write a Python 3 standard-library program `validate_timeline.py` that reads it and writes `report.`. Derive the supported operation catalogue, create-name requirement, optional defaults for add_clip/set_duration/play, wrapMode values and play-action values from the bundled frozen Timeline Skill's parameter tables. Operation names in this JSON adapter omit the `timeline_` prefix; no Unity process, REST server or remote schema is needed. Validate only the operation types listed under that Skill's Skills section. + +The offline validator additionally has these explicit constraints; they narrow the original API and must not be inferred from optional API fields: +- add_clip.start and add_clip.duration must be numbers >=0, applying their documented defaults when absent. set_duration.duration is optional with the documented default; if present, wrapMode must use a documented value. play.action likewise uses its documented default/value set. +- remove_track, add_clip and set_binding require trackName; set_binding also requires bindingObjectName, even where the underlying API table calls these optional. +- Any non-create operation before the first create fails with no_timeline. remove_track referring to a track never added by a previous typed add-track operation fails with track_not_found. +- Unknown operation names fail with unknown_op. For other invalid fields emit a nonempty reason string identifying the violation; no fixed spelling is required. + +For each operation emit `{index,op,ok,errors:[...]}`, with zero-based source index and all applicable reason strings. Also emit top-level summary `{total,passed,failed}`. Results may be in any order; index/op must identify their source operation. Only validate the plan; do not execute Timeline operations. + +Bounded runtime policy: the dependency condition is assessed only during the actual Python script/module invocations launched by the grader, including local helpers imported by those invocations. Standard-library and authored local imports are allowed. Dead branches, unused files and import-like strings are not analyzed. Native/FFI loading or calls are disallowed during those observed invocations; normal built-in standard-library C extensions remain allowed. The grader uses the per-invocation finite time budget (at most90 seconds); exceeding that budget or an uncaught candidate exception is a candidate execution failure. Missing/broken trusted fixtures or instrumentation is reported as an infrastructure error, separately from candidate check results. + + +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. 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/d3ce3afb97a91cfa9ec6e68f/skill/SKILL.md b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..c31747955e83f00b00d4cc137234c8b76152ba8a --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/skill/SKILL.md @@ -0,0 +1,187 @@ +--- +name: unity-timeline +description: "Unity Timeline editing: create Timeline assets, add typed tracks (animation/audio/activation/control/signal), add clips, set bindings, play/pause/stop via PlayableDirector. Triggers: timeline, cutscene, sequence, PlayableDirector, Director, track, animation track, audio track, activation track, control track, signal track, clip, playable, binding, wrap mode, editor preview, 时间轴, 过场动画, 序列, 轨道, 动画轨道, 音频轨道, 信号轨道, 剪辑, 绑定." +platforms: [unity-editor, claude-code] +task-categories: [timeline, animation, editor-automation] +use-when: |- + Load when the task requires: Unity Timeline editing: create Timeline assets, add typed tracks (animation/audio/activation/control/signal), add clips, set bindings, play/pause/stop via PlayableDirector. Unity Editor must be running with the unity-skills REST server reachable at http://localhost:8090. +do-not-use-when: |- + Do not load when Unity Editor is not running locally. Do not load when unity-skills REST server is unreachable at http://localhost:8090. For Animator parameters/states → use `animator` module instead. For runtime animation playback → use `editor_play` module instead. +metadata: + source: https://github.com/Besty0728/Unity-Skills + version: 1.9.2 + tier: 2 + +--- + +# Timeline Skills + +Create and modify Unity Timeline assets — add typed tracks, drop clips on tracks, bind objects, set duration / wrap mode, and play/pause/stop the editor preview through the PlayableDirector. + +## Operating Mode + +- **Approval**(默认):查询类 skill(`timeline_list_tracks`,源码标 `SkillMode.SemiAuto`)直接执行;其余变更/播放类(`timeline_create` / add_*_track / `timeline_add_clip` / `timeline_set_duration` / `timeline_play` / `timeline_set_binding`,标 `SkillMode.FullAuto`)需用户 grant,grant 后服务端一步执行返结果。 +- **Auto / Bypass**:未被禁列表拦截的 skill 直接执行。 +- 本模块**含 Delete 类 skill**:`timeline_remove_track` 标记为 `SkillOperation.Delete`,被 `IsForbiddenInSemi` 静态拦截 —— 仅 **Bypass** 模式或加入 **Allowlist** 才能调用。 +- `timeline_play` 仅驱动 Editor 预览(PlayableDirector.Evaluate / Play 在编辑器上下文),不会进入 Play mode。 + +**DO NOT** (common hallucinations): +- `timeline_create_animation` / `timeline_add_track` do not exist → use the typed track skills: `timeline_add_animation_track`, `timeline_add_audio_track`, `timeline_add_activation_track`, `timeline_add_control_track`, `timeline_add_signal_track` +- `timeline_add_keyframe` does not exist → Timeline uses clips, not direct keyframes; use `timeline_add_clip` +- `timeline_set_duration` sets the Timeline asset duration, not individual clip duration + +**Routing**: +- For Animator parameters/states → use `animator` module +- For runtime animation playback → use `editor_play` or write C# via `script` module + +## Skills + +### `timeline_create` +Create a new Timeline asset and Director instance. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | Yes | - | Name of the timeline/object | +| folder | string | No | "Assets/Timelines" | Folder to save asset | + +**Returns:** `{ success, assetPath, gameObjectName, directorInstanceId }` + +### `timeline_add_audio_track` +Add an Audio track to a Timeline. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | "Audio Track" | Name of the new track | + +**Returns:** `{ success, trackName }` + +### `timeline_add_animation_track` +Add an Animation track to a Timeline, optionally binding an object. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | "Animation Track" | Name of the new track | +| bindingObjectName | string | No | - | Name of the GameObject to bind (animator) | + +**Returns:** `{ success, trackName, boundObject }` + +### `timeline_add_activation_track` +Add an Activation track to control object visibility. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | "Activation Track" | Name of the new track | + +**Returns:** `{ success, trackName }` + +### `timeline_add_control_track` +Add a Control track for nested Timelines or prefab spawning. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | "Control Track" | Name of the new track | + +**Returns:** `{ success, trackName }` + +### `timeline_add_signal_track` +Add a Signal track for event markers. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | "Signal Track" | Name of the new track | + +**Returns:** `{ success, trackName }` + +### `timeline_remove_track` +Remove a track by name from a Timeline. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | - | Name of the track to remove | + +**Returns:** `{ success, removed }` + +### `timeline_list_tracks` +List all tracks in a Timeline. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | + +**Returns:** `{ count, tracks: [{ name, type, muted, clipCount }] }` + +### `timeline_add_clip` +Add a clip to a track by track name. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | - | Name of the target track | +| start | double | No | 0 | Clip start time in seconds | +| duration | double | No | 1 | Clip duration in seconds | + +**Returns:** `{ success, trackName, clipStart, clipDuration }` + +### `timeline_set_duration` +Set Timeline duration and wrap mode. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| duration | double | No | 0 | Fixed duration in seconds | +| wrapMode | string | No | - | Wrap mode: Hold/Loop/None | + +**Returns:** `{ success, duration, wrapMode }` + +### `timeline_play` +Play, pause, or stop a Timeline (Editor preview). + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| action | string | No | "play" | Action: play/pause/stop | + +**Returns:** `{ success, action, time }` + +### `timeline_set_binding` +Set the binding object for a track. + +| Parameter | Type | Required | Default | Description | +|-----------|------|----------|---------|-------------| +| name | string | No | - | GameObject name with PlayableDirector | +| instanceId | int | No | 0 | GameObject instance ID | +| path | string | No | - | GameObject hierarchy path | +| trackName | string | No | - | Name of the track | +| bindingObjectName | string | No | - | Name of the object to bind | + +**Returns:** `{ success, trackName, boundTo }` + +## Exact Signatures + +Exact names, parameters, defaults, and returns are defined by `GET /skills/schema` or `unity_skills.get_skill_schema()`, not by this file. diff --git a/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/task.json b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b7fbeac1ecd1cd2c7aaa05674a4c49ed2a3f77e0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d3ce3afb97a91cfa9ec6e68f/task.json @@ -0,0 +1,69 @@ +{ + "schema_version": "skill-search-synthesis-v1", + "task_id": "d3ce3afb97a91cfa9ec6e68f", + "environment": { + "image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56", + "network": "none" + }, + "query_id": "d3ce3afb97a91cfa9ec6e68f", + "outputs": [ + "report.", + "validate_timeline.py" + ], + "success_criteria": [ + "Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.", + "Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md." + ], + "evaluation": { + "kind": "python", + "type": "verified" + }, + "source_skill": { + "sha256": "c4395c7cc792ead8ac479cdf725ba194c475973b66cc90ce8025b33333bc3212", + "files": { + "SKILL.md": "0c17a81d705fb588b0cb34a02e22597b5f510dd833b12f26f666e4b6253c93b0" + } + }, + "workspace": { + "candidate_mode": "workspace", + "input_mappings": [ + { + "source": "inputs/ops.", + "workspace_target": "ops.", + "sha256": "ac82330057e41744c53cc9154ed2b4aa180df306d61411e71f514c69c7963063" + } + ], + "skill_packages": [ + { + "package_path": "skill", + "content_hash": "c4395c7cc792ead8ac479cdf725ba194c475973b66cc90ce8025b33333bc3212" + } + ] + }, + "autograde_runtime_policy": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true + }, + "autograde_contract_revision": "deterministic-v1", + "automatic_evaluation_runtime": { + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": false, + "forbid_subprocess": false, + "forbid_native": true, + "runtime_owner_ids": [ + "0" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420, + "contract": "Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. 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. 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/d62e6c1f73700f5fdfb53c7c/evaluator/auto_contract.json b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_contract.json new file mode 100644 index 0000000000000000000000000000000000000000..7ff26c7273a12246892c72f028e605b418530ec7 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_contract.json @@ -0,0 +1,26 @@ +{ + "expected_check_ids": [ + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ], + "criterion_weights": { + "0": 1, + "1": 1, + "2": 1, + "3": 1, + "4": 1, + "5": 1, + "6": 1, + "7": 1, + "8": 1, + "9": 1 + } +} diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_entry.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..172113b2556991f4188b53ad210df7db0e6165a2 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/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/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy.json b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy.json new file mode 100644 index 0000000000000000000000000000000000000000..d401546b7ec9eb320f44f75fe20e3d87b168da36 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy.json @@ -0,0 +1,14 @@ +{ + "schema": "bounded-policy-v1", + "stdlib_only": true, + "forbid_network": true, + "forbid_subprocess": true, + "forbid_native": true, + "runtime_owner_ids": [ + "6", + "9" + ], + "require_execution": true, + "execution_budget_seconds": 60, + "total_evaluation_budget_seconds": 420 +} diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c34f7c8a4e487198963bc76c19c73c6ff419d317 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/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)and argv[i].startswith('-'): + flag=argv[i] + if flag=='-m': + if i+1>=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):flags.append(argv[i]);i+=1 + if 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 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') + kwargs['timeout']=budget + remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None + if remaining is not None and remaining>0: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/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy_guard.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/auto_policy_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..1dad27e6344e280d1ef7178ae9de49185682f7ee --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/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('<frozen importlib'):frame=frame.f_back;continue + absolute=os.path.abspath(filename) + return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names) + return False +original_import=builtins.__import__;original_import_module=importlib.import_module +def bounded_import(name,globals=None,locals=None,fromlist=(),level=0): + if not busy and subject_active()and import_requested_by_candidate(): + absolute=name + if level: + package=(globals or{}).get('__package__')or(globals or{}).get('__name__','') + try:absolute=importlib.util.resolve_name('.'*level+name,package) + except(ImportError,ValueError):absolute=name + check_import(absolute) + return original_import(name,globals,locals,fromlist,level) +def bounded_import_module(name,package=None): + if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name) + return original_import_module(name,package) +save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module +@atexit.register +def finish():state['state']='finished';save() +for p in reversed(local_roots):sys.path.insert(0,str(p)) +sys.argv=[target,*arguments] +if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True) +else:runpy.run_path(target,run_name='__main__') diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/autograde_task_check.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/autograde_task_check.py new file mode 100644 index 0000000000000000000000000000000000000000..5d64e24a92e572666a6120a75e94ef05984742fa --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/autograde_task_check.py @@ -0,0 +1,122 @@ +"""Offline TTS planning compositions; original resolver checks remain intact.""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import json,sys,os,shutil,tempfile,subprocess,math +from pathlib import Path +from r4_recovery import (assess as r4_recovery_panel, output_bytes, prepare_fixture_directory, + write_fixture, remove_fixture_path) +HERE=Path(__file__).resolve().parent +PROVIDERS=['siliconflow','openai','minimax','elevenlabs','relay'];ENV_KEYS={p.upper()+suffix for p in PROVIDERS for suffix in['_API_KEY','_BASE_URL']} + +def tri(values): + values=list(values);return False if any(v is False for v in values)else None if any(v is None for v in values)else True + +def finite_number(value): + # Python integers are finite without conversion to a bounded IEEE float. + return type(value)is int or (type(value)is float and math.isfinite(value)) + +def same(a,b): + # Check bool before numeric equality; ordinary int/float values remain equivalent. + if type(a)is bool or type(b)is bool:return type(a)is type(b)and a==b + if type(a)in(int,float)and type(b)in(int,float):return finite_number(a)and finite_number(b)and a==b + if type(a)is not type(b):return False + if isinstance(a,dict):return set(a)==set(b)and all(same(a[k],b[k])for k in a) + if isinstance(a,list):return len(a)==len(b)and all(same(x,y)for x,y in zip(a,b)) + return a==b + +def previous(): + p=subprocess.run([sys.executable,str(HERE/'hard_original_check.py')],capture_output=True,text=True,timeout=600) + for line in reversed(p.stdout.splitlines()): + try:body=json.loads(line) + except ValueError:continue + if isinstance(body,dict)and isinstance(body.get('checks'),list):return body + return dict(checks=[dict(id=str(i),passed=None,reason='R12 resolver observation unavailable')for i in range(7)]) + +def environment(index): + return {p.upper()+'_API_KEY':p+'-secret-'+str(index)for p in PROVIDERS}|{'OPENAI_BASE_URL':'https://oa-inherited-'+str(index)+'.invalid/v1///','MINIMAX_BASE_URL':'https://mm-inherited-'+str(index)+'.invalid/'} + +def observe(rows,index=0,extra=None,raw=None,present=True): + with tempfile.TemporaryDirectory(prefix='hard-tts-',dir='/tmp')as td,tempfile.TemporaryDirectory(prefix='r5-tts-audit-',dir='/tmp')as audit_dir: + w=Path(td);shutil.copytree('/candidate',w,dirs_exist_ok=True,symlinks=True);prepare_fixture_directory(w/'scripts') + keys=environment(index) + cwd='\n'.join(k+'='+v for k,v in keys.items()if k not in['OPENAI_API_KEY','ELEVENLABS_API_KEY','OPENAI_BASE_URL','MINIMAX_BASE_URL'])+'\nSILICONFLOW_BASE_URL=https://sf-cwd-'+str(index)+'.invalid/v2///\nRELAY_BASE_URL=https://relay-cwd-'+str(index)+'.invalid/v1///\n' + fallback='\n'.join(k+'='+v for k,v in keys.items())+'\nSILICONFLOW_BASE_URL=https://wrong-script.invalid\nRELAY_BASE_URL=https://wrong-script-relay.invalid\nELEVENLABS_BASE_URL=https://el-script-'+str(index)+'.invalid///\n' + write_fixture(w/'.env',cwd);write_fixture(w/'scripts/.env',fallback);write_fixture(w/'requests.json',json.dumps(rows,ensure_ascii=False)if raw is None else raw) + immutable={r:(w/r).read_bytes()for r in['.env','scripts/.env','requests.json']};out=w/'plan.json';remove_fixture_path(out) + if present:out.write_bytes(b'operator-owned previous plan\x00\n') + before=out.read_bytes()if present else None + env={k:v for k,v in os.environ.items()if k not in ENV_KEYS};env.update({k:keys[k]for k in['OPENAI_BASE_URL','MINIMAX_BASE_URL']});env.update(extra or{}) + receipt=Path(audit_dir)/'receipt.json' + try:p=subprocess.run([sys.executable,str(HERE/'hard_plan_guard.py'),str(w/'resolve_providers.py'),str(receipt),'--plan','requests.json','plan.json'],cwd=w,env=env,capture_output=True,text=True,timeout=45) + except (OSError,subprocess.SubprocessError) as error:raise RuntimeError('Trusted plan launcher failed')from error + try:events=receipt.read_text().splitlines()if receipt.is_file()else [] + except OSError:events=[] + audit=False if any(x.startswith('violation:')for x in events)else None if'ready'not in events or'unknown-native'in events else True + try: + if out.is_file():output=out.read_bytes();output_readable=True + elif not os.path.lexists(out):output=None;output_readable=True + else:output=None;output_readable=False + except OSError:output=None;output_readable=False + try:doc=json.loads(output)if output is not None else None + except(ValueError,UnicodeError,RecursionError):doc=None + unchanged_inputs=all(output_bytes(w/r)==content for r,content in immutable.items()) + unchanged_output=output_readable and (output==before if before is not None else output is None) + secrets=[p+'-secret-'+str(index)for p in PROVIDERS];text=p.stdout+p.stderr+(output.decode('utf-8','replace')if output is not None else'');redacted=output_readable and all(secret not in text for secret in secrets) + return p,doc,audit,unchanged_inputs,unchanged_output,redacted + +def expected(row,provider,model,index): + voice=row.get('voice')or'';speed=float(row['speed'])if'speed'in row else None;rate=float(row['sample_rate'])if'sample_rate'in row else None + bases={'siliconflow':f'https://sf-cwd-{index}.invalid/v2','openai':f'https://oa-inherited-{index}.invalid/v1','minimax':f'https://mm-inherited-{index}.invalid','elevenlabs':f'https://el-script-{index}.invalid','relay':f'https://relay-cwd-{index}.invalid/v1'} + if provider in['siliconflow','openai','relay']: + url=bases[provider]+'/audio/speech';body={'model':model,'input':row['text']} + if voice:body['voice']=voice + if row.get('format'):body['response_format']=row['format'] + if speed is not None:body['speed']=speed + if rate is not None:body['sample_rate']=rate + elif provider=='minimax':url=bases[provider]+'/v1/t2a_v2';body={'model':model,'text':row['text'],'voice_setting':{'voice_id':voice or'male-qn-qingse','speed':speed if speed is not None else 1,'vol':1},'audio_setting':{'sample_rate':rate if rate is not None else 32000,'bitrate':128000,'format':'wav'if row.get('format')=='wav'else'mp3'}} + else: + url=bases[provider]+'/v1/text-to-speech/'+(voice or'pNInz6obpgDQGcFmaJgB');body={'text':row['text'],'model_id':model} + if speed is not None:body['speed']=speed + return dict(id=row['id'],provider=provider,model=model,url=url,method='POST',auth_env=provider.upper()+'_API_KEY',auth_header='xi-api-key'if provider=='elevenlabs'else'Authorization',auth_prefix=''if provider=='elevenlabs'else'Bearer ',body=body) + +def augment(body): + flags=[True]*3;notes=[] + for index in[1,4]: + rows=[dict(id='sf'+str(index),text='你好 '+str(index),voice='voice-A',format='wav',speed='1.25',sample_rate=24000),dict(id='forced'+str(index),provider='openai',model='speech-special',text='explicit beats inference'),dict(id='relay'+str(index),model='org/model-'+str(index),text='route slash',speed=.9),dict(id='mini'+str(index),provider='minimax',text='defaults',format='opus',sample_rate='48000'),dict(id='eleven'+str(index),model='eleven_custom',text='eleven options',voice='custom-voice',speed='1.1',format='wav',sample_rate=16000),dict(id='relay-default'+str(index),provider='relay',text='default relay'),dict(id='collision'+str(index),model='FunAudioLLM/elevenlabs',text='prefix before substring'),dict(id='mini-forced'+str(index),provider='minimax',model='fnlp/other',text='provider wins',voice='custom-minimax',format='wav',speed=1.2),dict(id='eleven-default'+str(index),provider='elevenlabs',text='default voice')] + routes=[('siliconflow','FunAudioLLM/CosyVoice2-0.5B'),('openai','speech-special'),('relay','org/model-'+str(index)),('minimax','speech-02-hd'),('elevenlabs','eleven_custom'),('relay','tts-1'),('siliconflow','FunAudioLLM/elevenlabs'),('minimax','fnlp/other'),('elevenlabs','eleven_multilingual_v2')] + rows.append(dict(id='minimax-inferred-'+str(index),model='speech-02-hd',text='Provider omitted: infer MiniMax from speech model')) + routes.append(('minimax','speech-02-hd')) + for provider,model in[('siliconflow','FunAudioLLM/CosyVoice2-0.5B'),('openai','tts-1'),('minimax','speech-02-hd'),('elevenlabs','eleven_multilingual_v2'),('relay','tts-1')]: + rows.append(dict(id='numeric-zero-'+provider+'-'+str(index),provider=provider,text='Explicit numeric zero follows CLI string semantics',speed=0,sample_rate=0));routes.append((provider,model)) + if index==4:rows=list(reversed(rows));routes=list(reversed(routes)) + want=[expected(row,provider,model,index)for row,(provider,model)in zip(rows,routes)] + p,actual,audit,unchanged,_,redacted=observe(rows,index) + route=None if p is None else p.returncode==0 and isinstance(actual,list)and len(actual)==len(want)and all(isinstance(a,dict)and all(same(a.get(k),e[k])for k in['id','provider','model','url'])for a,e in zip(actual,want)) + exact=None if p is None else p.returncode==0 and same(actual,want)and redacted + behavior=None if p is None else p.returncode==0 and p.stdout==''and unchanged + flags=[tri([flags[0],route]),tri([flags[1],exact]),tri([flags[2],behavior,audit])];notes.append(dict(panel=index,branch='provider_composition',route=route,exact=exact)) + # Public default bases must apply when non-relay base variables are explicitly empty. + rows=[dict(id='default-'+p,provider=p,text='default endpoint '+p)for p in['siliconflow','openai','minimax','elevenlabs']] + defaults={'siliconflow':('FunAudioLLM/CosyVoice2-0.5B','https://api.siliconflow.cn/v1/audio/speech'),'openai':('tts-1','https://api.openai.com/v1/audio/speech'),'minimax':('speech-02-hd','https://api.minimaxi.com/v1/t2a_v2'),'elevenlabs':('eleven_multilingual_v2','https://api.elevenlabs.io/v1/text-to-speech/pNInz6obpgDQGcFmaJgB')} + want=[] + for r in rows: + model,url=defaults[r['provider']];e=expected(r,r['provider'],model,7);e['url']=url;want.append(e) + p,actual,audit,unchanged,_,redacted=observe(rows,7,extra={x.upper()+'_BASE_URL':''for x in defaults}) + good=None if p is None else p.returncode==0 and same(actual,want)and redacted + flags[1]=tri([flags[1],good]);flags[2]=tri([flags[2],audit,unchanged,None if p is None else p.stdout=='']);notes.append(dict(branch='all_nonrelay_default_bases',passed=good)) + # An inherited empty relay key blocks lower file layers without disabling unrelated providers. + rows=[dict(id='inherited-empty',model='org/empty',text='fallback inference is siliconflow')];p,actual,audit,unchanged,_,_=observe(rows,8,extra={'RELAY_API_KEY':''});want=[expected(rows[0],'siliconflow','org/empty',8)] + flags[0]=tri([flags[0],None if p is None else p.returncode==0 and same(actual,want)]);flags[2]=tri([flags[2],audit,unchanged]) + failures=[([dict(id='valid-first',provider='siliconflow',text='okay'),dict(id='missing-key',provider='openai',text='must fail')],{'OPENAI_API_KEY':''},None,'missing-key'),([dict(id='missing-base',provider='relay',text='must fail')],{'RELAY_BASE_URL':''},None,'missing-base'),([dict(id='unknown-provider',provider='not-a-provider',text='must fail')],{},None,'unknown-provider'),([],{},'42',None),([],{},'{',None)] + for rows,extra,raw,identifier in failures: + for present in[True,False]: + p,actual,audit,unchanged,untouched,redacted=observe(rows,9,extra,raw,present) + value=None if p is None else p.returncode==1 and not p.stdout and bool(p.stderr.strip())and(identifier is None or identifier in p.stderr)and unchanged and untouched and redacted + flags[2]=tri([flags[2],value,audit]);notes.append(dict(branch='atomic_failure',id=identifier,old_output=present,passed=value)) + p,doc,audit,unchanged,_,_=observe([],11);flags[2]=tri([flags[2],audit,None if p is None else p.returncode==0 and same(doc,[])and not p.stdout and unchanged]) + recovery=r4_recovery_panel(expected,same,PROVIDERS,ENV_KEYS,HERE/'hard_plan_guard.py');flags=[tri([old,new])for old,new in zip(flags,recovery)];notes.append(dict(branch='same_workspace_retry_reconfiguration',flags=recovery)) + body['checks'] += [dict(id='7',passed=flags[0],reason='Inherited/cwd/script configuration precedence including empty presence; explicit provider/inference/default model composition on reordered requests'),dict(id='8',passed=flags[1],reason='Provider-specific endpoints/body/credential-name/header/prefix, options/defaults, Unicode and credential-value redaction'),dict(id='9',passed=flags[2],reason='Offline audit, silent success, no partial output on failure, prior output/input bytes preserved, empty batch succeeds')] + body['hardening_observations']=notes;body['scoreable']=all(type(r.get('passed'))is bool for r in body['checks']);return body +if __name__=='__main__': + try:result=augment(previous()) + except Exception as error:result=dict(scoreable=False,checks=[dict(id=str(i),passed=None,reason='trusted plan observation unavailable: '+type(error).__name__+': '+str(error))for i in range(10)]) + print(json.dumps(result,ensure_ascii=False)) diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/check.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21f6b2cceb8d75f5fd9719311b6a3da87a8b32ef --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/check.py @@ -0,0 +1,2 @@ +from auto_entry import main +raise SystemExit(main()) diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/dependency_scan.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/dependency_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..c445b715d75de8642f6156b6baedcc4d4f283afe --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/dependency_scan.py @@ -0,0 +1,16 @@ +"""Private static dependency validation, including local Python namespace packages. + +This module only parses source. It never imports or runs candidate modules. +""" +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() +import _imp +import ast +import sys +import tokenize +from pathlib import Path + + +def scan_stdlib(root, entries, external=()): + # Full-source dependency inference is intentionally absent. + # The final owner combines functional facts with the trusted invocation receipt. + return True, [], 'deferred: actual graded invocation policy' diff --git a/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/hard_original_check.py b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/hard_original_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7534a2a9d50a42a78236b2355b767c210b8e50a0 --- /dev/null +++ b/benchmarks/skillbench-venus-e/tasks/d62e6c1f73700f5fdfb53c7c/evaluator/hard_original_check.py @@ -0,0 +1,138 @@ +import auto_policy as _auto_policy_observer; _auto_policy_observer.install() + +from dependency_scan import scan_stdlib +def authored_stdlib_ok(candidate_dir,entry):return scan_stdlib(candidate_dir,[entry])[0] +import ast, json, os, shutil, subprocess, sys, tempfile, tokenize +from pathlib import Path +from r4_recovery import write_fixture, output_bytes +RUN_SILENT=[] + +ENV = '''# provider keys +SILICONFLOW_API_KEY=sk-test-123 +RELAY_BASE_URL = 'https://api.ofox.ai/v1' +RELAY_API_KEY="sk-relay-abc" +MINIMAX_API_KEY=sk-xxx +# commented out key +# OPENAI_API_KEY=sk-openai +''' +MODELS = ["FunAudioLLM/CosyVoice2-0.5B","speech-02-hd","eleven_multilingual_v2","tts-1","gpt-4o-mini-tts-latest","gpt-5-turbo","my-org/custom-voice","fishaudio/fish-speech-1.5","plainmodel","fnlp/basetts"] +EXPECTED = {"FunAudioLLM/CosyVoice2-0.5B":"siliconflow","speech-02-hd":"minimax","eleven_multilingual_v2":"elevenlabs","tts-1":"openai","gpt-4o-mini-tts-latest":"openai","gpt-5-turbo":"openai","my-org/custom-voice":"relay","fishaudio/fish-speech-1.5":"siliconflow","plainmodel":"siliconflow","fnlp/basetts":"siliconflow"} + +def result(checks, i, ok, reason): + checks.append({"id": str(i), "passed": None if ok is None else bool(ok), "reason": reason}) + +def run_script(script_src, env_text, extra_env=None, models=None): + models=MODELS if models is None else models + d = tempfile.mkdtemp(dir="/tmp") + try: + shutil.copytree("/candidate",d,dirs_exist_ok=True,symlinks=True,ignore=shutil.ignore_patterns("providers.","__pycache__","*.pyc")) + write_fixture(Path(d) / ".env", env_text) + write_fixture(Path(d) / "models.txt", "\n".join(models) + "\n") + sp = os.path.join(d, "resolve_providers.py") + # Copied entry keeps original physical bytes and its declared source encoding. + env = {k: v for k, v in os.environ.items() if not k.startswith("RELAY_") and k != "OPENAI_API_KEY"} + if extra_env: env.update(extra_env) + p = subprocess.run([sys.executable, "resolve_providers.py"], cwd=d, env=env, + capture_output=True, text=True, timeout=60) + out_path = os.path.join(d, "providers.") + blob = output_bytes(Path(out_path)) + try: + data = json.loads(blob) if blob is not None else None + except (ValueError, UnicodeError, RecursionError): + data = None + RUN_SILENT.append(p.returncode==0 and p.stdout=="") + return p, data + finally: + shutil.rmtree(d, ignore_errors=True) + +def main(): + checks = [] + src_path = "/candidate/resolve_providers.py" + if not os.path.isfile(src_path): + for i in range(7): + result(checks, i, False, "resolve_providers.py must be a readable Python source file") + print(json.dumps({"checks": checks})); return + try: + with tokenize.open(src_path) as f: src = f.read() + except (UnicodeError, SyntaxError) as error: + for i in range(7): + result(checks, i, False, "resolve_providers.py has invalid Python source encoding: " + type(error).__name__) + print(json.dumps({"checks": checks})); return + + p, data = run_script(src, ENV) + ran_ok = p.returncode == 0 + + # 0: file exists, valid JSON, all models mapped in order + ok0 = isinstance(data, dict) and list(data.keys()) == MODELS and all(isinstance(v, str) and v for v in data.values()) + result(checks, 0, ok0, "providers. is valid JSON with every model id as a key in input order" if ok0 else "providers. missing, invalid JSON, keys missing/misordered, or non-string values") + + got = data if isinstance(data, dict) else {} + # 1 siliconflow + sf = [m for m in ["FunAudioLLM/CosyVoice2-0.5B","fishaudio/fish-speech-1.5","fnlp/basetts","plainmodel"] if got.get(m) == "siliconflow"] + result(checks, 1, len(sf) == 4, "siliconflow models correct" if len(sf) == 4 else "wrong mapping for: " + ", ".join(m for m in ["FunAudioLLM/CosyVoice2-0.5B","fishaudio/fish-speech-1.5","fnlp/basetts","plainmodel"] if got.get(m) != "siliconflow")) + # 2 minimax/elevenlabs + ok2 = got.get("speech-02-hd") == "minimax" and got.get("eleven_multilingual_v2") == "elevenlabs" + result(checks, 2, ok2, "minimax/elevenlabs mappings correct" if ok2 else "speech-02-hd must be minimax and eleven_multilingual_v2 must be elevenlabs") + # 3 openai + oa = [m for m in ["tts-1","gpt-4o-mini-tts-latest","gpt-5-turbo"] if got.get(m) == "openai"] + result(checks, 3, len(oa) == 3, "openai models correct" if len(oa) == 3 else "wrong mapping for: " + ", ".join(m for m in ["tts-1","gpt-4o-mini-tts-latest","gpt-5-turbo"] if got.get(m) != "openai")) + # 4 relay + ok4 = got.get("my-org/custom-voice") == "relay" + result(checks, 4, ok4, "my-org/custom-voice maps to relay" if ok4 else "my-org/custom-voice should map to relay (RELAY_BASE_URL/RELAY_API_KEY configured after .env loading)") + + # 5 parser behavior probes (each observed via my-org/custom-voice) + probe_fail = [] + # a) commented-out RELAY_API_KEY must be ignored -> relay not configured -> siliconflow + _, d1 = run_script(src, "RELAY_BASE_URL=https://x/v1\n# RELAY_API_KEY=sk-x\n") + if not (isinstance(d1, dict) and d1.get("my-org/custom-voice") == "siliconflow"): + probe_fail.append("commented lines must be ignored") + # b) quoted empty value must strip to empty -> falsy -> siliconflow + _, d2 = run_script(src, "RELAY_BASE_URL='https://x/v1'\nRELAY_API_KEY=\"\"\n") + if not (isinstance(d2, dict) and d2.get("my-org/custom-voice") == "siliconflow"): + probe_fail.append("matching quotes must be stripped from values") + # c) existing env var must not be overridden by .env (empty preset stays falsy) + _, d3 = run_script(src, ENV, extra_env={"RELAY_API_KEY": "", "RELAY_BASE_URL": "https://preset/v1"}) + if not (isinstance(d3, dict) and d3.get("my-org/custom-voice") == "siliconflow"): + probe_fail.append("a variable must not override an already-set environment variable") + pp, dd=run_script(src," # RELAY_API_KEY=ignored\nRELAY_BASE_URL = 'https://x/v1?a=b'\nRELAY_API_KEY==\n") + if pp.returncode!=0 or not isinstance(dd,dict) or dd.get("my-org/custom-voice")!="relay":probe_fail.append("split FIRST equals and leading-space comments") + extras=["FunAudioLLM/elevenlabs","speech-v2/elevenlabs","acme/elevenlabs","gpt-5-custom/path"] + pp,dd=run_script(src,ENV,models=extras) + if pp.returncode!=0 or list(dd or {})!=extras or dd!=dict(zip(extras,["siliconflow","minimax","elevenlabs","relay"])):probe_fail.append("priority collision and actual models.txt reading") + result(checks, 5, not probe_fail, ".env parser handles comments, quote stripping and env non-override" if not probe_fail else "; ".join(probe_fail)) + + # 6 stdlib-only + runs successfully printing nothing else + stdlib_ok = True; detail = "" + try: + tree = ast.parse(src) + for node in ast.walk(tree): + names = [] + if isinstance(node, ast.Import): names = [a.name.split(".")[0] for a in node.names] + elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: names = [node.module.split(".")[0]] + for n in names: + if n not in sys.stdlib_module_names: + stdlib_ok = False; detail = "non-stdlib import: " + n + except Exception as e: + stdlib_ok = False; detail = "script does not parse: " + str(e) + dep_ok,dep_modules,dep_reason=scan_stdlib("/candidate",["resolve_providers.py"]) + dep_status=None if dep_reason.startswith("unknown:") else dep_ok + ok6 = dep_status if ran_ok and all(RUN_SILENT) else False + if not ran_ok: detail = "script exited with code %d" % p.returncode + elif p.stdout.strip(): detail = "script printed unexpected stdout" + result(checks, 6, ok6, dep_reason if ok6 is None else ("stdlib-only, runs successfully, prints nothing" if ok6 else detail or "script violates stdlib-only/silent-run requirement")) + + blob = output_bytes(Path('/candidate/providers.')) + try: + actual = json.loads(blob) if blob is not None else None + except (ValueError, UnicodeError, RecursionError): + actual = None + groups={0:MODELS,1:["FunAudioLLM/CosyVoice2-0.5B","fishaudio/fish-speech-1.5","fnlp/basetts","plainmodel"],2:["speech-02-hd","eleven_multilingual_v2"],3:["tts-1","gpt-4o-mini-tts-latest","gpt-5-turbo"],4:["my-org/custom-voice"]} + for check in checks: + index=int(check['id']) + if index in groups: + valid=isinstance(actual,dict) and all(actual.get(key)==EXPECTED[key]for key in groups[index]) + if index==0:valid=valid and list(actual)==MODELS + check['passed']=bool(check['passed']and valid);check['reason']+='; actual submitted providers. bound' + print(json.dumps({"scoreable":all(type(c["passed"])is bool for c in checks),"checks": checks})) + +main()