Upload Skill-Venus Data as released (part 11)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/instruction.md +7 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/SKILL.md +78 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/_export_skill_meta.json +20 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/references/fix-patterns.md +119 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/scripts/check-ci-failures.sh +57 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/skill-card.md +41 -0
- benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/task.json +86 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_contract.json +18 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.json +16 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/autograde_task_check.py +54 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/graph_probe.py +54 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/original_check.py +148 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/r10_support.py +107 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/grading/verified_config.json +86 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/bin/main.js +6 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/analyzer/summary.js +8 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/data/repo.js +7 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/model/store.js +6 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/util/format.js +2 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/instruction.md +7 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/SKILL.md +3 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M000/SKILL.md +56 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/SKILL.md +152 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/handler.js +511 -0
- benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/task.json +155 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_contract.json +8 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/autograde_task_check.py +12 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/check.py +2 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy-task.json +136 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/evaluate.py +159 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/objective_evaluators.py +1329 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/shell_invocations.py +265 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/test.sh +8 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/verifiers.py +554 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/grading/verified_config.json +99 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/instruction.md +1 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/skill/SKILL.md +36 -0
- benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/task.json +46 -0
- benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_contract.json +8 -0
- benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_entry.py +38 -0
- benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy.py +133 -0
- benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy_guard.py +86 -0
- benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/autograde_task_check.py +12 -0
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/instruction.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
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.
|
| 2 |
+
Bounded automatic resource contract: During the actual grader-launched Python invocations, Python imports must resolve to the standard library or submitted local modules/packages (including namespace packages and computed imports). Unused/dead source code and strings are not rejected by static import inference. Do not perform network operations during graded invocations. Do not load or call foreign native libraries through FFI during graded invocations. Child processes are not forbidden solely because they exist; all original output and interface requirements still apply. A launcher or instrumentation failure is an infrastructure error, not a wrong-answer score.
|
| 3 |
+
|
| 4 |
+
Execution budget: every grader-launched candidate Python invocation must complete within 60 seconds. A timeout after candidate startup fails this bounded-completion requirement; a trusted observer or launcher failure is an infrastructure error.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score.
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/SKILL.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: ci-failure-fixer
|
| 3 |
+
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.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# CI Failure Fixer
|
| 7 |
+
|
| 8 |
+
Monitor GitHub Actions for failures. Auto-fix what's fixable, report what's not.
|
| 9 |
+
|
| 10 |
+
## How It Works
|
| 11 |
+
|
| 12 |
+
1. `scripts/check-ci-failures.sh` polls repos for new failed runs
|
| 13 |
+
2. If failures found → read build logs via `gh run view --log`
|
| 14 |
+
3. Match error against known patterns → auto-fix if safe
|
| 15 |
+
4. Push fix → wait 90s → verify build passes
|
| 16 |
+
5. Report results (fixed or diagnosis-only)
|
| 17 |
+
|
| 18 |
+
## Quick Start
|
| 19 |
+
|
| 20 |
+
### On-demand
|
| 21 |
+
```bash
|
| 22 |
+
bash scripts/check-ci-failures.sh
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
Output: `OK` (no failures) or `FAILURES` with details.
|
| 26 |
+
|
| 27 |
+
### As Cron Job (OpenClaw)
|
| 28 |
+
|
| 29 |
+
Set up a cron that runs every 30 minutes:
|
| 30 |
+
- **Script:** `bash scripts/check-ci-failures.sh`
|
| 31 |
+
- **Model:** Haiku (cheap, sufficient)
|
| 32 |
+
- **On failure:** Read logs, attempt auto-fix, report
|
| 33 |
+
|
| 34 |
+
## Configuration
|
| 35 |
+
|
| 36 |
+
Environment variables:
|
| 37 |
+
- `GITHUB_OWNER` — GitHub username (auto-detected from `gh` if not set)
|
| 38 |
+
- `CI_REPOS` — Space-separated repo names (auto-discovers all repos if not set)
|
| 39 |
+
- `CI_STATE_FILE` — Path to state JSON (tracks last check time)
|
| 40 |
+
|
| 41 |
+
## Auto-Fixable Patterns
|
| 42 |
+
|
| 43 |
+
| Pattern | Detection | Fix |
|
| 44 |
+
|---------|-----------|-----|
|
| 45 |
+
| Dependency issues | `npm ERR! Could not resolve` | `npm install` + push |
|
| 46 |
+
| Test snapshots | `Snapshot mismatch` | `npm test -- --update` + push |
|
| 47 |
+
| Lint errors | `eslint`, `Formatting` | `eslint --fix` + push |
|
| 48 |
+
| E2E snapshots | Playwright snapshot diff | `playwright --update-snapshots` + push |
|
| 49 |
+
|
| 50 |
+
## Report-Only (Human Needed)
|
| 51 |
+
|
| 52 |
+
- Token/auth errors (secrets rotation)
|
| 53 |
+
- TypeScript errors (complex type issues)
|
| 54 |
+
- Build timeouts (resource/loop issues)
|
| 55 |
+
- Unknown errors
|
| 56 |
+
|
| 57 |
+
## Fix Patterns Reference
|
| 58 |
+
|
| 59 |
+
Read `references/fix-patterns.md` for detailed decision tree, log reading commands, and all known patterns with fix scripts.
|
| 60 |
+
|
| 61 |
+
## Reading Logs
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
# Latest failed run logs
|
| 65 |
+
gh run view --repo OWNER/REPO --log 2>&1 | tail -50
|
| 66 |
+
|
| 67 |
+
# Filter for errors
|
| 68 |
+
gh run view <run-id> --repo OWNER/REPO --log 2>&1 | grep -A5 "error\|FAIL"
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## After Fixing
|
| 72 |
+
|
| 73 |
+
Always verify the fix worked:
|
| 74 |
+
```bash
|
| 75 |
+
sleep 90 # Wait for new CI run
|
| 76 |
+
gh run list --repo OWNER/REPO --limit 1 --json conclusion -q '.[0].conclusion'
|
| 77 |
+
# Should be "success"
|
| 78 |
+
```
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/_export_skill_meta.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"slug": "ci-failure-fixer",
|
| 3 |
+
"displayName": "Ci Failure Fixer",
|
| 4 |
+
"sourceRef": "public-clawhub",
|
| 5 |
+
"version": "1.0.0",
|
| 6 |
+
"createdAt": 1774357146234,
|
| 7 |
+
"updatedAt": 1779078822481,
|
| 8 |
+
"stats": {
|
| 9 |
+
"comments": 0,
|
| 10 |
+
"downloads": 612,
|
| 11 |
+
"installsAllTime": 16,
|
| 12 |
+
"installsCurrent": 0,
|
| 13 |
+
"stars": 0,
|
| 14 |
+
"versions": 1
|
| 15 |
+
},
|
| 16 |
+
"owner": {
|
| 17 |
+
"handle": "danielgrobelny",
|
| 18 |
+
"displayName": "DanielGrobelny"
|
| 19 |
+
}
|
| 20 |
+
}
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/references/fix-patterns.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CI Failure Fix Patterns
|
| 2 |
+
|
| 3 |
+
Common GitHub Actions failure patterns and how to auto-fix them.
|
| 4 |
+
|
| 5 |
+
## Pattern 1: Dependency Issues
|
| 6 |
+
|
| 7 |
+
**Symptoms:** `npm ERR! Could not resolve dependency`, `Module not found`, `Cannot find module`
|
| 8 |
+
|
| 9 |
+
**Fix:**
|
| 10 |
+
```bash
|
| 11 |
+
cd <project-dir>
|
| 12 |
+
npm install
|
| 13 |
+
git add package-lock.json
|
| 14 |
+
git commit -m "fix: resolve dependency issue"
|
| 15 |
+
git push
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
## Pattern 2: Test Snapshot Mismatch
|
| 19 |
+
|
| 20 |
+
**Symptoms:** `Snapshot mismatch`, `toMatchSnapshot`, `received value does not match`
|
| 21 |
+
|
| 22 |
+
**Fix:**
|
| 23 |
+
```bash
|
| 24 |
+
cd <project-dir>
|
| 25 |
+
npm test -- --update
|
| 26 |
+
git add -A
|
| 27 |
+
git commit -m "fix: update test snapshots"
|
| 28 |
+
git push
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Pattern 3: TypeScript Errors
|
| 32 |
+
|
| 33 |
+
**Symptoms:** `TS2xxx`, `Type error`, `Property does not exist on type`
|
| 34 |
+
|
| 35 |
+
**Fix:** Read the error, fix the type issue in source code. Usually requires understanding the code — not auto-fixable for complex cases.
|
| 36 |
+
|
| 37 |
+
**Auto-fixable cases:**
|
| 38 |
+
- Missing `@ts-ignore` → add comment
|
| 39 |
+
- Unused imports → remove them
|
| 40 |
+
- Missing type exports → add `export type`
|
| 41 |
+
|
| 42 |
+
## Pattern 4: ESLint / Prettier Errors
|
| 43 |
+
|
| 44 |
+
**Symptoms:** `Lint errors`, `Formatting issues`, `eslint`
|
| 45 |
+
|
| 46 |
+
**Fix:**
|
| 47 |
+
```bash
|
| 48 |
+
cd <project-dir>
|
| 49 |
+
npx eslint --fix .
|
| 50 |
+
npx prettier --write .
|
| 51 |
+
git add -A
|
| 52 |
+
git commit -m "fix: resolve lint errors"
|
| 53 |
+
git push
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Pattern 5: Environment Variable / Token Issues
|
| 57 |
+
|
| 58 |
+
**Symptoms:** `Unauthorized`, `401`, `VERCEL_TOKEN`, `GITHUB_TOKEN`, `token expired`
|
| 59 |
+
|
| 60 |
+
**Fix:** Cannot auto-fix — requires human to rotate/update secrets. Report to user with diagnosis.
|
| 61 |
+
|
| 62 |
+
## Pattern 6: Build Timeout
|
| 63 |
+
|
| 64 |
+
**Symptoms:** `The job running on runner has exceeded the maximum execution time`
|
| 65 |
+
|
| 66 |
+
**Fix:** Usually indicates infinite loop or resource exhaustion. Read logs, identify the stuck step. Not auto-fixable.
|
| 67 |
+
|
| 68 |
+
## Pattern 7: E2E Test Failures (Playwright)
|
| 69 |
+
|
| 70 |
+
**Symptoms:** `browserType.launch`, `Timeout exceeded`, `locator.click`
|
| 71 |
+
|
| 72 |
+
**Fix:**
|
| 73 |
+
```bash
|
| 74 |
+
cd <project-dir>
|
| 75 |
+
npx playwright install
|
| 76 |
+
npx playwright test --update-snapshots
|
| 77 |
+
git add -A
|
| 78 |
+
git commit -m "fix: update E2E snapshots"
|
| 79 |
+
git push
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
## Decision Tree
|
| 83 |
+
|
| 84 |
+
```
|
| 85 |
+
Failure detected
|
| 86 |
+
├── Dependency error? → npm install + push
|
| 87 |
+
├── Snapshot mismatch? → npm test --update + push
|
| 88 |
+
├── Lint error? → eslint --fix + push
|
| 89 |
+
├── E2E snapshot? → playwright --update-snapshots + push
|
| 90 |
+
├── Token/Auth error? → REPORT ONLY (human needed)
|
| 91 |
+
├── Type error (simple)? → TRY fix, push if confident
|
| 92 |
+
└── Unknown? → REPORT ONLY with diagnosis
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
## Reading Build Logs
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
# Get the latest failed run's logs
|
| 99 |
+
gh run view --repo OWNER/REPO --log 2>&1 | tail -50
|
| 100 |
+
|
| 101 |
+
# Get specific run by ID
|
| 102 |
+
gh run view <run-id> --repo OWNER/REPO --log 2>&1 | grep -A5 "error\|Error\|FAIL"
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
## Cron Integration
|
| 106 |
+
|
| 107 |
+
Set up as an OpenClaw cron job:
|
| 108 |
+
```
|
| 109 |
+
Schedule: every 30m
|
| 110 |
+
Model: haiku (cheap, sufficient for script + log reading)
|
| 111 |
+
Script: scripts/check-ci-failures.sh
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
When failures detected, the agent should:
|
| 115 |
+
1. Read build logs (`gh run view --log`)
|
| 116 |
+
2. Match against known patterns above
|
| 117 |
+
3. Auto-fix if pattern is recognized and safe
|
| 118 |
+
4. Report to user with diagnosis if unknown
|
| 119 |
+
5. After fix: wait 90s, re-check if build passed
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/scripts/check-ci-failures.sh
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Check GitHub repos for failed CI runs and report new failures.
|
| 3 |
+
#
|
| 4 |
+
# Usage: ./check-ci-failures.sh [--repos "repo1 repo2"] [--owner "GitHubUser"]
|
| 5 |
+
#
|
| 6 |
+
# Requires: gh CLI (authenticated)
|
| 7 |
+
# Output: "OK" if no failures, "FAILURES\n❌ repo: details" if failures found.
|
| 8 |
+
# Tracks last check time in a state file to only report NEW failures.
|
| 9 |
+
|
| 10 |
+
OWNER="${GITHUB_OWNER:-$(gh api user -q .login 2>/dev/null)}"
|
| 11 |
+
STATE_FILE="${CI_STATE_FILE:-$HOME/.openclaw/workspace/memory/ci-check-state.json}"
|
| 12 |
+
|
| 13 |
+
# Auto-discover repos if not provided
|
| 14 |
+
if [ -n "$1" ] && [ "$1" = "--repos" ]; then
|
| 15 |
+
REPOS="$2"
|
| 16 |
+
elif [ -n "$CI_REPOS" ]; then
|
| 17 |
+
REPOS="$CI_REPOS"
|
| 18 |
+
else
|
| 19 |
+
# Auto-discover: all repos with GitHub Actions
|
| 20 |
+
REPOS=$(gh repo list "$OWNER" --limit 50 --json name,hasWiki \
|
| 21 |
+
-q '.[].name' 2>/dev/null | tr '\n' ' ')
|
| 22 |
+
fi
|
| 23 |
+
|
| 24 |
+
# Initialize state file if missing
|
| 25 |
+
if [ ! -f "$STATE_FILE" ]; then
|
| 26 |
+
mkdir -p "$(dirname "$STATE_FILE")"
|
| 27 |
+
echo '{"lastCheck":"2026-01-01T00:00:00Z"}' > "$STATE_FILE"
|
| 28 |
+
fi
|
| 29 |
+
|
| 30 |
+
LAST_CHECK=$(python3 -c "import json; print(json.load(open('$STATE_FILE'))['lastCheck'])" 2>/dev/null || echo "2026-01-01T00:00:00Z")
|
| 31 |
+
NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
| 32 |
+
FAILURES=""
|
| 33 |
+
CHECKED=0
|
| 34 |
+
|
| 35 |
+
for REPO in $REPOS; do
|
| 36 |
+
CHECKED=$((CHECKED + 1))
|
| 37 |
+
|
| 38 |
+
# Get failed runs since last check
|
| 39 |
+
FAILED=$(gh run list --repo "$OWNER/$REPO" --status failure --json databaseId,createdAt \
|
| 40 |
+
-q "[.[] | select(.createdAt > \"$LAST_CHECK\")] | length" 2>/dev/null)
|
| 41 |
+
|
| 42 |
+
if [ "$FAILED" != "" ] && [ "$FAILED" != "0" ]; then
|
| 43 |
+
DETAIL=$(gh run list --repo "$OWNER/$REPO" --status failure --limit 1 --json name,headBranch,url \
|
| 44 |
+
-q '.[0] | "\(.name) on \(.headBranch)"' 2>/dev/null)
|
| 45 |
+
URL=$(gh run list --repo "$OWNER/$REPO" --status failure --limit 1 --json url -q '.[0].url' 2>/dev/null)
|
| 46 |
+
FAILURES="$FAILURES\n❌ $REPO: $DETAIL ($FAILED new) $URL"
|
| 47 |
+
fi
|
| 48 |
+
done
|
| 49 |
+
|
| 50 |
+
# Update last check time
|
| 51 |
+
python3 -c "import json; json.dump({'lastCheck':'$NOW'}, open('$STATE_FILE','w'))" 2>/dev/null
|
| 52 |
+
|
| 53 |
+
if [ -n "$FAILURES" ]; then
|
| 54 |
+
echo -e "FAILURES ($CHECKED repos checked)$FAILURES"
|
| 55 |
+
else
|
| 56 |
+
echo "OK"
|
| 57 |
+
fi
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/skill/skill-card.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Description: <br>
|
| 2 |
+
Monitor GitHub Actions CI pipelines for failures and automatically fix common issues. <br>
|
| 3 |
+
|
| 4 |
+
This skill is ready for commercial/non-commercial use. <br>
|
| 5 |
+
|
| 6 |
+
## Publisher: <br>
|
| 7 |
+
[danielgrobelny](https://clawhub.ai/user/danielgrobelny) <br>
|
| 8 |
+
|
| 9 |
+
### License/Terms of Use: <br>
|
| 10 |
+
MIT-0 <br>
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
## Use Case: <br>
|
| 14 |
+
Developers and engineers use this skill to monitor GitHub Actions failures, inspect logs, apply common CI fixes, and report issues that require human intervention. <br>
|
| 15 |
+
|
| 16 |
+
### Deployment Geography for Use: <br>
|
| 17 |
+
Global <br>
|
| 18 |
+
|
| 19 |
+
## Known Risks and Mitigations: <br>
|
| 20 |
+
Risk: The skill can drive recurring automated repository changes and pushes using the user's GitHub access. <br>
|
| 21 |
+
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. <br>
|
| 22 |
+
Risk: The skill reads GitHub Actions logs, which may expose sensitive build details. <br>
|
| 23 |
+
Mitigation: Install only where access to GitHub Actions logs is acceptable, and scope credentials to the repositories that need CI monitoring. <br>
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
## Reference(s): <br>
|
| 27 |
+
- [CI Failure Fix Patterns](references/fix-patterns.md) <br>
|
| 28 |
+
- [ClawHub Skill Page](https://clawhub.ai/danielgrobelny/ci-failure-fixer) <br>
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
## Skill Output: <br>
|
| 32 |
+
**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance] <br>
|
| 33 |
+
**Output Format:** [Markdown with inline bash commands and diagnosis text] <br>
|
| 34 |
+
**Output Parameters:** [1D] <br>
|
| 35 |
+
**Other Properties Related to Output:** [Requires an authenticated GitHub CLI and may read GitHub Actions logs or propose repository changes.] <br>
|
| 36 |
+
|
| 37 |
+
## Skill Version(s): <br>
|
| 38 |
+
1.0.0 (source: server release metadata) <br>
|
| 39 |
+
|
| 40 |
+
## Ethical Considerations: <br>
|
| 41 |
+
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. <br>
|
benchmarks/skillbench-venus-e/tasks/aba6991804c4279544487710/task.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "aba6991804c4279544487710",
|
| 4 |
+
"environment": {
|
| 5 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 6 |
+
"network": "none"
|
| 7 |
+
},
|
| 8 |
+
"query_id": "aba6991804c4279544487710",
|
| 9 |
+
"outputs": [
|
| 10 |
+
"triage.py",
|
| 11 |
+
"triage_report."
|
| 12 |
+
],
|
| 13 |
+
"success_criteria": [
|
| 14 |
+
"Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.",
|
| 15 |
+
"Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md."
|
| 16 |
+
],
|
| 17 |
+
"evaluation": {
|
| 18 |
+
"kind": "python",
|
| 19 |
+
"type": "verified"
|
| 20 |
+
},
|
| 21 |
+
"source_skill": {
|
| 22 |
+
"sha256": "f6066978de15659025c9d81d0bf8754c3ab5224173e8f94f7ebca4fe99aab5e6",
|
| 23 |
+
"files": {
|
| 24 |
+
"SKILL.md": "b7bf0fb1ff16c9c8bb52b0f2b426b81a012ee61448f154124a5f924e44cc5ee8",
|
| 25 |
+
"_export_skill_meta.json": "9b1a1b6a2e3e52cdeac316f7b9d1696d55b27322b1c62d1f83d57e5c1179e821",
|
| 26 |
+
"references/fix-patterns.md": "d1db37bf7ca6cfec74f6117190a522338e8304108eea1644d295229e49fe0daa",
|
| 27 |
+
"scripts/check-ci-failures.sh": "53077b4c0ce1deeb1d4c50bf4bdad595a6643b75b5b1165474a54d61c498cf9d",
|
| 28 |
+
"skill-card.md": "3b20c3a903329bc322d8781a9b8b5ae310d90ae8d5354072e480afe318f9bf76"
|
| 29 |
+
}
|
| 30 |
+
},
|
| 31 |
+
"workspace": {
|
| 32 |
+
"candidate_mode": "workspace",
|
| 33 |
+
"input_mappings": [
|
| 34 |
+
{
|
| 35 |
+
"source": "inputs/logs/run-4821-webapp.log",
|
| 36 |
+
"workspace_target": "logs/run-4821-webapp.log",
|
| 37 |
+
"sha256": "eb92ffb4b509cfd47012abc7103fb51868e03401ab51c3b8a0bb7ff50583e29a"
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"source": "inputs/logs/run-4822-api.log",
|
| 41 |
+
"workspace_target": "logs/run-4822-api.log",
|
| 42 |
+
"sha256": "2201f178ef8a582bfbc71f46b08c82e7afca449cd86ea93b2f048cf728b747dd"
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"source": "inputs/logs/run-4823-deploy.log",
|
| 46 |
+
"workspace_target": "logs/run-4823-deploy.log",
|
| 47 |
+
"sha256": "1c9cd1a0ab31ee6fad9ea97783f557ecd7f96e47f7974d17a42b313814a9208d"
|
| 48 |
+
}
|
| 49 |
+
],
|
| 50 |
+
"skill_packages": [
|
| 51 |
+
{
|
| 52 |
+
"package_path": "skill",
|
| 53 |
+
"content_hash": "f6066978de15659025c9d81d0bf8754c3ab5224173e8f94f7ebca4fe99aab5e6"
|
| 54 |
+
}
|
| 55 |
+
]
|
| 56 |
+
},
|
| 57 |
+
"autograde_runtime_contract": {
|
| 58 |
+
"stdlib_only": true,
|
| 59 |
+
"forbid_network": true,
|
| 60 |
+
"forbid_subprocess": false,
|
| 61 |
+
"forbid_native": true,
|
| 62 |
+
"owner_ids": [
|
| 63 |
+
"0"
|
| 64 |
+
],
|
| 65 |
+
"require_execution": true,
|
| 66 |
+
"scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
|
| 67 |
+
"execution_budget_seconds": 60
|
| 68 |
+
},
|
| 69 |
+
"automatic_evaluation_runtime": {
|
| 70 |
+
"stdlib_only": true,
|
| 71 |
+
"forbid_network": true,
|
| 72 |
+
"forbid_subprocess": false,
|
| 73 |
+
"forbid_native": true,
|
| 74 |
+
"owner_ids": [
|
| 75 |
+
"0"
|
| 76 |
+
],
|
| 77 |
+
"require_execution": true,
|
| 78 |
+
"scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
|
| 79 |
+
"execution_budget_seconds": 60,
|
| 80 |
+
"runtime_owner_ids": [
|
| 81 |
+
"0"
|
| 82 |
+
],
|
| 83 |
+
"total_evaluation_budget_seconds": 420,
|
| 84 |
+
"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."
|
| 85 |
+
}
|
| 86 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0",
|
| 4 |
+
"1",
|
| 5 |
+
"2",
|
| 6 |
+
"3",
|
| 7 |
+
"4",
|
| 8 |
+
"5"
|
| 9 |
+
],
|
| 10 |
+
"criterion_weights": {
|
| 11 |
+
"0": 1,
|
| 12 |
+
"1": 1,
|
| 13 |
+
"2": 1,
|
| 14 |
+
"3": 1,
|
| 15 |
+
"4": 1,
|
| 16 |
+
"5": 1
|
| 17 |
+
}
|
| 18 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"stdlib_only": true,
|
| 3 |
+
"forbid_network": true,
|
| 4 |
+
"forbid_subprocess": false,
|
| 5 |
+
"forbid_native": true,
|
| 6 |
+
"owner_ids": [
|
| 7 |
+
"0"
|
| 8 |
+
],
|
| 9 |
+
"require_execution": true,
|
| 10 |
+
"scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
|
| 11 |
+
"execution_budget_seconds": 60,
|
| 12 |
+
"runtime_owner_ids": [
|
| 13 |
+
"0"
|
| 14 |
+
],
|
| 15 |
+
"total_evaluation_budget_seconds": 420
|
| 16 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
from r10_support import dependency,combine
|
| 3 |
+
BODY = 'import base64 as _repair_base64\n_REPAIR_PUBLIC_INPUTS = {\'lib/model/store.js\': \'Ly8gbW9kZWwgbGF5ZXI6IG5vIGRlcGVuZGVuY2llcyBvbiBvdGhlciBsYXllcnMKZXhwb3J0IGNsYXNzIFN0b3JlIHsKICBjb25zdHJ1Y3RvcigpIHsgdGhpcy5pdGVtcyA9IFtdOyB9CiAgYWRkKGl0ZW0pIHsgdGhpcy5pdGVtcy5wdXNoKGl0ZW0pOyB9CiAgYWxsKCkgeyByZXR1cm4gdGhpcy5pdGVtczsgfQp9Cg==\', \'lib/util/format.js\': \'ZXhwb3J0IGZ1bmN0aW9uIGZtdChuKSB7IHJldHVybiBuLnRvRml4ZWQoMik7IH0KZXhwb3J0IGZ1bmN0aW9uIGxhYmVsKHMpIHsgcmV0dXJuICdbJyArIHMgKyAnXSc7IH0K\', \'lib/data/repo.js\': \'aW1wb3J0IHsgU3RvcmUgfSBmcm9tICcuLi9tb2RlbC9zdG9yZS5qcyc7CmltcG9ydCB7IGZtdCB9IGZyb20gJy4uL3V0aWwvZm9ybWF0LmpzJzsKaW1wb3J0IHsgc3VtbWFyaXplIH0gZnJvbSAnLi4vYW5hbHl6ZXIvc3VtbWFyeS5qcyc7Cgpjb25zdCBzdG9yZSA9IG5ldyBTdG9yZSgpOwpleHBvcnQgZnVuY3Rpb24gcHV0KHgpIHsgc3RvcmUuYWRkKHgpOyB9CmV4cG9ydCBmdW5jdGlvbiByZXBvcnQoKSB7IHJldHVybiBzdW1tYXJpemUoc3RvcmUuYWxsKCkpICsgJyBhdmc9JyArIGZtdCgxKTsgfQo=\', \'lib/analyzer/summary.js\': \'aW1wb3J0IHsgZm10IH0gZnJvbSAnLi4vdXRpbC9mb3JtYXQuanMnOwppbXBvcnQgeyByZXBvcnQgfSBmcm9tICcuLi9kYXRhL3JlcG8uanMnOwoKZXhwb3J0IGZ1bmN0aW9uIHN1bW1hcml6ZShpdGVtcykgewogIGlmICghaXRlbXMubGVuZ3RoKSByZXR1cm4gJ2VtcHR5JzsKICByZXR1cm4gJ2NvdW50PScgKyBpdGVtcy5sZW5ndGg7Cn0KZXhwb3J0IGZ1bmN0aW9uIGZ1bGwoKSB7IHJldHVybiByZXBvcnQoKTsgfQo=\', \'bin/main.js\': \'Ly8gZW50cnkgcG9pbnQ6IG1heSBpbXBvcnQgZnJvbSBsaWIgb25seQppbXBvcnQgeyBwdXQsIHJlcG9ydCB9IGZyb20gJy4uL2xpYi9kYXRhL3JlcG8uanMnOwppbXBvcnQgeyBsYWJlbCB9IGZyb20gJy4uL2xpYi91dGlsL2Zvcm1hdC5qcyc7CgpwdXQoMyk7CmNvbnNvbGUubG9nKGxhYmVsKHJlcG9ydCgpKSk7Cg==\'}\n_REPAIR_PUBLIC_PATHS = set(_REPAIR_PUBLIC_INPUTS)\n_REPAIR_OUTPUT_PATHS = [\'report.\']\n_REPAIR_DELIVERY_ARTIFACTS = [\'report.\']\n_REPAIR_TASK_INDEX = 31\nimport os as _repair_os\nimport sys as _repair_sys, sysconfig as _repair_sysconfig, pkgutil as _repair_pkgutil\n_repair_stdlib_names = set(getattr(_repair_sys, \'stdlib_module_names\', ())) | set(_repair_sys.builtin_module_names) | {m.name for m in _repair_pkgutil.iter_modules([_repair_sysconfig.get_path(\'stdlib\'), _repair_os.path.join(_repair_sysconfig.get_path(\'stdlib\'), \'lib-dynload\')])}\nimport os as _repair_os\nimport shutil as _repair_shutil\n_REPAIR_CAND = _repair_os.environ.get(\'MYBENCH_CANDIDATE\', \'/candidate\')\nimport tempfile as _repair_tempfile\n_REPAIR_RMTREE = _repair_shutil.rmtree\n_REPAIR_MKDTEMP = _repair_tempfile.mkdtemp\n_REPAIR_COPYTREE = _repair_shutil.copytree\n\ndef _repair_stage_code(d):\n if not _repair_os.path.isdir(_REPAIR_CAND):\n return\n for root, dirs, files in _repair_os.walk(_REPAIR_CAND):\n dirs[:] = [x for x in dirs if x not in (\'inputs\', \'skill\', \'skills\', \'.git\', \'__pycache__\')]\n for f in files:\n if not f.endswith(\'.py\'):\n continue\n relative = _repair_os.path.relpath(_repair_os.path.join(root, f), _REPAIR_CAND)\n if relative in _REPAIR_PUBLIC_PATHS or any((relative == x or relative.startswith(x.rstrip(\'/\') + \'/\') for x in _REPAIR_OUTPUT_PATHS)):\n continue\n path = _repair_os.path.join(d, relative)\n _repair_os.makedirs(_repair_os.path.dirname(path), exist_ok=True)\n if _repair_os.path.abspath(path) != _repair_os.path.abspath(_repair_os.path.join(root, f)):\n _REPAIR_COPY(_repair_os.path.join(root, f), path)\n for rel, encoded in _REPAIR_PUBLIC_INPUTS.items():\n target = _repair_os.path.join(d, rel)\n _repair_os.makedirs(_repair_os.path.dirname(target), exist_ok=True)\n with open(target, \'wb\') as f:\n f.write(_repair_base64.b64decode(encoded))\n\ndef _repair_clear_workspace():\n _repair_os.makedirs(\'/workspace\', exist_ok=True)\n for name in _repair_os.listdir(\'/workspace\'):\n path = _repair_os.path.join(\'/workspace\', name)\n if _repair_os.path.isdir(path) and (not _repair_os.path.islink(path)):\n _REPAIR_RMTREE(path)\n else:\n _repair_os.unlink(path)\n\ndef _repair_mkdtemp(*a, **kw):\n if _repair_os.environ.get(\'MYBENCH_EPHEMERAL_WORKSPACE\') == \'1\':\n _repair_clear_workspace()\n _repair_stage_code(\'/workspace\')\n return \'/workspace\'\n d = _REPAIR_MKDTEMP(*a, **kw)\n _repair_stage_code(d)\n return d\n\ndef _repair_rmtree(path, *a, **kw):\n if _repair_os.path.abspath(path) == \'/workspace\' and _repair_os.environ.get(\'MYBENCH_EPHEMERAL_WORKSPACE\') == \'1\':\n _repair_clear_workspace()\n return\n return _REPAIR_RMTREE(path, *a, **kw)\n\nclass _RepairTemporaryDirectory:\n\n def __init__(self, *a, **kw):\n self.name = _repair_mkdtemp(*a, **kw)\n\n def __enter__(self):\n return self.name\n\n def __exit__(self, *a):\n self.cleanup()\n\n def cleanup(self):\n _repair_rmtree(self.name, ignore_errors=True)\n\ndef _repair_copytree(src, dst, *a, **kw):\n if _repair_os.path.abspath(dst) == \'/workspace\' and _repair_os.environ.get(\'MYBENCH_EPHEMERAL_WORKSPACE\') == \'1\':\n for name in _repair_os.listdir(src):\n source = _repair_os.path.join(src, name)\n target = _repair_os.path.join(dst, name)\n if _repair_os.path.isdir(source) and (not _repair_os.path.islink(source)):\n inner = dict(kw)\n inner[\'dirs_exist_ok\'] = True\n _REPAIR_COPYTREE(source, target, *a, **inner)\n elif _repair_os.path.islink(source) and kw.get(\'symlinks\'):\n if _repair_os.path.lexists(target):\n _repair_os.unlink(target)\n _repair_os.symlink(_repair_os.readlink(source), target)\n else:\n _repair_shutil.copy2(source, target)\n return dst\n return _REPAIR_COPYTREE(src, dst, *a, **kw)\n_repair_shutil.copytree = _repair_copytree\nif _repair_os.environ.get(\'MYBENCH_EPHEMERAL_WORKSPACE\') == \'1\':\n _repair_tempfile.TemporaryDirectory = _RepairTemporaryDirectory\n_repair_tempfile.mkdtemp = _repair_mkdtemp\n_repair_shutil.rmtree = _repair_rmtree\n_REPAIR_COPY = _repair_shutil.copy\n\ndef _repair_copy(src, dst, *a, **kw):\n if _repair_os.path.isfile(src) and str(src).startswith(_REPAIR_CAND + _repair_os.sep) and str(src).endswith(\'.py\'):\n target = dst if _repair_os.path.isdir(dst) else _repair_os.path.dirname(dst)\n for root, dirs, files in _repair_os.walk(_REPAIR_CAND):\n dirs[:] = [x for x in dirs if x not in (\'inputs\', \'skill\', \'skills\', \'.git\', \'__pycache__\')]\n for f in files:\n if f.endswith(\'.py\'):\n relative = _repair_os.path.relpath(_repair_os.path.join(root, f), _REPAIR_CAND)\n if relative in _REPAIR_PUBLIC_PATHS or any((relative == x or relative.startswith(x.rstrip(\'/\') + \'/\') for x in _REPAIR_OUTPUT_PATHS)):\n continue\n path = _repair_os.path.join(target, relative)\n _repair_os.makedirs(_repair_os.path.dirname(path), exist_ok=True)\n if _repair_os.path.abspath(_repair_os.path.join(root, f)) != _repair_os.path.abspath(path):\n _REPAIR_COPY(_repair_os.path.join(root, f), path)\n return _REPAIR_COPY(src, dst, *a, **kw)\n_repair_shutil.copy = _repair_copy\nimport builtins as _repair_builtins, io as _repair_io, subprocess as _repair_subprocess\n_REPAIR_OPEN = _repair_builtins.open\n_REPAIR_IOOPEN = _repair_io.open\n_REPAIR_RUN = _repair_subprocess.run\n_REPAIR_RUN_COUNT = 0\n_REPAIR_ARTIFACT_ACTIVE = False\n_REPAIR_CAPTURED = set()\n\ndef _repair_run(*a, **kw):\n global _REPAIR_RUN_COUNT, _REPAIR_ARTIFACT_ACTIVE\n args = a[0] if a else kw.get(\'args\', [])\n if isinstance(args, (list, tuple)) and any((str(x).endswith(\'.py\') for x in args)):\n _REPAIR_RUN_COUNT += 1\n _REPAIR_ARTIFACT_ACTIVE = _REPAIR_RUN_COUNT == 1\n if _REPAIR_DELIVERY_MODE and _REPAIR_ARTIFACT_ACTIVE and isinstance(args, (list, tuple)) and args and str(args[0]).endswith(\'bash\') and (\'-n\' in args):\n rewritten = list(args)\n for n, x in enumerate(rewritten):\n for rel in _REPAIR_DELIVERY_ARTIFACTS:\n if str(x).endswith(\'/\' + rel):\n rewritten[n] = _repair_os.path.join(_REPAIR_CAND, rel)\n if a:\n a = (rewritten,) + a[1:]\n else:\n kw[\'args\'] = rewritten\n return _REPAIR_RUN(*a, **kw)\n\ndef _repair_artifact_path(path, mode):\n if not _REPAIR_ARTIFACT_ACTIVE or not isinstance(path, (str, bytes, _repair_os.PathLike)) or any((c in mode for c in \'wax+\')):\n return path\n absolute = _repair_os.path.abspath(path)\n if absolute == _repair_os.path.abspath(_REPAIR_CAND) or absolute.startswith(_repair_os.path.abspath(_REPAIR_CAND) + _repair_os.sep):\n return path\n for rel in _REPAIR_DELIVERY_ARTIFACTS:\n normalized = rel.replace(\'/\', _repair_os.sep)\n if not absolute.endswith(_repair_os.sep + normalized):\n continue\n submitted = _repair_os.path.join(_REPAIR_CAND, rel)\n if _REPAIR_DELIVERY_MODE:\n return submitted\n if _repair_os.environ.get(\'MYBENCH_FIXTURE_MATERIALIZE\') == \'1\' and rel not in _REPAIR_CAPTURED:\n _REPAIR_CAPTURED.add(rel)\n if _repair_os.path.exists(submitted):\n return path\n _repair_os.makedirs(_repair_os.path.dirname(submitted), exist_ok=True)\n if _REPAIR_TASK_INDEX == 43:\n base = absolute[:-len(normalized)].rstrip(_repair_os.sep)\n for mod in (\'calc.py\', \'test_calc.py\', \'verify.py\'):\n source = _repair_os.path.join(base, mod)\n if _repair_os.path.isfile(source):\n _repair_shutil.copy2(source, _repair_os.path.join(_REPAIR_CAND, mod))\n with _REPAIR_OPEN(absolute, \'rb\') as f:\n data = f.read()\n with _REPAIR_OPEN(submitted, \'wb\') as f:\n f.write(data)\n return path\n return path\n\ndef _repair_open(path, mode=\'r\', *a, **kw):\n return _REPAIR_OPEN(_repair_artifact_path(path, mode), mode, *a, **kw)\n\ndef _repair_ioopen(path, mode=\'r\', *a, **kw):\n return _REPAIR_IOOPEN(_repair_artifact_path(path, mode), mode, *a, **kw)\n_repair_builtins.open = _repair_open\n_repair_io.open = _repair_ioopen\n_repair_subprocess.run = _repair_run\nimport json, os, shutil, subprocess, sys, tempfile, re, ast\nFILES = {\'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"}\nEXPECTED_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\')}\nMUST_VIOLATE = [\'lib/data/repo.js -> 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'
|
| 4 |
+
IDS = ['0', '1', '2', '3', '4', '5']
|
| 5 |
+
DELIVERY_IDS = {'0', '5', '1', '4', '3', '2'}
|
| 6 |
+
import io, json, contextlib, builtins, subprocess, tempfile, shutil, os
|
| 7 |
+
_ORIGINAL_APIS = (builtins.open, io.open, subprocess.run, tempfile.mkdtemp, tempfile.TemporaryDirectory, shutil.rmtree, shutil.copytree, shutil.copy)
|
| 8 |
+
|
| 9 |
+
def _restore():
|
| 10 |
+
builtins.open, io.open, subprocess.run, tempfile.mkdtemp, tempfile.TemporaryDirectory, shutil.rmtree, shutil.copytree, shutil.copy = _ORIGINAL_APIS
|
| 11 |
+
|
| 12 |
+
def _grade(delivery):
|
| 13 |
+
_restore()
|
| 14 |
+
_buffer = io.StringIO()
|
| 15 |
+
_problem = None
|
| 16 |
+
try:
|
| 17 |
+
with contextlib.redirect_stdout(_buffer):
|
| 18 |
+
exec(compile(BODY, __file__, 'exec'), {'__file__': __file__, '__name__': '__main__', '_REPAIR_DELIVERY_MODE': delivery})
|
| 19 |
+
except SystemExit:
|
| 20 |
+
pass
|
| 21 |
+
except Exception as e:
|
| 22 |
+
_problem = type(e).__name__ + ': ' + str(e)
|
| 23 |
+
finally:
|
| 24 |
+
_restore()
|
| 25 |
+
result = None
|
| 26 |
+
for line in reversed(_buffer.getvalue().splitlines()):
|
| 27 |
+
try:
|
| 28 |
+
x = json.loads(line)
|
| 29 |
+
if isinstance(x, dict) and isinstance(x.get('checks'), list):
|
| 30 |
+
result = x
|
| 31 |
+
break
|
| 32 |
+
except Exception:
|
| 33 |
+
pass
|
| 34 |
+
if result is None or _problem is not None:
|
| 35 |
+
result = {'checks': [{'id': i, 'passed': False, 'reason': 'evaluation failed: ' + str(_problem or 'missing valid checks JSON')} for i in IDS]}
|
| 36 |
+
return result
|
| 37 |
+
fresh = _grade(False)
|
| 38 |
+
from graph_probe import verify as _graph_verify
|
| 39 |
+
_graph_flags=_graph_verify()
|
| 40 |
+
for _item in fresh['checks']:
|
| 41 |
+
_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])
|
| 42 |
+
if DELIVERY_IDS and os.environ.get('MYBENCH_FIXTURE_MATERIALIZE') != '1':
|
| 43 |
+
submitted = _grade(True)
|
| 44 |
+
by = {str(c['id']): c for c in submitted['checks']}
|
| 45 |
+
for c in fresh['checks']:
|
| 46 |
+
if str(c['id']) in DELIVERY_IDS:
|
| 47 |
+
b = by.get(str(c['id']), {})
|
| 48 |
+
c['passed'] = bool(c['passed'] and b.get('passed', False))
|
| 49 |
+
if not b.get('passed', False):
|
| 50 |
+
c['reason'] += '; original public deliverable: ' + str(b.get('reason', 'missing semantic check'))
|
| 51 |
+
for _r10_row in fresh['checks']:
|
| 52 |
+
if str(_r10_row['id'])=='0':_r10_row['passed']=combine([_r10_row['passed'],dependency('analyze.py')]);_r10_row['reason']+='; complete local standard-library closure'
|
| 53 |
+
fresh['scoreable']=all(c['passed']is not None for c in fresh['checks'])
|
| 54 |
+
print(json.dumps(fresh, ensure_ascii=False))
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/graph_probe.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import json,re,shutil,subprocess,sys,tempfile,os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
FILES={
|
| 5 |
+
'lib/util/format.js':'export const fmt=1;\n',
|
| 6 |
+
'lib/model/store.js':"import { fmt } from '../util/format'; export const Store=fmt;\n",
|
| 7 |
+
'lib/model/index.js':"import { Store } from './store'; export { Store };\n",
|
| 8 |
+
'lib/data/repo.js':"const model=require('../model'); import { summary } from '../analyzer/summary.js';\n",
|
| 9 |
+
'lib/analyzer/summary.js':"import { repo } from '../data/repo';\n",
|
| 10 |
+
'bin/main.js':"import { summary } from '../lib/analyzer/summary';\n",
|
| 11 |
+
'bin/helpers/deep.js':"const repo=require('../../lib/data/repo');\n"}
|
| 12 |
+
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')}
|
| 13 |
+
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')}
|
| 14 |
+
def verify():
|
| 15 |
+
candidate=Path(os.environ.get('MYBENCH_CANDIDATE','/candidate'));root=Path('/workspace')if os.environ.get('MYBENCH_EPHEMERAL_WORKSPACE')=='1'else Path(tempfile.mkdtemp())
|
| 16 |
+
root.mkdir(exist_ok=True)
|
| 17 |
+
for p in list(root.iterdir()):
|
| 18 |
+
if p.is_dir()and not p.is_symlink():shutil.rmtree(p)
|
| 19 |
+
else:p.unlink()
|
| 20 |
+
shutil.copytree(candidate,root,dirs_exist_ok=True,symlinks=True)
|
| 21 |
+
for name in ['lib','bin']:
|
| 22 |
+
p=root/name
|
| 23 |
+
if p.exists():shutil.rmtree(p)
|
| 24 |
+
for name,value in FILES.items():p=root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(value)
|
| 25 |
+
p=root/'report.'
|
| 26 |
+
if p.is_symlink()or p.is_file():p.unlink()
|
| 27 |
+
elif p.is_dir():shutil.rmtree(p)
|
| 28 |
+
try:r=subprocess.run([sys.executable,'analyze.py'],cwd=root,capture_output=True,text=True,timeout=60)
|
| 29 |
+
except subprocess.TimeoutExpired:return[False]*6
|
| 30 |
+
except(OSError,subprocess.SubprocessError)as error:raise RuntimeError('Graph probe launcher infrastructure failure')from error
|
| 31 |
+
try:
|
| 32 |
+
if not p.is_file():return[False]*6
|
| 33 |
+
doc=json.loads(p.read_text())
|
| 34 |
+
except(OSError,ValueError,UnicodeError,RecursionError):return[False]*6
|
| 35 |
+
flags=[r.returncode==0 and isinstance(doc,dict)]*6
|
| 36 |
+
if not isinstance(doc,dict):return[False]*6
|
| 37 |
+
edges=doc.get('edges');got=[(e.get('from'),e.get('to'))for e in edges if isinstance(e,dict)]if isinstance(edges,list)else[]
|
| 38 |
+
flags[1]=got==sorted(EDGES)
|
| 39 |
+
cycles=doc.get('cycles');seen=[];valid=isinstance(cycles,list)and bool(cycles)
|
| 40 |
+
for cycle in cycles if isinstance(cycles,list)else []:
|
| 41 |
+
if not isinstance(cycle,list)or not all(isinstance(x,str)for x in cycle):valid=False;continue
|
| 42 |
+
c=cycle[:-1]if len(cycle)>1 and cycle[0]==cycle[-1]else cycle
|
| 43 |
+
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))
|
| 44 |
+
flags[2]=valid and len(seen)==1 and seen[0]=={'lib/data/repo.js','lib/analyzer/summary.js'}
|
| 45 |
+
violations=doc.get('violations');pairs=[]
|
| 46 |
+
for v in violations if isinstance(violations,list)else []:
|
| 47 |
+
m=re.fullmatch(r'VIOLATION:\s*(\S+)\s*->\s*(\S+)\s*\((.+)\)',v)if isinstance(v,str)else None
|
| 48 |
+
if m:pairs.append((m[1],m[2]))
|
| 49 |
+
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
|
| 50 |
+
impact=doc.get('impact');direct=['lib/model/store.js'];trans=sorted(set(FILES)-{'lib/util/format.js',*direct})
|
| 51 |
+
flags[4]=impact=={'target':'lib/util/format.js','direct':direct,'transitive':trans,'total':6}
|
| 52 |
+
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]
|
| 53 |
+
flags[5]=all(isinstance(x,str)and x in FILES and not x.startswith('/')and'..'not in Path(x).parts for x in paths)
|
| 54 |
+
return flags
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/original_check.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import json, os, shutil, subprocess, sys, tempfile
|
| 3 |
+
|
| 4 |
+
FILES = {
|
| 5 |
+
"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",
|
| 6 |
+
"lib/util/format.js": "export function fmt(n) { return n.toFixed(2); }\nexport function label(s) { return '[' + s + ']'; }\n",
|
| 7 |
+
"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",
|
| 8 |
+
"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",
|
| 9 |
+
"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",
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
EXPECTED_EDGES = {
|
| 13 |
+
("lib/data/repo.js","lib/model/store.js"),
|
| 14 |
+
("lib/data/repo.js","lib/util/format.js"),
|
| 15 |
+
("lib/data/repo.js","lib/analyzer/summary.js"),
|
| 16 |
+
("lib/analyzer/summary.js","lib/util/format.js"),
|
| 17 |
+
("lib/analyzer/summary.js","lib/data/repo.js"),
|
| 18 |
+
("bin/main.js","lib/data/repo.js"),
|
| 19 |
+
("bin/main.js","lib/util/format.js"),
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
MUST_VIOLATE = ["lib/data/repo.js -> lib/util/format.js", "lib/data/repo.js -> lib/analyzer/summary.js"]
|
| 23 |
+
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"]
|
| 24 |
+
|
| 25 |
+
KNOWN = set(FILES)
|
| 26 |
+
|
| 27 |
+
def rel_ok(p):
|
| 28 |
+
if not isinstance(p, str) or not p or "\\" in p or p.startswith("/") or ".." in p.split("/"):
|
| 29 |
+
return False
|
| 30 |
+
return p in KNOWN
|
| 31 |
+
|
| 32 |
+
def find_candidate():
|
| 33 |
+
for c in ("/candidate/analyze.py", "/candidate/analyze.py/analyze.py"):
|
| 34 |
+
if os.path.isfile(c):
|
| 35 |
+
return c
|
| 36 |
+
if os.path.isfile("/answer.txt"):
|
| 37 |
+
return "/answer.txt"
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
checks = [None]*6
|
| 42 |
+
tmp = tempfile.mkdtemp(dir="/tmp")
|
| 43 |
+
try:
|
| 44 |
+
for rel, content in FILES.items():
|
| 45 |
+
full = os.path.join(tmp, rel)
|
| 46 |
+
os.makedirs(os.path.dirname(full), exist_ok=True)
|
| 47 |
+
with open(full, "w") as f:
|
| 48 |
+
f.write(content)
|
| 49 |
+
src = find_candidate()
|
| 50 |
+
report = None
|
| 51 |
+
if src is None:
|
| 52 |
+
checks[0] = (False, "no analyze.py found in /candidate or /answer.txt")
|
| 53 |
+
else:
|
| 54 |
+
try:
|
| 55 |
+
shutil.copy(src, os.path.join(tmp, "analyze.py"))
|
| 56 |
+
except Exception as e:
|
| 57 |
+
checks[0] = (False, "could not stage analyze.py: %s" % e)
|
| 58 |
+
src = None
|
| 59 |
+
if src is not None and checks[0] is None:
|
| 60 |
+
try:
|
| 61 |
+
r = subprocess.run([sys.executable, "analyze.py"], cwd=tmp,
|
| 62 |
+
capture_output=True, text=True, timeout=60)
|
| 63 |
+
rp = os.path.join(tmp, "report.")
|
| 64 |
+
if not os.path.isfile(rp):
|
| 65 |
+
checks[0] = (False, "analyze.py ran (rc=%d) but did not write 'report.'" % r.returncode)
|
| 66 |
+
else:
|
| 67 |
+
try:
|
| 68 |
+
report = json.load(open(rp))
|
| 69 |
+
checks[0] = (True, "analyze.py ran and wrote a parseable report.")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
checks[0] = (False, "report. is not valid JSON: %s" % e)
|
| 72 |
+
except subprocess.TimeoutExpired:
|
| 73 |
+
checks[0] = (False, "analyze.py timed out")
|
| 74 |
+
except Exception as e:
|
| 75 |
+
checks[0] = (False, "failed to run analyze.py: %s" % e)
|
| 76 |
+
|
| 77 |
+
if report is None:
|
| 78 |
+
for i in range(1, 6):
|
| 79 |
+
checks[i] = (False, "no valid report. produced")
|
| 80 |
+
else:
|
| 81 |
+
edges = report.get("edges")
|
| 82 |
+
got = set()
|
| 83 |
+
edges_ok = isinstance(edges, list)
|
| 84 |
+
if edges_ok:
|
| 85 |
+
for e in edges:
|
| 86 |
+
if isinstance(e, dict) and rel_ok(e.get("from")) and rel_ok(e.get("to")):
|
| 87 |
+
got.add((e["from"], e["to"]))
|
| 88 |
+
else:
|
| 89 |
+
edges_ok = False
|
| 90 |
+
missing = EXPECTED_EDGES - got
|
| 91 |
+
checks[1] = (edges_ok and not missing,
|
| 92 |
+
"all 7 expected edges present" if (edges_ok and not missing)
|
| 93 |
+
else "missing/malformed edges: %s" % sorted(missing) if edges_ok else "edges malformed")
|
| 94 |
+
|
| 95 |
+
cycles = report.get("cycles")
|
| 96 |
+
found = False
|
| 97 |
+
if isinstance(cycles, list):
|
| 98 |
+
for c in cycles:
|
| 99 |
+
if isinstance(c, list) and len(c) >= 2:
|
| 100 |
+
s = [x for x in c if isinstance(x, str)]
|
| 101 |
+
if "lib/data/repo.js" in s and "lib/analyzer/summary.js" in s:
|
| 102 |
+
found = True
|
| 103 |
+
checks[2] = (found, "cycle between repo.js and summary.js reported" if found else "expected repo<->summary cycle not found in cycles")
|
| 104 |
+
|
| 105 |
+
viols = report.get("violations")
|
| 106 |
+
vlist = viols if isinstance(viols, list) else []
|
| 107 |
+
vstrs = [v for v in vlist if isinstance(v, str)]
|
| 108 |
+
miss_v = [m for m in MUST_VIOLATE if not any(m in v for v in vstrs)]
|
| 109 |
+
bad_v = [m for m in MUST_NOT_VIOLATE if any(m in v for v in vstrs)]
|
| 110 |
+
ok = isinstance(viols, list) and not miss_v and not bad_v
|
| 111 |
+
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")
|
| 112 |
+
checks[3] = (ok, reason)
|
| 113 |
+
|
| 114 |
+
imp = report.get("impact")
|
| 115 |
+
ok = isinstance(imp, dict)
|
| 116 |
+
detail = "impact malformed"
|
| 117 |
+
if ok:
|
| 118 |
+
direct = imp.get("direct"); trans = imp.get("transitive"); total = imp.get("total")
|
| 119 |
+
exp_direct = {"bin/main.js", "lib/analyzer/summary.js", "lib/data/repo.js"}
|
| 120 |
+
ok = (imp.get("target") == "lib/util/format.js"
|
| 121 |
+
and isinstance(direct, list) and set(direct) == exp_direct and len(direct) == 3
|
| 122 |
+
and isinstance(trans, list) and len(trans) == 0
|
| 123 |
+
and total == 3)
|
| 124 |
+
detail = "impact correct" if ok else "impact wrong: target=%r direct=%r transitive=%r total=%r" % (imp.get("target"), direct, trans, total)
|
| 125 |
+
checks[4] = (ok, detail)
|
| 126 |
+
|
| 127 |
+
paths = []
|
| 128 |
+
if isinstance(edges, list):
|
| 129 |
+
for e in edges:
|
| 130 |
+
if isinstance(e, dict):
|
| 131 |
+
paths += [e.get("from"), e.get("to")]
|
| 132 |
+
if isinstance(cycles, list):
|
| 133 |
+
for c in cycles:
|
| 134 |
+
if isinstance(c, list): paths += c
|
| 135 |
+
if isinstance(imp, dict):
|
| 136 |
+
paths += [imp.get("target")]
|
| 137 |
+
for k in ("direct", "transitive"):
|
| 138 |
+
v = imp.get(k)
|
| 139 |
+
if isinstance(v, list): paths += v
|
| 140 |
+
bad = [p for p in paths if not rel_ok(p)]
|
| 141 |
+
checks[5] = (not bad, "all paths relative, forward-slash, matching layout" if not bad else "bad paths: %s" % bad)
|
| 142 |
+
finally:
|
| 143 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 144 |
+
|
| 145 |
+
print(json.dumps({"checks": [{"id": str(i), "passed": bool(p), "reason": r} for i, (p, r) in enumerate(checks)]}))
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
main()
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/evaluator/r10_support.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""R10 evaluator helpers. Candidate programs are only run by the Docker harness."""
|
| 2 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 3 |
+
import ast, contextlib, io, json, os, pathlib, shutil, sys, tokenize
|
| 4 |
+
|
| 5 |
+
def combine(values):
|
| 6 |
+
values=list(values)
|
| 7 |
+
return False if any(v is False for v in values)else None if any(v is None for v in values)else True
|
| 8 |
+
|
| 9 |
+
def candidate_root():
|
| 10 |
+
return pathlib.Path(os.environ.get('MYBENCH_CANDIDATE',os.environ.get('CANDIDATE_ROOT','/candidate')))
|
| 11 |
+
|
| 12 |
+
def copy_program(destination,skip=()):
|
| 13 |
+
root=candidate_root();destination=pathlib.Path(destination);destination.mkdir(parents=True,exist_ok=True)
|
| 14 |
+
skip=set(skip)
|
| 15 |
+
def ignored(directory,names):
|
| 16 |
+
relative=pathlib.Path(directory).relative_to(root)
|
| 17 |
+
return [n for n in names if n in ('__pycache__','.git','.venv')or str(relative/n)in skip]
|
| 18 |
+
shutil.copytree(root,destination,dirs_exist_ok=True,symlinks=True,ignore=ignored)
|
| 19 |
+
return destination
|
| 20 |
+
|
| 21 |
+
def install_copy(skip=()):
|
| 22 |
+
original=shutil.copy
|
| 23 |
+
def copied(source,destination,*args,**kwargs):
|
| 24 |
+
source=pathlib.Path(source)
|
| 25 |
+
try:source.resolve().relative_to(candidate_root().resolve());local=True
|
| 26 |
+
except ValueError:local=False
|
| 27 |
+
if local and source.suffix=='.py':
|
| 28 |
+
target=pathlib.Path(destination)
|
| 29 |
+
if not target.is_dir():target=target.parent
|
| 30 |
+
copy_program(target,skip)
|
| 31 |
+
return original(source,destination,*args,**kwargs)
|
| 32 |
+
shutil.copy=copied
|
| 33 |
+
|
| 34 |
+
def _constant(node,constants):
|
| 35 |
+
if isinstance(node,ast.Constant):return node.value
|
| 36 |
+
if isinstance(node,ast.Name):return constants.get(node.id)
|
| 37 |
+
if isinstance(node,(ast.List,ast.Tuple)):
|
| 38 |
+
values=[_constant(n,constants)for n in node.elts]
|
| 39 |
+
return values if all(v is not None for v in values)else None
|
| 40 |
+
if isinstance(node,ast.BinOp)and isinstance(node.op,ast.Add):
|
| 41 |
+
a,b=_constant(node.left,constants),_constant(node.right,constants)
|
| 42 |
+
return a+b if isinstance(a,str)and isinstance(b,str)else None
|
| 43 |
+
if isinstance(node,ast.Call)and isinstance(node.func,ast.Attribute)and node.func.attr=='join'and len(node.args)==1:
|
| 44 |
+
separator=_constant(node.func.value,constants);values=_constant(node.args[0],constants)
|
| 45 |
+
return separator.join(values)if isinstance(separator,str)and isinstance(values,list)and all(isinstance(v,str)for v in values)else None
|
| 46 |
+
if isinstance(node,ast.JoinedStr):
|
| 47 |
+
values=[_constant(n.value,constants)if isinstance(n,ast.FormattedValue)else _constant(n,constants)for n in node.values]
|
| 48 |
+
return ''.join(map(str,values))if all(v is not None for v in values)else None
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
def scan_stdlib(root,entries,banned=()):
|
| 52 |
+
return True, [], 'Deferred to public bounded runtime policy; no whole-source inference'
|
| 53 |
+
|
| 54 |
+
def dependency(entry,banned=()):
|
| 55 |
+
return True
|
| 56 |
+
|
| 57 |
+
def strict_json(text):
|
| 58 |
+
def unique(pairs):
|
| 59 |
+
result={}
|
| 60 |
+
for k,v in pairs:
|
| 61 |
+
if k in result:raise ValueError('duplicate JSON member: '+k)
|
| 62 |
+
result[k]=v
|
| 63 |
+
return result
|
| 64 |
+
return json.loads(text,object_pairs_hook=unique,parse_constant=lambda value:(_ for _ in()).throw(ValueError(value)))
|
| 65 |
+
|
| 66 |
+
def strict_response(text):
|
| 67 |
+
import re
|
| 68 |
+
match=re.fullmatch(r'\s*```(?:json)?\s*\n(.*?)\n```\s*',text,re.S|re.I)
|
| 69 |
+
return strict_json(match[1]if match else text)
|
| 70 |
+
|
| 71 |
+
def trusted_stdout(query_id):
|
| 72 |
+
import hashlib
|
| 73 |
+
path=pathlib.Path(os.environ.get('MYBENCH_TRUSTED_TRACE','/tool_trajectory.json'))
|
| 74 |
+
expected=os.environ.get('MYBENCH_TRUSTED_TRACE_SHA256')
|
| 75 |
+
try:
|
| 76 |
+
path.resolve().relative_to(candidate_root().resolve())
|
| 77 |
+
return None
|
| 78 |
+
except ValueError:pass
|
| 79 |
+
try:
|
| 80 |
+
raw=path.read_bytes()
|
| 81 |
+
if not expected or hashlib.sha256(raw).hexdigest()!=expected:return None
|
| 82 |
+
trace=json.loads(raw)
|
| 83 |
+
metadata=json.loads(pathlib.Path(os.environ.get('MYBENCH_RUN_METADATA','/run_metadata.json')).read_text())
|
| 84 |
+
binding=metadata.get('trusted_trace_binding',metadata.get('derived',{}).get('trusted_trace_binding',{}))
|
| 85 |
+
if binding.get('query_id')!=query_id or binding.get('trajectory_sha256')!=expected:return None
|
| 86 |
+
hashes=binding.get('candidate_file_sha256')
|
| 87 |
+
if not isinstance(hashes,dict)or not hashes:return None
|
| 88 |
+
for relative,digest in hashes.items():
|
| 89 |
+
if pathlib.PurePosixPath(relative).is_absolute()or'..'in pathlib.PurePosixPath(relative).parts:return None
|
| 90 |
+
if hashlib.sha256((candidate_root()/relative).read_bytes()).hexdigest()!=digest:return None
|
| 91 |
+
except (OSError,ValueError):return None
|
| 92 |
+
if not isinstance(trace,dict)or not isinstance(trace.get('steps'),list):return None
|
| 93 |
+
outputs=[]
|
| 94 |
+
for step in trace['steps']:
|
| 95 |
+
observation=step.get('observation',{})
|
| 96 |
+
results=observation.get('results',[])if isinstance(observation,dict)else[]
|
| 97 |
+
calls={str(c.get('tool_call_id')):c for c in step.get('tool_calls',[])if isinstance(c,dict)and c.get('function_name')in ('bash','exec_command','shell','terminal','run_shell_command')}
|
| 98 |
+
for result in results:
|
| 99 |
+
if isinstance(result,dict)and str(result.get('source_call_id'))in calls and result.get('content')is not None:outputs.append(str(result['content']))
|
| 100 |
+
# A later successful printing may replace an earlier trial. Candidate
|
| 101 |
+
# formal answers and strings in tool arguments never enter this channel.
|
| 102 |
+
summaries=[output for output in outputs if re_search_summary(output)]
|
| 103 |
+
return summaries[-1]if summaries else ''
|
| 104 |
+
|
| 105 |
+
def re_search_summary(output):
|
| 106 |
+
import re
|
| 107 |
+
return bool(re.search(r'(?m)^G\d+:\s*(?:platformer|grid_logic|tower_defense|top_down|ui_heavy)\s*$',output))
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/grading/verified_config.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "ac993ee8a71a4ab4726c1662",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"graph_probe.py": "489c27f14aaa05bb6450fc7f87296022d4dbe8ddcefcf7f66c083fb0be63774e",
|
| 8 |
+
"original_check.py": "e1618214a64955e7dfcd211cd757fc13fcf9dba797b4e6c993b202a37852788e",
|
| 9 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 10 |
+
"auto_policy.json": "f245803a06b801617e2ec10e3bf5d2705663cbbcecbb21fff72555eaa9796161",
|
| 11 |
+
"r10_support.py": "40d42ef87dc72d111ac18afe6e413f07e8acbf342aac9d089b51e2c0a3dcefa6",
|
| 12 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 13 |
+
"autograde_task_check.py": "48e25d5b56963e0e094fe22b59ddf1cd203a221ade0af78b97850b65ef5bda80",
|
| 14 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 15 |
+
"auto_contract.json": "e34d2ed78db8d39ee6458195544227fc8d03cb33b4fbcada6c500eed294be002"
|
| 16 |
+
},
|
| 17 |
+
"runtime_requirements": {
|
| 18 |
+
"family": "verified2_repaired_workspace",
|
| 19 |
+
"container_image": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 20 |
+
"network": "none",
|
| 21 |
+
"read_only_mounts": [
|
| 22 |
+
"task:/source",
|
| 23 |
+
"task:/task",
|
| 24 |
+
"evaluator:/grader",
|
| 25 |
+
"candidate:/candidate",
|
| 26 |
+
"answer:/answer.txt"
|
| 27 |
+
],
|
| 28 |
+
"writable_tmpfs": [
|
| 29 |
+
"/app",
|
| 30 |
+
"/workspace",
|
| 31 |
+
"/tmp"
|
| 32 |
+
],
|
| 33 |
+
"copy_completed_candidate_children_to_app_before_grader": true,
|
| 34 |
+
"entrypoint": [
|
| 35 |
+
"python3",
|
| 36 |
+
"/grader/check.py"
|
| 37 |
+
],
|
| 38 |
+
"working_directory": "/candidate",
|
| 39 |
+
"environment": {
|
| 40 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 41 |
+
"MYBENCH_CANDIDATE_PATH": "/candidate",
|
| 42 |
+
"CANDIDATE_DIR": "/candidate",
|
| 43 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 44 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 45 |
+
"SOURCE_TASK_DIR": "/source",
|
| 46 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 47 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 48 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1"
|
| 49 |
+
},
|
| 50 |
+
"environment_names_detected": [
|
| 51 |
+
"MYBENCH_CANDIDATE",
|
| 52 |
+
"MYBENCH_EPHEMERAL_WORKSPACE",
|
| 53 |
+
"MYBENCH_FIXTURE_MATERIALIZE"
|
| 54 |
+
],
|
| 55 |
+
"expected_check_ids": [
|
| 56 |
+
"0",
|
| 57 |
+
"1",
|
| 58 |
+
"2",
|
| 59 |
+
"3",
|
| 60 |
+
"4",
|
| 61 |
+
"5"
|
| 62 |
+
],
|
| 63 |
+
"criterion_count": 6,
|
| 64 |
+
"criterion_weights": {
|
| 65 |
+
"0": 1,
|
| 66 |
+
"1": 1,
|
| 67 |
+
"2": 1,
|
| 68 |
+
"3": 1,
|
| 69 |
+
"4": 1,
|
| 70 |
+
"5": 1
|
| 71 |
+
},
|
| 72 |
+
"actual_original_success_criteria_count": 6,
|
| 73 |
+
"original_task_metadata_must_not_define_override_criterion_count": false,
|
| 74 |
+
"requires_external_actual_native_trace": false,
|
| 75 |
+
"requires_external_trusted_snapshot_binding": false,
|
| 76 |
+
"fresh_native_binding_must_not_require_historical_run_id": true,
|
| 77 |
+
"checker_can_execute_candidate_subprocesses": true,
|
| 78 |
+
"host_execution_forbidden": true,
|
| 79 |
+
"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.",
|
| 80 |
+
"docker_image_payload_in_source_tree": false,
|
| 81 |
+
"runtime_missing": [],
|
| 82 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 83 |
+
"grader_timeout_seconds": 600
|
| 84 |
+
},
|
| 85 |
+
"engine": "portable_verified_v1"
|
| 86 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/bin/main.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// entry point: may import from lib only
|
| 2 |
+
import { put, report } from '../lib/data/repo.js';
|
| 3 |
+
import { label } from '../lib/util/format.js';
|
| 4 |
+
|
| 5 |
+
put(3);
|
| 6 |
+
console.log(label(report()));
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/analyzer/summary.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { fmt } from '../util/format.js';
|
| 2 |
+
import { report } from '../data/repo.js';
|
| 3 |
+
|
| 4 |
+
export function summarize(items) {
|
| 5 |
+
if (!items.length) return 'empty';
|
| 6 |
+
return 'count=' + items.length;
|
| 7 |
+
}
|
| 8 |
+
export function full() { return report(); }
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/data/repo.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Store } from '../model/store.js';
|
| 2 |
+
import { fmt } from '../util/format.js';
|
| 3 |
+
import { summarize } from '../analyzer/summary.js';
|
| 4 |
+
|
| 5 |
+
const store = new Store();
|
| 6 |
+
export function put(x) { store.add(x); }
|
| 7 |
+
export function report() { return summarize(store.all()) + ' avg=' + fmt(1); }
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/model/store.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// model layer: no dependencies on other layers
|
| 2 |
+
export class Store {
|
| 3 |
+
constructor() { this.items = []; }
|
| 4 |
+
add(item) { this.items.push(item); }
|
| 5 |
+
all() { return this.items; }
|
| 6 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/inputs/lib/util/format.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export function fmt(n) { return n.toFixed(2); }
|
| 2 |
+
export function label(s) { return '[' + s + ']'; }
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/instruction.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
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: <from> -> <to> (<rule>)': 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..
|
| 2 |
+
Bounded automatic resource contract: During the actual grader-launched Python invocations, Python imports must resolve to the standard library or submitted local modules/packages (including namespace packages and computed imports). Unused/dead source code and strings are not rejected by static import inference. Do not perform network operations during graded invocations. Do not load or call foreign native libraries through FFI during graded invocations. Child processes are not forbidden solely because they exist; all original output and interface requirements still apply. A launcher or instrumentation failure is an infrastructure error, not a wrong-answer score.
|
| 3 |
+
|
| 4 |
+
Execution budget: every grader-launched candidate Python invocation must complete within 60 seconds. A timeout after candidate startup fails this bounded-completion requirement; a trusted observer or launcher failure is an infrastructure error.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
Bounded automatic-evaluation contract: Each grader-launched candidate Python script/module invocation, including a candidate called by a trusted probe, must finish within 60 seconds. A timeout or signal termination is a failed invocation. Normal nonzero exits follow the task-specific exit contract. The complete automatic evaluation has a 420-second wall-time budget; once exhausted, remaining candidate invocations fail without being launched. This bounds failed or hanging submissions within the outer evaluator deadline. Import checks concern imports requested by candidate-authored code during these invocations, including computed imports and caught failures; Python standard-library modules and local authored helpers/packages are allowed. Inactive code, string literals, and optional imports attempted internally by the standard library are not candidate dependency violations. Python socket network operations attempted within the observed invocation are disallowed, and the Docker environment has no network access. Attempting ctypes foreign-function loading/calls, including ctypes initialization that loads a library, is outside this execution contract. The observer applies to the actual bounded invocations; it does not infer whole-program properties. Trusted fixture/interpreter/observer failures are reported as evaluation errors without a candidate score.
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/SKILL.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Multi-skill source bundle
|
| 2 |
+
|
| 3 |
+
Private source bundle wrapper. The original skills are in members/.
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M000/SKILL.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: validate-architecture
|
| 3 |
+
description: Verify architectural consistency and dependency rules
|
| 4 |
+
trigger: when the user asks about architecture, rules, conventions, or dependency validation
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Validate Architecture
|
| 8 |
+
|
| 9 |
+
When invoked:
|
| 10 |
+
|
| 11 |
+
1. Detect project structure:
|
| 12 |
+
- Analyze `lib/` directory layout.
|
| 13 |
+
- Identify internal packages and subdirectories (`analyzer/`, `data/`, `model/`, `util/`).
|
| 14 |
+
- Note the `bin/` entry point.
|
| 15 |
+
|
| 16 |
+
2. Analyze dependencies between modules:
|
| 17 |
+
- Map which `lib/` subdirectories import from which others.
|
| 18 |
+
- Track imports across package boundaries.
|
| 19 |
+
|
| 20 |
+
3. Verify architecture rules for Dart packages:
|
| 21 |
+
|
| 22 |
+
### Package boundaries
|
| 23 |
+
- Public API should be minimal and intentional.
|
| 24 |
+
- Internal implementation details should not be exposed.
|
| 25 |
+
- Files outside `lib/` (e.g., `bin/`, `test/`) should not be imported by `lib/`.
|
| 26 |
+
|
| 27 |
+
### Layer separation
|
| 28 |
+
- `lib/model/` should have minimal dependencies (ideally none on other layers).
|
| 29 |
+
- `lib/data/` may depend on `model/` but not on `analyzer/` or `util/`.
|
| 30 |
+
- `lib/analyzer/` may depend on `model/` and `util/`.
|
| 31 |
+
- `lib/util/` should be independent of other layers.
|
| 32 |
+
- `bin/main.dart` should only depend on the public API entry point.
|
| 33 |
+
|
| 34 |
+
4. Detect:
|
| 35 |
+
|
| 36 |
+
### Violations
|
| 37 |
+
- Cyclic dependencies between packages/modules.
|
| 38 |
+
- Forbidden dependencies (e.g., data layer importing analyzer).
|
| 39 |
+
- Unused modules or files.
|
| 40 |
+
- Internal implementation leaks (private files imported externally).
|
| 41 |
+
|
| 42 |
+
### Warnings
|
| 43 |
+
- Overly broad exports.
|
| 44 |
+
- Files with too many dependencies.
|
| 45 |
+
- Modules with unclear responsibilities.
|
| 46 |
+
|
| 47 |
+
5. Produce a report with:
|
| 48 |
+
|
| 49 |
+
### Violations
|
| 50 |
+
Critical issues that break architectural rules.
|
| 51 |
+
|
| 52 |
+
### Warnings
|
| 53 |
+
Potential issues or code smells.
|
| 54 |
+
|
| 55 |
+
### Recommendations
|
| 56 |
+
Suggested improvements for the module structure and dependency graph.
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/SKILL.md
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: dependency-analyzer
|
| 3 |
+
display-name: Dependency Analyzer
|
| 4 |
+
description: 依赖分析技能 - 导入图构建、变更影响分析、CVE可达性、循环依赖检测
|
| 5 |
+
version: 1.0.0
|
| 6 |
+
category: analysis
|
| 7 |
+
user-invocable: true
|
| 8 |
+
tags: [dependency, import, graph, impact, circular, vulnerability, license]
|
| 9 |
+
capabilities:
|
| 10 |
+
[
|
| 11 |
+
import-graph,
|
| 12 |
+
impact-analysis,
|
| 13 |
+
circular-detection,
|
| 14 |
+
vulnerability-reachability,
|
| 15 |
+
license-check,
|
| 16 |
+
]
|
| 17 |
+
tools:
|
| 18 |
+
- file_reader
|
| 19 |
+
- code_analyzer
|
| 20 |
+
handler: ./handler.js
|
| 21 |
+
instructions: |
|
| 22 |
+
Use this skill when the user needs to understand module dependencies, analyze the
|
| 23 |
+
impact of code changes, detect circular dependencies, or check dependency vulnerabilities.
|
| 24 |
+
Build import/require graphs from source code and npm/pip/maven dependency trees.
|
| 25 |
+
Provide change impact analysis: given a file modification, enumerate all affected
|
| 26 |
+
downstream consumers. For security, perform reachability analysis to determine if
|
| 27 |
+
CVEs in dependencies actually affect the application.
|
| 28 |
+
examples:
|
| 29 |
+
- input: "/dependency-analyzer src/main/llm/session-manager.js --impact"
|
| 30 |
+
output: "Impact analysis: 14 files depend on session-manager. Changes affect: conversation-ipc, manus-optimizations, context-engineering..."
|
| 31 |
+
- input: "/dependency-analyzer --circular src/main/"
|
| 32 |
+
output: "Found 2 circular dependencies: llm/→hooks/→llm/ and browser/→actions/→browser/"
|
| 33 |
+
- input: "/dependency-analyzer package-lock.json --vulnerabilities"
|
| 34 |
+
output: "12 CVEs found, 3 reachable from application code, 9 in unused code paths"
|
| 35 |
+
os: [win32, darwin, linux]
|
| 36 |
+
author: ChainlessChain
|
| 37 |
+
---
|
| 38 |
+
|
| 39 |
+
# 依赖分析技能
|
| 40 |
+
|
| 41 |
+
## 描述
|
| 42 |
+
|
| 43 |
+
构建代码库的模块导入图和包依赖树。提供变更影响分析、循环依赖检测、CVE 可达性分析和许可证兼容性检查。
|
| 44 |
+
|
| 45 |
+
## 使用方法
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
/dependency-analyzer [目标] [选项]
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## 分析类型
|
| 52 |
+
|
| 53 |
+
### 导入图构建
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
/dependency-analyzer src/main/ --graph
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
解析所有 `import`/`require` 语句,构建模块依赖图:
|
| 60 |
+
|
| 61 |
+
- 直接依赖和传递依赖
|
| 62 |
+
- 导出/导入的具体符号
|
| 63 |
+
- Mermaid 图表输出
|
| 64 |
+
|
| 65 |
+
### 变更影响分析
|
| 66 |
+
|
| 67 |
+
```
|
| 68 |
+
/dependency-analyzer src/main/llm/session-manager.js --impact
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
给定一个文件修改,追踪所有受影响的下游消费者:
|
| 72 |
+
|
| 73 |
+
- 直接导入者
|
| 74 |
+
- 传递依赖者
|
| 75 |
+
- 受影响的 IPC 处理器
|
| 76 |
+
- 受影响的测试文件
|
| 77 |
+
|
| 78 |
+
### 循环依赖检测
|
| 79 |
+
|
| 80 |
+
```
|
| 81 |
+
/dependency-analyzer --circular src/main/
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
使用拓扑排序检测循环依赖:
|
| 85 |
+
|
| 86 |
+
- 列出所有循环路径
|
| 87 |
+
- 建议解耦方案
|
| 88 |
+
- 影响严重度评估
|
| 89 |
+
|
| 90 |
+
### CVE 可达性分析
|
| 91 |
+
|
| 92 |
+
```
|
| 93 |
+
/dependency-analyzer package-lock.json --vulnerabilities
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
不仅列出 CVE,还追踪漏洞是否可达:
|
| 97 |
+
|
| 98 |
+
- 运行 `npm audit` 获取 CVE 列表
|
| 99 |
+
- 追踪漏洞函数是否被应用代码调用
|
| 100 |
+
- 标记"可达"(需修复)vs "不可达"(低优先级)
|
| 101 |
+
- 修复建议(版本升级、替代包)
|
| 102 |
+
|
| 103 |
+
### 许可证检查
|
| 104 |
+
|
| 105 |
+
```
|
| 106 |
+
/dependency-analyzer --licenses
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
扫描所有依赖的许可证:
|
| 110 |
+
|
| 111 |
+
- 许可证类型汇总 (MIT, Apache, GPL, BSD 等)
|
| 112 |
+
- 兼容性矩阵
|
| 113 |
+
- GPL 传染风险警告
|
| 114 |
+
|
| 115 |
+
## 输出格式
|
| 116 |
+
|
| 117 |
+
### 影响分析报告
|
| 118 |
+
|
| 119 |
+
```
|
| 120 |
+
Impact Analysis: session-manager.js
|
| 121 |
+
====================================
|
| 122 |
+
Direct dependents: 6 files
|
| 123 |
+
→ conversation-ipc.js (imports: SessionManager)
|
| 124 |
+
→ manus-optimizations.js (imports: SessionManager)
|
| 125 |
+
→ context-engineering.js (imports: SessionManager)
|
| 126 |
+
...
|
| 127 |
+
|
| 128 |
+
Transitive dependents: 8 additional files
|
| 129 |
+
Affected IPC handlers: 12
|
| 130 |
+
Affected tests: 5 test files
|
| 131 |
+
Risk level: HIGH (core module)
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## 示例
|
| 135 |
+
|
| 136 |
+
分析影响范围:
|
| 137 |
+
|
| 138 |
+
```
|
| 139 |
+
/dependency-analyzer src/main/database.js --impact
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
检测循环依赖:
|
| 143 |
+
|
| 144 |
+
```
|
| 145 |
+
/dependency-analyzer --circular src/main/
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
漏洞可达性分析:
|
| 149 |
+
|
| 150 |
+
```
|
| 151 |
+
/dependency-analyzer package-lock.json --vulnerabilities --reachability
|
| 152 |
+
```
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/skill/members/M001/handler.js
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Dependency Analyzer Skill Handler
|
| 3 |
+
*
|
| 4 |
+
* Builds import/require graphs, detects circular dependencies,
|
| 5 |
+
* performs change impact analysis, and checks npm audit vulnerabilities.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
const fs = require("fs");
|
| 9 |
+
const path = require("path");
|
| 10 |
+
const { execSync } = require("child_process");
|
| 11 |
+
const { logger } = require("../../../../../utils/logger.js");
|
| 12 |
+
|
| 13 |
+
const IGNORE_DIRS = new Set([
|
| 14 |
+
"node_modules",
|
| 15 |
+
".git",
|
| 16 |
+
"dist",
|
| 17 |
+
"build",
|
| 18 |
+
"coverage",
|
| 19 |
+
".cache",
|
| 20 |
+
]);
|
| 21 |
+
const CODE_EXTS = new Set(["js", "mjs", "ts", "tsx", "jsx", "vue"]);
|
| 22 |
+
|
| 23 |
+
module.exports = {
|
| 24 |
+
async init(skill) {
|
| 25 |
+
logger.info("[DependencyAnalyzer] Handler initialized");
|
| 26 |
+
},
|
| 27 |
+
|
| 28 |
+
async execute(task, context = {}, skill) {
|
| 29 |
+
const input = task.input || task.args || "";
|
| 30 |
+
const { action, options } = parseInput(input, context);
|
| 31 |
+
|
| 32 |
+
logger.info(`[DependencyAnalyzer] Action: ${action}`, { options });
|
| 33 |
+
|
| 34 |
+
try {
|
| 35 |
+
switch (action) {
|
| 36 |
+
case "impact":
|
| 37 |
+
return await handleImpact(options.targetPath, options.targetDir);
|
| 38 |
+
case "circular":
|
| 39 |
+
return await handleCircular(options.targetDir);
|
| 40 |
+
case "vulnerabilities":
|
| 41 |
+
return await handleVulnerabilities(options.targetDir);
|
| 42 |
+
case "licenses":
|
| 43 |
+
return await handleLicenses(options.targetDir);
|
| 44 |
+
default:
|
| 45 |
+
return await handleGraph(options.targetDir);
|
| 46 |
+
}
|
| 47 |
+
} catch (error) {
|
| 48 |
+
logger.error(`[DependencyAnalyzer] Error: ${error.message}`);
|
| 49 |
+
return {
|
| 50 |
+
success: false,
|
| 51 |
+
error: error.message,
|
| 52 |
+
message: `Dependency analysis failed: ${error.message}`,
|
| 53 |
+
};
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
};
|
| 57 |
+
|
| 58 |
+
function parseInput(input, context) {
|
| 59 |
+
const parts = (input || "").trim().split(/\s+/);
|
| 60 |
+
const options = {
|
| 61 |
+
targetDir: context.workspacePath || process.cwd(),
|
| 62 |
+
targetPath: null,
|
| 63 |
+
};
|
| 64 |
+
let action = "graph";
|
| 65 |
+
|
| 66 |
+
for (let i = 0; i < parts.length; i++) {
|
| 67 |
+
const p = parts[i];
|
| 68 |
+
if (p === "--impact") {
|
| 69 |
+
action = "impact";
|
| 70 |
+
} else if (p === "--circular") {
|
| 71 |
+
action = "circular";
|
| 72 |
+
} else if (p === "--graph") {
|
| 73 |
+
action = "graph";
|
| 74 |
+
} else if (p === "--vulnerabilities") {
|
| 75 |
+
action = "vulnerabilities";
|
| 76 |
+
} else if (p === "--licenses") {
|
| 77 |
+
action = "licenses";
|
| 78 |
+
} else if (p && !p.startsWith("-")) {
|
| 79 |
+
const resolved = path.resolve(options.targetDir, p);
|
| 80 |
+
if (fs.existsSync(resolved)) {
|
| 81 |
+
const stat = fs.statSync(resolved);
|
| 82 |
+
if (stat.isDirectory()) {
|
| 83 |
+
options.targetDir = resolved;
|
| 84 |
+
} else {
|
| 85 |
+
options.targetPath = resolved;
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
return { action, options };
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
function collectFiles(dir, maxDepth = 6, depth = 0) {
|
| 95 |
+
const files = [];
|
| 96 |
+
if (depth > maxDepth || !fs.existsSync(dir)) {
|
| 97 |
+
return files;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
let entries;
|
| 101 |
+
try {
|
| 102 |
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
| 103 |
+
} catch {
|
| 104 |
+
return files;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
for (const entry of entries) {
|
| 108 |
+
if (
|
| 109 |
+
entry.isDirectory() &&
|
| 110 |
+
!IGNORE_DIRS.has(entry.name) &&
|
| 111 |
+
!entry.name.startsWith(".")
|
| 112 |
+
) {
|
| 113 |
+
files.push(
|
| 114 |
+
...collectFiles(path.join(dir, entry.name), maxDepth, depth + 1),
|
| 115 |
+
);
|
| 116 |
+
} else if (entry.isFile()) {
|
| 117 |
+
const ext = path.extname(entry.name).slice(1);
|
| 118 |
+
if (CODE_EXTS.has(ext)) {
|
| 119 |
+
files.push(path.join(dir, entry.name));
|
| 120 |
+
}
|
| 121 |
+
if (files.length >= 500) {
|
| 122 |
+
return files;
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
return files;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
function extractImports(filePath) {
|
| 130 |
+
let content;
|
| 131 |
+
try {
|
| 132 |
+
content = fs.readFileSync(filePath, "utf-8");
|
| 133 |
+
} catch {
|
| 134 |
+
return [];
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
const imports = [];
|
| 138 |
+
|
| 139 |
+
// ES6 imports: import ... from '...'
|
| 140 |
+
const esRe = /import\s+(?:.*?\s+from\s+)?['"]([^'"]+)['"]/g;
|
| 141 |
+
let m;
|
| 142 |
+
while ((m = esRe.exec(content)) !== null) {
|
| 143 |
+
imports.push(m[1]);
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// CommonJS require: require('...')
|
| 147 |
+
const cjsRe = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
| 148 |
+
while ((m = cjsRe.exec(content)) !== null) {
|
| 149 |
+
imports.push(m[1]);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
return imports;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
function resolveImport(importPath, fromFile, baseDir) {
|
| 156 |
+
if (!importPath.startsWith(".") && !importPath.startsWith("/")) {
|
| 157 |
+
return null;
|
| 158 |
+
} // npm package
|
| 159 |
+
|
| 160 |
+
const fromDir = path.dirname(fromFile);
|
| 161 |
+
const resolved = path.resolve(fromDir, importPath);
|
| 162 |
+
|
| 163 |
+
// Try extensions
|
| 164 |
+
const exts = [
|
| 165 |
+
".js",
|
| 166 |
+
".ts",
|
| 167 |
+
".mjs",
|
| 168 |
+
".jsx",
|
| 169 |
+
".tsx",
|
| 170 |
+
".vue",
|
| 171 |
+
"/index.js",
|
| 172 |
+
"/index.ts",
|
| 173 |
+
];
|
| 174 |
+
if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
|
| 175 |
+
return resolved;
|
| 176 |
+
}
|
| 177 |
+
for (const ext of exts) {
|
| 178 |
+
if (fs.existsSync(resolved + ext)) {
|
| 179 |
+
return resolved + ext;
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
return null;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
function buildImportGraph(files, baseDir) {
|
| 186 |
+
const graph = new Map(); // file -> [imported files]
|
| 187 |
+
const reverseGraph = new Map(); // file -> [files that import it]
|
| 188 |
+
|
| 189 |
+
for (const file of files) {
|
| 190 |
+
const imports = extractImports(file);
|
| 191 |
+
const resolvedImports = [];
|
| 192 |
+
|
| 193 |
+
for (const imp of imports) {
|
| 194 |
+
const resolved = resolveImport(imp, file, baseDir);
|
| 195 |
+
if (resolved && files.includes(resolved)) {
|
| 196 |
+
resolvedImports.push(resolved);
|
| 197 |
+
if (!reverseGraph.has(resolved)) {
|
| 198 |
+
reverseGraph.set(resolved, []);
|
| 199 |
+
}
|
| 200 |
+
reverseGraph.get(resolved).push(file);
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
graph.set(file, resolvedImports);
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
return { graph, reverseGraph };
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
async function handleGraph(targetDir) {
|
| 211 |
+
const files = collectFiles(targetDir);
|
| 212 |
+
const { graph } = buildImportGraph(files, targetDir);
|
| 213 |
+
|
| 214 |
+
const edges = [];
|
| 215 |
+
for (const [file, imports] of graph) {
|
| 216 |
+
for (const imp of imports) {
|
| 217 |
+
edges.push({
|
| 218 |
+
from: path.relative(targetDir, file),
|
| 219 |
+
to: path.relative(targetDir, imp),
|
| 220 |
+
});
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
const fileCount = files.length;
|
| 225 |
+
const edgeCount = edges.length;
|
| 226 |
+
|
| 227 |
+
// Top files by import count
|
| 228 |
+
const importCounts = {};
|
| 229 |
+
for (const edge of edges) {
|
| 230 |
+
importCounts[edge.to] = (importCounts[edge.to] || 0) + 1;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
const topImported = Object.entries(importCounts)
|
| 234 |
+
.sort(([, a], [, b]) => b - a)
|
| 235 |
+
.slice(0, 15);
|
| 236 |
+
|
| 237 |
+
const report =
|
| 238 |
+
`Dependency Graph\n${"=".repeat(25)}\n` +
|
| 239 |
+
`Files: ${fileCount}, Edges: ${edgeCount}\n\n` +
|
| 240 |
+
`Most imported files:\n` +
|
| 241 |
+
topImported
|
| 242 |
+
.map(([file, count]) => ` ${file} (imported by ${count} files)`)
|
| 243 |
+
.join("\n");
|
| 244 |
+
|
| 245 |
+
return {
|
| 246 |
+
success: true,
|
| 247 |
+
result: { fileCount, edgeCount, topImported, edges: edges.slice(0, 100) },
|
| 248 |
+
message: report,
|
| 249 |
+
};
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
async function handleImpact(targetPath, targetDir) {
|
| 253 |
+
if (!targetPath) {
|
| 254 |
+
return { success: false, message: "Usage: --impact <file-path>" };
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
const files = collectFiles(targetDir);
|
| 258 |
+
const { reverseGraph } = buildImportGraph(files, targetDir);
|
| 259 |
+
|
| 260 |
+
// BFS for transitive dependents
|
| 261 |
+
const visited = new Set();
|
| 262 |
+
const queue = [targetPath];
|
| 263 |
+
const directDeps = [];
|
| 264 |
+
const transitiveDeps = [];
|
| 265 |
+
let level = 0;
|
| 266 |
+
|
| 267 |
+
while (queue.length > 0) {
|
| 268 |
+
const size = queue.length;
|
| 269 |
+
for (let i = 0; i < size; i++) {
|
| 270 |
+
const current = queue.shift();
|
| 271 |
+
if (visited.has(current)) {
|
| 272 |
+
continue;
|
| 273 |
+
}
|
| 274 |
+
visited.add(current);
|
| 275 |
+
|
| 276 |
+
const dependents = reverseGraph.get(current) || [];
|
| 277 |
+
for (const dep of dependents) {
|
| 278 |
+
if (!visited.has(dep)) {
|
| 279 |
+
if (level === 0) {
|
| 280 |
+
directDeps.push(dep);
|
| 281 |
+
} else {
|
| 282 |
+
transitiveDeps.push(dep);
|
| 283 |
+
}
|
| 284 |
+
queue.push(dep);
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
level++;
|
| 289 |
+
if (level > 10) {
|
| 290 |
+
break;
|
| 291 |
+
} // prevent infinite loops
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
const relTarget = path.relative(targetDir, targetPath);
|
| 295 |
+
const report =
|
| 296 |
+
`Impact Analysis: ${relTarget}\n${"=".repeat(40)}\n\n` +
|
| 297 |
+
`Direct dependents: ${directDeps.length} files\n` +
|
| 298 |
+
directDeps.map((f) => ` -> ${path.relative(targetDir, f)}`).join("\n") +
|
| 299 |
+
`\n\nTransitive dependents: ${transitiveDeps.length} files\n` +
|
| 300 |
+
transitiveDeps
|
| 301 |
+
.slice(0, 20)
|
| 302 |
+
.map((f) => ` -> ${path.relative(targetDir, f)}`)
|
| 303 |
+
.join("\n") +
|
| 304 |
+
`\n\nTotal affected: ${directDeps.length + transitiveDeps.length} files` +
|
| 305 |
+
`\nRisk level: ${directDeps.length > 10 ? "HIGH" : directDeps.length > 5 ? "MEDIUM" : "LOW"}`;
|
| 306 |
+
|
| 307 |
+
return {
|
| 308 |
+
success: true,
|
| 309 |
+
result: {
|
| 310 |
+
target: relTarget,
|
| 311 |
+
directDeps: directDeps.length,
|
| 312 |
+
transitiveDeps: transitiveDeps.length,
|
| 313 |
+
},
|
| 314 |
+
message: report,
|
| 315 |
+
};
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
async function handleCircular(targetDir) {
|
| 319 |
+
const files = collectFiles(targetDir);
|
| 320 |
+
const { graph } = buildImportGraph(files, targetDir);
|
| 321 |
+
|
| 322 |
+
// Detect cycles using DFS
|
| 323 |
+
const cycles = [];
|
| 324 |
+
const visited = new Set();
|
| 325 |
+
const inStack = new Set();
|
| 326 |
+
const stackPath = [];
|
| 327 |
+
|
| 328 |
+
function dfs(node) {
|
| 329 |
+
if (inStack.has(node)) {
|
| 330 |
+
const cycleStart = stackPath.indexOf(node);
|
| 331 |
+
if (cycleStart >= 0) {
|
| 332 |
+
const cycle = stackPath
|
| 333 |
+
.slice(cycleStart)
|
| 334 |
+
.map((f) => path.relative(targetDir, f));
|
| 335 |
+
cycles.push(cycle);
|
| 336 |
+
}
|
| 337 |
+
return;
|
| 338 |
+
}
|
| 339 |
+
if (visited.has(node)) {
|
| 340 |
+
return;
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
visited.add(node);
|
| 344 |
+
inStack.add(node);
|
| 345 |
+
stackPath.push(node);
|
| 346 |
+
|
| 347 |
+
const deps = graph.get(node) || [];
|
| 348 |
+
for (const dep of deps) {
|
| 349 |
+
dfs(dep);
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
inStack.delete(node);
|
| 353 |
+
stackPath.pop();
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
for (const file of files) {
|
| 357 |
+
if (!visited.has(file)) {
|
| 358 |
+
dfs(file);
|
| 359 |
+
}
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
const report =
|
| 363 |
+
cycles.length > 0
|
| 364 |
+
? `Circular Dependencies Found: ${cycles.length}\n${"=".repeat(40)}\n\n` +
|
| 365 |
+
cycles
|
| 366 |
+
.slice(0, 10)
|
| 367 |
+
.map((cycle, i) => `${i + 1}. ${cycle.join(" -> ")} -> ${cycle[0]}`)
|
| 368 |
+
.join("\n\n")
|
| 369 |
+
: `No circular dependencies found in ${files.length} files.`;
|
| 370 |
+
|
| 371 |
+
return {
|
| 372 |
+
success: true,
|
| 373 |
+
result: { cycles: cycles.slice(0, 20), fileCount: files.length },
|
| 374 |
+
message: report,
|
| 375 |
+
};
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
async function handleVulnerabilities(targetDir) {
|
| 379 |
+
let auditOutput;
|
| 380 |
+
try {
|
| 381 |
+
auditOutput = execSync("npm audit --json 2>/dev/null", {
|
| 382 |
+
encoding: "utf-8",
|
| 383 |
+
cwd: targetDir,
|
| 384 |
+
timeout: 30000,
|
| 385 |
+
stdio: ["pipe", "pipe", "pipe"],
|
| 386 |
+
});
|
| 387 |
+
} catch (err) {
|
| 388 |
+
// npm audit returns non-zero when vulnerabilities exist
|
| 389 |
+
auditOutput = err.stdout || "";
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
if (!auditOutput) {
|
| 393 |
+
return {
|
| 394 |
+
success: true,
|
| 395 |
+
result: { vulnerabilities: [] },
|
| 396 |
+
message: "npm audit returned no data. Ensure package-lock.json exists.",
|
| 397 |
+
};
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
let audit;
|
| 401 |
+
try {
|
| 402 |
+
audit = JSON.parse(auditOutput);
|
| 403 |
+
} catch {
|
| 404 |
+
return {
|
| 405 |
+
success: true,
|
| 406 |
+
result: {},
|
| 407 |
+
message: "Could not parse npm audit output.",
|
| 408 |
+
};
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
const vulns = audit.vulnerabilities || {};
|
| 412 |
+
const summary = audit.metadata || {};
|
| 413 |
+
|
| 414 |
+
const vulnList = Object.entries(vulns).map(([pkg, info]) => ({
|
| 415 |
+
package: pkg,
|
| 416 |
+
severity: info.severity,
|
| 417 |
+
via: Array.isArray(info.via)
|
| 418 |
+
? info.via.filter((v) => typeof v === "string")
|
| 419 |
+
: [],
|
| 420 |
+
fixAvailable: !!info.fixAvailable,
|
| 421 |
+
}));
|
| 422 |
+
|
| 423 |
+
const bySeverity = { critical: 0, high: 0, moderate: 0, low: 0 };
|
| 424 |
+
for (const v of vulnList) {
|
| 425 |
+
if (bySeverity[v.severity] !== undefined) {
|
| 426 |
+
bySeverity[v.severity]++;
|
| 427 |
+
}
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
const report =
|
| 431 |
+
`Vulnerability Report\n${"=".repeat(25)}\n` +
|
| 432 |
+
`Total: ${vulnList.length} vulnerable packages\n` +
|
| 433 |
+
`Critical: ${bySeverity.critical}, High: ${bySeverity.high}, Moderate: ${bySeverity.moderate}, Low: ${bySeverity.low}\n\n` +
|
| 434 |
+
vulnList
|
| 435 |
+
.sort((a, b) => {
|
| 436 |
+
const order = { critical: 0, high: 1, moderate: 2, low: 3 };
|
| 437 |
+
return (order[a.severity] || 4) - (order[b.severity] || 4);
|
| 438 |
+
})
|
| 439 |
+
.slice(0, 30)
|
| 440 |
+
.map(
|
| 441 |
+
(v) =>
|
| 442 |
+
` ${v.severity.toUpperCase()} ${v.package}${v.fixAvailable ? " (fix available)" : ""}`,
|
| 443 |
+
)
|
| 444 |
+
.join("\n");
|
| 445 |
+
|
| 446 |
+
return {
|
| 447 |
+
success: true,
|
| 448 |
+
result: { vulnerabilities: vulnList, bySeverity },
|
| 449 |
+
message: report,
|
| 450 |
+
};
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
async function handleLicenses(targetDir) {
|
| 454 |
+
const pkgLockPath = path.join(targetDir, "node_modules");
|
| 455 |
+
if (!fs.existsSync(pkgLockPath)) {
|
| 456 |
+
return {
|
| 457 |
+
success: false,
|
| 458 |
+
message: "node_modules not found. Run npm install first.",
|
| 459 |
+
};
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
const licenses = {};
|
| 463 |
+
let entries;
|
| 464 |
+
try {
|
| 465 |
+
entries = fs.readdirSync(pkgLockPath, { withFileTypes: true });
|
| 466 |
+
} catch {
|
| 467 |
+
return { success: false, message: "Cannot read node_modules." };
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
let scanned = 0;
|
| 471 |
+
for (const entry of entries) {
|
| 472 |
+
if (!entry.isDirectory() || entry.name.startsWith(".")) {
|
| 473 |
+
continue;
|
| 474 |
+
}
|
| 475 |
+
const pkgJsonPath = path.join(pkgLockPath, entry.name, "package.json");
|
| 476 |
+
if (!fs.existsSync(pkgJsonPath)) {
|
| 477 |
+
continue;
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
try {
|
| 481 |
+
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
| 482 |
+
const license = pkg.license || "UNKNOWN";
|
| 483 |
+
licenses[license] = (licenses[license] || 0) + 1;
|
| 484 |
+
scanned++;
|
| 485 |
+
} catch {
|
| 486 |
+
/* skip */
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
if (scanned >= 500) {
|
| 490 |
+
break;
|
| 491 |
+
}
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
const sorted = Object.entries(licenses).sort(([, a], [, b]) => b - a);
|
| 495 |
+
const gplWarnings = sorted.filter(
|
| 496 |
+
([lic]) => /GPL/i.test(lic) && !/LGPL/i.test(lic),
|
| 497 |
+
);
|
| 498 |
+
|
| 499 |
+
const report =
|
| 500 |
+
`License Report\n${"=".repeat(20)}\nPackages scanned: ${scanned}\n\n` +
|
| 501 |
+
sorted.map(([lic, count]) => ` ${lic}: ${count} packages`).join("\n") +
|
| 502 |
+
(gplWarnings.length > 0
|
| 503 |
+
? `\n\n GPL Warning: ${gplWarnings.map(([lic, count]) => `${lic} (${count})`).join(", ")} - may have copyleft requirements`
|
| 504 |
+
: "");
|
| 505 |
+
|
| 506 |
+
return {
|
| 507 |
+
success: true,
|
| 508 |
+
result: { licenses, scanned, gplWarnings: gplWarnings.map(([lic]) => lic) },
|
| 509 |
+
message: report,
|
| 510 |
+
};
|
| 511 |
+
}
|
benchmarks/skillbench-venus-e/tasks/ac993ee8a71a4ab4726c1662/task.json
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "ac993ee8a71a4ab4726c1662",
|
| 4 |
+
"environment": {
|
| 5 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 6 |
+
"network": "none"
|
| 7 |
+
},
|
| 8 |
+
"query_id": "ac993ee8a71a4ab4726c1662",
|
| 9 |
+
"outputs": [
|
| 10 |
+
"analyze.py",
|
| 11 |
+
"report."
|
| 12 |
+
],
|
| 13 |
+
"success_criteria": [
|
| 14 |
+
"Produce the artifacts and satisfy the observable input, output and exception requirements in instruction.md.",
|
| 15 |
+
"Apply the frozen Skill only for the business rules explicitly delegated to it; follow every public benchmark adapter convention in instruction.md."
|
| 16 |
+
],
|
| 17 |
+
"evaluation": {
|
| 18 |
+
"kind": "python",
|
| 19 |
+
"type": "verified"
|
| 20 |
+
},
|
| 21 |
+
"source_skill": {
|
| 22 |
+
"sha256": "450202932be3f6ef368e619c323fb1120ab2ae1940ec76c2d793ded0b6686460",
|
| 23 |
+
"files": {
|
| 24 |
+
"SKILL.md": "c026851d0b60cc1e9687b03a24dfadf626b1e352c79c1d0b3ee85fc61ff4766c",
|
| 25 |
+
"members/M000/SKILL.md": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50",
|
| 26 |
+
"members/M001/SKILL.md": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49",
|
| 27 |
+
"members/M001/handler.js": "23e720a63e968b5129569f915f1227fe7ff745d35d664450bab6a257c419aa27"
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
"workspace": {
|
| 31 |
+
"candidate_mode": "workspace",
|
| 32 |
+
"input_mappings": [
|
| 33 |
+
{
|
| 34 |
+
"source": "inputs/lib/model/store.js",
|
| 35 |
+
"workspace_target": "lib/model/store.js",
|
| 36 |
+
"sha256": "a3f6d8663d055e39d6b6747b69580c5c6e7b1e6581b692ee8ad91c1a32999d1c"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"source": "inputs/lib/util/format.js",
|
| 40 |
+
"workspace_target": "lib/util/format.js",
|
| 41 |
+
"sha256": "2f7d90b4f059ee5c8276db9bf0ef95084e2871d3d3165117bf0e95e7c3c54591"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"source": "inputs/lib/data/repo.js",
|
| 45 |
+
"workspace_target": "lib/data/repo.js",
|
| 46 |
+
"sha256": "bbe2f1ceccc8dde7061f90b315045309e7ae5bb45cd670fbc3f6f99d22f94aff"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"source": "inputs/lib/analyzer/summary.js",
|
| 50 |
+
"workspace_target": "lib/analyzer/summary.js",
|
| 51 |
+
"sha256": "62aba452b46669556b461718d0b09f93d7a4b1f0799911f9eb81a59d240195ba"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"source": "inputs/bin/main.js",
|
| 55 |
+
"workspace_target": "bin/main.js",
|
| 56 |
+
"sha256": "25370136857dfdb033d21fd56ff6e62e77024b8474cc87cd3ccabb2d27c65749"
|
| 57 |
+
}
|
| 58 |
+
],
|
| 59 |
+
"skill_packages": [
|
| 60 |
+
{
|
| 61 |
+
"package_path": "skill/members/M000",
|
| 62 |
+
"content_hash": "4d1d5042054ac7ac2f427041b67bfb2238573c0b909b162a9612d7621fb88424",
|
| 63 |
+
"member_id": "M000"
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"package_path": "skill/members/M001",
|
| 67 |
+
"content_hash": "771b1f7265a1bfd8972019b920aafaf6dc891f3be2ad43bd74c101f1c1fff5a4",
|
| 68 |
+
"member_id": "M001"
|
| 69 |
+
}
|
| 70 |
+
]
|
| 71 |
+
},
|
| 72 |
+
"source_group": {
|
| 73 |
+
"schema_version": "multi-skill-source-v1",
|
| 74 |
+
"group_id": "48067dafeda4b985974ccc55",
|
| 75 |
+
"members": [
|
| 76 |
+
{
|
| 77 |
+
"skill_id": "skill-5663c6660ebc397463aed38b",
|
| 78 |
+
"store_id": "skill-release",
|
| 79 |
+
"original_package_path": "skill-release-archive/skills/56/skill-5663c6660ebc397463aed38b",
|
| 80 |
+
"snapshot": {
|
| 81 |
+
"sha256": "4d1d5042054ac7ac2f427041b67bfb2238573c0b909b162a9612d7621fb88424",
|
| 82 |
+
"files": {
|
| 83 |
+
"SKILL.md": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50"
|
| 84 |
+
},
|
| 85 |
+
"bytes": 1846
|
| 86 |
+
},
|
| 87 |
+
"skill_md_sha256": "bae6596885fb95d9c810e6154e026300bbd69c406c7ec91a088a5e87976ccb50",
|
| 88 |
+
"member_id": "M000",
|
| 89 |
+
"package_path": "members/M000"
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"skill_id": "skill-9e3d94e0234104258cb84843",
|
| 93 |
+
"store_id": "skill-release",
|
| 94 |
+
"original_package_path": "skill-release-archive/skills/9e/skill-9e3d94e0234104258cb84843",
|
| 95 |
+
"snapshot": {
|
| 96 |
+
"sha256": "771b1f7265a1bfd8972019b920aafaf6dc891f3be2ad43bd74c101f1c1fff5a4",
|
| 97 |
+
"files": {
|
| 98 |
+
"SKILL.md": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49",
|
| 99 |
+
"handler.js": "23e720a63e968b5129569f915f1227fe7ff745d35d664450bab6a257c419aa27"
|
| 100 |
+
},
|
| 101 |
+
"bytes": 16979
|
| 102 |
+
},
|
| 103 |
+
"skill_md_sha256": "46658a134b3d09d2ccc3022fb6e565d3c48dba610f2afc5b8fe10378326cec49",
|
| 104 |
+
"member_id": "M001",
|
| 105 |
+
"package_path": "members/M001"
|
| 106 |
+
}
|
| 107 |
+
]
|
| 108 |
+
},
|
| 109 |
+
"label_scope": {
|
| 110 |
+
"comparison": "none_vs_all_members",
|
| 111 |
+
"unit": "skill_group",
|
| 112 |
+
"individual_member_necessity_tested": false
|
| 113 |
+
},
|
| 114 |
+
"member_contributions": [
|
| 115 |
+
{
|
| 116 |
+
"member_id": "M000",
|
| 117 |
+
"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",
|
| 118 |
+
"relationship": "Supplies the rule set the import graph is validated against; violations are edges found by the other member's graph construction"
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"member_id": "M001",
|
| 122 |
+
"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",
|
| 123 |
+
"relationship": "Builds the dependency graph and impact/cycle analyses that the layer rules are evaluated over, producing the report contents"
|
| 124 |
+
}
|
| 125 |
+
],
|
| 126 |
+
"autograde_runtime_contract": {
|
| 127 |
+
"stdlib_only": true,
|
| 128 |
+
"forbid_network": true,
|
| 129 |
+
"forbid_subprocess": false,
|
| 130 |
+
"forbid_native": true,
|
| 131 |
+
"owner_ids": [
|
| 132 |
+
"0"
|
| 133 |
+
],
|
| 134 |
+
"require_execution": true,
|
| 135 |
+
"scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
|
| 136 |
+
"execution_budget_seconds": 60
|
| 137 |
+
},
|
| 138 |
+
"automatic_evaluation_runtime": {
|
| 139 |
+
"stdlib_only": true,
|
| 140 |
+
"forbid_network": true,
|
| 141 |
+
"forbid_subprocess": false,
|
| 142 |
+
"forbid_native": true,
|
| 143 |
+
"owner_ids": [
|
| 144 |
+
"0"
|
| 145 |
+
],
|
| 146 |
+
"require_execution": true,
|
| 147 |
+
"scope": "Actual grader-launched Python script/module invocations only; dead code and string contents are not source properties.",
|
| 148 |
+
"execution_budget_seconds": 60,
|
| 149 |
+
"runtime_owner_ids": [
|
| 150 |
+
"0"
|
| 151 |
+
],
|
| 152 |
+
"total_evaluation_budget_seconds": 420,
|
| 153 |
+
"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."
|
| 154 |
+
}
|
| 155 |
+
}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0"
|
| 4 |
+
],
|
| 5 |
+
"criterion_weights": {
|
| 6 |
+
"0": 1
|
| 7 |
+
}
|
| 8 |
+
}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
root=Path(__file__).resolve().parent
|
| 5 |
+
sys.path.insert(0,str(root/'legacy_tests'))
|
| 6 |
+
from evaluate import evaluate
|
| 7 |
+
t=json.loads((root/'legacy-task.json').read_text())
|
| 8 |
+
mode=t['workspace']['candidate_mode']
|
| 9 |
+
r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
|
| 10 |
+
if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
|
| 11 |
+
if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
|
| 12 |
+
print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/check.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from auto_entry import main
|
| 2 |
+
raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy-task.json
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "mybench-portable-task-v2",
|
| 3 |
+
"task_id": "acf457a314e435c5",
|
| 4 |
+
"query_id": "acf457a314e435c5_q1",
|
| 5 |
+
"prompt": {
|
| 6 |
+
"path": "instruction.md",
|
| 7 |
+
"sha256": "4bda42592cd2db72667399ec1b1def5913316a5cf73c58517f2841a892195a5d"
|
| 8 |
+
},
|
| 9 |
+
"workspace": {
|
| 10 |
+
"input_mappings": [],
|
| 11 |
+
"skill_packages": [
|
| 12 |
+
{
|
| 13 |
+
"content_hash": "463e1031f1a05eb823497dda24d993dea5f775fad5be1be6d61a53d766c0396b",
|
| 14 |
+
"name": "engram-business-rules",
|
| 15 |
+
"package_path": "environment/skills/engram-business-rules-463e1031",
|
| 16 |
+
"install_name": "engram-business-rules-463e1031",
|
| 17 |
+
"archive_provenance": {
|
| 18 |
+
"archive_id": "logical-skill-025c477b476ea3288f1af450",
|
| 19 |
+
"archive_schema": "skill-release-v1",
|
| 20 |
+
"release_skill_id": "logical-skill-025c477b476ea3288f1af450",
|
| 21 |
+
"site": "skills-sh",
|
| 22 |
+
"local_path": "skills/02/logical-skill-025c477b476ea3288f1af450",
|
| 23 |
+
"skill_md_sha256": "0832c148a3f12da6b59142b07ae3b3c6967389945ddc567ed8df5e7bfb3f738f",
|
| 24 |
+
"release_payload_sha256": "463e1031f1a05eb823497dda24d993dea5f775fad5be1be6d61a53d766c0396b",
|
| 25 |
+
"license": "Apache-2.0",
|
| 26 |
+
"license_status": "detected",
|
| 27 |
+
"canonical_source_id": "skills-sh:gentleman-programming/engram/engram-business-rules"
|
| 28 |
+
},
|
| 29 |
+
"omitted_entries": []
|
| 30 |
+
}
|
| 31 |
+
],
|
| 32 |
+
"default_skill_target": ".claude/skills",
|
| 33 |
+
"candidate_mode": "response"
|
| 34 |
+
},
|
| 35 |
+
"ground_truth_skills": [
|
| 36 |
+
"463e1031f1a05eb823497dda24d993dea5f775fad5be1be6d61a53d766c0396b"
|
| 37 |
+
],
|
| 38 |
+
"evaluation": {
|
| 39 |
+
"type": "verified",
|
| 40 |
+
"ground_truth_answer": {
|
| 41 |
+
"answers": {
|
| 42 |
+
"q1": "Local-first",
|
| 43 |
+
"q2": "cloud",
|
| 44 |
+
"q3": "Cloud pause",
|
| 45 |
+
"q4": "fail loudly"
|
| 46 |
+
}
|
| 47 |
+
},
|
| 48 |
+
"verifier": {
|
| 49 |
+
"type": "atomic_json",
|
| 50 |
+
"version": 1,
|
| 51 |
+
"list_order": "ordered",
|
| 52 |
+
"float_tolerance": 0.01,
|
| 53 |
+
"completeness": {
|
| 54 |
+
"forbid_extra": true,
|
| 55 |
+
"shape": {
|
| 56 |
+
"type": "object",
|
| 57 |
+
"keys": {
|
| 58 |
+
"answers": {
|
| 59 |
+
"type": "object",
|
| 60 |
+
"keys": {
|
| 61 |
+
"q1": {
|
| 62 |
+
"type": "string"
|
| 63 |
+
},
|
| 64 |
+
"q2": {
|
| 65 |
+
"type": "string"
|
| 66 |
+
},
|
| 67 |
+
"q3": {
|
| 68 |
+
"type": "string"
|
| 69 |
+
},
|
| 70 |
+
"q4": {
|
| 71 |
+
"type": "string"
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
},
|
| 78 |
+
"assertions": [
|
| 79 |
+
{
|
| 80 |
+
"id": "leaf_001",
|
| 81 |
+
"path": "$.answers.q1",
|
| 82 |
+
"tokens": [
|
| 83 |
+
"answers",
|
| 84 |
+
"q1"
|
| 85 |
+
],
|
| 86 |
+
"operator": "eq",
|
| 87 |
+
"expected": "Local-first"
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"id": "leaf_002",
|
| 91 |
+
"path": "$.answers.q2",
|
| 92 |
+
"tokens": [
|
| 93 |
+
"answers",
|
| 94 |
+
"q2"
|
| 95 |
+
],
|
| 96 |
+
"operator": "eq",
|
| 97 |
+
"expected": "cloud"
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"id": "leaf_003",
|
| 101 |
+
"path": "$.answers.q3",
|
| 102 |
+
"tokens": [
|
| 103 |
+
"answers",
|
| 104 |
+
"q3"
|
| 105 |
+
],
|
| 106 |
+
"operator": "eq",
|
| 107 |
+
"expected": "Cloud pause"
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"id": "leaf_004",
|
| 111 |
+
"path": "$.answers.q4",
|
| 112 |
+
"tokens": [
|
| 113 |
+
"answers",
|
| 114 |
+
"q4"
|
| 115 |
+
],
|
| 116 |
+
"operator": "eq",
|
| 117 |
+
"expected": "fail loudly"
|
| 118 |
+
}
|
| 119 |
+
],
|
| 120 |
+
"self_test_passed": true
|
| 121 |
+
},
|
| 122 |
+
"dependency_contract": {
|
| 123 |
+
"version": 2,
|
| 124 |
+
"mode": "core_answer",
|
| 125 |
+
"dependency_type": "package_knowledge",
|
| 126 |
+
"requirement_ids": [
|
| 127 |
+
"skill_a014",
|
| 128 |
+
"skill_a015",
|
| 129 |
+
"skill_a021",
|
| 130 |
+
"skill_a022"
|
| 131 |
+
],
|
| 132 |
+
"forbid_meta_reference": true,
|
| 133 |
+
"forbid_answer_leakage": true
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/evaluate.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Evaluate a candidate response for one portable MyBench task."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import shlex
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _load_verify():
|
| 15 |
+
try:
|
| 16 |
+
from verifiers import verify
|
| 17 |
+
return verify
|
| 18 |
+
except ImportError:
|
| 19 |
+
project_src = Path(__file__).resolve().parents[1] / "src"
|
| 20 |
+
if project_src.is_dir():
|
| 21 |
+
sys.path.insert(0, str(project_src))
|
| 22 |
+
from verifiers import verify
|
| 23 |
+
return verify
|
| 24 |
+
raise
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _emit(result, output=None):
|
| 28 |
+
text = json.dumps(result, ensure_ascii=False)
|
| 29 |
+
print(text)
|
| 30 |
+
if output:
|
| 31 |
+
Path(output).write_text(text + "\n", encoding="utf-8")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _judge_contract(judge):
|
| 35 |
+
if not isinstance(judge, dict):
|
| 36 |
+
return "Judge output must be a JSON object"
|
| 37 |
+
if type(judge.get("passed")) is not bool:
|
| 38 |
+
return "Judge field passed must be a JSON boolean"
|
| 39 |
+
for key in ("score", "max_score"):
|
| 40 |
+
value = judge.get(key, 100 if key == "max_score" else None)
|
| 41 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
| 42 |
+
return f"Judge field {key} must be a finite number"
|
| 43 |
+
if not math.isfinite(float(value)):
|
| 44 |
+
return f"Judge field {key} must be a finite number"
|
| 45 |
+
score = float(judge["score"])
|
| 46 |
+
max_score = float(judge.get("max_score", 100))
|
| 47 |
+
if max_score <= 0:
|
| 48 |
+
return "Judge field max_score must be greater than zero"
|
| 49 |
+
if score < 0 or score > max_score:
|
| 50 |
+
return "Judge score must be between zero and max_score"
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def evaluate(task_json, candidate_path, open_judge_command=None,
|
| 55 |
+
open_judge_timeout=None):
|
| 56 |
+
task_json = Path(task_json).resolve()
|
| 57 |
+
candidate_path = Path(candidate_path).resolve()
|
| 58 |
+
task = json.loads(task_json.read_text(encoding="utf-8"))
|
| 59 |
+
evaluation = task.get("evaluation") or {}
|
| 60 |
+
track = evaluation.get("type")
|
| 61 |
+
base = {
|
| 62 |
+
"schema_version": task.get("schema_version"),
|
| 63 |
+
"task_id": task.get("task_id"),
|
| 64 |
+
"query_id": task.get("query_id"),
|
| 65 |
+
"track": track,
|
| 66 |
+
}
|
| 67 |
+
if track == "verified":
|
| 68 |
+
workspace_mode = ((evaluation.get("verifier") or {}).get("type") ==
|
| 69 |
+
"workspace_objective")
|
| 70 |
+
if workspace_mode and not candidate_path.is_dir():
|
| 71 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 72 |
+
"score": 0, "max_score": 1,
|
| 73 |
+
"details": "workspace evaluator requires a candidate directory"}, 2
|
| 74 |
+
if not workspace_mode and not candidate_path.is_file():
|
| 75 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 76 |
+
"score": 0, "max_score": 1,
|
| 77 |
+
"details": "response evaluator requires a candidate file"}, 2
|
| 78 |
+
if workspace_mode:
|
| 79 |
+
candidate = str(candidate_path)
|
| 80 |
+
else:
|
| 81 |
+
try:
|
| 82 |
+
candidate = candidate_path.read_text(encoding="utf-8")
|
| 83 |
+
except UnicodeError:
|
| 84 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 85 |
+
"score": 0, "max_score": 1,
|
| 86 |
+
"details": "candidate response must use valid UTF-8"}, 2
|
| 87 |
+
passed, detail = _load_verify()(
|
| 88 |
+
evaluation.get("verifier") or {},
|
| 89 |
+
evaluation.get("ground_truth_answer"),
|
| 90 |
+
candidate,
|
| 91 |
+
None,
|
| 92 |
+
)
|
| 93 |
+
return {**base, "status": "scored", "passed": bool(passed),
|
| 94 |
+
"score": 1 if passed else 0, "max_score": 1, "details": detail}, 0 if passed else 1
|
| 95 |
+
if track != "open":
|
| 96 |
+
return {**base, "status": "unsupported_track", "passed": False,
|
| 97 |
+
"score": None, "details": f"unsupported track: {track}"}, 2
|
| 98 |
+
if not candidate_path.is_file():
|
| 99 |
+
return {**base, "status": "candidate_contract_error", "passed": False,
|
| 100 |
+
"score": None, "details": "open judge requires a candidate response file"}, 2
|
| 101 |
+
candidate_file = candidate_path
|
| 102 |
+
command = open_judge_command or os.environ.get("MYBENCH_OPEN_JUDGE_COMMAND")
|
| 103 |
+
if not command:
|
| 104 |
+
return {**base, "status": "requires_external_judge", "passed": None,
|
| 105 |
+
"score": None, "details": (
|
| 106 |
+
"Set MYBENCH_OPEN_JUDGE_COMMAND to an adapter that reads "
|
| 107 |
+
"MYBENCH_TASK_JSON and MYBENCH_CANDIDATE_FILE and prints JSON.")}, 2
|
| 108 |
+
environment = os.environ.copy()
|
| 109 |
+
environment["MYBENCH_TASK_JSON"] = str(task_json)
|
| 110 |
+
environment["MYBENCH_CANDIDATE_FILE"] = str(candidate_file)
|
| 111 |
+
timeout = float(open_judge_timeout or os.environ.get(
|
| 112 |
+
"MYBENCH_OPEN_JUDGE_TIMEOUT", 600))
|
| 113 |
+
if not math.isfinite(timeout) or timeout <= 0:
|
| 114 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 115 |
+
"score": None, "details": "Judge timeout must be a positive number"}, 2
|
| 116 |
+
try:
|
| 117 |
+
completed = subprocess.run(
|
| 118 |
+
shlex.split(command), cwd=str(task_json.parent), env=environment,
|
| 119 |
+
text=True, capture_output=True, timeout=timeout)
|
| 120 |
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
| 121 |
+
return {**base, "status": "judge_error", "passed": False,
|
| 122 |
+
"score": None, "details": str(exc)}, 2
|
| 123 |
+
if completed.returncode:
|
| 124 |
+
return {**base, "status": "judge_error", "passed": False, "score": None,
|
| 125 |
+
"details": completed.stderr.strip() or completed.stdout.strip()}, 2
|
| 126 |
+
try:
|
| 127 |
+
judge = json.loads(completed.stdout)
|
| 128 |
+
except json.JSONDecodeError as exc:
|
| 129 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 130 |
+
"score": None, "details": str(exc)}, 2
|
| 131 |
+
contract_error = _judge_contract(judge)
|
| 132 |
+
if contract_error:
|
| 133 |
+
return {**base, "status": "judge_contract_error", "passed": False,
|
| 134 |
+
"score": None, "details": contract_error}, 2
|
| 135 |
+
result = {**base, "status": "scored", "passed": judge.get("passed"),
|
| 136 |
+
"score": judge.get("score"), "max_score": judge.get("max_score", 100),
|
| 137 |
+
"details": judge.get("details", judge)}
|
| 138 |
+
return result, 0 if result["passed"] else 1
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def main():
|
| 142 |
+
parser = argparse.ArgumentParser()
|
| 143 |
+
parser.add_argument("--task-json", required=True)
|
| 144 |
+
candidates = parser.add_mutually_exclusive_group(required=True)
|
| 145 |
+
candidates.add_argument("--candidate-path")
|
| 146 |
+
candidates.add_argument("--candidate-file") # v1 compatibility
|
| 147 |
+
parser.add_argument("--result-output")
|
| 148 |
+
parser.add_argument("--open-judge-command")
|
| 149 |
+
parser.add_argument("--open-judge-timeout", type=float)
|
| 150 |
+
args = parser.parse_args()
|
| 151 |
+
result, code = evaluate(args.task_json,
|
| 152 |
+
args.candidate_path or args.candidate_file,
|
| 153 |
+
args.open_judge_command, args.open_judge_timeout)
|
| 154 |
+
_emit(result, args.result_output)
|
| 155 |
+
raise SystemExit(code)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
main()
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/objective_evaluators.py
ADDED
|
@@ -0,0 +1,1329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Composable objective evaluators for response and workspace tasks.
|
| 2 |
+
|
| 3 |
+
Task semantics are deliberately *not* enumerated here. A task may describe any
|
| 4 |
+
real user goal; verified membership depends on whether its deliverables compile
|
| 5 |
+
to one of these small, trusted evaluator primitives and pass counterfactual
|
| 6 |
+
execution. This keeps the objective surface closed and auditable without
|
| 7 |
+
turning the benchmark's task ontology into a closed template list.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import ast
|
| 12 |
+
import copy
|
| 13 |
+
import builtins
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import shlex
|
| 19 |
+
import subprocess
|
| 20 |
+
import tempfile
|
| 21 |
+
import tomllib
|
| 22 |
+
from pathlib import Path, PurePosixPath
|
| 23 |
+
try:
|
| 24 |
+
from .shell_invocations import shell_invocations
|
| 25 |
+
except ImportError:
|
| 26 |
+
from shell_invocations import shell_invocations
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
WORKSPACE_EVALUATOR = "workspace_objective"
|
| 30 |
+
WORKSPACE_EVALUATOR_VERSION = 15
|
| 31 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS = {6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
|
| 32 |
+
ARTIFACT_FORMATS = {"json", "toml", "python", "shell"}
|
| 33 |
+
_DOTTED = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ObjectiveEvaluatorError(ValueError):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def safe_relative_path(value):
|
| 41 |
+
"""Return a normalized portable relative path or fail closed."""
|
| 42 |
+
text = str(value or "").strip().replace("\\", "/")
|
| 43 |
+
path = PurePosixPath(text)
|
| 44 |
+
if (not text or text.startswith("/") or path.is_absolute() or
|
| 45 |
+
any(part in {"", ".", ".."} for part in path.parts)):
|
| 46 |
+
raise ObjectiveEvaluatorError(f"unsafe workspace path: {value!r}")
|
| 47 |
+
if len(path.parts) > 8 or len(text) > 180:
|
| 48 |
+
raise ObjectiveEvaluatorError("workspace path is too deep or long")
|
| 49 |
+
return path.as_posix()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _json_value(value):
|
| 53 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 54 |
+
return value
|
| 55 |
+
return json.loads(str(value))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _canonical(value):
|
| 59 |
+
if isinstance(value, dict):
|
| 60 |
+
return {key: _canonical(value[key]) for key in sorted(value)}
|
| 61 |
+
if isinstance(value, list):
|
| 62 |
+
return [_canonical(item) for item in value]
|
| 63 |
+
return value
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _same_native_json_types(actual, expected):
|
| 68 |
+
if type(expected)is float:
|
| 69 |
+
return type(actual)in(int,float)and math.isfinite(actual)
|
| 70 |
+
if type(actual)is not type(expected):return False
|
| 71 |
+
if isinstance(expected,dict):
|
| 72 |
+
return set(actual)==set(expected)and all(_same_native_json_types(actual[k],expected[k])for k in expected)
|
| 73 |
+
if isinstance(expected,list):
|
| 74 |
+
return len(actual)==len(expected)and all(_same_native_json_types(a,b)for a,b in zip(actual,expected))
|
| 75 |
+
if isinstance(actual,float):return math.isfinite(actual)
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
def _file_content(item):
|
| 79 |
+
fmt = str(item.get("format") or "").casefold()
|
| 80 |
+
content = item.get("content")
|
| 81 |
+
if fmt == "json":
|
| 82 |
+
parsed = _json_value(content)
|
| 83 |
+
return json.dumps(parsed, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 84 |
+
if not isinstance(content, str):
|
| 85 |
+
raise ObjectiveEvaluatorError(f"{fmt} artifact content must be text")
|
| 86 |
+
return content.rstrip() + "\n"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _ast_name(node):
|
| 90 |
+
if isinstance(node, ast.Name):
|
| 91 |
+
return node.id
|
| 92 |
+
if isinstance(node, ast.Attribute):
|
| 93 |
+
parent = _ast_name(node.value)
|
| 94 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 95 |
+
return ""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _python_inventory(text):
|
| 99 |
+
tree = ast.parse(text)
|
| 100 |
+
imports, calls = set(), set()
|
| 101 |
+
for node in ast.walk(tree):
|
| 102 |
+
if isinstance(node, ast.Import):
|
| 103 |
+
imports.update(alias.name for alias in node.names)
|
| 104 |
+
elif isinstance(node, ast.ImportFrom):
|
| 105 |
+
module = node.module or ""
|
| 106 |
+
for alias in node.names:
|
| 107 |
+
imports.add(f"{module}.{alias.name}".strip("."))
|
| 108 |
+
elif isinstance(node, ast.Call):
|
| 109 |
+
name = _ast_name(node.func)
|
| 110 |
+
if name:
|
| 111 |
+
calls.add(name)
|
| 112 |
+
return imports, calls
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _literal_value(node, constants=None):
|
| 116 |
+
constants = constants or {}
|
| 117 |
+
if isinstance(node, ast.Constant) and isinstance(
|
| 118 |
+
node.value, (str, int, float, bool, type(None))):
|
| 119 |
+
return node.value
|
| 120 |
+
if isinstance(node, ast.Name) and node.id in constants:
|
| 121 |
+
return constants[node.id]
|
| 122 |
+
if isinstance(node, (ast.Tuple, ast.List)):
|
| 123 |
+
values = [_literal_value(item, constants) for item in node.elts]
|
| 124 |
+
if all(value is not _UNRESOLVED for value in values):
|
| 125 |
+
return tuple(values) if isinstance(node, ast.Tuple) else values
|
| 126 |
+
return _UNRESOLVED
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
_UNRESOLVED = object()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _python_semantics(text):
|
| 133 |
+
tree = ast.parse(text)
|
| 134 |
+
_annotate_assignment_contexts(tree)
|
| 135 |
+
imports, calls = _python_inventory(text)
|
| 136 |
+
constants = {}
|
| 137 |
+
for node in tree.body:
|
| 138 |
+
name = None
|
| 139 |
+
value_node = None
|
| 140 |
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 141 |
+
isinstance(node.targets[0], ast.Name)):
|
| 142 |
+
name, value_node = node.targets[0].id, node.value
|
| 143 |
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
|
| 144 |
+
name, value_node = node.target.id, node.value
|
| 145 |
+
if name and value_node is not None:
|
| 146 |
+
value = _literal_value(value_node, constants)
|
| 147 |
+
if value is not _UNRESOLVED:
|
| 148 |
+
constants[name] = value
|
| 149 |
+
elif (isinstance(node, ast.Assign) and len(node.targets) == 1 and
|
| 150 |
+
isinstance(node.targets[0], (ast.Tuple, ast.List)) and
|
| 151 |
+
isinstance(node.value, (ast.Tuple, ast.List)) and
|
| 152 |
+
len(node.targets[0].elts) == len(node.value.elts)):
|
| 153 |
+
# Treat ordinary constant unpacking as semantically equivalent to
|
| 154 |
+
# separate assignments. Generated implementation files commonly
|
| 155 |
+
# use ``WIDTH, HEIGHT = 1200, 630``; rejecting that spelling would
|
| 156 |
+
# test formatting rather than the required repository values.
|
| 157 |
+
for target, value_node in zip(node.targets[0].elts, node.value.elts):
|
| 158 |
+
if not isinstance(target, ast.Name):
|
| 159 |
+
continue
|
| 160 |
+
value = _literal_value(value_node, constants)
|
| 161 |
+
if value is not _UNRESOLVED:
|
| 162 |
+
constants[target.id] = value
|
| 163 |
+
call_nodes = []
|
| 164 |
+
for node in ast.walk(tree):
|
| 165 |
+
if isinstance(node, ast.Call):
|
| 166 |
+
call_nodes.append((_ast_name(node.func), node))
|
| 167 |
+
return imports, calls, constants, call_nodes
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _python_resolved_call_nodes(text):
|
| 171 |
+
"""Resolve call targets through imports and simple constructor bindings.
|
| 172 |
+
|
| 173 |
+
The evaluator intentionally supports a small static subset: imports,
|
| 174 |
+
local definitions, direct aliases, and names assigned from calls. That is
|
| 175 |
+
enough to recognize semantic equivalents such as ``import datetime`` vs
|
| 176 |
+
``from datetime import timedelta as td`` and instance-variable renames,
|
| 177 |
+
without pretending to perform general Python type inference.
|
| 178 |
+
"""
|
| 179 |
+
tree = ast.parse(text)
|
| 180 |
+
_annotate_assignment_contexts(tree)
|
| 181 |
+
bindings = {}
|
| 182 |
+
nodes = sorted(ast.walk(tree), key=lambda node: (
|
| 183 |
+
int(getattr(node, "lineno", -1)), int(getattr(node, "col_offset", -1))))
|
| 184 |
+
|
| 185 |
+
def resolve(node):
|
| 186 |
+
if isinstance(node, ast.Name):
|
| 187 |
+
return bindings.get(node.id, node.id)
|
| 188 |
+
if isinstance(node, ast.Attribute):
|
| 189 |
+
parent = resolve(node.value)
|
| 190 |
+
return f"{parent}.{node.attr}" if parent else node.attr
|
| 191 |
+
return ""
|
| 192 |
+
|
| 193 |
+
# A few fixed-point passes cover aliases declared after an imported name
|
| 194 |
+
# and ordinary ``client = Client()`` instance construction.
|
| 195 |
+
for _ in range(4):
|
| 196 |
+
changed = False
|
| 197 |
+
for node in nodes:
|
| 198 |
+
updates = {}
|
| 199 |
+
if isinstance(node, ast.Import):
|
| 200 |
+
for alias in node.names:
|
| 201 |
+
local = alias.asname or alias.name.split(".")[0]
|
| 202 |
+
updates[local] = alias.name if alias.asname else local
|
| 203 |
+
elif isinstance(node, ast.ImportFrom):
|
| 204 |
+
module = node.module or ""
|
| 205 |
+
for alias in node.names:
|
| 206 |
+
if alias.name == "*":
|
| 207 |
+
continue
|
| 208 |
+
updates[alias.asname or alias.name] = \
|
| 209 |
+
f"{module}.{alias.name}".strip(".")
|
| 210 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 211 |
+
ast.ClassDef)):
|
| 212 |
+
updates[node.name] = "__local__." + node.name
|
| 213 |
+
elif isinstance(node, (ast.Assign, ast.AnnAssign)):
|
| 214 |
+
targets = (node.targets if isinstance(node, ast.Assign)
|
| 215 |
+
else [node.target])
|
| 216 |
+
value = node.value
|
| 217 |
+
if isinstance(value, ast.Call):
|
| 218 |
+
provenance = resolve(value.func)
|
| 219 |
+
elif isinstance(value, (ast.Name, ast.Attribute)):
|
| 220 |
+
provenance = resolve(value)
|
| 221 |
+
else:
|
| 222 |
+
provenance = ""
|
| 223 |
+
if provenance:
|
| 224 |
+
for target in targets:
|
| 225 |
+
if isinstance(target, ast.Name):
|
| 226 |
+
updates[target.id] = provenance
|
| 227 |
+
for name, value in updates.items():
|
| 228 |
+
if bindings.get(name) != value:
|
| 229 |
+
bindings[name] = value
|
| 230 |
+
changed = True
|
| 231 |
+
if not changed:
|
| 232 |
+
break
|
| 233 |
+
return [(_ast_name(node.func), resolve(node.func), node)
|
| 234 |
+
for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _call_name_matches(observed, expected):
|
| 238 |
+
return observed == expected or observed.endswith("." + expected)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _objective_call_targets(kind, check, resolved_calls, constants):
|
| 242 |
+
"""Return canonical targets satisfying one already-validated call check."""
|
| 243 |
+
function = str(check.get("function") or check.get("value") or "")
|
| 244 |
+
targets = set()
|
| 245 |
+
for name, target, node in resolved_calls:
|
| 246 |
+
if not _call_name_matches(name, function):
|
| 247 |
+
continue
|
| 248 |
+
if kind == "python_call_literal" and not _node_contains_literal(
|
| 249 |
+
node, check.get("value"), constants):
|
| 250 |
+
continue
|
| 251 |
+
if kind == "python_call_keyword_literal" and not _call_keyword_matches(
|
| 252 |
+
node, str(check.get("keyword") or ""), check.get("value"),
|
| 253 |
+
constants):
|
| 254 |
+
continue
|
| 255 |
+
if kind == "python_call_signature" and not _call_signature_matches(
|
| 256 |
+
node, check.get("arguments") or [],
|
| 257 |
+
check.get("keywords") or {}, constants,
|
| 258 |
+
check.get("argument_expressions") or [],
|
| 259 |
+
check.get("keyword_expressions") or {},
|
| 260 |
+
check.get("assignment")):
|
| 261 |
+
continue
|
| 262 |
+
if target:
|
| 263 |
+
targets.add(target)
|
| 264 |
+
return targets
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def python_unbound_call_roots(text):
|
| 268 |
+
"""Return call-root names that have no static binding in the module.
|
| 269 |
+
|
| 270 |
+
Objective call checks must not accept a syntactically valid file that will
|
| 271 |
+
immediately raise ``NameError``. This deliberately proves only the
|
| 272 |
+
conservative prerequisite that a root is imported, assigned, declared,
|
| 273 |
+
passed as an argument, or provided by Python builtins; it does not claim to
|
| 274 |
+
execute or type-check the program.
|
| 275 |
+
"""
|
| 276 |
+
tree = ast.parse(text)
|
| 277 |
+
bound = set(dir(builtins))
|
| 278 |
+
for node in ast.walk(tree):
|
| 279 |
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
| 280 |
+
bound.add(node.id)
|
| 281 |
+
elif isinstance(node, ast.arg):
|
| 282 |
+
bound.add(node.arg)
|
| 283 |
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
|
| 284 |
+
ast.ClassDef)):
|
| 285 |
+
bound.add(node.name)
|
| 286 |
+
elif isinstance(node, ast.Import):
|
| 287 |
+
for alias in node.names:
|
| 288 |
+
bound.add(alias.asname or alias.name.split(".")[0])
|
| 289 |
+
elif isinstance(node, ast.ImportFrom):
|
| 290 |
+
for alias in node.names:
|
| 291 |
+
bound.add(alias.asname or alias.name)
|
| 292 |
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
| 293 |
+
bound.add(node.name)
|
| 294 |
+
unbound = set()
|
| 295 |
+
for node in ast.walk(tree):
|
| 296 |
+
if not isinstance(node, ast.Call):
|
| 297 |
+
continue
|
| 298 |
+
root = node.func
|
| 299 |
+
while isinstance(root, ast.Attribute):
|
| 300 |
+
root = root.value
|
| 301 |
+
if isinstance(root, ast.Name) and root.id not in bound:
|
| 302 |
+
unbound.add(root.id)
|
| 303 |
+
return sorted(unbound)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _node_contains_literal(node, expected, constants):
|
| 307 |
+
for child in ast.walk(node):
|
| 308 |
+
value = _literal_value(child, constants)
|
| 309 |
+
if value is _UNRESOLVED:
|
| 310 |
+
continue
|
| 311 |
+
if value == expected:
|
| 312 |
+
return True
|
| 313 |
+
if isinstance(value, (list, tuple)) and expected in value:
|
| 314 |
+
return True
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _call_keyword_matches(node, keyword, expected, constants):
|
| 319 |
+
"""Return whether a direct call keyword resolves to the expected scalar."""
|
| 320 |
+
return any(
|
| 321 |
+
item.arg == keyword and _literal_value(item.value, constants) == expected
|
| 322 |
+
for item in getattr(node, "keywords", [])
|
| 323 |
+
if item.arg is not None)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _portable_literal(value):
|
| 327 |
+
if isinstance(value, tuple):
|
| 328 |
+
return [_portable_literal(item) for item in value]
|
| 329 |
+
if isinstance(value, list):
|
| 330 |
+
return [_portable_literal(item) for item in value]
|
| 331 |
+
return value
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _expression_text(node):
|
| 335 |
+
"""Return a formatting-independent, non-executed Python expression."""
|
| 336 |
+
return ast.unparse(node).strip()
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _expression_fingerprint(value):
|
| 340 |
+
if not isinstance(value, str) or not value.strip() or len(value) > 500:
|
| 341 |
+
return None
|
| 342 |
+
try:
|
| 343 |
+
tree = ast.parse(value, mode="eval")
|
| 344 |
+
except SyntaxError:
|
| 345 |
+
return None
|
| 346 |
+
return ast.dump(tree.body, annotate_fields=True, include_attributes=False)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _expression_matches(node, expected):
|
| 350 |
+
fingerprint = _expression_fingerprint(expected)
|
| 351 |
+
return bool(fingerprint and ast.dump(
|
| 352 |
+
node, annotate_fields=True, include_attributes=False) == fingerprint)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _annotate_assignment_contexts(tree):
|
| 356 |
+
"""Attach one conservative simple-assignment context to nested calls."""
|
| 357 |
+
for statement in ast.walk(tree):
|
| 358 |
+
target, value = None, None
|
| 359 |
+
if (isinstance(statement, ast.Assign) and
|
| 360 |
+
len(statement.targets) == 1 and
|
| 361 |
+
isinstance(statement.targets[0], ast.Name)):
|
| 362 |
+
target, value = statement.targets[0].id, statement.value
|
| 363 |
+
elif (isinstance(statement, ast.AnnAssign) and
|
| 364 |
+
isinstance(statement.target, ast.Name) and
|
| 365 |
+
statement.value is not None):
|
| 366 |
+
target, value = statement.target.id, statement.value
|
| 367 |
+
if not target or value is None:
|
| 368 |
+
continue
|
| 369 |
+
context = {"target": target, "expression": _expression_text(value)}
|
| 370 |
+
for child in ast.walk(value):
|
| 371 |
+
if isinstance(child, ast.Call):
|
| 372 |
+
setattr(child, "_mybench_assignment", context)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _call_signature(node, constants):
|
| 376 |
+
arguments = []
|
| 377 |
+
argument_expressions = []
|
| 378 |
+
for index, argument in enumerate(getattr(node, "args", [])):
|
| 379 |
+
value = _literal_value(argument, constants)
|
| 380 |
+
if value is not _UNRESOLVED:
|
| 381 |
+
arguments.append({"index": index,
|
| 382 |
+
"value": _portable_literal(value)})
|
| 383 |
+
else:
|
| 384 |
+
argument_expressions.append({
|
| 385 |
+
"index": index, "expression": _expression_text(argument)})
|
| 386 |
+
keywords = {}
|
| 387 |
+
keyword_expressions = {}
|
| 388 |
+
for keyword in getattr(node, "keywords", []):
|
| 389 |
+
if keyword.arg is None:
|
| 390 |
+
continue
|
| 391 |
+
value = _literal_value(keyword.value, constants)
|
| 392 |
+
if value is not _UNRESOLVED:
|
| 393 |
+
keywords[keyword.arg] = _portable_literal(value)
|
| 394 |
+
else:
|
| 395 |
+
keyword_expressions[keyword.arg] = _expression_text(keyword.value)
|
| 396 |
+
signature = {"arguments": arguments, "keywords": keywords,
|
| 397 |
+
"argument_expressions": argument_expressions,
|
| 398 |
+
"keyword_expressions": keyword_expressions}
|
| 399 |
+
assignment = getattr(node, "_mybench_assignment", None)
|
| 400 |
+
if isinstance(assignment, dict):
|
| 401 |
+
signature["assignment"] = dict(assignment)
|
| 402 |
+
return signature
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _call_signature_matches(node, arguments, keywords, constants,
|
| 406 |
+
argument_expressions=None,
|
| 407 |
+
keyword_expressions=None, assignment=None):
|
| 408 |
+
for expected in arguments or []:
|
| 409 |
+
index = expected.get("index")
|
| 410 |
+
if (not isinstance(index, int) or index < 0 or
|
| 411 |
+
index >= len(getattr(node, "args", []))):
|
| 412 |
+
return False
|
| 413 |
+
actual = _literal_value(node.args[index], constants)
|
| 414 |
+
if (actual is _UNRESOLVED or
|
| 415 |
+
_canonical(_portable_literal(actual)) !=
|
| 416 |
+
_canonical(expected.get("value"))):
|
| 417 |
+
return False
|
| 418 |
+
for keyword, expected in (keywords or {}).items():
|
| 419 |
+
if not _call_keyword_matches(node, keyword, expected, constants):
|
| 420 |
+
return False
|
| 421 |
+
for expected in argument_expressions or []:
|
| 422 |
+
index = expected.get("index")
|
| 423 |
+
if (not isinstance(index, int) or index < 0 or
|
| 424 |
+
index >= len(getattr(node, "args", [])) or
|
| 425 |
+
not _expression_matches(
|
| 426 |
+
node.args[index], expected.get("expression"))):
|
| 427 |
+
return False
|
| 428 |
+
node_keywords = {item.arg: item.value for item in
|
| 429 |
+
getattr(node, "keywords", []) if item.arg is not None}
|
| 430 |
+
for keyword, expected in (keyword_expressions or {}).items():
|
| 431 |
+
if (keyword not in node_keywords or
|
| 432 |
+
not _expression_matches(node_keywords[keyword], expected)):
|
| 433 |
+
return False
|
| 434 |
+
if assignment:
|
| 435 |
+
actual = getattr(node, "_mybench_assignment", None)
|
| 436 |
+
if (not isinstance(actual, dict) or
|
| 437 |
+
actual.get("target") != assignment.get("target") or
|
| 438 |
+
_expression_fingerprint(actual.get("expression")) !=
|
| 439 |
+
_expression_fingerprint(assignment.get("expression"))):
|
| 440 |
+
return False
|
| 441 |
+
return bool(arguments or keywords or argument_expressions or
|
| 442 |
+
keyword_expressions or assignment)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def python_call_literal_signatures(text, function, expected, keyword=None):
|
| 446 |
+
"""Return full literal signatures for matching reference call sites."""
|
| 447 |
+
_, _, constants, call_nodes = _python_semantics(text)
|
| 448 |
+
out = []
|
| 449 |
+
for name, node in call_nodes:
|
| 450 |
+
if not (name == function or name.endswith("." + function)):
|
| 451 |
+
continue
|
| 452 |
+
matches = (_call_keyword_matches(node, keyword, expected, constants)
|
| 453 |
+
if keyword else
|
| 454 |
+
_node_contains_literal(node, expected, constants))
|
| 455 |
+
if matches:
|
| 456 |
+
out.append(_call_signature(node, constants))
|
| 457 |
+
return out
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def python_signature_expression_coverage_issues(evaluator, requirements=None):
|
| 461 |
+
"""Detect anchored call expressions omitted by a static verifier.
|
| 462 |
+
|
| 463 |
+
Literal-only call checks used to silently discard non-literal positional
|
| 464 |
+
and keyword expressions from the same package-owned call. That allowed a
|
| 465 |
+
candidate to retain one easy literal while replacing the actual callback,
|
| 466 |
+
input binding, or argument tuple. Only expressions present in the
|
| 467 |
+
selected requirement text are required here; unrelated reference-file
|
| 468 |
+
context remains outside the objective contract.
|
| 469 |
+
"""
|
| 470 |
+
if not isinstance(evaluator, dict) or evaluator.get("type") != \
|
| 471 |
+
WORKSPACE_EVALUATOR:
|
| 472 |
+
return []
|
| 473 |
+
reference_files = {
|
| 474 |
+
str(item.get("path") or ""): str(item.get("content") or "")
|
| 475 |
+
for item in evaluator.get("reference_files") or []
|
| 476 |
+
if isinstance(item, dict)}
|
| 477 |
+
requirement_texts = [
|
| 478 |
+
re.sub(r"\s+", "", str(item.get("requirement") or ""))
|
| 479 |
+
for item in requirements or [] if isinstance(item, dict)]
|
| 480 |
+
issues = []
|
| 481 |
+
for check in evaluator.get("checks") or []:
|
| 482 |
+
if (not isinstance(check, dict) or
|
| 483 |
+
check.get("type") != "python_call_signature"):
|
| 484 |
+
continue
|
| 485 |
+
function = str(check.get("function") or "")
|
| 486 |
+
source = reference_files.get(str(check.get("path") or ""), "")
|
| 487 |
+
if not function or not source:
|
| 488 |
+
continue
|
| 489 |
+
try:
|
| 490 |
+
_, _, constants, call_nodes = _python_semantics(source)
|
| 491 |
+
except SyntaxError:
|
| 492 |
+
issues.append("Python signature reference content is invalid")
|
| 493 |
+
continue
|
| 494 |
+
matches = [node for name, node in call_nodes
|
| 495 |
+
if _call_name_matches(name, function) and
|
| 496 |
+
_call_signature_matches(
|
| 497 |
+
node, check.get("arguments") or [],
|
| 498 |
+
check.get("keywords") or {}, constants,
|
| 499 |
+
check.get("argument_expressions") or [],
|
| 500 |
+
check.get("keyword_expressions") or {},
|
| 501 |
+
check.get("assignment"))]
|
| 502 |
+
if len(matches) != 1:
|
| 503 |
+
issues.append(
|
| 504 |
+
"Python call signature does not identify one reference call")
|
| 505 |
+
continue
|
| 506 |
+
reference_signature = _call_signature(matches[0], constants)
|
| 507 |
+
function_tokens = {re.sub(r"\s+", "", function),
|
| 508 |
+
re.sub(r"\s+", "", function.rsplit(".", 1)[-1])}
|
| 509 |
+
|
| 510 |
+
def positional_is_anchored(expression):
|
| 511 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 512 |
+
return any(compact and compact in text and any(
|
| 513 |
+
token and token in text for token in function_tokens)
|
| 514 |
+
for text in requirement_texts)
|
| 515 |
+
|
| 516 |
+
def keyword_is_anchored(name, expression):
|
| 517 |
+
compact = re.sub(r"\s+", "", str(expression or ""))
|
| 518 |
+
needle = f"{name}={compact}"
|
| 519 |
+
return any(compact and needle in text and any(
|
| 520 |
+
token and token in text for token in function_tokens)
|
| 521 |
+
for text in requirement_texts)
|
| 522 |
+
|
| 523 |
+
expected_arguments = {
|
| 524 |
+
item["index"]: item.get("expression")
|
| 525 |
+
for item in reference_signature.get("argument_expressions") or []
|
| 526 |
+
if positional_is_anchored(item.get("expression"))}
|
| 527 |
+
expected_keywords = {
|
| 528 |
+
name: expression for name, expression in
|
| 529 |
+
(reference_signature.get("keyword_expressions") or {}).items()
|
| 530 |
+
if keyword_is_anchored(name, expression)}
|
| 531 |
+
actual_arguments = {
|
| 532 |
+
item.get("index"): item.get("expression")
|
| 533 |
+
for item in check.get("argument_expressions") or []
|
| 534 |
+
if isinstance(item, dict)}
|
| 535 |
+
actual_keywords = check.get("keyword_expressions") or {}
|
| 536 |
+
expected_assignment = reference_signature.get("assignment")
|
| 537 |
+
if expected_assignment:
|
| 538 |
+
compact_assignment = re.sub(
|
| 539 |
+
r"\s+", "", f"{expected_assignment.get('target')}="
|
| 540 |
+
f"{expected_assignment.get('expression')}")
|
| 541 |
+
assignment_is_anchored = any(
|
| 542 |
+
compact_assignment and compact_assignment in text and any(
|
| 543 |
+
token and token in text for token in function_tokens)
|
| 544 |
+
for text in requirement_texts)
|
| 545 |
+
else:
|
| 546 |
+
assignment_is_anchored = False
|
| 547 |
+
actual_assignment = check.get("assignment")
|
| 548 |
+
missing_argument = any(
|
| 549 |
+
index not in actual_arguments or
|
| 550 |
+
_expression_fingerprint(actual_arguments[index]) !=
|
| 551 |
+
_expression_fingerprint(expression)
|
| 552 |
+
for index, expression in expected_arguments.items())
|
| 553 |
+
missing_keyword = any(
|
| 554 |
+
name not in actual_keywords or
|
| 555 |
+
_expression_fingerprint(actual_keywords[name]) !=
|
| 556 |
+
_expression_fingerprint(expression)
|
| 557 |
+
for name, expression in expected_keywords.items())
|
| 558 |
+
missing_assignment = bool(
|
| 559 |
+
assignment_is_anchored and (
|
| 560 |
+
not isinstance(actual_assignment, dict) or
|
| 561 |
+
actual_assignment.get("target") !=
|
| 562 |
+
expected_assignment.get("target") or
|
| 563 |
+
_expression_fingerprint(actual_assignment.get("expression")) !=
|
| 564 |
+
_expression_fingerprint(
|
| 565 |
+
expected_assignment.get("expression"))))
|
| 566 |
+
if missing_argument or missing_keyword or missing_assignment:
|
| 567 |
+
issues.append(
|
| 568 |
+
"Python call signature omits an anchored expression or assignment")
|
| 569 |
+
return issues
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def _shell_lines(text):
|
| 573 |
+
"""Return executable lines with conservative local scalar substitution.
|
| 574 |
+
|
| 575 |
+
Shell authors routinely name a fixed argument before using it (for example
|
| 576 |
+
``LIMIT=50`` followed by ``git log -$LIMIT``). Resolve only literal scalar
|
| 577 |
+
assignments; never evaluate shell expressions, commands, or defaults.
|
| 578 |
+
"""
|
| 579 |
+
logical, pending = [], ""
|
| 580 |
+
for raw in str(text or "").splitlines():
|
| 581 |
+
line = " ".join(raw.strip().split())
|
| 582 |
+
if not line or line.startswith("#") or line in {"set -e", "set -eu", "set -euo pipefail"}:
|
| 583 |
+
continue
|
| 584 |
+
pending = (pending + " " + line).strip() if pending else line
|
| 585 |
+
if pending.endswith("\\"):
|
| 586 |
+
pending = pending[:-1].rstrip()
|
| 587 |
+
continue
|
| 588 |
+
logical.append(pending)
|
| 589 |
+
pending = ""
|
| 590 |
+
if pending:
|
| 591 |
+
logical.append(pending)
|
| 592 |
+
|
| 593 |
+
constants, out = {}, []
|
| 594 |
+
assignment = re.compile(
|
| 595 |
+
r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|"
|
| 596 |
+
r"([A-Za-z0-9_./:+-]+))$")
|
| 597 |
+
variable = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)")
|
| 598 |
+
for line in logical:
|
| 599 |
+
match = assignment.fullmatch(line)
|
| 600 |
+
if match:
|
| 601 |
+
constants[match.group(1)] = next(
|
| 602 |
+
value for value in match.groups()[1:] if value is not None)
|
| 603 |
+
out.append(line)
|
| 604 |
+
continue
|
| 605 |
+
|
| 606 |
+
def replace(match):
|
| 607 |
+
name = match.group(1) or match.group(2)
|
| 608 |
+
return constants.get(name, match.group(0))
|
| 609 |
+
|
| 610 |
+
out.append(variable.sub(replace, line))
|
| 611 |
+
return out
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def _shell_command_matches(expected, actual):
|
| 615 |
+
"""Accept the frozen invocation plus documented optional arguments/path prefixes."""
|
| 616 |
+
try:
|
| 617 |
+
wanted = shlex.split(str(expected))
|
| 618 |
+
found = shlex.split(str(actual))
|
| 619 |
+
except ValueError:
|
| 620 |
+
return False
|
| 621 |
+
def normalize_git_log_limit(tokens):
|
| 622 |
+
if len(tokens) < 2 or tokens[:2] != ["git", "log"]:
|
| 623 |
+
return tokens
|
| 624 |
+
normalized, index = [], 0
|
| 625 |
+
while index < len(tokens):
|
| 626 |
+
token = tokens[index]
|
| 627 |
+
short = re.fullmatch(r"-(\d+)", token)
|
| 628 |
+
long = re.fullmatch(r"--max-count=(\d+)", token)
|
| 629 |
+
if short or long:
|
| 630 |
+
normalized.append("--max-count=" + (short or long).group(1))
|
| 631 |
+
elif (token in {"-n", "--max-count"} and index + 1 < len(tokens) and
|
| 632 |
+
re.fullmatch(r"\d+", tokens[index + 1])):
|
| 633 |
+
normalized.append("--max-count=" + tokens[index + 1])
|
| 634 |
+
index += 1
|
| 635 |
+
else:
|
| 636 |
+
normalized.append(token)
|
| 637 |
+
index += 1
|
| 638 |
+
return normalized
|
| 639 |
+
|
| 640 |
+
wanted = normalize_git_log_limit(wanted)
|
| 641 |
+
found = normalize_git_log_limit(found)
|
| 642 |
+
if not wanted or len(found) < len(wanted) or found[0] != wanted[0]:
|
| 643 |
+
return False
|
| 644 |
+
for index, token in enumerate(wanted[1:], 1):
|
| 645 |
+
observed = found[index]
|
| 646 |
+
if observed == token:
|
| 647 |
+
continue
|
| 648 |
+
# A solver may anchor a package-relative script at $REPO_ROOT while
|
| 649 |
+
# preserving the exact package path selected by the Skill.
|
| 650 |
+
if (index == 1 and "/" in token and
|
| 651 |
+
observed.rstrip("/").endswith(token.lstrip("./"))):
|
| 652 |
+
continue
|
| 653 |
+
return False
|
| 654 |
+
return True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _shell_command_sequence_matches(expected, actual_lines):
|
| 658 |
+
"""Require every frozen command in order while allowing extra lines."""
|
| 659 |
+
cursor = 0
|
| 660 |
+
for command in expected:
|
| 661 |
+
for index in range(cursor, len(actual_lines)):
|
| 662 |
+
if _shell_command_matches(command, actual_lines[index]):
|
| 663 |
+
cursor = index + 1
|
| 664 |
+
break
|
| 665 |
+
else:
|
| 666 |
+
return False
|
| 667 |
+
return True
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def _shell_unconditional_lines(text):
|
| 671 |
+
"""Return conservative top-level command lines from a shell artifact.
|
| 672 |
+
|
| 673 |
+
Checked commands hidden in a conditional branch or an uncalled function do
|
| 674 |
+
not establish that the requested script performs them. This is not a full
|
| 675 |
+
shell parser: unsupported control flow simply makes nested lines
|
| 676 |
+
ineligible, which is appropriate for the small straight-line command
|
| 677 |
+
artifacts compiled by this evaluator.
|
| 678 |
+
"""
|
| 679 |
+
lines = _shell_lines(text)
|
| 680 |
+
depth = 0
|
| 681 |
+
out = []
|
| 682 |
+
opener = re.compile(
|
| 683 |
+
r"^(?:if\b|for\b|while\b|until\b|case\b|select\b|"
|
| 684 |
+
r"(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{)")
|
| 685 |
+
closer = re.compile(r"^(?:fi\b|done\b|esac\b|\})")
|
| 686 |
+
for line in lines:
|
| 687 |
+
if closer.match(line):
|
| 688 |
+
depth = max(0, depth - 1)
|
| 689 |
+
continue
|
| 690 |
+
if depth == 0 and not opener.match(line):
|
| 691 |
+
out.append(line)
|
| 692 |
+
if opener.match(line):
|
| 693 |
+
depth += 1
|
| 694 |
+
return out
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def _shell_is_straight_line(text):
|
| 698 |
+
"""Return whether every executable logical line is top-level.
|
| 699 |
+
|
| 700 |
+
This deliberately reuses the conservative control-flow recognizer used by
|
| 701 |
+
unconditional command checks. Any recognized conditional, loop, case, or
|
| 702 |
+
function makes the whole-script straight-line contract fail closed.
|
| 703 |
+
"""
|
| 704 |
+
lines = _shell_lines(text)
|
| 705 |
+
return lines == _shell_unconditional_lines(text)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def compile_workspace_evaluator(deliverables):
|
| 709 |
+
"""Compile trusted checks from validated deliverable specifications."""
|
| 710 |
+
if not isinstance(deliverables, list) or not 1 <= len(deliverables) <= 6:
|
| 711 |
+
raise ObjectiveEvaluatorError("workspace task requires 1-6 deliverables")
|
| 712 |
+
reference_files, checks, paths = [], [], set()
|
| 713 |
+
for index, raw in enumerate(deliverables, 1):
|
| 714 |
+
if not isinstance(raw, dict):
|
| 715 |
+
raise ObjectiveEvaluatorError("deliverable is not an object")
|
| 716 |
+
path = safe_relative_path(raw.get("path"))
|
| 717 |
+
if path in paths:
|
| 718 |
+
raise ObjectiveEvaluatorError(f"duplicate deliverable path: {path}")
|
| 719 |
+
paths.add(path)
|
| 720 |
+
fmt = str(raw.get("format") or "").strip().casefold()
|
| 721 |
+
if fmt not in ARTIFACT_FORMATS:
|
| 722 |
+
raise ObjectiveEvaluatorError(f"unsupported artifact format: {fmt}")
|
| 723 |
+
content = _file_content({**raw, "format": fmt})
|
| 724 |
+
if len(content.encode("utf-8")) > 200_000:
|
| 725 |
+
raise ObjectiveEvaluatorError("reference artifact exceeds 200 KB")
|
| 726 |
+
reference_files.append({"path": path, "format": fmt, "content": content})
|
| 727 |
+
checks.append({"id": f"file_{index:03d}", "type": "file_exists",
|
| 728 |
+
"path": path})
|
| 729 |
+
if fmt == "json":
|
| 730 |
+
checks.append({"id": f"json_{index:03d}", "type": "json_exact",
|
| 731 |
+
"path": path, "expected": _json_value(raw.get("content"))})
|
| 732 |
+
elif fmt == "toml":
|
| 733 |
+
try:
|
| 734 |
+
expected = tomllib.loads(content)
|
| 735 |
+
except (tomllib.TOMLDecodeError, ValueError) as exc:
|
| 736 |
+
raise ObjectiveEvaluatorError("reference TOML is invalid") from exc
|
| 737 |
+
checks.append({"id": f"toml_{index:03d}", "type": "toml_exact",
|
| 738 |
+
"path": path, "expected": expected})
|
| 739 |
+
elif fmt == "python":
|
| 740 |
+
try:
|
| 741 |
+
_, _, constants, call_nodes = _python_semantics(content)
|
| 742 |
+
resolved_calls = _python_resolved_call_nodes(content)
|
| 743 |
+
except SyntaxError as exc:
|
| 744 |
+
raise ObjectiveEvaluatorError("reference Python is invalid") from exc
|
| 745 |
+
checks.append({"id": f"python_{index:03d}", "type": "python_syntax",
|
| 746 |
+
"path": path})
|
| 747 |
+
checks.append({"id": f"python_{index:03d}_bindings",
|
| 748 |
+
"type": "python_bound_calls", "path": path})
|
| 749 |
+
raw_checks = raw.get("checks") or []
|
| 750 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 751 |
+
raise ObjectiveEvaluatorError(
|
| 752 |
+
"Python deliverable requires 1-12 objective import/call checks")
|
| 753 |
+
for check_index, check in enumerate(raw_checks, 1):
|
| 754 |
+
if not isinstance(check, dict):
|
| 755 |
+
raise ObjectiveEvaluatorError("Python check is not an object")
|
| 756 |
+
kind = str(check.get("type") or "").strip().casefold()
|
| 757 |
+
if kind in {"python_import", "python_call"}:
|
| 758 |
+
value = str(check.get("value") or "").strip()
|
| 759 |
+
if not _DOTTED.fullmatch(value):
|
| 760 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 761 |
+
compiled = {"type": kind, "path": path, "value": value}
|
| 762 |
+
elif kind == "python_constant":
|
| 763 |
+
name = str(check.get("name") or "").strip()
|
| 764 |
+
value = check.get("value")
|
| 765 |
+
if (not _DOTTED.fullmatch(name) or "." in name or
|
| 766 |
+
isinstance(value, (dict, list)) or value is None or
|
| 767 |
+
constants.get(name, _UNRESOLVED) != value):
|
| 768 |
+
raise ObjectiveEvaluatorError(
|
| 769 |
+
"Python constant check is invalid or fails reference content")
|
| 770 |
+
compiled = {"type": kind, "path": path, "name": name,
|
| 771 |
+
"value": value}
|
| 772 |
+
elif kind == "python_call_literal":
|
| 773 |
+
function = str(check.get("function") or "").strip()
|
| 774 |
+
value = check.get("value")
|
| 775 |
+
if (not _DOTTED.fullmatch(function) or
|
| 776 |
+
isinstance(value, (dict, list)) or value is None or
|
| 777 |
+
not any(
|
| 778 |
+
(name == function or name.endswith("." + function)) and
|
| 779 |
+
_node_contains_literal(node, value, constants)
|
| 780 |
+
for name, node in call_nodes)):
|
| 781 |
+
raise ObjectiveEvaluatorError(
|
| 782 |
+
"Python call-literal check is invalid or fails reference content")
|
| 783 |
+
compiled = {"type": kind, "path": path,
|
| 784 |
+
"function": function, "value": value}
|
| 785 |
+
elif kind == "python_call_keyword_literal":
|
| 786 |
+
function = str(check.get("function") or "").strip()
|
| 787 |
+
keyword = str(check.get("keyword") or "").strip()
|
| 788 |
+
value = check.get("value")
|
| 789 |
+
if (not _DOTTED.fullmatch(function) or
|
| 790 |
+
not _DOTTED.fullmatch(keyword) or "." in keyword or
|
| 791 |
+
isinstance(value, (dict, list)) or value is None or
|
| 792 |
+
not any(
|
| 793 |
+
(name == function or name.endswith("." + function)) and
|
| 794 |
+
_call_keyword_matches(node, keyword, value, constants)
|
| 795 |
+
for name, node in call_nodes)):
|
| 796 |
+
raise ObjectiveEvaluatorError(
|
| 797 |
+
"Python call-keyword check is invalid or fails reference content")
|
| 798 |
+
compiled = {"type": kind, "path": path,
|
| 799 |
+
"function": function, "keyword": keyword,
|
| 800 |
+
"value": value}
|
| 801 |
+
elif kind == "python_call_signature":
|
| 802 |
+
function = str(check.get("function") or "").strip()
|
| 803 |
+
arguments = check.get("arguments") or []
|
| 804 |
+
keywords = check.get("keywords") or {}
|
| 805 |
+
argument_expressions = check.get(
|
| 806 |
+
"argument_expressions") or []
|
| 807 |
+
keyword_expressions = check.get(
|
| 808 |
+
"keyword_expressions") or {}
|
| 809 |
+
assignment = check.get("assignment")
|
| 810 |
+
if (not _DOTTED.fullmatch(function) or
|
| 811 |
+
not isinstance(arguments, list) or
|
| 812 |
+
not isinstance(keywords, dict) or
|
| 813 |
+
not isinstance(argument_expressions, list) or
|
| 814 |
+
not isinstance(keyword_expressions, dict) or
|
| 815 |
+
not (arguments or keywords or
|
| 816 |
+
argument_expressions or keyword_expressions or
|
| 817 |
+
assignment) or
|
| 818 |
+
any(not isinstance(item, dict) or
|
| 819 |
+
not isinstance(item.get("index"), int) or
|
| 820 |
+
item.get("index") < 0 or
|
| 821 |
+
isinstance(item.get("value"), dict)
|
| 822 |
+
for item in arguments) or
|
| 823 |
+
len({item["index"] for item in arguments}) !=
|
| 824 |
+
len(arguments) or
|
| 825 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 826 |
+
"." in str(name) or isinstance(value, dict)
|
| 827 |
+
for name, value in keywords.items()) or
|
| 828 |
+
any(not isinstance(item, dict) or
|
| 829 |
+
not isinstance(item.get("index"), int) or
|
| 830 |
+
item.get("index") < 0 or
|
| 831 |
+
not _expression_fingerprint(
|
| 832 |
+
item.get("expression"))
|
| 833 |
+
for item in argument_expressions) or
|
| 834 |
+
len({item["index"] for item in
|
| 835 |
+
argument_expressions}) !=
|
| 836 |
+
len(argument_expressions) or
|
| 837 |
+
({item["index"] for item in arguments} &
|
| 838 |
+
{item["index"] for item in
|
| 839 |
+
argument_expressions}) or
|
| 840 |
+
any(not _DOTTED.fullmatch(str(name)) or
|
| 841 |
+
"." in str(name) or
|
| 842 |
+
not _expression_fingerprint(value)
|
| 843 |
+
for name, value in
|
| 844 |
+
keyword_expressions.items()) or
|
| 845 |
+
(set(keywords) & set(keyword_expressions)) or
|
| 846 |
+
(assignment is not None and (
|
| 847 |
+
not isinstance(assignment, dict) or
|
| 848 |
+
not _DOTTED.fullmatch(str(
|
| 849 |
+
assignment.get("target") or "")) or
|
| 850 |
+
"." in str(assignment.get("target") or "") or
|
| 851 |
+
not _expression_fingerprint(
|
| 852 |
+
assignment.get("expression")))) or
|
| 853 |
+
not any(
|
| 854 |
+
(name == function or
|
| 855 |
+
name.endswith("." + function)) and
|
| 856 |
+
_call_signature_matches(
|
| 857 |
+
node, arguments, keywords, constants,
|
| 858 |
+
argument_expressions,
|
| 859 |
+
keyword_expressions, assignment)
|
| 860 |
+
for name, node in call_nodes)):
|
| 861 |
+
raise ObjectiveEvaluatorError(
|
| 862 |
+
"Python call-signature check is invalid or fails reference content")
|
| 863 |
+
compiled = {"type": kind, "path": path,
|
| 864 |
+
"function": function,
|
| 865 |
+
"arguments": arguments,
|
| 866 |
+
"keywords": keywords,
|
| 867 |
+
"argument_expressions": argument_expressions,
|
| 868 |
+
"keyword_expressions": keyword_expressions,
|
| 869 |
+
"assignment": assignment}
|
| 870 |
+
else:
|
| 871 |
+
raise ObjectiveEvaluatorError("unsupported Python objective check")
|
| 872 |
+
if kind in {"python_call", "python_call_literal",
|
| 873 |
+
"python_call_keyword_literal",
|
| 874 |
+
"python_call_signature"}:
|
| 875 |
+
targets = _objective_call_targets(
|
| 876 |
+
kind, compiled, resolved_calls, constants)
|
| 877 |
+
if len(targets) != 1:
|
| 878 |
+
raise ObjectiveEvaluatorError(
|
| 879 |
+
"Python call check has no unique canonical target")
|
| 880 |
+
compiled["target"] = next(iter(targets))
|
| 881 |
+
checks.append({"id": f"python_{index:03d}_{check_index:03d}",
|
| 882 |
+
**compiled})
|
| 883 |
+
else:
|
| 884 |
+
raw_checks = raw.get("checks") or []
|
| 885 |
+
if not isinstance(raw_checks, list) or not 1 <= len(raw_checks) <= 12:
|
| 886 |
+
raise ObjectiveEvaluatorError(
|
| 887 |
+
"shell deliverable requires 1-12 objective command checks")
|
| 888 |
+
checks.append({"id": f"shell_{index:03d}", "type": "shell_syntax",
|
| 889 |
+
"path": path})
|
| 890 |
+
reference_sequence = _shell_lines(content)
|
| 891 |
+
reference_lines = set(reference_sequence)
|
| 892 |
+
unconditional_lines = _shell_unconditional_lines(content)
|
| 893 |
+
command_checks = []
|
| 894 |
+
for check in raw_checks:
|
| 895 |
+
value = " ".join(str(check.get("value") or "").strip().split())
|
| 896 |
+
if (not isinstance(check, dict) or
|
| 897 |
+
str(check.get("type") or "").strip().casefold() != "shell_command" or
|
| 898 |
+
not value or value not in reference_lines):
|
| 899 |
+
raise ObjectiveEvaluatorError("unsupported shell objective check")
|
| 900 |
+
command_checks.append({"type": "shell_command", "path": path,
|
| 901 |
+
"value": value})
|
| 902 |
+
if len({item["value"] for item in command_checks}) != len(command_checks):
|
| 903 |
+
raise ObjectiveEvaluatorError("shell objective checks must be unique")
|
| 904 |
+
command_checks.sort(key=lambda item: reference_sequence.index(item["value"]))
|
| 905 |
+
if not all(any(_shell_command_matches(
|
| 906 |
+
item["value"], line) for line in unconditional_lines)
|
| 907 |
+
for item in command_checks):
|
| 908 |
+
raise ObjectiveEvaluatorError(
|
| 909 |
+
"checked shell commands must be top-level and unconditional")
|
| 910 |
+
for check_index, check in enumerate(command_checks, 1):
|
| 911 |
+
checks.append({"id": f"shell_{index:03d}_{check_index:03d}",
|
| 912 |
+
**check})
|
| 913 |
+
if len(command_checks) >= 2:
|
| 914 |
+
checks.append({
|
| 915 |
+
"id": f"shell_{index:03d}_sequence",
|
| 916 |
+
"type": "shell_command_sequence", "path": path,
|
| 917 |
+
"values": [item["value"] for item in command_checks],
|
| 918 |
+
})
|
| 919 |
+
checks.append({
|
| 920 |
+
"id": f"shell_{index:03d}_unconditional",
|
| 921 |
+
"type": "shell_unconditional_commands", "path": path,
|
| 922 |
+
"values": [item["value"] for item in command_checks],
|
| 923 |
+
})
|
| 924 |
+
# Preserve the reference's fail-fast behavior when accepting normal
|
| 925 |
+
# command-substitution/guard wrappers. Never turn `|| true` into a
|
| 926 |
+
# passing preflight simply because it contains the correct argv.
|
| 927 |
+
reference_calls = shell_invocations(content)
|
| 928 |
+
protected = [item["value"] for item in command_checks if any(
|
| 929 |
+
call["fail_fast"] and _shell_command_matches(item["value"], call["command"])
|
| 930 |
+
for call in reference_calls)]
|
| 931 |
+
if protected:
|
| 932 |
+
checks.append({"id": f"shell_{index:03d}_failure_propagation",
|
| 933 |
+
"type": "shell_failure_propagation", "path": path,
|
| 934 |
+
"values": protected})
|
| 935 |
+
# Candidate workspaces may also contain root-level public inputs and
|
| 936 |
+
# installed Skill packages. Deliverables use dedicated top-level output
|
| 937 |
+
# directories, so enforce an exact file set inside those namespaces while
|
| 938 |
+
# leaving the read-only environment outside them untouched.
|
| 939 |
+
output_roots = sorted({path.split("/", 1)[0] for path in paths if "/" in path})
|
| 940 |
+
if len(output_roots) == len({path.split("/", 1)[0] for path in paths}):
|
| 941 |
+
checks.insert(0, {
|
| 942 |
+
"id": "workspace_file_set", "type": "workspace_file_set",
|
| 943 |
+
"paths": sorted(paths), "roots": output_roots,
|
| 944 |
+
})
|
| 945 |
+
return {
|
| 946 |
+
"type": WORKSPACE_EVALUATOR,
|
| 947 |
+
"version": WORKSPACE_EVALUATOR_VERSION,
|
| 948 |
+
"output_mode": "workspace",
|
| 949 |
+
"reference_files": reference_files,
|
| 950 |
+
"checks": checks,
|
| 951 |
+
}
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def reference_bundle(evaluator):
|
| 955 |
+
if evaluator.get("type") != WORKSPACE_EVALUATOR:
|
| 956 |
+
raise ObjectiveEvaluatorError("not a workspace evaluator")
|
| 957 |
+
return {"files": [
|
| 958 |
+
{"path": item["path"], "content": item["content"]}
|
| 959 |
+
for item in evaluator.get("reference_files") or []
|
| 960 |
+
]}
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
def hidden_workspace_values(evaluator):
|
| 964 |
+
"""Return decisive package-owned values that public queries must not leak."""
|
| 965 |
+
values = []
|
| 966 |
+
for check in (evaluator or {}).get("checks") or []:
|
| 967 |
+
kind = check.get("type")
|
| 968 |
+
if kind in {"json_exact", "toml_exact"}:
|
| 969 |
+
values.extend(value for _, value in _flatten(check.get("expected")))
|
| 970 |
+
elif kind in {"python_import", "python_call", "shell_command",
|
| 971 |
+
"python_constant", "python_call_literal",
|
| 972 |
+
"python_call_keyword_literal"}:
|
| 973 |
+
values.append(check.get("value"))
|
| 974 |
+
elif kind == "python_call_signature":
|
| 975 |
+
values.extend(value for _, value in _flatten({
|
| 976 |
+
"arguments": [item.get("value") for item in
|
| 977 |
+
check.get("arguments") or []],
|
| 978 |
+
"keywords": check.get("keywords") or {},
|
| 979 |
+
"argument_expressions": [item.get("expression") for item in
|
| 980 |
+
check.get("argument_expressions") or []],
|
| 981 |
+
"keyword_expressions": check.get("keyword_expressions") or {},
|
| 982 |
+
"assignment": check.get("assignment"),
|
| 983 |
+
}))
|
| 984 |
+
return [value for value in values if value is not None]
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
def _flatten(value, path=()):
|
| 988 |
+
if isinstance(value, dict):
|
| 989 |
+
out = []
|
| 990 |
+
for key, item in value.items():
|
| 991 |
+
out.extend(_flatten(item, path + (str(key),)))
|
| 992 |
+
return out
|
| 993 |
+
if isinstance(value, list):
|
| 994 |
+
out = []
|
| 995 |
+
for index, item in enumerate(value):
|
| 996 |
+
out.extend(_flatten(item, path + (index,)))
|
| 997 |
+
return out
|
| 998 |
+
return [(path, value)]
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
def _bundle_rows(candidate):
|
| 1002 |
+
if isinstance(candidate, str):
|
| 1003 |
+
text = candidate.strip()
|
| 1004 |
+
# Chat solvers often wrap the requested file bundle in a Markdown fence
|
| 1005 |
+
# or append a duplicate FINAL_ANSWER object. Decode one complete JSON
|
| 1006 |
+
# value at a time instead of requiring the entire response to be JSON;
|
| 1007 |
+
# only an object carrying the explicit ``files`` transport field is
|
| 1008 |
+
# eligible, so unrelated prose/objects are not silently accepted.
|
| 1009 |
+
decoder = json.JSONDecoder()
|
| 1010 |
+
candidate = None
|
| 1011 |
+
for match in re.finditer(r"\{", text):
|
| 1012 |
+
try:
|
| 1013 |
+
parsed, _ = decoder.raw_decode(text, match.start())
|
| 1014 |
+
except json.JSONDecodeError:
|
| 1015 |
+
continue
|
| 1016 |
+
if isinstance(parsed, dict) and "files" in parsed:
|
| 1017 |
+
candidate = parsed
|
| 1018 |
+
break
|
| 1019 |
+
if candidate is None:
|
| 1020 |
+
raise ObjectiveEvaluatorError(
|
| 1021 |
+
"workspace response contains no complete JSON file bundle")
|
| 1022 |
+
if not isinstance(candidate, dict):
|
| 1023 |
+
raise ObjectiveEvaluatorError("workspace candidate must be a file bundle object")
|
| 1024 |
+
files = candidate.get("files")
|
| 1025 |
+
if isinstance(files, dict):
|
| 1026 |
+
files = [{"path": path, "content": content}
|
| 1027 |
+
for path, content in files.items()]
|
| 1028 |
+
if not isinstance(files, list) or len(files) > 30:
|
| 1029 |
+
raise ObjectiveEvaluatorError("workspace candidate files must be a bounded list")
|
| 1030 |
+
return files
|
| 1031 |
+
|
| 1032 |
+
|
| 1033 |
+
def materialize_bundle(candidate, workspace):
|
| 1034 |
+
root = Path(workspace).resolve()
|
| 1035 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 1036 |
+
seen = set()
|
| 1037 |
+
for item in _bundle_rows(candidate):
|
| 1038 |
+
if not isinstance(item, dict):
|
| 1039 |
+
raise ObjectiveEvaluatorError("candidate file entry is not an object")
|
| 1040 |
+
relative = safe_relative_path(item.get("path"))
|
| 1041 |
+
if relative in seen:
|
| 1042 |
+
raise ObjectiveEvaluatorError(f"duplicate candidate file: {relative}")
|
| 1043 |
+
seen.add(relative)
|
| 1044 |
+
content = item.get("content")
|
| 1045 |
+
if isinstance(content, (dict, list)):
|
| 1046 |
+
content = json.dumps(content, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
|
| 1047 |
+
if not isinstance(content, str) or len(content.encode("utf-8")) > 500_000:
|
| 1048 |
+
raise ObjectiveEvaluatorError("candidate file content is invalid or too large")
|
| 1049 |
+
target = (root / relative).resolve()
|
| 1050 |
+
if root not in target.parents:
|
| 1051 |
+
raise ObjectiveEvaluatorError("candidate file escapes workspace")
|
| 1052 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 1053 |
+
target.write_text(content, encoding="utf-8")
|
| 1054 |
+
return root
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def evaluate_workspace(evaluator, workspace):
|
| 1058 |
+
if (not isinstance(evaluator, dict) or
|
| 1059 |
+
evaluator.get("type") != WORKSPACE_EVALUATOR or
|
| 1060 |
+
int(evaluator.get("version") or 0) not in
|
| 1061 |
+
SUPPORTED_WORKSPACE_EVALUATOR_VERSIONS):
|
| 1062 |
+
return False, {"error": "invalid workspace evaluator contract"}
|
| 1063 |
+
root = Path(workspace).resolve()
|
| 1064 |
+
results = []
|
| 1065 |
+
for check in evaluator.get("checks") or []:
|
| 1066 |
+
kind = check.get("type")
|
| 1067 |
+
relative, path = "", None
|
| 1068 |
+
if kind != "workspace_file_set":
|
| 1069 |
+
relative = safe_relative_path(check.get("path"))
|
| 1070 |
+
path = (root / relative).resolve()
|
| 1071 |
+
if root not in path.parents:
|
| 1072 |
+
return False, {"error": "evaluator path escapes workspace"}
|
| 1073 |
+
passed, detail = False, ""
|
| 1074 |
+
try:
|
| 1075 |
+
if kind == "workspace_file_set":
|
| 1076 |
+
expected = {safe_relative_path(value)
|
| 1077 |
+
for value in check.get("paths") or []}
|
| 1078 |
+
roots = [safe_relative_path(value)
|
| 1079 |
+
for value in check.get("roots") or []]
|
| 1080 |
+
actual = set()
|
| 1081 |
+
for relative_root in roots:
|
| 1082 |
+
scan_root = (root / relative_root).resolve()
|
| 1083 |
+
if root not in scan_root.parents:
|
| 1084 |
+
raise ObjectiveEvaluatorError(
|
| 1085 |
+
"workspace file-set root escapes workspace")
|
| 1086 |
+
if not scan_root.exists():
|
| 1087 |
+
continue
|
| 1088 |
+
for candidate in scan_root.rglob("*"):
|
| 1089 |
+
if candidate.is_file() or candidate.is_symlink():
|
| 1090 |
+
actual.add(candidate.relative_to(root).as_posix())
|
| 1091 |
+
passed = bool(expected) and actual == expected
|
| 1092 |
+
detail = ("exact deliverable file set" if passed else
|
| 1093 |
+
f"expected_files={sorted(expected)}; "
|
| 1094 |
+
f"actual_files={sorted(actual)}")
|
| 1095 |
+
elif kind == "file_exists":
|
| 1096 |
+
passed = path.is_file()
|
| 1097 |
+
detail = "present" if passed else "missing"
|
| 1098 |
+
elif kind == "json_exact":
|
| 1099 |
+
actual = json.loads(path.read_text(encoding="utf-8"))
|
| 1100 |
+
passed = (_same_native_json_types(actual, check.get("expected")) and
|
| 1101 |
+
_canonical(actual) == _canonical(check.get("expected")))
|
| 1102 |
+
detail = "semantic JSON match" if passed else "JSON value mismatch"
|
| 1103 |
+
elif kind == "toml_exact":
|
| 1104 |
+
actual = tomllib.loads(path.read_text(encoding="utf-8"))
|
| 1105 |
+
passed = _canonical(actual) == _canonical(check.get("expected"))
|
| 1106 |
+
detail = "semantic TOML match" if passed else "TOML value mismatch"
|
| 1107 |
+
elif kind in {"python_syntax", "python_bound_calls",
|
| 1108 |
+
"python_import", "python_call",
|
| 1109 |
+
"python_constant", "python_call_literal",
|
| 1110 |
+
"python_call_keyword_literal",
|
| 1111 |
+
"python_call_signature"}:
|
| 1112 |
+
source = path.read_text(encoding="utf-8")
|
| 1113 |
+
imports, calls, constants, call_nodes = _python_semantics(source)
|
| 1114 |
+
resolved_calls = _python_resolved_call_nodes(source)
|
| 1115 |
+
if kind == "python_syntax":
|
| 1116 |
+
passed, detail = True, "valid Python syntax"
|
| 1117 |
+
elif kind == "python_bound_calls":
|
| 1118 |
+
unbound = python_unbound_call_roots(
|
| 1119 |
+
path.read_text(encoding="utf-8"))
|
| 1120 |
+
passed = not unbound
|
| 1121 |
+
detail = ("all call roots are statically bound" if passed else
|
| 1122 |
+
"unbound call roots=" + repr(unbound))
|
| 1123 |
+
elif kind == "python_import":
|
| 1124 |
+
expected = str(check.get("value") or "")
|
| 1125 |
+
passed = expected in imports or any(
|
| 1126 |
+
value == expected or value.startswith(expected + ".")
|
| 1127 |
+
for value in imports)
|
| 1128 |
+
detail = f"imports={sorted(imports)}"
|
| 1129 |
+
elif kind == "python_call":
|
| 1130 |
+
expected = str(check.get("value") or "")
|
| 1131 |
+
target = str(check.get("target") or "")
|
| 1132 |
+
passed = (any(
|
| 1133 |
+
canonical == target
|
| 1134 |
+
for _, canonical, _ in resolved_calls)
|
| 1135 |
+
if target else expected in calls or any(
|
| 1136 |
+
value.endswith("." + expected)
|
| 1137 |
+
for value in calls))
|
| 1138 |
+
detail = f"calls={sorted(calls)}"
|
| 1139 |
+
elif kind == "python_constant":
|
| 1140 |
+
name, expected = str(check.get("name") or ""), check.get("value")
|
| 1141 |
+
actual = constants.get(name, _UNRESOLVED)
|
| 1142 |
+
passed = actual is not _UNRESOLVED and actual == expected
|
| 1143 |
+
detail = f"constant {name}={actual!r}"
|
| 1144 |
+
elif kind == "python_call_literal":
|
| 1145 |
+
function, expected = (str(check.get("function") or ""),
|
| 1146 |
+
check.get("value"))
|
| 1147 |
+
target = str(check.get("target") or "")
|
| 1148 |
+
source_calls = (resolved_calls if target else
|
| 1149 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1150 |
+
passed = any(
|
| 1151 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1152 |
+
(not target or canonical == target) and
|
| 1153 |
+
_node_contains_literal(node, expected, constants)
|
| 1154 |
+
for name, canonical, node in source_calls)
|
| 1155 |
+
detail = f"call={function} literal={expected!r}"
|
| 1156 |
+
elif kind == "python_call_keyword_literal":
|
| 1157 |
+
function = str(check.get("function") or "")
|
| 1158 |
+
keyword = str(check.get("keyword") or "")
|
| 1159 |
+
expected = check.get("value")
|
| 1160 |
+
target = str(check.get("target") or "")
|
| 1161 |
+
source_calls = (resolved_calls if target else
|
| 1162 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1163 |
+
passed = any(
|
| 1164 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1165 |
+
(not target or canonical == target) and
|
| 1166 |
+
_call_keyword_matches(node, keyword, expected, constants)
|
| 1167 |
+
for name, canonical, node in source_calls)
|
| 1168 |
+
detail = (f"call={function} keyword={keyword} "
|
| 1169 |
+
f"literal={expected!r}")
|
| 1170 |
+
else:
|
| 1171 |
+
function = str(check.get("function") or "")
|
| 1172 |
+
arguments = check.get("arguments") or []
|
| 1173 |
+
keywords = check.get("keywords") or {}
|
| 1174 |
+
argument_expressions = check.get(
|
| 1175 |
+
"argument_expressions") or []
|
| 1176 |
+
keyword_expressions = check.get(
|
| 1177 |
+
"keyword_expressions") or {}
|
| 1178 |
+
assignment = check.get("assignment")
|
| 1179 |
+
target = str(check.get("target") or "")
|
| 1180 |
+
source_calls = (resolved_calls if target else
|
| 1181 |
+
[(name, "", node) for name, node in call_nodes])
|
| 1182 |
+
passed = any(
|
| 1183 |
+
(bool(target) or _call_name_matches(name, function)) and
|
| 1184 |
+
(not target or canonical == target) and
|
| 1185 |
+
_call_signature_matches(
|
| 1186 |
+
node, arguments, keywords, constants,
|
| 1187 |
+
argument_expressions, keyword_expressions,
|
| 1188 |
+
assignment)
|
| 1189 |
+
for name, canonical, node in source_calls)
|
| 1190 |
+
detail = (f"call={function} arguments={arguments!r} "
|
| 1191 |
+
f"keywords={keywords!r} "
|
| 1192 |
+
f"argument_expressions={argument_expressions!r} "
|
| 1193 |
+
f"keyword_expressions={keyword_expressions!r} "
|
| 1194 |
+
f"assignment={assignment!r}")
|
| 1195 |
+
elif kind == "shell_syntax":
|
| 1196 |
+
completed = subprocess.run(
|
| 1197 |
+
["bash", "-n", str(path)], capture_output=True, text=True,
|
| 1198 |
+
timeout=5, check=False)
|
| 1199 |
+
passed = completed.returncode == 0
|
| 1200 |
+
detail = ("valid shell syntax" if passed else
|
| 1201 |
+
(completed.stderr or "invalid shell syntax").strip())
|
| 1202 |
+
elif kind == "shell_command":
|
| 1203 |
+
source = path.read_text(encoding="utf-8")
|
| 1204 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1205 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1206 |
+
expected = " ".join(str(check.get("value") or "").split())
|
| 1207 |
+
passed = any(_shell_command_matches(expected, line) for line in lines)
|
| 1208 |
+
detail = f"executable_lines={lines[:30]}"
|
| 1209 |
+
elif kind == "shell_command_sequence":
|
| 1210 |
+
source = path.read_text(encoding="utf-8")
|
| 1211 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1212 |
+
if int(evaluator.get("version", 0)) >= 15 else _shell_lines(source))
|
| 1213 |
+
expected = [" ".join(str(value).split())
|
| 1214 |
+
for value in check.get("values") or []]
|
| 1215 |
+
passed = (len(expected) >= 2 and
|
| 1216 |
+
_shell_command_sequence_matches(expected, lines))
|
| 1217 |
+
detail = f"expected_sequence={expected}; executable_lines={lines[:30]}"
|
| 1218 |
+
elif kind == "shell_unconditional_commands":
|
| 1219 |
+
source = path.read_text(encoding="utf-8")
|
| 1220 |
+
lines = ([call["command"] for call in shell_invocations(source)]
|
| 1221 |
+
if int(evaluator.get("version", 0)) >= 15
|
| 1222 |
+
else _shell_unconditional_lines(source))
|
| 1223 |
+
expected = [" ".join(str(value).split())
|
| 1224 |
+
for value in check.get("values") or []]
|
| 1225 |
+
passed = (bool(expected) and all(
|
| 1226 |
+
any(_shell_command_matches(command, line) for line in lines)
|
| 1227 |
+
for command in expected))
|
| 1228 |
+
if check.get("require_straight_line"):
|
| 1229 |
+
passed = passed and _shell_is_straight_line(source)
|
| 1230 |
+
detail = (f"expected_unconditional={expected}; "
|
| 1231 |
+
f"top_level_lines={lines[:30]}")
|
| 1232 |
+
elif kind == "shell_failure_propagation":
|
| 1233 |
+
calls = shell_invocations(path.read_text(encoding="utf-8"))
|
| 1234 |
+
expected = [" ".join(str(value).split())
|
| 1235 |
+
for value in check.get("values") or []]
|
| 1236 |
+
passed = bool(expected) and all(any(
|
| 1237 |
+
call["fail_fast"] and _shell_command_matches(command, call["command"])
|
| 1238 |
+
for call in calls) for command in expected)
|
| 1239 |
+
detail = f"expected_failure_propagation={expected}; invocations={calls[:30]}"
|
| 1240 |
+
elif kind == "shell_straight_line":
|
| 1241 |
+
source = path.read_text(encoding="utf-8")
|
| 1242 |
+
passed = _shell_is_straight_line(source)
|
| 1243 |
+
if "allowed_commands" in check:
|
| 1244 |
+
calls = shell_invocations(source)
|
| 1245 |
+
allowed = check["allowed_commands"]
|
| 1246 |
+
passed = (passed and len(calls) == int(check.get("exact_operation_count", len(allowed))) and
|
| 1247 |
+
all(any(_shell_command_matches(value, call["command"]) for value in allowed) for call in calls))
|
| 1248 |
+
detail = ("all executable lines are top-level" if passed else
|
| 1249 |
+
"shell contains conditional, loop, case, or function")
|
| 1250 |
+
else:
|
| 1251 |
+
detail = f"unsupported check: {kind}"
|
| 1252 |
+
except (OSError, ValueError, SyntaxError, subprocess.SubprocessError,
|
| 1253 |
+
json.JSONDecodeError,
|
| 1254 |
+
tomllib.TOMLDecodeError) as exc:
|
| 1255 |
+
detail = str(exc)
|
| 1256 |
+
results.append({"id": check.get("id"), "type": kind,
|
| 1257 |
+
"path": relative, "passed": bool(passed),
|
| 1258 |
+
"detail": detail[:1000]})
|
| 1259 |
+
return bool(results) and all(item["passed"] for item in results), {
|
| 1260 |
+
"type": WORKSPACE_EVALUATOR,
|
| 1261 |
+
"assertions_passed": sum(item["passed"] for item in results),
|
| 1262 |
+
"assertions_total": len(results),
|
| 1263 |
+
"assertions": results,
|
| 1264 |
+
}
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
def evaluate_candidate(evaluator, candidate):
|
| 1268 |
+
if isinstance(candidate, os.PathLike):
|
| 1269 |
+
try:
|
| 1270 |
+
return evaluate_workspace(evaluator, candidate) if Path(candidate).is_dir() else (
|
| 1271 |
+
False, {"type": WORKSPACE_EVALUATOR, "error": "candidate path is not a directory"})
|
| 1272 |
+
except (OSError, ValueError) as exc:
|
| 1273 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1274 |
+
if isinstance(candidate, str):
|
| 1275 |
+
# A chat file-bundle can be much longer than a filesystem path. Avoid
|
| 1276 |
+
# passing arbitrary model output to stat(), which can raise ENAMETOOLONG.
|
| 1277 |
+
stripped = candidate.strip()
|
| 1278 |
+
if (len(stripped) <= 4096 and '\n' not in stripped and '\r' not in stripped
|
| 1279 |
+
and not stripped.startswith(("{", "[", "```"))):
|
| 1280 |
+
try:
|
| 1281 |
+
if Path(stripped).is_dir():
|
| 1282 |
+
return evaluate_workspace(evaluator, stripped)
|
| 1283 |
+
except (OSError, ValueError):
|
| 1284 |
+
# Python/platform versions differ on ENAMETOOLONG and invalid
|
| 1285 |
+
# path errors. It is still candidate text: parse it unchanged.
|
| 1286 |
+
pass
|
| 1287 |
+
try:
|
| 1288 |
+
with tempfile.TemporaryDirectory(prefix="mybench-objective-") as temp:
|
| 1289 |
+
materialize_bundle(candidate, temp)
|
| 1290 |
+
return evaluate_workspace(evaluator, temp)
|
| 1291 |
+
except (ObjectiveEvaluatorError, ValueError, OSError, json.JSONDecodeError) as exc:
|
| 1292 |
+
return False, {"type": WORKSPACE_EVALUATOR, "error": str(exc)}
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
def self_test_workspace_evaluator(evaluator):
|
| 1296 |
+
correct = reference_bundle(evaluator)
|
| 1297 |
+
ok_correct, correct_detail = evaluate_candidate(evaluator, correct)
|
| 1298 |
+
rows = list(correct.get("files") or [])
|
| 1299 |
+
perturbed = {"files": rows[1:] if len(rows) > 1 else []}
|
| 1300 |
+
ok_wrong, wrong_detail = evaluate_candidate(evaluator, perturbed)
|
| 1301 |
+
mutations = []
|
| 1302 |
+
# Exact JSON fields must each matter, not merely the file's existence.
|
| 1303 |
+
for check in evaluator.get("checks") or []:
|
| 1304 |
+
if check.get("type") != "json_exact":
|
| 1305 |
+
continue
|
| 1306 |
+
for path, value in _flatten(check.get("expected")):
|
| 1307 |
+
candidate = copy.deepcopy(correct)
|
| 1308 |
+
file_row = next(row for row in candidate["files"]
|
| 1309 |
+
if row["path"] == check["path"])
|
| 1310 |
+
data = json.loads(file_row["content"])
|
| 1311 |
+
replacement = (not value if isinstance(value, bool) else
|
| 1312 |
+
value + 1 if isinstance(value, (int, float)) else
|
| 1313 |
+
str(value) + "__mutation__")
|
| 1314 |
+
if not path:
|
| 1315 |
+
data = replacement
|
| 1316 |
+
else:
|
| 1317 |
+
container = data
|
| 1318 |
+
for key in path[:-1]:
|
| 1319 |
+
container = container[key]
|
| 1320 |
+
container[path[-1]] = replacement
|
| 1321 |
+
file_row["content"] = json.dumps(data)
|
| 1322 |
+
passed, _ = evaluate_candidate(evaluator, candidate)
|
| 1323 |
+
mutations.append({"path": check["path"], "field": list(path),
|
| 1324 |
+
"rejected": not passed})
|
| 1325 |
+
return ok_correct and not ok_wrong and all(m["rejected"] for m in mutations), {
|
| 1326 |
+
"correct": correct_detail,
|
| 1327 |
+
"perturbed": wrong_detail,
|
| 1328 |
+
"scalar_mutations": mutations,
|
| 1329 |
+
}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/shell_invocations.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A deliberately bounded, non-executing shell structure recognizer.
|
| 2 |
+
|
| 3 |
+
Supports simple commands, literal scalar assignments, one command substitution
|
| 4 |
+
on an assignment RHS, and top-level `if ! command; then ... exit N; fi` guards.
|
| 5 |
+
It does not interpret shell code or credit commands in branch bodies/functions.
|
| 6 |
+
Pipelines, command lists, substitutions within substitutions, and swallowed
|
| 7 |
+
failures are outside this grammar. bash -n remains a separate required check.
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
import shlex
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _statements(text):
|
| 14 |
+
out, current = [], []
|
| 15 |
+
quote, escaped, comment, depth = None, False, False, 0
|
| 16 |
+
for ch in str(text):
|
| 17 |
+
if comment:
|
| 18 |
+
if ch == '\n':
|
| 19 |
+
comment = False
|
| 20 |
+
else:
|
| 21 |
+
continue
|
| 22 |
+
if escaped:
|
| 23 |
+
if ch != '\n':
|
| 24 |
+
current.extend(('\\', ch))
|
| 25 |
+
escaped = False
|
| 26 |
+
continue
|
| 27 |
+
if ch == '\\' and quote != "'":
|
| 28 |
+
escaped = True
|
| 29 |
+
continue
|
| 30 |
+
if quote:
|
| 31 |
+
current.append(ch)
|
| 32 |
+
if ch == quote:
|
| 33 |
+
quote = None
|
| 34 |
+
continue
|
| 35 |
+
if ch in "'\"":
|
| 36 |
+
quote = ch
|
| 37 |
+
current.append(ch)
|
| 38 |
+
elif ch == '#' and (not current or current[-1].isspace()):
|
| 39 |
+
comment = True
|
| 40 |
+
elif ch == '(':
|
| 41 |
+
depth += 1
|
| 42 |
+
current.append(ch)
|
| 43 |
+
elif ch == ')':
|
| 44 |
+
depth -= 1
|
| 45 |
+
if depth < 0:
|
| 46 |
+
return []
|
| 47 |
+
current.append(ch)
|
| 48 |
+
elif ch in '\n;' and depth == 0:
|
| 49 |
+
value = ''.join(current).strip()
|
| 50 |
+
if value:
|
| 51 |
+
out.append(value)
|
| 52 |
+
current = []
|
| 53 |
+
else:
|
| 54 |
+
current.append(ch)
|
| 55 |
+
if quote or escaped or depth:
|
| 56 |
+
return []
|
| 57 |
+
if ''.join(current).strip():
|
| 58 |
+
out.append(''.join(current).strip())
|
| 59 |
+
expanded = []
|
| 60 |
+
for statement in out:
|
| 61 |
+
inline_then = re.fullmatch(r'then\s+(.+)', statement, re.S)
|
| 62 |
+
expanded.extend(['then', inline_then.group(1)] if inline_then else [statement])
|
| 63 |
+
return expanded
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _simple_argv(text):
|
| 67 |
+
if '$(' in text or '`' in text:
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
lexer = shlex.shlex(text, posix=True, punctuation_chars=';&|<>()')
|
| 71 |
+
lexer.whitespace_split = True
|
| 72 |
+
tokens = list(lexer)
|
| 73 |
+
except ValueError:
|
| 74 |
+
return None
|
| 75 |
+
argv, index = [], 0
|
| 76 |
+
redirects = {'>', '>>', '<', '>&', '<&', '&>', '&>>'}
|
| 77 |
+
while index < len(tokens):
|
| 78 |
+
token = tokens[index]
|
| 79 |
+
if token.isdigit() and index + 1 < len(tokens) and tokens[index + 1] in redirects:
|
| 80 |
+
index += 1
|
| 81 |
+
token = tokens[index]
|
| 82 |
+
if token in redirects:
|
| 83 |
+
if index + 1 >= len(tokens):
|
| 84 |
+
return None
|
| 85 |
+
target = tokens[index + 1]
|
| 86 |
+
if (not target or any(c in target for c in '$`;&|<>()')
|
| 87 |
+
or target in ('{', '}')):
|
| 88 |
+
return None
|
| 89 |
+
index += 2
|
| 90 |
+
continue
|
| 91 |
+
if token in ('{', '}', '!') or any(c in token for c in ';&|<>()'):
|
| 92 |
+
return None
|
| 93 |
+
argv.append(token)
|
| 94 |
+
index += 1
|
| 95 |
+
return argv or None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _invocation(text):
|
| 99 |
+
substitution = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)=(?:"\$\((.*)\)"|\$\((.*)\))', text)
|
| 100 |
+
if substitution:
|
| 101 |
+
inner = substitution.group(2) if substitution.group(2) is not None else substitution.group(3)
|
| 102 |
+
argv = _simple_argv(inner)
|
| 103 |
+
return (argv, 'assignment_substitution') if argv else (None, None)
|
| 104 |
+
return _simple_argv(text), 'simple'
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _guard_end(statements, start):
|
| 108 |
+
depth = 1
|
| 109 |
+
for index in range(start + 1, len(statements)):
|
| 110 |
+
item = statements[index]
|
| 111 |
+
if re.match(r'^if\s', item):
|
| 112 |
+
depth += 1
|
| 113 |
+
elif item == 'fi':
|
| 114 |
+
depth -= 1
|
| 115 |
+
if depth == 0:
|
| 116 |
+
return index
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _nonzero_exit_body(statements):
|
| 121 |
+
"""Only literal logging followed by a final unconditional nonzero exit."""
|
| 122 |
+
if not statements:
|
| 123 |
+
return False
|
| 124 |
+
for index, statement in enumerate(statements):
|
| 125 |
+
argv = _simple_argv(statement)
|
| 126 |
+
if not argv:
|
| 127 |
+
return False
|
| 128 |
+
if argv[0] == 'exit':
|
| 129 |
+
return (index == len(statements) - 1 and len(argv) == 2
|
| 130 |
+
and argv[1].isdigit() and 1 <= int(argv[1]) <= 255)
|
| 131 |
+
if argv[0] not in ('echo', 'printf'):
|
| 132 |
+
return False
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _expand_known_variables(text, constants):
|
| 138 |
+
"""Preserve quote/escape expansion semantics in the bounded shell grammar.
|
| 139 |
+
|
| 140 |
+
Active unknown variables stay symbolic. A quoted/escaped literal dollar or
|
| 141 |
+
tilde has a separate token, so it cannot satisfy an expanding shell call.
|
| 142 |
+
This is parsing only; no shell command is evaluated.
|
| 143 |
+
"""
|
| 144 |
+
out,quote,i=[],None,0
|
| 145 |
+
variable=re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 146 |
+
while i<len(text):
|
| 147 |
+
ch=text[i]
|
| 148 |
+
if ch=='\\' and quote!="'" and i+1<len(text):
|
| 149 |
+
nxt=text[i+1]
|
| 150 |
+
if nxt=='$':out.append('__MYBENCH_LITERAL_DOLLAR__')
|
| 151 |
+
elif nxt=='~':out.append('__MYBENCH_LITERAL_TILDE__')
|
| 152 |
+
else:out.extend((ch,nxt))
|
| 153 |
+
i+=2;continue
|
| 154 |
+
if ch in "'\"":
|
| 155 |
+
if quote is None:quote=ch
|
| 156 |
+
elif quote==ch:quote=None
|
| 157 |
+
out.append(ch);i+=1;continue
|
| 158 |
+
if ch=='$':
|
| 159 |
+
if quote=="'":out.append('__MYBENCH_LITERAL_DOLLAR__');i+=1;continue
|
| 160 |
+
m=variable.match(text,i)
|
| 161 |
+
if m:
|
| 162 |
+
value=constants.get(m.group(1)or m.group(2))
|
| 163 |
+
if value is None:out.append(m.group(0))
|
| 164 |
+
elif quote=='"':out.append(value.replace('\\','\\\\').replace('"','\\"').replace('$','\\$'))
|
| 165 |
+
else:out.append(value)
|
| 166 |
+
i=m.end();continue
|
| 167 |
+
if ch=='~' and quote is not None:
|
| 168 |
+
out.append('__MYBENCH_LITERAL_TILDE__');i+=1;continue
|
| 169 |
+
out.append(ch);i+=1
|
| 170 |
+
return ''.join(out)
|
| 171 |
+
|
| 172 |
+
def shell_invocations(text):
|
| 173 |
+
"""Return ordered, actually evaluated invocation nodes in the supported subset.
|
| 174 |
+
|
| 175 |
+
fail_fast is a structural proof: a simple command/assignment runs under
|
| 176 |
+
errexit, or a negated test exits nonzero on failure. This is not a complete
|
| 177 |
+
shell interpreter, and unsupported syntax earns no invocation credit.
|
| 178 |
+
"""
|
| 179 |
+
statements = _statements(text)
|
| 180 |
+
# Function definitions or dynamic shell mutation can shadow the command or
|
| 181 |
+
# `exit` itself. They are outside this objective subset, even if uncalled.
|
| 182 |
+
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)
|
| 183 |
+
or re.match(r'^(?:source\b|\.\s|eval\b|alias\b|enable\b|shopt\b|trap\b)', s)
|
| 184 |
+
for s in statements):
|
| 185 |
+
return []
|
| 186 |
+
constants, result, index, errexit = {}, [], 0, False
|
| 187 |
+
assignment = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(?:'([^'$`]*)'|\"([^\"$`]*)\"|([A-Za-z0-9_./:+-]+))$")
|
| 188 |
+
variable = re.compile(r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)')
|
| 189 |
+
while index < len(statements):
|
| 190 |
+
statement = statements[index]
|
| 191 |
+
literal = assignment.fullmatch(statement)
|
| 192 |
+
if literal:
|
| 193 |
+
constants[literal.group(1)] = next(v for v in literal.groups()[1:] if v is not None)
|
| 194 |
+
index += 1
|
| 195 |
+
continue
|
| 196 |
+
statement = _expand_known_variables(statement, constants)
|
| 197 |
+
setting = _simple_argv(statement)
|
| 198 |
+
if setting and setting[0] == 'set':
|
| 199 |
+
flag_index = 1
|
| 200 |
+
while flag_index < len(setting):
|
| 201 |
+
flag = setting[flag_index]
|
| 202 |
+
if flag == '--' or not flag.startswith(('-', '+')):
|
| 203 |
+
break # Remaining words set positional parameters.
|
| 204 |
+
if not re.fullmatch(r'[-+][eufxEo]+', flag):
|
| 205 |
+
return [] # e.g. `set -n` suppresses execution entirely.
|
| 206 |
+
if 'e' in flag[1:]:
|
| 207 |
+
errexit = flag[0] == '-'
|
| 208 |
+
if 'o' in flag[1:]:
|
| 209 |
+
if flag_index + 1 >= len(setting):
|
| 210 |
+
return []
|
| 211 |
+
option = setting[flag_index + 1]
|
| 212 |
+
if option not in ('errexit', 'nounset', 'pipefail', 'noglob', 'xtrace', 'errtrace'):
|
| 213 |
+
return []
|
| 214 |
+
if option == 'errexit':
|
| 215 |
+
errexit = flag[0] == '-'
|
| 216 |
+
flag_index += 1
|
| 217 |
+
flag_index += 1
|
| 218 |
+
index += 1
|
| 219 |
+
continue
|
| 220 |
+
if re.match(r'^if\s', statement):
|
| 221 |
+
end = _guard_end(statements, index)
|
| 222 |
+
if end is None:
|
| 223 |
+
return []
|
| 224 |
+
negated = re.fullmatch(r'if\s+!\s+(.+)', statement)
|
| 225 |
+
if (negated and index + 1 < end
|
| 226 |
+
and statements[index + 1] == 'then'
|
| 227 |
+
and _nonzero_exit_body(statements[index + 2:end])):
|
| 228 |
+
argv, kind = _invocation(negated.group(1).strip())
|
| 229 |
+
if argv:
|
| 230 |
+
if argv[0] == 'false':
|
| 231 |
+
break
|
| 232 |
+
result.append({'command': shlex.join(argv), 'kind': 'failure_guard_' + kind,
|
| 233 |
+
'fail_fast': True, 'statement_index': index})
|
| 234 |
+
else:
|
| 235 |
+
return []
|
| 236 |
+
else:
|
| 237 |
+
# Arbitrary conditions may terminate the script or shadow its
|
| 238 |
+
# commands. Do not infer a reachable suffix through them.
|
| 239 |
+
return []
|
| 240 |
+
# Bodies are never credited and may have assigned local variables.
|
| 241 |
+
constants.clear()
|
| 242 |
+
index = end + 1
|
| 243 |
+
continue
|
| 244 |
+
if re.match(r'^(?:for|while|until|select|case)\b', statement) or statement == '{':
|
| 245 |
+
# Unsupported compounds are not searched for command substrings.
|
| 246 |
+
return []
|
| 247 |
+
argv, kind = _invocation(statement)
|
| 248 |
+
if not argv:
|
| 249 |
+
# An unparsed statement may change control flow or shell state.
|
| 250 |
+
# Skipping it would incorrectly credit an unreachable suffix.
|
| 251 |
+
return []
|
| 252 |
+
if argv[0] in ('return', 'exec', 'break', 'continue', 'let', 'declare',
|
| 253 |
+
'typeset', 'local', 'read', 'mapfile', 'readarray',
|
| 254 |
+
'unset', 'readonly', '[', '[[', 'test'):
|
| 255 |
+
return []
|
| 256 |
+
if argv[0] == 'exit' or (argv[0] == 'false' and errexit):
|
| 257 |
+
break
|
| 258 |
+
if kind == 'assignment_substitution':
|
| 259 |
+
assigned = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=', statement)
|
| 260 |
+
if assigned:
|
| 261 |
+
constants.pop(assigned.group(1), None)
|
| 262 |
+
result.append({'command': shlex.join(argv), 'kind': kind,
|
| 263 |
+
'fail_fast': errexit, 'statement_index': index})
|
| 264 |
+
index += 1
|
| 265 |
+
return result
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/test.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
candidate=${CANDIDATE_RESPONSE:-${CANDIDATE_WORKSPACE:-${1:-}}}
|
| 4 |
+
if [[ -z "$candidate" ]]; then
|
| 5 |
+
echo 'usage: CANDIDATE_RESPONSE=/path/to/response or CANDIDATE_WORKSPACE=/path/to/workspace tests/test.sh' >&2
|
| 6 |
+
exit 64
|
| 7 |
+
fi
|
| 8 |
+
python3 "$(dirname "$0")/evaluate.py" --task-json "$(dirname "$0")/../task.json" --candidate-path "$candidate"
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/evaluator/legacy_tests/verifiers.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verifier execution engine and fail-closed self-tests.
|
| 2 |
+
|
| 3 |
+
New verified tasks use atomic_json (complete shape plus scalar assertions).
|
| 4 |
+
Legacy verifier types remain readable so historical runs can still be audited.
|
| 5 |
+
自测:正确解(埋点构造)必须 pass;扰动解(破坏埋点)必须 fail。
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import posixpath
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from .objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 16 |
+
reference_bundle,
|
| 17 |
+
self_test_workspace_evaluator)
|
| 18 |
+
except ImportError: # portable task copies these modules beside each other
|
| 19 |
+
from objective_evaluators import (WORKSPACE_EVALUATOR, evaluate_candidate,
|
| 20 |
+
reference_bundle,
|
| 21 |
+
self_test_workspace_evaluator)
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger("pipeline")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _norm(s):
|
| 27 |
+
return str(s).strip().lower()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _json_value(value):
|
| 31 |
+
"""Parse a JSON answer from an object, FINAL_ANSWER line, or fenced block."""
|
| 32 |
+
if isinstance(value, (dict, list, int, float, bool)) or value is None:
|
| 33 |
+
return value
|
| 34 |
+
text = str(value).strip()
|
| 35 |
+
match = re.search(r"FINAL_ANSWER:\s*(.*)", text, re.I | re.S)
|
| 36 |
+
if match:
|
| 37 |
+
text = match.group(1).strip()
|
| 38 |
+
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I)
|
| 39 |
+
text = re.sub(r"\s*```$", "", text)
|
| 40 |
+
start_obj, start_arr = text.find("{"), text.find("[")
|
| 41 |
+
starts = [x for x in (start_obj, start_arr) if x >= 0]
|
| 42 |
+
if starts:
|
| 43 |
+
start = min(starts)
|
| 44 |
+
closing = "}" if text[start] == "{" else "]"
|
| 45 |
+
end = text.rfind(closing)
|
| 46 |
+
if end >= start:
|
| 47 |
+
text = text[start:end + 1]
|
| 48 |
+
try:return json.loads(text)
|
| 49 |
+
except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _strict_json_value(value):
|
| 54 |
+
"""Atomic answer contract: one complete JSON value, no extra prose/keys."""
|
| 55 |
+
def unique(pairs):
|
| 56 |
+
d={}
|
| 57 |
+
for k,v in pairs:
|
| 58 |
+
if k in d:raise ValueError('duplicate JSON key: '+k)
|
| 59 |
+
d[k]=v
|
| 60 |
+
return d
|
| 61 |
+
def invalid(s):raise ValueError('non-finite JSON number: '+s)
|
| 62 |
+
try:
|
| 63 |
+
result=(json.loads(value,object_pairs_hook=unique,parse_constant=invalid)
|
| 64 |
+
if isinstance(value,str) else value)
|
| 65 |
+
except RecursionError as error:
|
| 66 |
+
raise ValueError('Candidate JSON nesting is too deep') from error
|
| 67 |
+
def finite(v):
|
| 68 |
+
if isinstance(v,dict):return all(finite(x)for x in v.values())
|
| 69 |
+
if isinstance(v,list):return all(finite(x)for x in v)
|
| 70 |
+
return not isinstance(v,float)or math.isfinite(v)
|
| 71 |
+
try:is_finite=finite(result)
|
| 72 |
+
except RecursionError as error:raise ValueError('Candidate JSON nesting is too deep') from error
|
| 73 |
+
if not is_finite:raise ValueError('non-finite JSON number')
|
| 74 |
+
return result
|
| 75 |
+
|
| 76 |
+
def _path_equal(actual, expected):
|
| 77 |
+
if not isinstance(actual,str)or not isinstance(expected,str):return False
|
| 78 |
+
# A trailing slash is not a harmless spelling for a named file.
|
| 79 |
+
suffix=posixpath.splitext(expected.rstrip('/'))[1]
|
| 80 |
+
if suffix and not expected.endswith('/')and actual.strip().endswith('/'):return False
|
| 81 |
+
return _path_value(actual)==_path_value(expected)
|
| 82 |
+
|
| 83 |
+
def _canonical_json(value):
|
| 84 |
+
if isinstance(value, dict):
|
| 85 |
+
return {key: _canonical_json(value[key]) for key in sorted(value)}
|
| 86 |
+
if isinstance(value, list):
|
| 87 |
+
values = [_canonical_json(item) for item in value]
|
| 88 |
+
return sorted(values, key=lambda item: json.dumps(
|
| 89 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 90 |
+
return value
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _atomic_prepare(value, list_order):
|
| 94 |
+
if isinstance(value, dict):
|
| 95 |
+
return {key: _atomic_prepare(value[key], list_order) for key in sorted(value)}
|
| 96 |
+
if isinstance(value, list):
|
| 97 |
+
values = [_atomic_prepare(item, list_order) for item in value]
|
| 98 |
+
if list_order == "unordered":
|
| 99 |
+
values.sort(key=lambda item: json.dumps(
|
| 100 |
+
item, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
|
| 101 |
+
return values
|
| 102 |
+
return value
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _atomic_shape(value):
|
| 106 |
+
if isinstance(value, dict):
|
| 107 |
+
return {"type": "object", "keys": {
|
| 108 |
+
key: _atomic_shape(item) for key, item in value.items()}}
|
| 109 |
+
if isinstance(value, list):
|
| 110 |
+
return {"type": "array", "length": len(value),
|
| 111 |
+
"items": [_atomic_shape(item) for item in value]}
|
| 112 |
+
if isinstance(value, bool):
|
| 113 |
+
return {"type": "boolean"}
|
| 114 |
+
if value is None:
|
| 115 |
+
return {"type": "null"}
|
| 116 |
+
if isinstance(value, (int, float)):
|
| 117 |
+
return {"type": "number"}
|
| 118 |
+
return {"type": "string"}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _atomic_leaves(value, path="$", tokens=()):
|
| 122 |
+
if isinstance(value, dict):
|
| 123 |
+
out = []
|
| 124 |
+
for key, item in value.items():
|
| 125 |
+
out.extend(_atomic_leaves(
|
| 126 |
+
item, path + "." + key, tokens + (key,)))
|
| 127 |
+
return out
|
| 128 |
+
if isinstance(value, list):
|
| 129 |
+
out = []
|
| 130 |
+
for index, item in enumerate(value):
|
| 131 |
+
out.extend(_atomic_leaves(
|
| 132 |
+
item, f"{path}[{index}]", tokens + (index,)))
|
| 133 |
+
return out
|
| 134 |
+
return [(path, tokens, value)]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _normalize_path_equivalence_tokens(values):
|
| 138 |
+
"""Freeze a stable set of scalar JSON paths allowed to ignore a final slash."""
|
| 139 |
+
normalized = []
|
| 140 |
+
for tokens in values or []:
|
| 141 |
+
if (not isinstance(tokens, (list, tuple)) or not tokens or
|
| 142 |
+
any(not isinstance(token, (str, int)) for token in tokens)):
|
| 143 |
+
raise ValueError("path equivalence tokens must be non-empty JSON paths")
|
| 144 |
+
item = list(tokens)
|
| 145 |
+
if item not in normalized:
|
| 146 |
+
normalized.append(item)
|
| 147 |
+
return sorted(normalized, key=lambda item: json.dumps(item, ensure_ascii=False))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _path_value(value):
|
| 151 |
+
"""Normalize only portable path spelling, not general answer text."""
|
| 152 |
+
if not isinstance(value, str):
|
| 153 |
+
return None
|
| 154 |
+
text = value.strip().replace("\\", "/")
|
| 155 |
+
text = posixpath.normpath(text) if text else text
|
| 156 |
+
if text != "/":
|
| 157 |
+
text = text.rstrip("/")
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def compile_atomic_verifier(expected, list_order="ordered", float_tolerance=0.01,
|
| 162 |
+
path_equivalence_tokens=None):
|
| 163 |
+
"""Freeze a complete JSON shape plus one assertion for every scalar leaf."""
|
| 164 |
+
if list_order not in {"ordered", "unordered"}:
|
| 165 |
+
raise ValueError(f"unsupported atomic list_order: {list_order}")
|
| 166 |
+
tolerance = float(float_tolerance)
|
| 167 |
+
prepared = _atomic_prepare(_json_value(expected), list_order)
|
| 168 |
+
path_tokens = _normalize_path_equivalence_tokens(path_equivalence_tokens)
|
| 169 |
+
assertions = []
|
| 170 |
+
for index, (path, tokens, value) in enumerate(_atomic_leaves(prepared), 1):
|
| 171 |
+
assertion = {"id": f"leaf_{index:03d}", "path": path,
|
| 172 |
+
"tokens": list(tokens), "operator": "eq", "expected": value}
|
| 173 |
+
if isinstance(value, float):
|
| 174 |
+
assertion.update({"operator": "abs_diff", "tolerance": tolerance})
|
| 175 |
+
elif list(tokens) in path_tokens:
|
| 176 |
+
if not isinstance(value, str):
|
| 177 |
+
raise ValueError("path equivalence can only target string leaves")
|
| 178 |
+
assertion["operator"] = "path_eq"
|
| 179 |
+
assertions.append(assertion)
|
| 180 |
+
compiled = {
|
| 181 |
+
"type": "atomic_json", "version": 2 if path_tokens else 1,
|
| 182 |
+
"list_order": list_order,
|
| 183 |
+
"float_tolerance": tolerance,
|
| 184 |
+
"completeness": {"forbid_extra": True, "shape": _atomic_shape(prepared)},
|
| 185 |
+
"assertions": assertions,
|
| 186 |
+
}
|
| 187 |
+
if path_tokens:
|
| 188 |
+
compiled["path_equivalence_tokens"] = path_tokens
|
| 189 |
+
return compiled
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _shape_differences(expected, actual, path="$"):
|
| 193 |
+
if not isinstance(actual, dict) or actual.get("type") != expected.get("type"):
|
| 194 |
+
return [f"{path}: expected {expected.get('type')}, got "
|
| 195 |
+
f"{actual.get('type') if isinstance(actual, dict) else 'missing'}"]
|
| 196 |
+
kind = expected.get("type")
|
| 197 |
+
if kind == "object":
|
| 198 |
+
expected_keys = set((expected.get("keys") or {}))
|
| 199 |
+
actual_keys = set((actual.get("keys") or {}))
|
| 200 |
+
differences = [f"{path}: missing key {key}" for key in sorted(
|
| 201 |
+
expected_keys - actual_keys)]
|
| 202 |
+
differences.extend(f"{path}: extra key {key}" for key in sorted(
|
| 203 |
+
actual_keys - expected_keys))
|
| 204 |
+
for key in sorted(expected_keys & actual_keys):
|
| 205 |
+
differences.extend(_shape_differences(
|
| 206 |
+
expected["keys"][key], actual["keys"][key], path + "." + key))
|
| 207 |
+
return differences
|
| 208 |
+
if kind == "array":
|
| 209 |
+
differences = []
|
| 210 |
+
if actual.get("length") != expected.get("length"):
|
| 211 |
+
differences.append(
|
| 212 |
+
f"{path}: expected length {expected.get('length')}, got {actual.get('length')}")
|
| 213 |
+
for index, (expected_item, actual_item) in enumerate(zip(
|
| 214 |
+
expected.get("items") or [], actual.get("items") or [])):
|
| 215 |
+
differences.extend(_shape_differences(
|
| 216 |
+
expected_item, actual_item, f"{path}[{index}]"))
|
| 217 |
+
return differences
|
| 218 |
+
return []
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _atomic_get(value, tokens):
|
| 222 |
+
current = value
|
| 223 |
+
for token in tokens:
|
| 224 |
+
current = current[token]
|
| 225 |
+
return current
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _int_values(value):
|
| 229 |
+
if isinstance(value, (list, tuple)):
|
| 230 |
+
out = []
|
| 231 |
+
for item in value:
|
| 232 |
+
out.extend(_int_values(item))
|
| 233 |
+
return out
|
| 234 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 235 |
+
return [value]
|
| 236 |
+
return [int(number) for number in re.findall(r"\d+", str(value or ""))]
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _finding_type(value):
|
| 240 |
+
text = str(value or "").lower().replace("-", "_")
|
| 241 |
+
if "duplicate" in text:
|
| 242 |
+
return "duplicate_rows"
|
| 243 |
+
if ("none" in text or "null" in text) and "check" in text:
|
| 244 |
+
return "none_check"
|
| 245 |
+
if "missing" in text or "empty" in text or "null" in text:
|
| 246 |
+
return "missing"
|
| 247 |
+
if "outlier" in text or "large" in text or ">=" in text or "greater" in text:
|
| 248 |
+
return "outlier"
|
| 249 |
+
if "invalid" in text and "config" in text:
|
| 250 |
+
return "invalid_config"
|
| 251 |
+
if "off" in text and "one" in text:
|
| 252 |
+
return "off_by_one"
|
| 253 |
+
return text.strip().replace(" ", "_")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _normalized_findings(value, family):
|
| 257 |
+
obj = _json_value(value)
|
| 258 |
+
findings = obj.get("findings") if isinstance(obj, dict) else None
|
| 259 |
+
if not isinstance(findings, list):
|
| 260 |
+
raise ValueError("answer must contain a findings array")
|
| 261 |
+
normalized = set()
|
| 262 |
+
for finding in findings:
|
| 263 |
+
if not isinstance(finding, dict):
|
| 264 |
+
raise ValueError("each finding must be an object")
|
| 265 |
+
# The public contract uses type/function. Accept common semantically
|
| 266 |
+
# equivalent aliases as a robustness layer, while still comparing the
|
| 267 |
+
# normalized values and exact locations against generator-owned GT.
|
| 268 |
+
kind = _finding_type(finding.get("type", finding.get(
|
| 269 |
+
"defect_type", finding.get("defect"))))
|
| 270 |
+
if family == "csv":
|
| 271 |
+
if kind == "duplicate_rows":
|
| 272 |
+
rows = _int_values(finding.get("rows", finding.get("row")))
|
| 273 |
+
if len(rows) != 2:
|
| 274 |
+
raise ValueError("duplicate finding requires exactly two row numbers")
|
| 275 |
+
normalized.add((kind, *sorted(rows)))
|
| 276 |
+
elif kind in {"missing", "outlier"}:
|
| 277 |
+
rows = _int_values(finding.get("row"))
|
| 278 |
+
column = str(finding.get("column") or "").strip().lower()
|
| 279 |
+
if len(rows) != 1 or not column:
|
| 280 |
+
raise ValueError(f"{kind} requires one row and column")
|
| 281 |
+
normalized.add((kind, rows[0], column))
|
| 282 |
+
else:
|
| 283 |
+
raise ValueError(f"unsupported CSV finding type: {kind}")
|
| 284 |
+
elif family == "config":
|
| 285 |
+
if kind != "invalid_config":
|
| 286 |
+
raise ValueError(f"unsupported config finding type: {kind}")
|
| 287 |
+
normalized.add((kind, str(finding.get("path") or "").lower(),
|
| 288 |
+
json.dumps(finding.get("value"), sort_keys=True),
|
| 289 |
+
str(finding.get("expected") or "").lower()))
|
| 290 |
+
elif family == "code":
|
| 291 |
+
if kind not in {"off_by_one", "none_check"}:
|
| 292 |
+
raise ValueError(f"unsupported code finding type: {kind}")
|
| 293 |
+
function = finding.get("function", finding.get("function_name"))
|
| 294 |
+
function = str(function or "").strip().lower()
|
| 295 |
+
if not function:
|
| 296 |
+
raise ValueError(f"{kind} requires a function")
|
| 297 |
+
normalized.add((kind, function))
|
| 298 |
+
else:
|
| 299 |
+
raise ValueError(f"unsupported findings family: {family}")
|
| 300 |
+
return normalized
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _normalized_facts(value):
|
| 304 |
+
obj = _json_value(value)
|
| 305 |
+
facts = obj.get("facts") if isinstance(obj, dict) else None
|
| 306 |
+
if not isinstance(facts, list):
|
| 307 |
+
raise ValueError("answer must contain a facts array")
|
| 308 |
+
def textual(item):
|
| 309 |
+
# The document generator serializes scalar values as visible text. JSON
|
| 310 |
+
# has no way to infer whether the source token "30" was authored from an
|
| 311 |
+
# integer or a string, so facts_match compares that surface text. Nested
|
| 312 |
+
# values retain structural JSON comparison.
|
| 313 |
+
if isinstance(item, (dict, list)):
|
| 314 |
+
return json.dumps(item, sort_keys=True, ensure_ascii=False,
|
| 315 |
+
separators=(",", ":"))
|
| 316 |
+
if item is None:
|
| 317 |
+
return "None"
|
| 318 |
+
return str(item)
|
| 319 |
+
return {(str(fact.get("key") or ""), textual(fact.get("value")))
|
| 320 |
+
for fact in facts if isinstance(fact, dict)}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def verify(verifier, gt_answer, solver_output, material_paths=None):
|
| 324 |
+
"""执行 verifier。返回 (passed, detail)。"""
|
| 325 |
+
vtype = verifier.get("type")
|
| 326 |
+
try:
|
| 327 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 328 |
+
return evaluate_candidate(verifier, solver_output)
|
| 329 |
+
|
| 330 |
+
if vtype == "json_exact":
|
| 331 |
+
pred = _canonical_json(_json_value(solver_output))
|
| 332 |
+
gold = _canonical_json(_json_value(gt_answer))
|
| 333 |
+
ok = pred == gold
|
| 334 |
+
return ok, "json_exact: pass" if ok else f"json_exact mismatch: pred={pred!r}"
|
| 335 |
+
|
| 336 |
+
if vtype == "atomic_json":
|
| 337 |
+
try:
|
| 338 |
+
pred = _atomic_prepare(_strict_json_value(solver_output),
|
| 339 |
+
verifier.get("list_order", "ordered"))
|
| 340 |
+
pred_shape = _atomic_shape(pred)
|
| 341 |
+
except RecursionError:
|
| 342 |
+
return False, "candidate JSON nesting is too deep"
|
| 343 |
+
compiled = compile_atomic_verifier(
|
| 344 |
+
gt_answer, verifier.get("list_order", "ordered"),
|
| 345 |
+
verifier.get("float_tolerance", 0.01),
|
| 346 |
+
verifier.get("path_equivalence_tokens"))
|
| 347 |
+
frozen = {key: verifier.get(key) for key in
|
| 348 |
+
("type", "version", "list_order", "float_tolerance",
|
| 349 |
+
"completeness", "assertions", "path_equivalence_tokens")}
|
| 350 |
+
expected_frozen = {key: compiled.get(key) for key in frozen}
|
| 351 |
+
if frozen != expected_frozen:
|
| 352 |
+
return False, {"error": "atomic verifier does not match ground truth"}
|
| 353 |
+
shape_failures = _shape_differences(
|
| 354 |
+
verifier["completeness"]["shape"], pred_shape)
|
| 355 |
+
assertion_results = []
|
| 356 |
+
for assertion in verifier.get("assertions") or []:
|
| 357 |
+
try:
|
| 358 |
+
actual = _atomic_get(pred, assertion["tokens"])
|
| 359 |
+
if assertion["operator"] == "abs_diff":
|
| 360 |
+
passed = abs(float(actual) - float(assertion["expected"])) <= float(
|
| 361 |
+
assertion.get("tolerance", 0.0))
|
| 362 |
+
elif assertion["operator"] == "path_eq":
|
| 363 |
+
passed = _path_equal(actual, assertion["expected"])
|
| 364 |
+
else:
|
| 365 |
+
passed = (actual is assertion["expected"] if
|
| 366 |
+
isinstance(assertion["expected"], bool) else
|
| 367 |
+
actual == assertion["expected"])
|
| 368 |
+
message = "" if passed else (
|
| 369 |
+
f"actual={actual!r} expected={assertion['expected']!r}")
|
| 370 |
+
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
| 371 |
+
actual, passed, message = None, False, f"lookup/compare failed: {exc}"
|
| 372 |
+
assertion_results.append({
|
| 373 |
+
"id": assertion["id"], "path": assertion["path"],
|
| 374 |
+
"operator": assertion["operator"], "expected": assertion["expected"],
|
| 375 |
+
"actual": actual, "passed": passed, "message": message})
|
| 376 |
+
passed_count = sum(item["passed"] for item in assertion_results)
|
| 377 |
+
ok = not shape_failures and passed_count == len(assertion_results)
|
| 378 |
+
return ok, {
|
| 379 |
+
"type": "atomic_json", "completeness_passed": not shape_failures,
|
| 380 |
+
"completeness_failures": shape_failures,
|
| 381 |
+
"assertions_passed": passed_count,
|
| 382 |
+
"assertions_total": len(assertion_results),
|
| 383 |
+
"assertion_pass_rate": (passed_count / len(assertion_results)
|
| 384 |
+
if assertion_results else 1.0),
|
| 385 |
+
"assertions": assertion_results,
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
if vtype == "findings_match":
|
| 389 |
+
family = verifier.get("family")
|
| 390 |
+
pred = _normalized_findings(solver_output, family)
|
| 391 |
+
gold = _normalized_findings(gt_answer, family)
|
| 392 |
+
ok = pred == gold
|
| 393 |
+
return ok, ("findings_match: pass" if ok else
|
| 394 |
+
f"findings_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 395 |
+
|
| 396 |
+
if vtype == "facts_match":
|
| 397 |
+
pred, gold = _normalized_facts(solver_output), _normalized_facts(gt_answer)
|
| 398 |
+
ok = pred == gold
|
| 399 |
+
return ok, ("facts_match: pass" if ok else
|
| 400 |
+
f"facts_match: missing={sorted(gold-pred)} extra={sorted(pred-gold)}")
|
| 401 |
+
|
| 402 |
+
if vtype == "exact_match":
|
| 403 |
+
ok = _norm(solver_output) == _norm(gt_answer)
|
| 404 |
+
return ok, f"exact_match: {'pass' if ok else 'mismatch'}"
|
| 405 |
+
|
| 406 |
+
if vtype == "numeric":
|
| 407 |
+
tol = verifier.get("tolerance") or 1e-6
|
| 408 |
+
pred = float(str(solver_output).strip().split()[0])
|
| 409 |
+
gold = float(gt_answer)
|
| 410 |
+
ok = abs(pred - gold) <= tol
|
| 411 |
+
return ok, f"numeric: pred={pred} gold={gold} tol={tol}"
|
| 412 |
+
|
| 413 |
+
if vtype == "set_match":
|
| 414 |
+
pred = set(_as_list(solver_output))
|
| 415 |
+
gold = set(_as_list(gt_answer))
|
| 416 |
+
ok = pred == gold
|
| 417 |
+
return ok, f"set_match: extra={list(pred - gold)[:5]} missing={list(gold - pred)[:5]}"
|
| 418 |
+
|
| 419 |
+
if vtype == "structured_match":
|
| 420 |
+
pred = _json_value(solver_output)
|
| 421 |
+
gold = _json_value(gt_answer)
|
| 422 |
+
if not isinstance(pred, dict) or not isinstance(gold, dict):
|
| 423 |
+
return False, "structured_match requires JSON objects"
|
| 424 |
+
missing = [f for f in verifier.get("required_fields", []) if f not in pred]
|
| 425 |
+
wrong = [f for f in verifier.get("required_fields", [])
|
| 426 |
+
if f in pred and f in gold and pred[f] != gold[f]]
|
| 427 |
+
ok = not missing and not wrong
|
| 428 |
+
return ok, f"structured_match: missing_fields={missing} wrong_values={wrong}"
|
| 429 |
+
|
| 430 |
+
if vtype == "execution":
|
| 431 |
+
return False, "execution verifier is disabled in verified-first v2"
|
| 432 |
+
|
| 433 |
+
if vtype == "constraint":
|
| 434 |
+
fails = _check_constraints(verifier.get("criteria", []), solver_output)
|
| 435 |
+
return not fails, f"constraint: failed={fails[:5]}"
|
| 436 |
+
|
| 437 |
+
if vtype == "file_inspection":
|
| 438 |
+
fails = _inspect_files(verifier.get("expected_files", []), material_paths or [])
|
| 439 |
+
return not fails, f"file_inspection: failed={fails[:5]}"
|
| 440 |
+
|
| 441 |
+
return False, f"unknown verifier type: {vtype}"
|
| 442 |
+
except Exception as e:
|
| 443 |
+
return False, f"verifier error: {e}"
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _as_list(x):
|
| 447 |
+
if isinstance(x, list):
|
| 448 |
+
return [_norm(i) for i in x]
|
| 449 |
+
# 逗号/换行分隔的字符串
|
| 450 |
+
return [_norm(i) for i in str(x).replace("\n", ",").split(",") if i.strip()]
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def _check_constraints(criteria, solver_output):
|
| 454 |
+
"""criteria: ["must contain X", "must be valid json", "length <= 500"]"""
|
| 455 |
+
fails = []
|
| 456 |
+
text = str(solver_output)
|
| 457 |
+
for c in criteria:
|
| 458 |
+
cl = c.lower()
|
| 459 |
+
if cl.startswith("must contain "):
|
| 460 |
+
needle = c[len("must contain "):]
|
| 461 |
+
if needle.lower() not in text.lower():
|
| 462 |
+
fails.append(c)
|
| 463 |
+
elif "valid json" in cl:
|
| 464 |
+
try:
|
| 465 |
+
json.loads(text)
|
| 466 |
+
except Exception:
|
| 467 |
+
fails.append(c)
|
| 468 |
+
elif cl.startswith("length <="):
|
| 469 |
+
limit = int(cl.split("<=")[1].strip())
|
| 470 |
+
if len(text) > limit:
|
| 471 |
+
fails.append(c)
|
| 472 |
+
else:
|
| 473 |
+
# Deterministic verifier DSL is closed-world: unknown checks fail.
|
| 474 |
+
fails.append(f"unsupported criterion: {c}")
|
| 475 |
+
return fails
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _inspect_files(expected, material_paths):
|
| 479 |
+
fails = []
|
| 480 |
+
paths = set(material_paths or [])
|
| 481 |
+
for e in expected:
|
| 482 |
+
fname = e.get("filename") if isinstance(e, dict) else str(e)
|
| 483 |
+
if not any(os.path.basename(p) == os.path.basename(fname) for p in paths):
|
| 484 |
+
fails.append(f"missing file: {fname}")
|
| 485 |
+
return fails
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
# ---------------- 自测 ----------------
|
| 489 |
+
|
| 490 |
+
def build_correct_solution(verifier, gt_answer, planted_info):
|
| 491 |
+
"""由埋点/ground truth 直接构造正确解。"""
|
| 492 |
+
vtype = verifier.get("type")
|
| 493 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 494 |
+
return reference_bundle(verifier)
|
| 495 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match", "exact_match", "numeric",
|
| 496 |
+
"set_match", "structured_match"):
|
| 497 |
+
return gt_answer
|
| 498 |
+
if vtype == "constraint":
|
| 499 |
+
parts = [c[len("must contain "):] for c in verifier.get("criteria", [])
|
| 500 |
+
if c.lower().startswith("must contain ")]
|
| 501 |
+
return " ".join(parts) if parts else str(gt_answer)
|
| 502 |
+
# execution / file_inspection 复杂场景:返回 None 表示跳过正确解构造
|
| 503 |
+
return None
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def build_perturbed_solution(verifier, gt_answer, planted_info):
|
| 507 |
+
"""破坏埋点构造扰动解。"""
|
| 508 |
+
vtype = verifier.get("type")
|
| 509 |
+
if vtype == WORKSPACE_EVALUATOR:
|
| 510 |
+
files = list(reference_bundle(verifier).get("files") or [])
|
| 511 |
+
return {"files": files[1:] if len(files) > 1 else []}
|
| 512 |
+
if vtype in ("json_exact", "atomic_json", "findings_match", "facts_match"):
|
| 513 |
+
gold = _json_value(gt_answer)
|
| 514 |
+
if isinstance(gold, dict):
|
| 515 |
+
perturbed = dict(gold)
|
| 516 |
+
key = next(iter(perturbed), "__missing__")
|
| 517 |
+
if key in perturbed:
|
| 518 |
+
perturbed.pop(key)
|
| 519 |
+
else:
|
| 520 |
+
perturbed["__wrong__"] = True
|
| 521 |
+
return perturbed
|
| 522 |
+
if isinstance(gold, list):
|
| 523 |
+
return gold[:-1] if gold else ["__wrong__"]
|
| 524 |
+
return "__wrong__"
|
| 525 |
+
if vtype in ("exact_match", "numeric"):
|
| 526 |
+
return "0" if vtype == "numeric" else "PERTURBED_WRONG_ANSWER"
|
| 527 |
+
if vtype == "set_match":
|
| 528 |
+
gold = _as_list(gt_answer)
|
| 529 |
+
return gold[: max(0, len(gold) - 1)] + ["perturbed_item"]
|
| 530 |
+
if vtype == "structured_match":
|
| 531 |
+
fields = verifier.get("required_fields", [])
|
| 532 |
+
return {f: None for i, f in enumerate(fields) if i > 0} # 缺第一个字段
|
| 533 |
+
if vtype == "constraint":
|
| 534 |
+
return "perturbed output lacking required content"
|
| 535 |
+
return None
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def self_test(verifier, gt_answer, planted_info, material_paths):
|
| 539 |
+
"""返回 (passed, detail)。无法构造正确/扰动解的 verifier 类型 = 未通过(不算数)。
|
| 540 |
+
|
| 541 |
+
之前这里对 execution / file_inspection 直接 return True("skipped"),等于坏 verifier
|
| 542 |
+
可无证据通过 S5;改为按未通过处理,由 S5 转 open 支路或丢弃。
|
| 543 |
+
"""
|
| 544 |
+
if verifier.get("type") == WORKSPACE_EVALUATOR:
|
| 545 |
+
return self_test_workspace_evaluator(verifier)
|
| 546 |
+
correct = build_correct_solution(verifier, gt_answer, planted_info)
|
| 547 |
+
perturbed = build_perturbed_solution(verifier, gt_answer, planted_info)
|
| 548 |
+
if correct is None or perturbed is None:
|
| 549 |
+
return False, (f"cannot self-test verifier type {verifier.get('type')} "
|
| 550 |
+
"(execution/file_inspection need real correct/perturbed solutions)")
|
| 551 |
+
ok1, d1 = verify(verifier, gt_answer, correct, material_paths)
|
| 552 |
+
ok2, d2 = verify(verifier, gt_answer, perturbed, material_paths)
|
| 553 |
+
passed = ok1 and not ok2
|
| 554 |
+
return passed, {"correct": d1, "perturbed": d2}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/grading/verified_config.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "audited-verified-grader-v1",
|
| 3 |
+
"query_id": "acf457a314e435c5_q1",
|
| 4 |
+
"selected_checker_sha256": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 5 |
+
"grader_file_sha256": {
|
| 6 |
+
"auto_entry.py": "787feed62d2dec22d96d0903deafa0cb8f48264744e5beadd01d0333da1816fa",
|
| 7 |
+
"check.py": "f85f2855faf3e869f60d44776a2962f27c945c3222b397d4c4b8fa2002fa1703",
|
| 8 |
+
"legacy-task.json": "1df3b6f6e233d6567cc9c93efc5dd176cb098c6d9f383a9f1d6c80501ddfaa19",
|
| 9 |
+
"auto_policy_guard.py": "b9e8d8bfa10b689c5123b80e88a9e8eb4d78895ab6fc195dc4831b375bb110d0",
|
| 10 |
+
"autograde_task_check.py": "7d521601969631f78b1a5f0f355417d5843a95098dc25e5901eabe1a79501278",
|
| 11 |
+
"auto_policy.py": "d3b0e29cef4674856428891b5e01f69b4d04d7831b720b000139de317c887932",
|
| 12 |
+
"auto_contract.json": "3abe95b444639b04d97b75062909ad6e96ebbbe9bd2d280b95e7355c68edae37",
|
| 13 |
+
"legacy_tests/test.sh": "5cd6f8a11872c646ad309f863e6415996ba09b12f02b9c6f2a6b8c5d835f7089",
|
| 14 |
+
"legacy_tests/evaluate.py": "56b876bc7c90457da11c3a4aadd849c2edd8f827bef4561e2500a03247ad05a1",
|
| 15 |
+
"legacy_tests/objective_evaluators.py": "a2239e13117fa5e393bcd2bedcb933aeeddfbcf8ae2524255f66bb9c50f9024a",
|
| 16 |
+
"legacy_tests/shell_invocations.py": "dac4e83e710900f6e5c75b349d975decbc3155883f490af2db18324d5d6d81bc",
|
| 17 |
+
"legacy_tests/verifiers.py": "d153a42a42f6a4e454b3f110b733f9da7d1cd8c238015e3087edcc9b2abd975b"
|
| 18 |
+
},
|
| 19 |
+
"runtime_requirements": {
|
| 20 |
+
"candidate_mode": "response",
|
| 21 |
+
"candidate_snapshot_copy_to_ephemeral_app": true,
|
| 22 |
+
"container_private_entry": "/grader/check.py",
|
| 23 |
+
"environment": {
|
| 24 |
+
"CANDIDATE_DIR": "/candidate",
|
| 25 |
+
"CANDIDATE_ROOT": "/candidate",
|
| 26 |
+
"MYBENCH_ANSWER": "/answer.txt",
|
| 27 |
+
"MYBENCH_ANSWER_FILE": "/answer.txt",
|
| 28 |
+
"MYBENCH_CANDIDATE": "/candidate",
|
| 29 |
+
"MYBENCH_EPHEMERAL_APP": "1",
|
| 30 |
+
"MYBENCH_EPHEMERAL_WORKSPACE": "1",
|
| 31 |
+
"MYBENCH_RUN_METADATA": "/run_metadata.json",
|
| 32 |
+
"MYBENCH_SOURCE_TASK": "/source",
|
| 33 |
+
"SOURCE_TASK_DIR": "/source"
|
| 34 |
+
},
|
| 35 |
+
"expected_check_ids": [
|
| 36 |
+
"0"
|
| 37 |
+
],
|
| 38 |
+
"external_final_answer": "verbatim actual agent final UTF-8 outside candidate; never reference/proxy answer",
|
| 39 |
+
"external_trace": "when consumed, complete executor-owned trace outside candidate, read-only and SHA-bound; unavailable evidence remains unscored",
|
| 40 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 41 |
+
"image_included": false,
|
| 42 |
+
"legacy_adapter": true,
|
| 43 |
+
"mounts_readonly": [
|
| 44 |
+
"/candidate",
|
| 45 |
+
"/source",
|
| 46 |
+
"/grader",
|
| 47 |
+
"/answer.txt"
|
| 48 |
+
],
|
| 49 |
+
"network": "none",
|
| 50 |
+
"original_declared_resources": {
|
| 51 |
+
"agent": {
|
| 52 |
+
"basis": "advisory_not_measured",
|
| 53 |
+
"cpus": 2,
|
| 54 |
+
"memory_mib": 4096,
|
| 55 |
+
"timeout_sec": 1200
|
| 56 |
+
},
|
| 57 |
+
"oracle": {
|
| 58 |
+
"timeout_sec": 120
|
| 59 |
+
},
|
| 60 |
+
"source_agent": {
|
| 61 |
+
"command_timeout_sec": null,
|
| 62 |
+
"max_steps": null
|
| 63 |
+
},
|
| 64 |
+
"verifier": {
|
| 65 |
+
"cpus": 1,
|
| 66 |
+
"memory_mib": 1024,
|
| 67 |
+
"pids": 64,
|
| 68 |
+
"timeout_sec": 900,
|
| 69 |
+
"tmpfs_mib": 128
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
"private_entry": "evaluator/check.py",
|
| 73 |
+
"private_tree_environment_tokens": [
|
| 74 |
+
"MYBENCH_CANDIDATE_FILE",
|
| 75 |
+
"MYBENCH_OPEN_JUDGE_COMMAND",
|
| 76 |
+
"MYBENCH_OPEN_JUDGE_TIMEOUT",
|
| 77 |
+
"MYBENCH_TASK_JSON"
|
| 78 |
+
],
|
| 79 |
+
"trusted_trace_environment_aliases": [
|
| 80 |
+
"MYBENCH_TOOL_TRAJECTORY",
|
| 81 |
+
"MYBENCH_TRUSTED_TRACE",
|
| 82 |
+
"TOOL_TRAJECTORY",
|
| 83 |
+
"TOOL_TRAJECTORY_FILE"
|
| 84 |
+
],
|
| 85 |
+
"trusted_trace_sha256_environment": "MYBENCH_TRUSTED_TRACE_SHA256",
|
| 86 |
+
"working_directory": "/candidate",
|
| 87 |
+
"writable_ephemeral_roots": [
|
| 88 |
+
"/app",
|
| 89 |
+
"/workspace",
|
| 90 |
+
"/tmp"
|
| 91 |
+
],
|
| 92 |
+
"criterion_weights": {
|
| 93 |
+
"0": 1
|
| 94 |
+
},
|
| 95 |
+
"grader_timeout_seconds": 600,
|
| 96 |
+
"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."
|
| 97 |
+
},
|
| 98 |
+
"engine": "portable_verified_v1"
|
| 99 |
+
}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/instruction.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 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"}}
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/skill/SKILL.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: engram-business-rules
|
| 3 |
+
description: >
|
| 4 |
+
Product and business-rule guardrails for Engram. Trigger: Any change that
|
| 5 |
+
affects sync behavior, project controls, permissions, or memory semantics.
|
| 6 |
+
license: Apache-2.0
|
| 7 |
+
metadata:
|
| 8 |
+
author: gentleman-programming
|
| 9 |
+
version: "1.0"
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## When to Use
|
| 13 |
+
|
| 14 |
+
Use this skill when:
|
| 15 |
+
- Changing enrollment, sync, auth, admin controls, or cloud behavior
|
| 16 |
+
- Implementing project-level or org-level policy
|
| 17 |
+
- Adjusting what data appears locally vs remotely
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## Product Rules
|
| 22 |
+
|
| 23 |
+
1. Local-first remains the default mental model.
|
| 24 |
+
2. Org-wide security controls belong in cloud, not only in local clients.
|
| 25 |
+
3. Project sync policy must be enforceable server-side if it is meant for admins.
|
| 26 |
+
4. UI controls must map to real business rules, never fake toggles.
|
| 27 |
+
5. Data visibility and sync permissions must be deterministic and testable.
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
## Sync Rules
|
| 32 |
+
|
| 33 |
+
- Enrollment controls what may sync from local.
|
| 34 |
+
- Cloud pause controls what the organization currently allows.
|
| 35 |
+
- When a policy blocks sync, fail loudly rather than dropping data silently.
|
| 36 |
+
- Preserve auditability whenever admin policy changes behavior.
|
benchmarks/skillbench-venus-e/tasks/acf457a314e435c5_q1/task.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "skill-search-synthesis-v1",
|
| 3 |
+
"task_id": "acf457a314e435c5",
|
| 4 |
+
"query_id": "acf457a314e435c5_q1",
|
| 5 |
+
"environment": {
|
| 6 |
+
"image_id": "sha256:40a2ee6d73082b69ad27ac153f68fa37c541797eb9e3f07fc47f5f31dabdca56",
|
| 7 |
+
"network": "none"
|
| 8 |
+
},
|
| 9 |
+
"outputs": [],
|
| 10 |
+
"success_criteria": [
|
| 11 |
+
"Pass the complete original deterministic verifier (binary score); original checks preserved in evaluator/legacy-task.json."
|
| 12 |
+
],
|
| 13 |
+
"evaluation": {
|
| 14 |
+
"kind": "python",
|
| 15 |
+
"type": "verified"
|
| 16 |
+
},
|
| 17 |
+
"workspace": {
|
| 18 |
+
"input_mappings": [],
|
| 19 |
+
"skill_packages": [
|
| 20 |
+
{
|
| 21 |
+
"content_hash": "e682803f9137854a0cb35dcdb4525331708770b70c2fcfc095c3bbb78f206acb",
|
| 22 |
+
"name": "engram-business-rules",
|
| 23 |
+
"package_path": "skill",
|
| 24 |
+
"install_name": "engram-business-rules-463e1031"
|
| 25 |
+
}
|
| 26 |
+
],
|
| 27 |
+
"default_skill_target": ".claude/skills",
|
| 28 |
+
"candidate_mode": "response"
|
| 29 |
+
},
|
| 30 |
+
"source_skill": {
|
| 31 |
+
"sha256": "e682803f9137854a0cb35dcdb4525331708770b70c2fcfc095c3bbb78f206acb",
|
| 32 |
+
"files": {
|
| 33 |
+
"SKILL.md": "0832c148a3f12da6b59142b07ae3b3c6967389945ddc567ed8df5e7bfb3f738f"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"migration": {
|
| 37 |
+
"source_schema": "mybench-portable-task-v2",
|
| 38 |
+
"legacy_task_json": "provenance/legacy-package/task.json",
|
| 39 |
+
"historical_gain_protocol": "legacy; not Harbor certified",
|
| 40 |
+
"reference_available": true,
|
| 41 |
+
"skill_evidence_status": "not available in native evidence schema; original dependency/rubric anchors retained in private legacy task",
|
| 42 |
+
"original_skill_content_hashes": [
|
| 43 |
+
"463e1031f1a05eb823497dda24d993dea5f775fad5be1be6d61a53d766c0396b"
|
| 44 |
+
]
|
| 45 |
+
}
|
| 46 |
+
}
|
benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_contract.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"expected_check_ids": [
|
| 3 |
+
"0"
|
| 4 |
+
],
|
| 5 |
+
"criterion_weights": {
|
| 6 |
+
"0": 1
|
| 7 |
+
}
|
| 8 |
+
}
|
benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_entry.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable result protocol; candidate failures and evaluator errors stay distinct."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib,io,json,runpy,sys
|
| 4 |
+
from auto_policy import install,finalize
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
captured=io.StringIO()
|
| 9 |
+
try:
|
| 10 |
+
install()
|
| 11 |
+
with contextlib.redirect_stdout(captured):
|
| 12 |
+
try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__')
|
| 13 |
+
except SystemExit as error:
|
| 14 |
+
if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code))
|
| 15 |
+
body=None
|
| 16 |
+
for line in reversed(captured.getvalue().splitlines()):
|
| 17 |
+
try:value=json.loads(line)
|
| 18 |
+
except(ValueError,TypeError):continue
|
| 19 |
+
if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break
|
| 20 |
+
if body is None:raise RuntimeError('Trusted checker did not emit its result schema')
|
| 21 |
+
if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error','')))
|
| 22 |
+
cfgfile=HERE/'auto_policy.json'
|
| 23 |
+
if cfgfile.is_file():
|
| 24 |
+
cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[]))
|
| 25 |
+
if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True))
|
| 26 |
+
checks=body['checks']
|
| 27 |
+
if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned')
|
| 28 |
+
ids=[str(c['id'])for c in checks]
|
| 29 |
+
if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID')
|
| 30 |
+
contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids']
|
| 31 |
+
if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract')
|
| 32 |
+
weights=contract['criterion_weights']
|
| 33 |
+
body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks))
|
| 34 |
+
print(json.dumps(body,ensure_ascii=True));return 0
|
| 35 |
+
except Exception as error:
|
| 36 |
+
print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
|
| 37 |
+
|
| 38 |
+
if __name__=='__main__':raise SystemExit(main())
|
benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted bounded-invocation policy; never infer whole-program properties."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,os,subprocess,sys,tempfile,time,uuid
|
| 4 |
+
|
| 5 |
+
HERE=Path(__file__).resolve().parent
|
| 6 |
+
ENV='MYBENCH_AUTO_POLICY_RECEIPTS'
|
| 7 |
+
DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'
|
| 8 |
+
class PolicyInfrastructureError(RuntimeError): pass
|
| 9 |
+
_installed=False
|
| 10 |
+
_original_popen=subprocess.Popen
|
| 11 |
+
_original_run=subprocess.run
|
| 12 |
+
|
| 13 |
+
def _config():
|
| 14 |
+
p=HERE/'auto_policy.json'
|
| 15 |
+
if not p.is_file():return None
|
| 16 |
+
value=json.loads(p.read_text())
|
| 17 |
+
if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy')
|
| 18 |
+
return value
|
| 19 |
+
|
| 20 |
+
def _folder():
|
| 21 |
+
if ENV not in os.environ:
|
| 22 |
+
os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp')
|
| 23 |
+
p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
|
| 24 |
+
|
| 25 |
+
def _python_target(command,cwd):
|
| 26 |
+
if not isinstance(command,(list,tuple))or not command:return None
|
| 27 |
+
argv=[os.fspath(x)for x in command]
|
| 28 |
+
if 'python'not in Path(argv[0]).name.lower():return None
|
| 29 |
+
i=1;flags=[]
|
| 30 |
+
while i<len(argv)and argv[i].startswith('-'):
|
| 31 |
+
flag=argv[i]
|
| 32 |
+
if flag=='-m':
|
| 33 |
+
if i+1>=len(argv):return None
|
| 34 |
+
name=argv[i+1];p=Path(cwd)/name.replace('.','/')
|
| 35 |
+
if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None
|
| 36 |
+
return argv[0],flags,'module',name,argv[i+2:]
|
| 37 |
+
if flag in ['-c','-']:return None
|
| 38 |
+
flags.append(flag);i+=1
|
| 39 |
+
if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1
|
| 40 |
+
if i>=len(argv)or not argv[i].endswith('.py'):return None
|
| 41 |
+
path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path
|
| 42 |
+
path=path.resolve()
|
| 43 |
+
if path==HERE or HERE in path.parents:
|
| 44 |
+
if path.name in ['auto_policy.py','auto_policy_guard.py']:return None
|
| 45 |
+
for value in argv[i+1:]:
|
| 46 |
+
if not value.endswith('.py')or value.startswith('-'):continue
|
| 47 |
+
subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject
|
| 48 |
+
subject=subject.resolve()
|
| 49 |
+
if HERE not in subject.parents:
|
| 50 |
+
return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]]
|
| 51 |
+
return None
|
| 52 |
+
return argv[0],flags,'script',str(path),argv[i+1:]
|
| 53 |
+
|
| 54 |
+
def install():
|
| 55 |
+
global _installed
|
| 56 |
+
if _installed:return
|
| 57 |
+
_installed=True
|
| 58 |
+
cfg=_config()
|
| 59 |
+
if cfg is None:return
|
| 60 |
+
_folder()
|
| 61 |
+
os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420)))
|
| 62 |
+
class GuardedPopen(_original_popen):
|
| 63 |
+
def __init__(self,args,*pos,**kwargs):
|
| 64 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 65 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd)
|
| 66 |
+
receipt=None
|
| 67 |
+
if target:
|
| 68 |
+
executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json')
|
| 69 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value)))
|
| 70 |
+
if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S']
|
| 71 |
+
args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail]
|
| 72 |
+
env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env
|
| 73 |
+
if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE]
|
| 74 |
+
try:super().__init__(args,*pos,**kwargs)
|
| 75 |
+
except OSError as error:
|
| 76 |
+
if receipt:
|
| 77 |
+
receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error))))
|
| 78 |
+
raise
|
| 79 |
+
subprocess.Popen=GuardedPopen
|
| 80 |
+
def bounded_run(*pos,**kwargs):
|
| 81 |
+
command=pos[0]if pos else kwargs.get('args')
|
| 82 |
+
cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve()
|
| 83 |
+
target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd)
|
| 84 |
+
if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace'
|
| 85 |
+
if target is not None and cfg.get('execution_budget_seconds')is not None:
|
| 86 |
+
budget=cfg['execution_budget_seconds']
|
| 87 |
+
if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget')
|
| 88 |
+
kwargs['timeout']=budget
|
| 89 |
+
remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None
|
| 90 |
+
if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining)
|
| 91 |
+
try:
|
| 92 |
+
if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0)
|
| 93 |
+
result=_original_run(*pos,**kwargs)
|
| 94 |
+
if target is not None and result.returncode<0:
|
| 95 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[])))
|
| 96 |
+
return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr)
|
| 97 |
+
return result
|
| 98 |
+
except subprocess.TimeoutExpired as error:
|
| 99 |
+
if target is None:raise
|
| 100 |
+
(_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[])))
|
| 101 |
+
textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding')
|
| 102 |
+
empty=''if textual else b''
|
| 103 |
+
def output(value):
|
| 104 |
+
if value is None:return empty
|
| 105 |
+
return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value
|
| 106 |
+
return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr))
|
| 107 |
+
subprocess.run=bounded_run
|
| 108 |
+
|
| 109 |
+
def status(require_execution=True):
|
| 110 |
+
install();p=_folder();rows=[]
|
| 111 |
+
for receipt in sorted(p.glob('*.json')):
|
| 112 |
+
try:row=json.loads(receipt.read_text())
|
| 113 |
+
except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error
|
| 114 |
+
if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']:
|
| 115 |
+
raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt))
|
| 116 |
+
rows.append(row)
|
| 117 |
+
if require_execution and not any(r.get('target_present')for r in rows):return False
|
| 118 |
+
return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
|
| 119 |
+
|
| 120 |
+
def finalize(body,owner_ids,require_execution=True):
|
| 121 |
+
observed=status(require_execution=require_execution)
|
| 122 |
+
wanted=set(map(str,owner_ids))
|
| 123 |
+
for row in body.get('checks',[]):
|
| 124 |
+
if str(row['id'])in wanted:
|
| 125 |
+
if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id']))
|
| 126 |
+
row['passed']=row['passed']and observed
|
| 127 |
+
row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy'
|
| 128 |
+
body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[]))
|
| 129 |
+
body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed)
|
| 130 |
+
return body
|
| 131 |
+
|
| 132 |
+
def run(*args,**kwargs):
|
| 133 |
+
install();return subprocess.run(*args,**kwargs)
|
benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/auto_policy_guard.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Child-side observer for the exact public bounded-invocation policy."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import atexit,builtins,importlib,importlib.util,json,os,runpy,sys,sysconfig
|
| 4 |
+
|
| 5 |
+
receipt,config_file,kind,target,*arguments=sys.argv[1:]
|
| 6 |
+
subject=arguments.pop(0)if kind=='probe'else target
|
| 7 |
+
subject_filename=os.path.abspath(subject)
|
| 8 |
+
receipt=Path(receipt);cfg=json.loads(Path(config_file).read_text());cwd=Path.cwd().resolve()
|
| 9 |
+
local_roots=[cwd,*[p for p in [Path('/candidate'),Path('/app'),Path('/workspace')] if p.is_dir()]]
|
| 10 |
+
if kind=='script':local_roots.insert(0,Path(target).resolve().parent)
|
| 11 |
+
if kind=='probe':local_roots[:0]=[Path(subject).resolve().parent,Path(__file__).resolve().parent]
|
| 12 |
+
candidate_root_names=[str(p)for p in local_roots if str(p)!='/grader']
|
| 13 |
+
observer_filename=__file__
|
| 14 |
+
stdlib_names=set(getattr(sys,'stdlib_module_names',()))|set(sys.builtin_module_names)
|
| 15 |
+
stdlib_root=Path(sysconfig.get_path('stdlib')).resolve()
|
| 16 |
+
if not getattr(sys,'stdlib_module_names',None):
|
| 17 |
+
for p in stdlib_root.iterdir():
|
| 18 |
+
if p.name not in ['site-packages','dist-packages']:stdlib_names.add(p.stem if p.suffix=='.py'else p.name)
|
| 19 |
+
state=dict(schema='bounded-policy-v1',state='running',target=subject,target_present=Path(subject).is_file()if kind in ['script','probe']else True,violations=[])
|
| 20 |
+
busy=False
|
| 21 |
+
def save():
|
| 22 |
+
global busy
|
| 23 |
+
was=busy;busy=True
|
| 24 |
+
try:
|
| 25 |
+
temporary=receipt.with_suffix('.tmp');temporary.write_text(json.dumps(state));temporary.replace(receipt)
|
| 26 |
+
finally:busy=was
|
| 27 |
+
def violation(code,detail):
|
| 28 |
+
state['violations'].append(dict(code=code,detail=str(detail)));save();raise PermissionError('AUTOGRADE_POLICY:'+code)
|
| 29 |
+
def local_module(name):
|
| 30 |
+
first=name.partition('.')[0]
|
| 31 |
+
roots=list(local_roots)
|
| 32 |
+
for value in sys.path:
|
| 33 |
+
try:p=Path(value or cwd).resolve()
|
| 34 |
+
except (OSError,TypeError,ValueError):continue
|
| 35 |
+
if any(p==r or r in p.parents for r in local_roots):roots.append(p)
|
| 36 |
+
return any((p/(first+'.py')).is_file()or(p/first).is_dir()for p in roots)
|
| 37 |
+
def subject_active():
|
| 38 |
+
if kind!='probe':return True
|
| 39 |
+
frame=sys._getframe(1)
|
| 40 |
+
while frame:
|
| 41 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 42 |
+
if isinstance(filename,str):
|
| 43 |
+
absolute=os.path.abspath(filename)
|
| 44 |
+
if any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names):return True
|
| 45 |
+
frame=frame.f_back
|
| 46 |
+
return False
|
| 47 |
+
def audit(event,args):
|
| 48 |
+
relevant=event=='import'and cfg.get('stdlib_only')or cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}or cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}or cfg.get('forbid_native')and event.startswith('ctypes.')
|
| 49 |
+
if busy or not relevant or not subject_active():return
|
| 50 |
+
if event=='import'and cfg.get('stdlib_only')and import_requested_by_candidate():
|
| 51 |
+
check_import(str(args[0]))
|
| 52 |
+
if cfg.get('forbid_network')and event in {'socket.connect','socket.connect_ex','socket.sendto','socket.sendmsg','socket.getaddrinfo','socket.gethostbyname','socket.gethostbyaddr','socket.getnameinfo'}:violation('network_operation',event)
|
| 53 |
+
if cfg.get('forbid_subprocess')and event in {'subprocess.Popen','os.system','os.exec','os.posix_spawn','os.fork','os.forkpty'}:violation('subprocess_operation',event)
|
| 54 |
+
if cfg.get('forbid_native')and event.startswith('ctypes.'):violation('foreign_function_interface',event)
|
| 55 |
+
def check_import(name):
|
| 56 |
+
if any(name==prefix or name.startswith(prefix+'.')for prefix in cfg.get('forbidden_module_prefixes',[])):violation('forbidden_candidate_import',name)
|
| 57 |
+
base=name.partition('.')[0]
|
| 58 |
+
if cfg.get('stdlib_only')and base not in stdlib_names and not local_module(name):violation('nonstdlib_import',name)
|
| 59 |
+
def import_requested_by_candidate():
|
| 60 |
+
frame=sys._getframe(1)
|
| 61 |
+
while frame:
|
| 62 |
+
filename=frame.f_globals.get('__file__',frame.f_code.co_filename)
|
| 63 |
+
if not isinstance(filename,str)or filename==observer_filename or filename.startswith('<frozen importlib'):frame=frame.f_back;continue
|
| 64 |
+
absolute=os.path.abspath(filename)
|
| 65 |
+
return any(absolute==root or absolute.startswith(root+os.sep)for root in candidate_root_names)
|
| 66 |
+
return False
|
| 67 |
+
original_import=builtins.__import__;original_import_module=importlib.import_module
|
| 68 |
+
def bounded_import(name,globals=None,locals=None,fromlist=(),level=0):
|
| 69 |
+
if not busy and subject_active()and import_requested_by_candidate():
|
| 70 |
+
absolute=name
|
| 71 |
+
if level:
|
| 72 |
+
package=(globals or{}).get('__package__')or(globals or{}).get('__name__','')
|
| 73 |
+
try:absolute=importlib.util.resolve_name('.'*level+name,package)
|
| 74 |
+
except(ImportError,ValueError):absolute=name
|
| 75 |
+
check_import(absolute)
|
| 76 |
+
return original_import(name,globals,locals,fromlist,level)
|
| 77 |
+
def bounded_import_module(name,package=None):
|
| 78 |
+
if not busy and subject_active()and import_requested_by_candidate():check_import(importlib.util.resolve_name(name,package)if name.startswith('.')else name)
|
| 79 |
+
return original_import_module(name,package)
|
| 80 |
+
save();sys.addaudithook(audit);builtins.__import__=bounded_import;importlib.import_module=bounded_import_module
|
| 81 |
+
@atexit.register
|
| 82 |
+
def finish():state['state']='finished';save()
|
| 83 |
+
for p in reversed(local_roots):sys.path.insert(0,str(p))
|
| 84 |
+
sys.argv=[target,*arguments]
|
| 85 |
+
if kind=='module':runpy.run_module(target,run_name='__main__',alter_sys=True)
|
| 86 |
+
else:runpy.run_path(target,run_name='__main__')
|
benchmarks/skillbench-venus-e/tasks/adc122d50c75da6b_q1/evaluator/autograde_task_check.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import auto_policy as _auto_policy_observer; _auto_policy_observer.install()
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
root=Path(__file__).resolve().parent
|
| 5 |
+
sys.path.insert(0,str(root/'legacy_tests'))
|
| 6 |
+
from evaluate import evaluate
|
| 7 |
+
t=json.loads((root/'legacy-task.json').read_text())
|
| 8 |
+
mode=t['workspace']['candidate_mode']
|
| 9 |
+
r,code=evaluate(root/'legacy-task.json','/candidate' if mode=='workspace' else '/answer.txt')
|
| 10 |
+
if r.get('status')=='candidate_contract_error':r=dict(r,status='scored',passed=False)
|
| 11 |
+
if r.get('status')!='scored':raise RuntimeError(json.dumps(r))
|
| 12 |
+
print(json.dumps({'checks':[{'id':'0','passed':r['passed'],'reason':json.dumps(r.get('details'),ensure_ascii=False)}]}))
|